Fix problems with 'fullscreen' and :mksession
[MacVim.git] / src / ex_docmd.c
blobb8b98daf263a5f18caf4bb87b49cac29a1bdd3af
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * ex_docmd.c: functions for executing an Ex command line.
14 #include "vim.h"
16 static int quitmore = 0;
17 static int ex_pressedreturn = FALSE;
18 #ifndef FEAT_PRINTER
19 # define ex_hardcopy ex_ni
20 #endif
22 #ifdef FEAT_USR_CMDS
23 typedef struct ucmd
25 char_u *uc_name; /* The command name */
26 long_u uc_argt; /* The argument type */
27 char_u *uc_rep; /* The command's replacement string */
28 long uc_def; /* The default value for a range/count */
29 scid_T uc_scriptID; /* SID where the command was defined */
30 int uc_compl; /* completion type */
31 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
32 char_u *uc_compl_arg; /* completion argument if any */
33 # endif
34 } ucmd_T;
36 #define UC_BUFFER 1 /* -buffer: local to current buffer */
38 static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL};
40 #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
41 #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
43 static void do_ucmd __ARGS((exarg_T *eap));
44 static void ex_command __ARGS((exarg_T *eap));
45 static void ex_delcommand __ARGS((exarg_T *eap));
46 # ifdef FEAT_CMDL_COMPL
47 static char_u *get_user_command_name __ARGS((int idx));
48 # endif
50 #else
51 # define ex_command ex_ni
52 # define ex_comclear ex_ni
53 # define ex_delcommand ex_ni
54 #endif
56 #ifdef FEAT_EVAL
57 static char_u *do_one_cmd __ARGS((char_u **, int, struct condstack *, char_u *(*fgetline)(int, void *, int), void *cookie));
58 #else
59 static char_u *do_one_cmd __ARGS((char_u **, int, char_u *(*fgetline)(int, void *, int), void *cookie));
60 static int if_level = 0; /* depth in :if */
61 #endif
62 static char_u *find_command __ARGS((exarg_T *eap, int *full));
64 static void ex_abbreviate __ARGS((exarg_T *eap));
65 static void ex_map __ARGS((exarg_T *eap));
66 static void ex_unmap __ARGS((exarg_T *eap));
67 static void ex_mapclear __ARGS((exarg_T *eap));
68 static void ex_abclear __ARGS((exarg_T *eap));
69 #ifndef FEAT_MENU
70 # define ex_emenu ex_ni
71 # define ex_menu ex_ni
72 # define ex_menutranslate ex_ni
73 #endif
74 #ifdef FEAT_AUTOCMD
75 static void ex_autocmd __ARGS((exarg_T *eap));
76 static void ex_doautocmd __ARGS((exarg_T *eap));
77 #else
78 # define ex_autocmd ex_ni
79 # define ex_doautocmd ex_ni
80 # define ex_doautoall ex_ni
81 #endif
82 #ifdef FEAT_LISTCMDS
83 static void ex_bunload __ARGS((exarg_T *eap));
84 static void ex_buffer __ARGS((exarg_T *eap));
85 static void ex_bmodified __ARGS((exarg_T *eap));
86 static void ex_bnext __ARGS((exarg_T *eap));
87 static void ex_bprevious __ARGS((exarg_T *eap));
88 static void ex_brewind __ARGS((exarg_T *eap));
89 static void ex_blast __ARGS((exarg_T *eap));
90 #else
91 # define ex_bunload ex_ni
92 # define ex_buffer ex_ni
93 # define ex_bmodified ex_ni
94 # define ex_bnext ex_ni
95 # define ex_bprevious ex_ni
96 # define ex_brewind ex_ni
97 # define ex_blast ex_ni
98 # define buflist_list ex_ni
99 # define ex_checktime ex_ni
100 #endif
101 #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS)
102 # define ex_buffer_all ex_ni
103 #endif
104 static char_u *getargcmd __ARGS((char_u **));
105 static char_u *skip_cmd_arg __ARGS((char_u *p, int rembs));
106 static int getargopt __ARGS((exarg_T *eap));
107 #ifndef FEAT_QUICKFIX
108 # define ex_make ex_ni
109 # define ex_cbuffer ex_ni
110 # define ex_cc ex_ni
111 # define ex_cnext ex_ni
112 # define ex_cfile ex_ni
113 # define qf_list ex_ni
114 # define qf_age ex_ni
115 # define ex_helpgrep ex_ni
116 # define ex_vimgrep ex_ni
117 #endif
118 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS)
119 # define ex_cclose ex_ni
120 # define ex_copen ex_ni
121 # define ex_cwindow ex_ni
122 #endif
123 #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL)
124 # define ex_cexpr ex_ni
125 #endif
127 static int check_more __ARGS((int, int));
128 static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file));
129 static void get_flags __ARGS((exarg_T *eap));
130 #if !defined(FEAT_PERL) || !defined(FEAT_PYTHON) || !defined(FEAT_TCL) \
131 || !defined(FEAT_RUBY) || !defined(FEAT_MZSCHEME)
132 # define HAVE_EX_SCRIPT_NI
133 static void ex_script_ni __ARGS((exarg_T *eap));
134 #endif
135 static char_u *invalid_range __ARGS((exarg_T *eap));
136 static void correct_range __ARGS((exarg_T *eap));
137 #ifdef FEAT_QUICKFIX
138 static char_u *replace_makeprg __ARGS((exarg_T *eap, char_u *p, char_u **cmdlinep));
139 #endif
140 static char_u *repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep));
141 static void ex_highlight __ARGS((exarg_T *eap));
142 static void ex_colorscheme __ARGS((exarg_T *eap));
143 static void ex_quit __ARGS((exarg_T *eap));
144 static void ex_cquit __ARGS((exarg_T *eap));
145 static void ex_quit_all __ARGS((exarg_T *eap));
146 #ifdef FEAT_WINDOWS
147 static void ex_close __ARGS((exarg_T *eap));
148 static void ex_win_close __ARGS((int forceit, win_T *win, tabpage_T *tp));
149 static void ex_only __ARGS((exarg_T *eap));
150 static void ex_resize __ARGS((exarg_T *eap));
151 static void ex_stag __ARGS((exarg_T *eap));
152 static void ex_tabclose __ARGS((exarg_T *eap));
153 static void ex_tabonly __ARGS((exarg_T *eap));
154 static void ex_tabnext __ARGS((exarg_T *eap));
155 static void ex_tabmove __ARGS((exarg_T *eap));
156 static void ex_tabs __ARGS((exarg_T *eap));
157 #else
158 # define ex_close ex_ni
159 # define ex_only ex_ni
160 # define ex_all ex_ni
161 # define ex_resize ex_ni
162 # define ex_splitview ex_ni
163 # define ex_stag ex_ni
164 # define ex_tabnext ex_ni
165 # define ex_tabmove ex_ni
166 # define ex_tabs ex_ni
167 # define ex_tabclose ex_ni
168 # define ex_tabonly ex_ni
169 #endif
170 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
171 static void ex_pclose __ARGS((exarg_T *eap));
172 static void ex_ptag __ARGS((exarg_T *eap));
173 static void ex_pedit __ARGS((exarg_T *eap));
174 #else
175 # define ex_pclose ex_ni
176 # define ex_ptag ex_ni
177 # define ex_pedit ex_ni
178 #endif
179 static void ex_hide __ARGS((exarg_T *eap));
180 static void ex_stop __ARGS((exarg_T *eap));
181 static void ex_exit __ARGS((exarg_T *eap));
182 static void ex_print __ARGS((exarg_T *eap));
183 #ifdef FEAT_BYTEOFF
184 static void ex_goto __ARGS((exarg_T *eap));
185 #else
186 # define ex_goto ex_ni
187 #endif
188 static void ex_shell __ARGS((exarg_T *eap));
189 static void ex_preserve __ARGS((exarg_T *eap));
190 static void ex_recover __ARGS((exarg_T *eap));
191 #ifndef FEAT_LISTCMDS
192 # define ex_argedit ex_ni
193 # define ex_argadd ex_ni
194 # define ex_argdelete ex_ni
195 # define ex_listdo ex_ni
196 #endif
197 static void ex_mode __ARGS((exarg_T *eap));
198 static void ex_wrongmodifier __ARGS((exarg_T *eap));
199 static void ex_find __ARGS((exarg_T *eap));
200 static void ex_open __ARGS((exarg_T *eap));
201 static void ex_edit __ARGS((exarg_T *eap));
202 #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER)
203 # define ex_drop ex_ni
204 #endif
205 #ifndef FEAT_GUI
206 # define ex_gui ex_nogui
207 static void ex_nogui __ARGS((exarg_T *eap));
208 #endif
209 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
210 static void ex_tearoff __ARGS((exarg_T *eap));
211 #else
212 # define ex_tearoff ex_ni
213 #endif
214 #if defined(FEAT_MENU) && (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK) \
215 || defined(FEAT_GUI_MACVIM))
216 static void ex_popup __ARGS((exarg_T *eap));
217 #else
218 # define ex_popup ex_ni
219 #endif
220 #ifndef FEAT_GUI_MSWIN
221 # define ex_simalt ex_ni
222 #endif
223 #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
224 # define gui_mch_find_dialog ex_ni
225 # define gui_mch_replace_dialog ex_ni
226 #endif
227 #if !defined(FEAT_GUI_GTK)
228 # define ex_helpfind ex_ni
229 #endif
230 #ifndef FEAT_CSCOPE
231 # define do_cscope ex_ni
232 # define do_scscope ex_ni
233 # define do_cstag ex_ni
234 #endif
235 #ifndef FEAT_SYN_HL
236 # define ex_syntax ex_ni
237 #endif
238 #ifndef FEAT_SPELL
239 # define ex_spell ex_ni
240 # define ex_mkspell ex_ni
241 # define ex_spelldump ex_ni
242 # define ex_spellinfo ex_ni
243 # define ex_spellrepall ex_ni
244 #endif
245 #ifndef FEAT_MZSCHEME
246 # define ex_mzscheme ex_script_ni
247 # define ex_mzfile ex_ni
248 #endif
249 #ifndef FEAT_PERL
250 # define ex_perl ex_script_ni
251 # define ex_perldo ex_ni
252 #endif
253 #ifndef FEAT_PYTHON
254 # define ex_python ex_script_ni
255 # define ex_pyfile ex_ni
256 #endif
257 #ifndef FEAT_TCL
258 # define ex_tcl ex_script_ni
259 # define ex_tcldo ex_ni
260 # define ex_tclfile ex_ni
261 #endif
262 #ifndef FEAT_RUBY
263 # define ex_ruby ex_script_ni
264 # define ex_rubydo ex_ni
265 # define ex_rubyfile ex_ni
266 #endif
267 #ifndef FEAT_SNIFF
268 # define ex_sniff ex_ni
269 #endif
270 #ifndef FEAT_KEYMAP
271 # define ex_loadkeymap ex_ni
272 #endif
273 static void ex_swapname __ARGS((exarg_T *eap));
274 static void ex_syncbind __ARGS((exarg_T *eap));
275 static void ex_read __ARGS((exarg_T *eap));
276 static void ex_pwd __ARGS((exarg_T *eap));
277 static void ex_equal __ARGS((exarg_T *eap));
278 static void ex_sleep __ARGS((exarg_T *eap));
279 static void do_exmap __ARGS((exarg_T *eap, int isabbrev));
280 static void ex_winsize __ARGS((exarg_T *eap));
281 #ifdef FEAT_WINDOWS
282 static void ex_wincmd __ARGS((exarg_T *eap));
283 #else
284 # define ex_wincmd ex_ni
285 #endif
286 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
287 static void ex_winpos __ARGS((exarg_T *eap));
288 #else
289 # define ex_winpos ex_ni
290 #endif
291 static void ex_operators __ARGS((exarg_T *eap));
292 static void ex_put __ARGS((exarg_T *eap));
293 static void ex_copymove __ARGS((exarg_T *eap));
294 static void ex_may_print __ARGS((exarg_T *eap));
295 static void ex_submagic __ARGS((exarg_T *eap));
296 static void ex_join __ARGS((exarg_T *eap));
297 static void ex_at __ARGS((exarg_T *eap));
298 static void ex_bang __ARGS((exarg_T *eap));
299 static void ex_undo __ARGS((exarg_T *eap));
300 static void ex_redo __ARGS((exarg_T *eap));
301 static void ex_later __ARGS((exarg_T *eap));
302 static void ex_redir __ARGS((exarg_T *eap));
303 static void ex_redraw __ARGS((exarg_T *eap));
304 static void ex_redrawstatus __ARGS((exarg_T *eap));
305 static void close_redir __ARGS((void));
306 static void ex_mkrc __ARGS((exarg_T *eap));
307 static void ex_mark __ARGS((exarg_T *eap));
308 #ifdef FEAT_USR_CMDS
309 static char_u *uc_fun_cmd __ARGS((void));
310 static char_u *find_ucmd __ARGS((exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl));
311 #endif
312 #ifdef FEAT_EX_EXTRA
313 static void ex_normal __ARGS((exarg_T *eap));
314 static void ex_startinsert __ARGS((exarg_T *eap));
315 static void ex_stopinsert __ARGS((exarg_T *eap));
316 #else
317 # define ex_normal ex_ni
318 # define ex_align ex_ni
319 # define ex_retab ex_ni
320 # define ex_startinsert ex_ni
321 # define ex_stopinsert ex_ni
322 # define ex_helptags ex_ni
323 # define ex_sort ex_ni
324 #endif
325 #ifdef FEAT_FIND_ID
326 static void ex_checkpath __ARGS((exarg_T *eap));
327 static void ex_findpat __ARGS((exarg_T *eap));
328 #else
329 # define ex_findpat ex_ni
330 # define ex_checkpath ex_ni
331 #endif
332 #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
333 static void ex_psearch __ARGS((exarg_T *eap));
334 #else
335 # define ex_psearch ex_ni
336 #endif
337 static void ex_tag __ARGS((exarg_T *eap));
338 static void ex_tag_cmd __ARGS((exarg_T *eap, char_u *name));
339 #ifndef FEAT_EVAL
340 # define ex_scriptnames ex_ni
341 # define ex_finish ex_ni
342 # define ex_echo ex_ni
343 # define ex_echohl ex_ni
344 # define ex_execute ex_ni
345 # define ex_call ex_ni
346 # define ex_if ex_ni
347 # define ex_endif ex_ni
348 # define ex_else ex_ni
349 # define ex_while ex_ni
350 # define ex_for ex_ni
351 # define ex_continue ex_ni
352 # define ex_break ex_ni
353 # define ex_endwhile ex_ni
354 # define ex_endfor ex_ni
355 # define ex_throw ex_ni
356 # define ex_try ex_ni
357 # define ex_catch ex_ni
358 # define ex_finally ex_ni
359 # define ex_endtry ex_ni
360 # define ex_endfunction ex_ni
361 # define ex_let ex_ni
362 # define ex_unlet ex_ni
363 # define ex_lockvar ex_ni
364 # define ex_unlockvar ex_ni
365 # define ex_function ex_ni
366 # define ex_delfunction ex_ni
367 # define ex_return ex_ni
368 #endif
369 static char_u *arg_all __ARGS((void));
370 #ifdef FEAT_SESSION
371 static int makeopens __ARGS((FILE *fd, char_u *dirnow));
372 static int put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx));
373 static void ex_loadview __ARGS((exarg_T *eap));
374 static char_u *get_view_file __ARGS((int c));
375 static int did_lcd; /* whether ":lcd" was produced for a session */
376 #else
377 # define ex_loadview ex_ni
378 #endif
379 #ifndef FEAT_EVAL
380 # define ex_compiler ex_ni
381 #endif
382 #ifdef FEAT_VIMINFO
383 static void ex_viminfo __ARGS((exarg_T *eap));
384 #else
385 # define ex_viminfo ex_ni
386 #endif
387 static void ex_behave __ARGS((exarg_T *eap));
388 #ifdef FEAT_AUTOCMD
389 static void ex_filetype __ARGS((exarg_T *eap));
390 static void ex_setfiletype __ARGS((exarg_T *eap));
391 #else
392 # define ex_filetype ex_ni
393 # define ex_setfiletype ex_ni
394 #endif
395 #ifndef FEAT_DIFF
396 # define ex_diffoff ex_ni
397 # define ex_diffpatch ex_ni
398 # define ex_diffgetput ex_ni
399 # define ex_diffsplit ex_ni
400 # define ex_diffthis ex_ni
401 # define ex_diffupdate ex_ni
402 #endif
403 static void ex_digraphs __ARGS((exarg_T *eap));
404 static void ex_set __ARGS((exarg_T *eap));
405 #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD)
406 # define ex_options ex_ni
407 #endif
408 #ifdef FEAT_SEARCH_EXTRA
409 static void ex_nohlsearch __ARGS((exarg_T *eap));
410 static void ex_match __ARGS((exarg_T *eap));
411 #else
412 # define ex_nohlsearch ex_ni
413 # define ex_match ex_ni
414 #endif
415 #ifdef FEAT_CRYPT
416 static void ex_X __ARGS((exarg_T *eap));
417 #else
418 # define ex_X ex_ni
419 #endif
420 #ifdef FEAT_FOLDING
421 static void ex_fold __ARGS((exarg_T *eap));
422 static void ex_foldopen __ARGS((exarg_T *eap));
423 static void ex_folddo __ARGS((exarg_T *eap));
424 #else
425 # define ex_fold ex_ni
426 # define ex_foldopen ex_ni
427 # define ex_folddo ex_ni
428 #endif
429 #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
430 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)))
431 # define ex_language ex_ni
432 #endif
433 #ifndef FEAT_SIGNS
434 # define ex_sign ex_ni
435 #endif
436 #ifndef FEAT_SUN_WORKSHOP
437 # define ex_wsverb ex_ni
438 #endif
439 #ifndef FEAT_NETBEANS_INTG
440 # define ex_nbkey ex_ni
441 #endif
443 #ifndef FEAT_EVAL
444 # define ex_debug ex_ni
445 # define ex_breakadd ex_ni
446 # define ex_debuggreedy ex_ni
447 # define ex_breakdel ex_ni
448 # define ex_breaklist ex_ni
449 #endif
451 #ifndef FEAT_CMDHIST
452 # define ex_history ex_ni
453 #endif
454 #ifndef FEAT_JUMPLIST
455 # define ex_jumps ex_ni
456 # define ex_changes ex_ni
457 #endif
459 #ifndef FEAT_PROFILE
460 # define ex_profile ex_ni
461 #endif
463 #ifndef FEAT_GUI_MACVIM
464 # define ex_macaction ex_ni
465 # define ex_macmenu ex_ni
466 #endif
469 * Declare cmdnames[].
471 #define DO_DECLARE_EXCMD
472 #include "ex_cmds.h"
475 * Table used to quickly search for a command, based on its first character.
477 static cmdidx_T cmdidxs[27] =
479 CMD_append,
480 CMD_buffer,
481 CMD_change,
482 CMD_delete,
483 CMD_edit,
484 CMD_file,
485 CMD_global,
486 CMD_help,
487 CMD_insert,
488 CMD_join,
489 CMD_k,
490 CMD_list,
491 CMD_move,
492 CMD_next,
493 CMD_open,
494 CMD_print,
495 CMD_quit,
496 CMD_read,
497 CMD_substitute,
498 CMD_t,
499 CMD_undo,
500 CMD_vglobal,
501 CMD_write,
502 CMD_xit,
503 CMD_yank,
504 CMD_z,
505 CMD_bang
508 static char_u dollar_command[2] = {'$', 0};
511 #ifdef FEAT_EVAL
512 /* Struct for storing a line inside a while/for loop */
513 typedef struct
515 char_u *line; /* command line */
516 linenr_T lnum; /* sourcing_lnum of the line */
517 } wcmd_T;
520 * Structure used to store info for line position in a while or for loop.
521 * This is required, because do_one_cmd() may invoke ex_function(), which
522 * reads more lines that may come from the while/for loop.
524 struct loop_cookie
526 garray_T *lines_gap; /* growarray with line info */
527 int current_line; /* last read line from growarray */
528 int repeating; /* TRUE when looping a second time */
529 /* When "repeating" is FALSE use "getline" and "cookie" to get lines */
530 char_u *(*getline) __ARGS((int, void *, int));
531 void *cookie;
534 static char_u *get_loop_line __ARGS((int c, void *cookie, int indent));
535 static int store_loop_line __ARGS((garray_T *gap, char_u *line));
536 static void free_cmdlines __ARGS((garray_T *gap));
538 /* Struct to save a few things while debugging. Used in do_cmdline() only. */
539 struct dbg_stuff
541 int trylevel;
542 int force_abort;
543 except_T *caught_stack;
544 char_u *vv_exception;
545 char_u *vv_throwpoint;
546 int did_emsg;
547 int got_int;
548 int did_throw;
549 int need_rethrow;
550 int check_cstack;
551 except_T *current_exception;
554 static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp));
555 static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp));
557 static void
558 save_dbg_stuff(dsp)
559 struct dbg_stuff *dsp;
561 dsp->trylevel = trylevel; trylevel = 0;
562 dsp->force_abort = force_abort; force_abort = FALSE;
563 dsp->caught_stack = caught_stack; caught_stack = NULL;
564 dsp->vv_exception = v_exception(NULL);
565 dsp->vv_throwpoint = v_throwpoint(NULL);
567 /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */
568 dsp->did_emsg = did_emsg; did_emsg = FALSE;
569 dsp->got_int = got_int; got_int = FALSE;
570 dsp->did_throw = did_throw; did_throw = FALSE;
571 dsp->need_rethrow = need_rethrow; need_rethrow = FALSE;
572 dsp->check_cstack = check_cstack; check_cstack = FALSE;
573 dsp->current_exception = current_exception; current_exception = NULL;
576 static void
577 restore_dbg_stuff(dsp)
578 struct dbg_stuff *dsp;
580 suppress_errthrow = FALSE;
581 trylevel = dsp->trylevel;
582 force_abort = dsp->force_abort;
583 caught_stack = dsp->caught_stack;
584 (void)v_exception(dsp->vv_exception);
585 (void)v_throwpoint(dsp->vv_throwpoint);
586 did_emsg = dsp->did_emsg;
587 got_int = dsp->got_int;
588 did_throw = dsp->did_throw;
589 need_rethrow = dsp->need_rethrow;
590 check_cstack = dsp->check_cstack;
591 current_exception = dsp->current_exception;
593 #endif
597 * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi"
598 * command is given.
600 void
601 do_exmode(improved)
602 int improved; /* TRUE for "improved Ex" mode */
604 int save_msg_scroll;
605 int prev_msg_row;
606 linenr_T prev_line;
607 int changedtick;
609 if (improved)
610 exmode_active = EXMODE_VIM;
611 else
612 exmode_active = EXMODE_NORMAL;
613 State = NORMAL;
615 /* When using ":global /pat/ visual" and then "Q" we return to continue
616 * the :global command. */
617 if (global_busy)
618 return;
620 save_msg_scroll = msg_scroll;
621 ++RedrawingDisabled; /* don't redisplay the window */
622 ++no_wait_return; /* don't wait for return */
623 #ifdef FEAT_GUI
624 /* Ignore scrollbar and mouse events in Ex mode */
625 ++hold_gui_events;
626 #endif
627 #ifdef FEAT_SNIFF
628 want_sniff_request = 0; /* No K_SNIFF wanted */
629 #endif
631 MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode."));
632 while (exmode_active)
634 #ifdef FEAT_EX_EXTRA
635 /* Check for a ":normal" command and no more characters left. */
636 if (ex_normal_busy > 0 && typebuf.tb_len == 0)
638 exmode_active = FALSE;
639 break;
641 #endif
642 msg_scroll = TRUE;
643 need_wait_return = FALSE;
644 ex_pressedreturn = FALSE;
645 ex_no_reprint = FALSE;
646 changedtick = curbuf->b_changedtick;
647 prev_msg_row = msg_row;
648 prev_line = curwin->w_cursor.lnum;
649 #ifdef FEAT_SNIFF
650 ProcessSniffRequests();
651 #endif
652 if (improved)
654 cmdline_row = msg_row;
655 do_cmdline(NULL, getexline, NULL, 0);
657 else
658 do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT);
659 lines_left = Rows - 1;
661 if ((prev_line != curwin->w_cursor.lnum
662 || changedtick != curbuf->b_changedtick) && !ex_no_reprint)
664 if (curbuf->b_ml.ml_flags & ML_EMPTY)
665 EMSG(_(e_emptybuf));
666 else
668 if (ex_pressedreturn)
670 /* go up one line, to overwrite the ":<CR>" line, so the
671 * output doesn't contain empty lines. */
672 msg_row = prev_msg_row;
673 if (prev_msg_row == Rows - 1)
674 msg_row--;
676 msg_col = 0;
677 print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE);
678 msg_clr_eos();
681 else if (ex_pressedreturn && !ex_no_reprint) /* must be at EOF */
683 if (curbuf->b_ml.ml_flags & ML_EMPTY)
684 EMSG(_(e_emptybuf));
685 else
686 EMSG(_("E501: At end-of-file"));
690 #ifdef FEAT_GUI
691 --hold_gui_events;
692 #endif
693 --RedrawingDisabled;
694 --no_wait_return;
695 update_screen(CLEAR);
696 need_wait_return = FALSE;
697 msg_scroll = save_msg_scroll;
701 * Execute a simple command line. Used for translated commands like "*".
704 do_cmdline_cmd(cmd)
705 char_u *cmd;
707 return do_cmdline(cmd, NULL, NULL,
708 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
712 * do_cmdline(): execute one Ex command line
714 * 1. Execute "cmdline" when it is not NULL.
715 * If "cmdline" is NULL, or more lines are needed, getline() is used.
716 * 2. Split up in parts separated with '|'.
718 * This function can be called recursively!
720 * flags:
721 * DOCMD_VERBOSE - The command will be included in the error message.
722 * DOCMD_NOWAIT - Don't call wait_return() and friends.
723 * DOCMD_REPEAT - Repeat execution until getline() returns NULL.
724 * DOCMD_KEYTYPED - Don't reset KeyTyped.
725 * DOCMD_EXCRESET - Reset the exception environment (used for debugging).
726 * DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
728 * return FAIL if cmdline could not be executed, OK otherwise
731 do_cmdline(cmdline, getline, cookie, flags)
732 char_u *cmdline;
733 char_u *(*getline) __ARGS((int, void *, int));
734 void *cookie; /* argument for getline() */
735 int flags;
737 char_u *next_cmdline; /* next cmd to execute */
738 char_u *cmdline_copy = NULL; /* copy of cmd line */
739 int used_getline = FALSE; /* used "getline" to obtain command */
740 static int recursive = 0; /* recursive depth */
741 int msg_didout_before_start = 0;
742 int count = 0; /* line number count */
743 int did_inc = FALSE; /* incremented RedrawingDisabled */
744 int retval = OK;
745 #ifdef FEAT_EVAL
746 struct condstack cstack; /* conditional stack */
747 garray_T lines_ga; /* keep lines for ":while"/":for" */
748 int current_line = 0; /* active line in lines_ga */
749 char_u *fname = NULL; /* function or script name */
750 linenr_T *breakpoint = NULL; /* ptr to breakpoint field in cookie */
751 int *dbg_tick = NULL; /* ptr to dbg_tick field in cookie */
752 struct dbg_stuff debug_saved; /* saved things for debug mode */
753 int initial_trylevel;
754 struct msglist **saved_msg_list = NULL;
755 struct msglist *private_msg_list;
757 /* "getline" and "cookie" passed to do_one_cmd() */
758 char_u *(*cmd_getline) __ARGS((int, void *, int));
759 void *cmd_cookie;
760 struct loop_cookie cmd_loop_cookie;
761 void *real_cookie;
762 int getline_is_func;
763 #else
764 # define cmd_getline getline
765 # define cmd_cookie cookie
766 #endif
767 static int call_depth = 0; /* recursiveness */
769 #ifdef FEAT_EVAL
770 /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
771 * location for storing error messages to be converted to an exception.
772 * This ensures that the do_errthrow() call in do_one_cmd() does not
773 * combine the messages stored by an earlier invocation of do_one_cmd()
774 * with the command name of the later one. This would happen when
775 * BufWritePost autocommands are executed after a write error. */
776 saved_msg_list = msg_list;
777 msg_list = &private_msg_list;
778 private_msg_list = NULL;
779 #endif
781 /* It's possible to create an endless loop with ":execute", catch that
782 * here. The value of 200 allows nested function calls, ":source", etc. */
783 if (call_depth == 200)
785 EMSG(_("E169: Command too recursive"));
786 #ifdef FEAT_EVAL
787 /* When converting to an exception, we do not include the command name
788 * since this is not an error of the specific command. */
789 do_errthrow((struct condstack *)NULL, (char_u *)NULL);
790 msg_list = saved_msg_list;
791 #endif
792 return FAIL;
794 ++call_depth;
796 #ifdef FEAT_EVAL
797 cstack.cs_idx = -1;
798 cstack.cs_looplevel = 0;
799 cstack.cs_trylevel = 0;
800 cstack.cs_emsg_silent_list = NULL;
801 cstack.cs_lflags = 0;
802 ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10);
804 real_cookie = getline_cookie(getline, cookie);
806 /* Inside a function use a higher nesting level. */
807 getline_is_func = getline_equal(getline, cookie, get_func_line);
808 if (getline_is_func && ex_nesting_level == func_level(real_cookie))
809 ++ex_nesting_level;
811 /* Get the function or script name and the address where the next breakpoint
812 * line and the debug tick for a function or script are stored. */
813 if (getline_is_func)
815 fname = func_name(real_cookie);
816 breakpoint = func_breakpoint(real_cookie);
817 dbg_tick = func_dbg_tick(real_cookie);
819 else if (getline_equal(getline, cookie, getsourceline))
821 fname = sourcing_name;
822 breakpoint = source_breakpoint(real_cookie);
823 dbg_tick = source_dbg_tick(real_cookie);
827 * Initialize "force_abort" and "suppress_errthrow" at the top level.
829 if (!recursive)
831 force_abort = FALSE;
832 suppress_errthrow = FALSE;
836 * If requested, store and reset the global values controlling the
837 * exception handling (used when debugging). Otherwise clear it to avoid
838 * a bogus compiler warning when the optimizer uses inline functions...
840 if (flags & DOCMD_EXCRESET)
841 save_dbg_stuff(&debug_saved);
842 else
843 memset(&debug_saved, 0, 1);
845 initial_trylevel = trylevel;
848 * "did_throw" will be set to TRUE when an exception is being thrown.
850 did_throw = FALSE;
851 #endif
853 * "did_emsg" will be set to TRUE when emsg() is used, in which case we
854 * cancel the whole command line, and any if/endif or loop.
855 * If force_abort is set, we cancel everything.
857 did_emsg = FALSE;
860 * KeyTyped is only set when calling vgetc(). Reset it here when not
861 * calling vgetc() (sourced command lines).
863 if (!(flags & DOCMD_KEYTYPED) && !getline_equal(getline, cookie, getexline))
864 KeyTyped = FALSE;
867 * Continue executing command lines:
868 * - when inside an ":if", ":while" or ":for"
869 * - for multiple commands on one line, separated with '|'
870 * - when repeating until there are no more lines (for ":source")
872 next_cmdline = cmdline;
875 #ifdef FEAT_EVAL
876 getline_is_func = getline_equal(getline, cookie, get_func_line);
877 #endif
879 /* stop skipping cmds for an error msg after all endif/while/for */
880 if (next_cmdline == NULL
881 #ifdef FEAT_EVAL
882 && !force_abort
883 && cstack.cs_idx < 0
884 && !(getline_is_func && func_has_abort(real_cookie))
885 #endif
887 did_emsg = FALSE;
890 * 1. If repeating a line in a loop, get a line from lines_ga.
891 * 2. If no line given: Get an allocated line with getline().
892 * 3. If a line is given: Make a copy, so we can mess with it.
895 #ifdef FEAT_EVAL
896 /* 1. If repeating, get a previous line from lines_ga. */
897 if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
899 /* Each '|' separated command is stored separately in lines_ga, to
900 * be able to jump to it. Don't use next_cmdline now. */
901 vim_free(cmdline_copy);
902 cmdline_copy = NULL;
904 /* Check if a function has returned or, unless it has an unclosed
905 * try conditional, aborted. */
906 if (getline_is_func)
908 # ifdef FEAT_PROFILE
909 if (do_profiling == PROF_YES)
910 func_line_end(real_cookie);
911 # endif
912 if (func_has_ended(real_cookie))
914 retval = FAIL;
915 break;
918 #ifdef FEAT_PROFILE
919 else if (do_profiling == PROF_YES
920 && getline_equal(getline, cookie, getsourceline))
921 script_line_end();
922 #endif
924 /* Check if a sourced file hit a ":finish" command. */
925 if (source_finished(getline, cookie))
927 retval = FAIL;
928 break;
931 /* If breakpoints have been added/deleted need to check for it. */
932 if (breakpoint != NULL && dbg_tick != NULL
933 && *dbg_tick != debug_tick)
935 *breakpoint = dbg_find_breakpoint(
936 getline_equal(getline, cookie, getsourceline),
937 fname, sourcing_lnum);
938 *dbg_tick = debug_tick;
941 next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
942 sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
944 /* Did we encounter a breakpoint? */
945 if (breakpoint != NULL && *breakpoint != 0
946 && *breakpoint <= sourcing_lnum)
948 dbg_breakpoint(fname, sourcing_lnum);
949 /* Find next breakpoint. */
950 *breakpoint = dbg_find_breakpoint(
951 getline_equal(getline, cookie, getsourceline),
952 fname, sourcing_lnum);
953 *dbg_tick = debug_tick;
955 # ifdef FEAT_PROFILE
956 if (do_profiling == PROF_YES)
958 if (getline_is_func)
959 func_line_start(real_cookie);
960 else if (getline_equal(getline, cookie, getsourceline))
961 script_line_start();
963 # endif
966 if (cstack.cs_looplevel > 0)
968 /* Inside a while/for loop we need to store the lines and use them
969 * again. Pass a different "getline" function to do_one_cmd()
970 * below, so that it stores lines in or reads them from
971 * "lines_ga". Makes it possible to define a function inside a
972 * while/for loop. */
973 cmd_getline = get_loop_line;
974 cmd_cookie = (void *)&cmd_loop_cookie;
975 cmd_loop_cookie.lines_gap = &lines_ga;
976 cmd_loop_cookie.current_line = current_line;
977 cmd_loop_cookie.getline = getline;
978 cmd_loop_cookie.cookie = cookie;
979 cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
981 else
983 cmd_getline = getline;
984 cmd_cookie = cookie;
986 #endif
988 /* 2. If no line given, get an allocated line with getline(). */
989 if (next_cmdline == NULL)
992 * Need to set msg_didout for the first line after an ":if",
993 * otherwise the ":if" will be overwritten.
995 if (count == 1 && getline_equal(getline, cookie, getexline))
996 msg_didout = TRUE;
997 if (getline == NULL || (next_cmdline = getline(':', cookie,
998 #ifdef FEAT_EVAL
999 cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
1000 #else
1002 #endif
1003 )) == NULL)
1005 /* Don't call wait_return for aborted command line. The NULL
1006 * returned for the end of a sourced file or executed function
1007 * doesn't do this. */
1008 if (KeyTyped && !(flags & DOCMD_REPEAT))
1009 need_wait_return = FALSE;
1010 retval = FAIL;
1011 break;
1013 used_getline = TRUE;
1016 * Keep the first typed line. Clear it when more lines are typed.
1018 if (flags & DOCMD_KEEPLINE)
1020 vim_free(repeat_cmdline);
1021 if (count == 0)
1022 repeat_cmdline = vim_strsave(next_cmdline);
1023 else
1024 repeat_cmdline = NULL;
1028 /* 3. Make a copy of the command so we can mess with it. */
1029 else if (cmdline_copy == NULL)
1031 next_cmdline = vim_strsave(next_cmdline);
1032 if (next_cmdline == NULL)
1034 EMSG(_(e_outofmem));
1035 retval = FAIL;
1036 break;
1039 cmdline_copy = next_cmdline;
1041 #ifdef FEAT_EVAL
1043 * Save the current line when inside a ":while" or ":for", and when
1044 * the command looks like a ":while" or ":for", because we may need it
1045 * later. When there is a '|' and another command, it is stored
1046 * separately, because we need to be able to jump back to it from an
1047 * :endwhile/:endfor.
1049 if (current_line == lines_ga.ga_len
1050 && (cstack.cs_looplevel || has_loop_cmd(next_cmdline)))
1052 if (store_loop_line(&lines_ga, next_cmdline) == FAIL)
1054 retval = FAIL;
1055 break;
1058 did_endif = FALSE;
1059 #endif
1061 if (count++ == 0)
1064 * All output from the commands is put below each other, without
1065 * waiting for a return. Don't do this when executing commands
1066 * from a script or when being called recursive (e.g. for ":e
1067 * +command file").
1069 if (!(flags & DOCMD_NOWAIT) && !recursive)
1071 msg_didout_before_start = msg_didout;
1072 msg_didany = FALSE; /* no output yet */
1073 msg_start();
1074 msg_scroll = TRUE; /* put messages below each other */
1075 ++no_wait_return; /* dont wait for return until finished */
1076 ++RedrawingDisabled;
1077 did_inc = TRUE;
1081 if (p_verbose >= 15 && sourcing_name != NULL)
1083 ++no_wait_return;
1084 verbose_enter_scroll();
1086 smsg((char_u *)_("line %ld: %s"),
1087 (long)sourcing_lnum, cmdline_copy);
1088 if (msg_silent == 0)
1089 msg_puts((char_u *)"\n"); /* don't overwrite this */
1091 verbose_leave_scroll();
1092 --no_wait_return;
1096 * 2. Execute one '|' separated command.
1097 * do_one_cmd() will return NULL if there is no trailing '|'.
1098 * "cmdline_copy" can change, e.g. for '%' and '#' expansion.
1100 ++recursive;
1101 next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE,
1102 #ifdef FEAT_EVAL
1103 &cstack,
1104 #endif
1105 cmd_getline, cmd_cookie);
1106 --recursive;
1108 #ifdef FEAT_EVAL
1109 if (cmd_cookie == (void *)&cmd_loop_cookie)
1110 /* Use "current_line" from "cmd_loop_cookie", it may have been
1111 * incremented when defining a function. */
1112 current_line = cmd_loop_cookie.current_line;
1113 #endif
1115 if (next_cmdline == NULL)
1117 vim_free(cmdline_copy);
1118 cmdline_copy = NULL;
1119 #ifdef FEAT_CMDHIST
1121 * If the command was typed, remember it for the ':' register.
1122 * Do this AFTER executing the command to make :@: work.
1124 if (getline_equal(getline, cookie, getexline)
1125 && new_last_cmdline != NULL)
1127 vim_free(last_cmdline);
1128 last_cmdline = new_last_cmdline;
1129 new_last_cmdline = NULL;
1131 #endif
1133 else
1135 /* need to copy the command after the '|' to cmdline_copy, for the
1136 * next do_one_cmd() */
1137 STRMOVE(cmdline_copy, next_cmdline);
1138 next_cmdline = cmdline_copy;
1142 #ifdef FEAT_EVAL
1143 /* reset did_emsg for a function that is not aborted by an error */
1144 if (did_emsg && !force_abort
1145 && getline_equal(getline, cookie, get_func_line)
1146 && !func_has_abort(real_cookie))
1147 did_emsg = FALSE;
1149 if (cstack.cs_looplevel > 0)
1151 ++current_line;
1154 * An ":endwhile", ":endfor" and ":continue" is handled here.
1155 * If we were executing commands, jump back to the ":while" or
1156 * ":for".
1157 * If we were not executing commands, decrement cs_looplevel.
1159 if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
1161 cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
1163 /* Jump back to the matching ":while" or ":for". Be careful
1164 * not to use a cs_line[] from an entry that isn't a ":while"
1165 * or ":for": It would make "current_line" invalid and can
1166 * cause a crash. */
1167 if (!did_emsg && !got_int && !did_throw
1168 && cstack.cs_idx >= 0
1169 && (cstack.cs_flags[cstack.cs_idx]
1170 & (CSF_WHILE | CSF_FOR))
1171 && cstack.cs_line[cstack.cs_idx] >= 0
1172 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
1174 current_line = cstack.cs_line[cstack.cs_idx];
1175 /* remember we jumped there */
1176 cstack.cs_lflags |= CSL_HAD_LOOP;
1177 line_breakcheck(); /* check if CTRL-C typed */
1179 /* Check for the next breakpoint at or after the ":while"
1180 * or ":for". */
1181 if (breakpoint != NULL)
1183 *breakpoint = dbg_find_breakpoint(
1184 getline_equal(getline, cookie, getsourceline),
1185 fname,
1186 ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
1187 *dbg_tick = debug_tick;
1190 else
1192 /* can only get here with ":endwhile" or ":endfor" */
1193 if (cstack.cs_idx >= 0)
1194 rewind_conditionals(&cstack, cstack.cs_idx - 1,
1195 CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
1200 * For a ":while" or ":for" we need to remember the line number.
1202 else if (cstack.cs_lflags & CSL_HAD_LOOP)
1204 cstack.cs_lflags &= ~CSL_HAD_LOOP;
1205 cstack.cs_line[cstack.cs_idx] = current_line - 1;
1210 * When not inside any ":while" loop, clear remembered lines.
1212 if (cstack.cs_looplevel == 0)
1214 if (lines_ga.ga_len > 0)
1216 sourcing_lnum =
1217 ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
1218 free_cmdlines(&lines_ga);
1220 current_line = 0;
1224 * A ":finally" makes did_emsg, got_int, and did_throw pending for
1225 * being restored at the ":endtry". Reset them here and set the
1226 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
1227 * This includes the case where a missing ":endif", ":endwhile" or
1228 * ":endfor" was detected by the ":finally" itself.
1230 if (cstack.cs_lflags & CSL_HAD_FINA)
1232 cstack.cs_lflags &= ~CSL_HAD_FINA;
1233 report_make_pending(cstack.cs_pending[cstack.cs_idx]
1234 & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
1235 did_throw ? (void *)current_exception : NULL);
1236 did_emsg = got_int = did_throw = FALSE;
1237 cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
1240 /* Update global "trylevel" for recursive calls to do_cmdline() from
1241 * within this loop. */
1242 trylevel = initial_trylevel + cstack.cs_trylevel;
1245 * If the outermost try conditional (across function calls and sourced
1246 * files) is aborted because of an error, an interrupt, or an uncaught
1247 * exception, cancel everything. If it is left normally, reset
1248 * force_abort to get the non-EH compatible abortion behavior for
1249 * the rest of the script.
1251 if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
1252 force_abort = FALSE;
1254 /* Convert an interrupt to an exception if appropriate. */
1255 (void)do_intthrow(&cstack);
1256 #endif /* FEAT_EVAL */
1260 * Continue executing command lines when:
1261 * - no CTRL-C typed, no aborting error, no exception thrown or try
1262 * conditionals need to be checked for executing finally clauses or
1263 * catching an interrupt exception
1264 * - didn't get an error message or lines are not typed
1265 * - there is a command after '|', inside a :if, :while, :for or :try, or
1266 * looping for ":source" command or function call.
1268 while (!((got_int
1269 #ifdef FEAT_EVAL
1270 || (did_emsg && force_abort) || did_throw
1271 #endif
1273 #ifdef FEAT_EVAL
1274 && cstack.cs_trylevel == 0
1275 #endif
1277 && !(did_emsg && used_getline
1278 && (getline_equal(getline, cookie, getexmodeline)
1279 || getline_equal(getline, cookie, getexline)))
1280 && (next_cmdline != NULL
1281 #ifdef FEAT_EVAL
1282 || cstack.cs_idx >= 0
1283 #endif
1284 || (flags & DOCMD_REPEAT)));
1286 vim_free(cmdline_copy);
1287 #ifdef FEAT_EVAL
1288 free_cmdlines(&lines_ga);
1289 ga_clear(&lines_ga);
1291 if (cstack.cs_idx >= 0)
1294 * If a sourced file or executed function ran to its end, report the
1295 * unclosed conditional.
1297 if (!got_int && !did_throw
1298 && ((getline_equal(getline, cookie, getsourceline)
1299 && !source_finished(getline, cookie))
1300 || (getline_equal(getline, cookie, get_func_line)
1301 && !func_has_ended(real_cookie))))
1303 if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
1304 EMSG(_(e_endtry));
1305 else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
1306 EMSG(_(e_endwhile));
1307 else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
1308 EMSG(_(e_endfor));
1309 else
1310 EMSG(_(e_endif));
1314 * Reset "trylevel" in case of a ":finish" or ":return" or a missing
1315 * ":endtry" in a sourced file or executed function. If the try
1316 * conditional is in its finally clause, ignore anything pending.
1317 * If it is in a catch clause, finish the caught exception.
1318 * Also cleanup any "cs_forinfo" structures.
1322 int idx = cleanup_conditionals(&cstack, 0, TRUE);
1324 if (idx >= 0)
1325 --idx; /* remove try block not in its finally clause */
1326 rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
1327 &cstack.cs_looplevel);
1329 while (cstack.cs_idx >= 0);
1330 trylevel = initial_trylevel;
1333 /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
1334 * lack was reported above and the error message is to be converted to an
1335 * exception, do this now after rewinding the cstack. */
1336 do_errthrow(&cstack, getline_equal(getline, cookie, get_func_line)
1337 ? (char_u *)"endfunction" : (char_u *)NULL);
1339 if (trylevel == 0)
1342 * When an exception is being thrown out of the outermost try
1343 * conditional, discard the uncaught exception, disable the conversion
1344 * of interrupts or errors to exceptions, and ensure that no more
1345 * commands are executed.
1347 if (did_throw)
1349 void *p = NULL;
1350 char_u *saved_sourcing_name;
1351 int saved_sourcing_lnum;
1352 struct msglist *messages = NULL, *next;
1355 * If the uncaught exception is a user exception, report it as an
1356 * error. If it is an error exception, display the saved error
1357 * message now. For an interrupt exception, do nothing; the
1358 * interrupt message is given elsewhere.
1360 switch (current_exception->type)
1362 case ET_USER:
1363 vim_snprintf((char *)IObuff, IOSIZE,
1364 _("E605: Exception not caught: %s"),
1365 current_exception->value);
1366 p = vim_strsave(IObuff);
1367 break;
1368 case ET_ERROR:
1369 messages = current_exception->messages;
1370 current_exception->messages = NULL;
1371 break;
1372 case ET_INTERRUPT:
1373 break;
1374 default:
1375 p = vim_strsave((char_u *)_(e_internal));
1378 saved_sourcing_name = sourcing_name;
1379 saved_sourcing_lnum = sourcing_lnum;
1380 sourcing_name = current_exception->throw_name;
1381 sourcing_lnum = current_exception->throw_lnum;
1382 current_exception->throw_name = NULL;
1384 discard_current_exception(); /* uses IObuff if 'verbose' */
1385 suppress_errthrow = TRUE;
1386 force_abort = TRUE;
1388 if (messages != NULL)
1392 next = messages->next;
1393 emsg(messages->msg);
1394 vim_free(messages->msg);
1395 vim_free(messages);
1396 messages = next;
1398 while (messages != NULL);
1400 else if (p != NULL)
1402 emsg(p);
1403 vim_free(p);
1405 vim_free(sourcing_name);
1406 sourcing_name = saved_sourcing_name;
1407 sourcing_lnum = saved_sourcing_lnum;
1411 * On an interrupt or an aborting error not converted to an exception,
1412 * disable the conversion of errors to exceptions. (Interrupts are not
1413 * converted any more, here.) This enables also the interrupt message
1414 * when force_abort is set and did_emsg unset in case of an interrupt
1415 * from a finally clause after an error.
1417 else if (got_int || (did_emsg && force_abort))
1418 suppress_errthrow = TRUE;
1422 * The current cstack will be freed when do_cmdline() returns. An uncaught
1423 * exception will have to be rethrown in the previous cstack. If a function
1424 * has just returned or a script file was just finished and the previous
1425 * cstack belongs to the same function or, respectively, script file, it
1426 * will have to be checked for finally clauses to be executed due to the
1427 * ":return" or ":finish". This is done in do_one_cmd().
1429 if (did_throw)
1430 need_rethrow = TRUE;
1431 if ((getline_equal(getline, cookie, getsourceline)
1432 && ex_nesting_level > source_level(real_cookie))
1433 || (getline_equal(getline, cookie, get_func_line)
1434 && ex_nesting_level > func_level(real_cookie) + 1))
1436 if (!did_throw)
1437 check_cstack = TRUE;
1439 else
1441 /* When leaving a function, reduce nesting level. */
1442 if (getline_equal(getline, cookie, get_func_line))
1443 --ex_nesting_level;
1445 * Go to debug mode when returning from a function in which we are
1446 * single-stepping.
1448 if ((getline_equal(getline, cookie, getsourceline)
1449 || getline_equal(getline, cookie, get_func_line))
1450 && ex_nesting_level + 1 <= debug_break_level)
1451 do_debug(getline_equal(getline, cookie, getsourceline)
1452 ? (char_u *)_("End of sourced file")
1453 : (char_u *)_("End of function"));
1457 * Restore the exception environment (done after returning from the
1458 * debugger).
1460 if (flags & DOCMD_EXCRESET)
1461 restore_dbg_stuff(&debug_saved);
1463 msg_list = saved_msg_list;
1464 #endif /* FEAT_EVAL */
1467 * If there was too much output to fit on the command line, ask the user to
1468 * hit return before redrawing the screen. With the ":global" command we do
1469 * this only once after the command is finished.
1471 if (did_inc)
1473 --RedrawingDisabled;
1474 --no_wait_return;
1475 msg_scroll = FALSE;
1478 * When just finished an ":if"-":else" which was typed, no need to
1479 * wait for hit-return. Also for an error situation.
1481 if (retval == FAIL
1482 #ifdef FEAT_EVAL
1483 || (did_endif && KeyTyped && !did_emsg)
1484 #endif
1487 need_wait_return = FALSE;
1488 msg_didany = FALSE; /* don't wait when restarting edit */
1490 else if (need_wait_return)
1493 * The msg_start() above clears msg_didout. The wait_return we do
1494 * here should not overwrite the command that may be shown before
1495 * doing that.
1497 msg_didout |= msg_didout_before_start;
1498 wait_return(FALSE);
1502 #ifndef FEAT_EVAL
1504 * Reset if_level, in case a sourced script file contains more ":if" than
1505 * ":endif" (could be ":if x | foo | endif").
1507 if_level = 0;
1508 #endif
1510 --call_depth;
1511 return retval;
1514 #ifdef FEAT_EVAL
1516 * Obtain a line when inside a ":while" or ":for" loop.
1518 static char_u *
1519 get_loop_line(c, cookie, indent)
1520 int c;
1521 void *cookie;
1522 int indent;
1524 struct loop_cookie *cp = (struct loop_cookie *)cookie;
1525 wcmd_T *wp;
1526 char_u *line;
1528 if (cp->current_line + 1 >= cp->lines_gap->ga_len)
1530 if (cp->repeating)
1531 return NULL; /* trying to read past ":endwhile"/":endfor" */
1533 /* First time inside the ":while"/":for": get line normally. */
1534 if (cp->getline == NULL)
1535 line = getcmdline(c, 0L, indent);
1536 else
1537 line = cp->getline(c, cp->cookie, indent);
1538 if (line != NULL && store_loop_line(cp->lines_gap, line) == OK)
1539 ++cp->current_line;
1541 return line;
1544 KeyTyped = FALSE;
1545 ++cp->current_line;
1546 wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
1547 sourcing_lnum = wp->lnum;
1548 return vim_strsave(wp->line);
1552 * Store a line in "gap" so that a ":while" loop can execute it again.
1554 static int
1555 store_loop_line(gap, line)
1556 garray_T *gap;
1557 char_u *line;
1559 if (ga_grow(gap, 1) == FAIL)
1560 return FAIL;
1561 ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line);
1562 ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum;
1563 ++gap->ga_len;
1564 return OK;
1568 * Free the lines stored for a ":while" or ":for" loop.
1570 static void
1571 free_cmdlines(gap)
1572 garray_T *gap;
1574 while (gap->ga_len > 0)
1576 vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line);
1577 --gap->ga_len;
1580 #endif
1583 * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals
1584 * "func". * Otherwise return TRUE when "fgetline" equals "func".
1586 /*ARGSUSED*/
1588 getline_equal(fgetline, cookie, func)
1589 char_u *(*fgetline) __ARGS((int, void *, int));
1590 void *cookie; /* argument for fgetline() */
1591 char_u *(*func) __ARGS((int, void *, int));
1593 #ifdef FEAT_EVAL
1594 char_u *(*gp) __ARGS((int, void *, int));
1595 struct loop_cookie *cp;
1597 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1598 * function that's originally used to obtain the lines. This may be
1599 * nested several levels. */
1600 gp = fgetline;
1601 cp = (struct loop_cookie *)cookie;
1602 while (gp == get_loop_line)
1604 gp = cp->getline;
1605 cp = cp->cookie;
1607 return gp == func;
1608 #else
1609 return fgetline == func;
1610 #endif
1613 #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO)
1615 * If "fgetline" is get_loop_line(), return the cookie used by the original
1616 * getline function. Otherwise return "cookie".
1618 /*ARGSUSED*/
1619 void *
1620 getline_cookie(fgetline, cookie)
1621 char_u *(*fgetline) __ARGS((int, void *, int));
1622 void *cookie; /* argument for fgetline() */
1624 # ifdef FEAT_EVAL
1625 char_u *(*gp) __ARGS((int, void *, int));
1626 struct loop_cookie *cp;
1628 /* When "fgetline" is "get_loop_line()" use the "cookie" to find the
1629 * cookie that's originally used to obtain the lines. This may be nested
1630 * several levels. */
1631 gp = fgetline;
1632 cp = (struct loop_cookie *)cookie;
1633 while (gp == get_loop_line)
1635 gp = cp->getline;
1636 cp = cp->cookie;
1638 return cp;
1639 # else
1640 return cookie;
1641 # endif
1643 #endif
1646 * Execute one Ex command.
1648 * If 'sourcing' is TRUE, the command will be included in the error message.
1650 * 1. skip comment lines and leading space
1651 * 2. handle command modifiers
1652 * 3. parse range
1653 * 4. parse command
1654 * 5. parse arguments
1655 * 6. switch on command name
1657 * Note: "fgetline" can be NULL.
1659 * This function may be called recursively!
1661 #if (_MSC_VER == 1200)
1663 * Avoid optimisation bug in VC++ version 6.0
1665 #pragma optimize( "g", off )
1666 #endif
1667 static char_u *
1668 do_one_cmd(cmdlinep, sourcing,
1669 #ifdef FEAT_EVAL
1670 cstack,
1671 #endif
1672 fgetline, cookie)
1673 char_u **cmdlinep;
1674 int sourcing;
1675 #ifdef FEAT_EVAL
1676 struct condstack *cstack;
1677 #endif
1678 char_u *(*fgetline) __ARGS((int, void *, int));
1679 void *cookie; /* argument for fgetline() */
1681 char_u *p;
1682 linenr_T lnum;
1683 long n;
1684 char_u *errormsg = NULL; /* error message */
1685 exarg_T ea; /* Ex command arguments */
1686 long verbose_save = -1;
1687 int save_msg_scroll = 0;
1688 int did_silent = 0;
1689 int did_esilent = 0;
1690 #ifdef HAVE_SANDBOX
1691 int did_sandbox = FALSE;
1692 #endif
1693 cmdmod_T save_cmdmod;
1694 int ni; /* set when Not Implemented */
1696 vim_memset(&ea, 0, sizeof(ea));
1697 ea.line1 = 1;
1698 ea.line2 = 1;
1699 #ifdef FEAT_EVAL
1700 ++ex_nesting_level;
1701 #endif
1703 /* when not editing the last file :q has to be typed twice */
1704 if (quitmore
1705 #ifdef FEAT_EVAL
1706 /* avoid that a function call in 'statusline' does this */
1707 && !getline_equal(fgetline, cookie, get_func_line)
1708 #endif
1710 --quitmore;
1713 * Reset browse, confirm, etc.. They are restored when returning, for
1714 * recursive calls.
1716 save_cmdmod = cmdmod;
1717 vim_memset(&cmdmod, 0, sizeof(cmdmod));
1719 /* "#!anything" is handled like a comment. */
1720 if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!')
1721 goto doend;
1724 * Repeat until no more command modifiers are found.
1726 ea.cmd = *cmdlinep;
1727 for (;;)
1730 * 1. skip comment lines and leading white space and colons
1732 while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':')
1733 ++ea.cmd;
1735 /* in ex mode, an empty line works like :+ */
1736 if (*ea.cmd == NUL && exmode_active
1737 && (getline_equal(fgetline, cookie, getexmodeline)
1738 || getline_equal(fgetline, cookie, getexline))
1739 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1741 ea.cmd = (char_u *)"+";
1742 ex_pressedreturn = TRUE;
1745 /* ignore comment and empty lines */
1746 if (*ea.cmd == '"')
1747 goto doend;
1748 if (*ea.cmd == NUL)
1750 ex_pressedreturn = TRUE;
1751 goto doend;
1755 * 2. handle command modifiers.
1757 p = ea.cmd;
1758 if (VIM_ISDIGIT(*ea.cmd))
1759 p = skipwhite(skipdigits(ea.cmd));
1760 switch (*p)
1762 /* When adding an entry, also modify cmd_exists(). */
1763 case 'a': if (!checkforcmd(&ea.cmd, "aboveleft", 3))
1764 break;
1765 #ifdef FEAT_WINDOWS
1766 cmdmod.split |= WSP_ABOVE;
1767 #endif
1768 continue;
1770 case 'b': if (checkforcmd(&ea.cmd, "belowright", 3))
1772 #ifdef FEAT_WINDOWS
1773 cmdmod.split |= WSP_BELOW;
1774 #endif
1775 continue;
1777 if (checkforcmd(&ea.cmd, "browse", 3))
1779 #ifdef FEAT_BROWSE
1780 cmdmod.browse = TRUE;
1781 #endif
1782 continue;
1784 if (!checkforcmd(&ea.cmd, "botright", 2))
1785 break;
1786 #ifdef FEAT_WINDOWS
1787 cmdmod.split |= WSP_BOT;
1788 #endif
1789 continue;
1791 case 'c': if (!checkforcmd(&ea.cmd, "confirm", 4))
1792 break;
1793 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1794 cmdmod.confirm = TRUE;
1795 #endif
1796 continue;
1798 case 'k': if (checkforcmd(&ea.cmd, "keepmarks", 3))
1800 cmdmod.keepmarks = TRUE;
1801 continue;
1803 if (checkforcmd(&ea.cmd, "keepalt", 5))
1805 cmdmod.keepalt = TRUE;
1806 continue;
1808 if (!checkforcmd(&ea.cmd, "keepjumps", 5))
1809 break;
1810 cmdmod.keepjumps = TRUE;
1811 continue;
1813 /* ":hide" and ":hide | cmd" are not modifiers */
1814 case 'h': if (p != ea.cmd || !checkforcmd(&p, "hide", 3)
1815 || *p == NUL || ends_excmd(*p))
1816 break;
1817 ea.cmd = p;
1818 cmdmod.hide = TRUE;
1819 continue;
1821 case 'l': if (checkforcmd(&ea.cmd, "lockmarks", 3))
1823 cmdmod.lockmarks = TRUE;
1824 continue;
1827 if (!checkforcmd(&ea.cmd, "leftabove", 5))
1828 break;
1829 #ifdef FEAT_WINDOWS
1830 cmdmod.split |= WSP_ABOVE;
1831 #endif
1832 continue;
1834 case 'n': if (!checkforcmd(&ea.cmd, "noautocmd", 3))
1835 break;
1836 #ifdef FEAT_AUTOCMD
1837 if (cmdmod.save_ei == NULL)
1839 /* Set 'eventignore' to "all". Restore the
1840 * existing option value later. */
1841 cmdmod.save_ei = vim_strsave(p_ei);
1842 set_string_option_direct((char_u *)"ei", -1,
1843 (char_u *)"all", OPT_FREE, SID_NONE);
1845 #endif
1846 continue;
1848 case 'r': if (!checkforcmd(&ea.cmd, "rightbelow", 6))
1849 break;
1850 #ifdef FEAT_WINDOWS
1851 cmdmod.split |= WSP_BELOW;
1852 #endif
1853 continue;
1855 case 's': if (checkforcmd(&ea.cmd, "sandbox", 3))
1857 #ifdef HAVE_SANDBOX
1858 if (!did_sandbox)
1859 ++sandbox;
1860 did_sandbox = TRUE;
1861 #endif
1862 continue;
1864 if (!checkforcmd(&ea.cmd, "silent", 3))
1865 break;
1866 ++did_silent;
1867 ++msg_silent;
1868 save_msg_scroll = msg_scroll;
1869 if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1]))
1871 /* ":silent!", but not "silent !cmd" */
1872 ea.cmd = skipwhite(ea.cmd + 1);
1873 ++emsg_silent;
1874 ++did_esilent;
1876 continue;
1878 case 't': if (checkforcmd(&p, "tab", 3))
1880 #ifdef FEAT_WINDOWS
1881 if (vim_isdigit(*ea.cmd))
1882 cmdmod.tab = atoi((char *)ea.cmd) + 1;
1883 else
1884 cmdmod.tab = tabpage_index(curtab) + 1;
1885 ea.cmd = p;
1886 #endif
1887 continue;
1889 if (!checkforcmd(&ea.cmd, "topleft", 2))
1890 break;
1891 #ifdef FEAT_WINDOWS
1892 cmdmod.split |= WSP_TOP;
1893 #endif
1894 continue;
1896 case 'v': if (checkforcmd(&ea.cmd, "vertical", 4))
1898 #ifdef FEAT_VERTSPLIT
1899 cmdmod.split |= WSP_VERT;
1900 #endif
1901 continue;
1903 if (!checkforcmd(&p, "verbose", 4))
1904 break;
1905 if (verbose_save < 0)
1906 verbose_save = p_verbose;
1907 if (vim_isdigit(*ea.cmd))
1908 p_verbose = atoi((char *)ea.cmd);
1909 else
1910 p_verbose = 1;
1911 ea.cmd = p;
1912 continue;
1914 break;
1917 #ifdef FEAT_EVAL
1918 ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0
1919 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE));
1920 #else
1921 ea.skip = (if_level > 0);
1922 #endif
1924 #ifdef FEAT_EVAL
1925 # ifdef FEAT_PROFILE
1926 /* Count this line for profiling if ea.skip is FALSE. */
1927 if (do_profiling == PROF_YES && !ea.skip)
1929 if (getline_equal(fgetline, cookie, get_func_line))
1930 func_line_exec(getline_cookie(fgetline, cookie));
1931 else if (getline_equal(fgetline, cookie, getsourceline))
1932 script_line_exec();
1934 #endif
1936 /* May go to debug mode. If this happens and the ">quit" debug command is
1937 * used, throw an interrupt exception and skip the next command. */
1938 dbg_check_breakpoint(&ea);
1939 if (!ea.skip && got_int)
1941 ea.skip = TRUE;
1942 (void)do_intthrow(cstack);
1944 #endif
1947 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
1949 * where 'addr' is:
1951 * % (entire file)
1952 * $ [+-NUM]
1953 * 'x [+-NUM] (where x denotes a currently defined mark)
1954 * . [+-NUM]
1955 * [+-NUM]..
1956 * NUM
1958 * The ea.cmd pointer is updated to point to the first character following the
1959 * range spec. If an initial address is found, but no second, the upper bound
1960 * is equal to the lower.
1963 /* repeat for all ',' or ';' separated addresses */
1964 for (;;)
1966 ea.line1 = ea.line2;
1967 ea.line2 = curwin->w_cursor.lnum; /* default is current line number */
1968 ea.cmd = skipwhite(ea.cmd);
1969 lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0);
1970 if (ea.cmd == NULL) /* error detected */
1971 goto doend;
1972 if (lnum == MAXLNUM)
1974 if (*ea.cmd == '%') /* '%' - all lines */
1976 ++ea.cmd;
1977 ea.line1 = 1;
1978 ea.line2 = curbuf->b_ml.ml_line_count;
1979 ++ea.addr_count;
1981 /* '*' - visual area */
1982 else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL)
1984 pos_T *fp;
1986 ++ea.cmd;
1987 if (!ea.skip)
1989 fp = getmark('<', FALSE);
1990 if (check_mark(fp) == FAIL)
1991 goto doend;
1992 ea.line1 = fp->lnum;
1993 fp = getmark('>', FALSE);
1994 if (check_mark(fp) == FAIL)
1995 goto doend;
1996 ea.line2 = fp->lnum;
1997 ++ea.addr_count;
2001 else
2002 ea.line2 = lnum;
2003 ea.addr_count++;
2005 if (*ea.cmd == ';')
2007 if (!ea.skip)
2008 curwin->w_cursor.lnum = ea.line2;
2010 else if (*ea.cmd != ',')
2011 break;
2012 ++ea.cmd;
2015 /* One address given: set start and end lines */
2016 if (ea.addr_count == 1)
2018 ea.line1 = ea.line2;
2019 /* ... but only implicit: really no address given */
2020 if (lnum == MAXLNUM)
2021 ea.addr_count = 0;
2024 /* Don't leave the cursor on an illegal line (caused by ';') */
2025 check_cursor_lnum();
2028 * 4. parse command
2032 * Skip ':' and any white space
2034 ea.cmd = skipwhite(ea.cmd);
2035 while (*ea.cmd == ':')
2036 ea.cmd = skipwhite(ea.cmd + 1);
2039 * If we got a line, but no command, then go to the line.
2040 * If we find a '|' or '\n' we set ea.nextcmd.
2042 if (*ea.cmd == NUL || *ea.cmd == '"' ||
2043 (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL)
2046 * strange vi behaviour:
2047 * ":3" jumps to line 3
2048 * ":3|..." prints line 3
2049 * ":|" prints current line
2051 if (ea.skip) /* skip this if inside :if */
2052 goto doend;
2053 if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2))
2055 ea.cmdidx = CMD_print;
2056 ea.argt = RANGE+COUNT+TRLBAR;
2057 if ((errormsg = invalid_range(&ea)) == NULL)
2059 correct_range(&ea);
2060 ex_print(&ea);
2063 else if (ea.addr_count != 0)
2065 if (ea.line2 > curbuf->b_ml.ml_line_count)
2067 /* With '-' in 'cpoptions' a line number past the file is an
2068 * error, otherwise put it at the end of the file. */
2069 if (vim_strchr(p_cpo, CPO_MINUS) != NULL)
2070 ea.line2 = -1;
2071 else
2072 ea.line2 = curbuf->b_ml.ml_line_count;
2075 if (ea.line2 < 0)
2076 errormsg = (char_u *)_(e_invrange);
2077 else
2079 if (ea.line2 == 0)
2080 curwin->w_cursor.lnum = 1;
2081 else
2082 curwin->w_cursor.lnum = ea.line2;
2083 beginline(BL_SOL | BL_FIX);
2086 goto doend;
2089 /* Find the command and let "p" point to after it. */
2090 p = find_command(&ea, NULL);
2092 #ifdef FEAT_USR_CMDS
2093 if (p == NULL)
2095 if (!ea.skip)
2096 errormsg = (char_u *)_("E464: Ambiguous use of user-defined command");
2097 goto doend;
2099 /* Check for wrong commands. */
2100 if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78)
2102 errormsg = uc_fun_cmd();
2103 goto doend;
2105 #endif
2106 if (ea.cmdidx == CMD_SIZE)
2108 if (!ea.skip)
2110 STRCPY(IObuff, _("E492: Not an editor command"));
2111 if (!sourcing)
2113 STRCAT(IObuff, ": ");
2114 STRNCAT(IObuff, *cmdlinep, 40);
2116 errormsg = IObuff;
2118 goto doend;
2121 ni = (
2122 #ifdef FEAT_USR_CMDS
2123 !USER_CMDIDX(ea.cmdidx) &&
2124 #endif
2125 (cmdnames[ea.cmdidx].cmd_func == ex_ni
2126 #ifdef HAVE_EX_SCRIPT_NI
2127 || cmdnames[ea.cmdidx].cmd_func == ex_script_ni
2128 #endif
2131 #ifndef FEAT_EVAL
2133 * When the expression evaluation is disabled, recognize the ":if" and
2134 * ":endif" commands and ignore everything in between it.
2136 if (ea.cmdidx == CMD_if)
2137 ++if_level;
2138 if (if_level)
2140 if (ea.cmdidx == CMD_endif)
2141 --if_level;
2142 goto doend;
2145 #endif
2147 /* forced commands */
2148 if (*p == '!' && ea.cmdidx != CMD_substitute
2149 && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic)
2151 ++p;
2152 ea.forceit = TRUE;
2154 else
2155 ea.forceit = FALSE;
2158 * 5. parse arguments
2160 #ifdef FEAT_USR_CMDS
2161 if (!USER_CMDIDX(ea.cmdidx))
2162 #endif
2163 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
2165 if (!ea.skip)
2167 #ifdef HAVE_SANDBOX
2168 if (sandbox != 0 && !(ea.argt & SBOXOK))
2170 /* Command not allowed in sandbox. */
2171 errormsg = (char_u *)_(e_sandbox);
2172 goto doend;
2174 #endif
2175 if (!curbuf->b_p_ma && (ea.argt & MODIFY))
2177 /* Command not allowed in non-'modifiable' buffer */
2178 errormsg = (char_u *)_(e_modifiable);
2179 goto doend;
2182 if (text_locked() && !(ea.argt & CMDWIN)
2183 # ifdef FEAT_USR_CMDS
2184 && !USER_CMDIDX(ea.cmdidx)
2185 # endif
2188 /* Command not allowed when editing the command line. */
2189 #ifdef FEAT_CMDWIN
2190 if (cmdwin_type != 0)
2191 errormsg = (char_u *)_(e_cmdwin);
2192 else
2193 #endif
2194 errormsg = (char_u *)_(e_secure);
2195 goto doend;
2197 #ifdef FEAT_AUTOCMD
2198 /* Disallow editing another buffer when "curbuf_lock" is set.
2199 * Do allow ":edit" (check for argument later).
2200 * Do allow ":checktime" (it's postponed). */
2201 if (!(ea.argt & CMDWIN)
2202 && ea.cmdidx != CMD_edit
2203 && ea.cmdidx != CMD_checktime
2204 # ifdef FEAT_USR_CMDS
2205 && !USER_CMDIDX(ea.cmdidx)
2206 # endif
2207 && curbuf_locked())
2208 goto doend;
2209 #endif
2211 if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0)
2213 /* no range allowed */
2214 errormsg = (char_u *)_(e_norange);
2215 goto doend;
2219 if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */
2221 errormsg = (char_u *)_(e_nobang);
2222 goto doend;
2226 * Don't complain about the range if it is not used
2227 * (could happen if line_count is accidentally set to 0).
2229 if (!ea.skip && !ni)
2232 * If the range is backwards, ask for confirmation and, if given, swap
2233 * ea.line1 & ea.line2 so it's forwards again.
2234 * When global command is busy, don't ask, will fail below.
2236 if (!global_busy && ea.line1 > ea.line2)
2238 if (msg_silent == 0)
2240 if (sourcing || exmode_active)
2242 errormsg = (char_u *)_("E493: Backwards range given");
2243 goto doend;
2245 if (ask_yesno((char_u *)
2246 _("Backwards range given, OK to swap"), FALSE) != 'y')
2247 goto doend;
2249 lnum = ea.line1;
2250 ea.line1 = ea.line2;
2251 ea.line2 = lnum;
2253 if ((errormsg = invalid_range(&ea)) != NULL)
2254 goto doend;
2257 if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */
2258 ea.line2 = 1;
2260 correct_range(&ea);
2262 #ifdef FEAT_FOLDING
2263 if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy)
2265 /* Put the first line at the start of a closed fold, put the last line
2266 * at the end of a closed fold. */
2267 (void)hasFolding(ea.line1, &ea.line1, NULL);
2268 (void)hasFolding(ea.line2, NULL, &ea.line2);
2270 #endif
2272 #ifdef FEAT_QUICKFIX
2274 * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2275 * option here, so things like % get expanded.
2277 p = replace_makeprg(&ea, p, cmdlinep);
2278 if (p == NULL)
2279 goto doend;
2280 #endif
2283 * Skip to start of argument.
2284 * Don't do this for the ":!" command, because ":!! -l" needs the space.
2286 if (ea.cmdidx == CMD_bang)
2287 ea.arg = p;
2288 else
2289 ea.arg = skipwhite(p);
2292 * Check for "++opt=val" argument.
2293 * Must be first, allow ":w ++enc=utf8 !cmd"
2295 if (ea.argt & ARGOPT)
2296 while (ea.arg[0] == '+' && ea.arg[1] == '+')
2297 if (getargopt(&ea) == FAIL && !ni)
2299 errormsg = (char_u *)_(e_invarg);
2300 goto doend;
2303 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
2305 if (*ea.arg == '>') /* append */
2307 if (*++ea.arg != '>') /* typed wrong */
2309 errormsg = (char_u *)_("E494: Use w or w>>");
2310 goto doend;
2312 ea.arg = skipwhite(ea.arg + 1);
2313 ea.append = TRUE;
2315 else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
2317 ++ea.arg;
2318 ea.usefilter = TRUE;
2322 if (ea.cmdidx == CMD_read)
2324 if (ea.forceit)
2326 ea.usefilter = TRUE; /* :r! filter if ea.forceit */
2327 ea.forceit = FALSE;
2329 else if (*ea.arg == '!') /* :r !filter */
2331 ++ea.arg;
2332 ea.usefilter = TRUE;
2336 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
2338 ea.amount = 1;
2339 while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */
2341 ++ea.arg;
2342 ++ea.amount;
2344 ea.arg = skipwhite(ea.arg);
2348 * Check for "+command" argument, before checking for next command.
2349 * Don't do this for ":read !cmd" and ":write !cmd".
2351 if ((ea.argt & EDITCMD) && !ea.usefilter)
2352 ea.do_ecmd_cmd = getargcmd(&ea.arg);
2355 * Check for '|' to separate commands and '"' to start comments.
2356 * Don't do this for ":read !cmd" and ":write !cmd".
2358 if ((ea.argt & TRLBAR) && !ea.usefilter)
2359 separate_nextcmd(&ea);
2362 * Check for <newline> to end a shell command.
2363 * Also do this for ":read !cmd", ":write !cmd" and ":global".
2364 * Any others?
2366 else if (ea.cmdidx == CMD_bang
2367 || ea.cmdidx == CMD_global
2368 || ea.cmdidx == CMD_vglobal
2369 || ea.usefilter)
2371 for (p = ea.arg; *p; ++p)
2373 /* Remove one backslash before a newline, so that it's possible to
2374 * pass a newline to the shell and also a newline that is preceded
2375 * with a backslash. This makes it impossible to end a shell
2376 * command in a backslash, but that doesn't appear useful.
2377 * Halving the number of backslashes is incompatible with previous
2378 * versions. */
2379 if (*p == '\\' && p[1] == '\n')
2380 STRMOVE(p, p + 1);
2381 else if (*p == '\n')
2383 ea.nextcmd = p + 1;
2384 *p = NUL;
2385 break;
2390 if ((ea.argt & DFLALL) && ea.addr_count == 0)
2392 ea.line1 = 1;
2393 ea.line2 = curbuf->b_ml.ml_line_count;
2396 /* accept numbered register only when no count allowed (:put) */
2397 if ( (ea.argt & REGSTR)
2398 && *ea.arg != NUL
2399 #ifdef FEAT_USR_CMDS
2400 && valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put
2401 && USER_CMDIDX(ea.cmdidx)))
2402 /* Do not allow register = for user commands */
2403 && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=')
2404 #else
2405 && valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put)
2406 #endif
2407 && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)))
2409 ea.regname = *ea.arg++;
2410 #ifdef FEAT_EVAL
2411 /* for '=' register: accept the rest of the line as an expression */
2412 if (ea.arg[-1] == '=' && ea.arg[0] != NUL)
2414 set_expr_line(vim_strsave(ea.arg));
2415 ea.arg += STRLEN(ea.arg);
2417 #endif
2418 ea.arg = skipwhite(ea.arg);
2422 * Check for a count. When accepting a BUFNAME, don't use "123foo" as a
2423 * count, it's a buffer name.
2425 if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg)
2426 && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL
2427 || vim_iswhite(*p)))
2429 n = getdigits(&ea.arg);
2430 ea.arg = skipwhite(ea.arg);
2431 if (n <= 0 && !ni && (ea.argt & ZEROR) == 0)
2433 errormsg = (char_u *)_(e_zerocount);
2434 goto doend;
2436 if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */
2438 ea.line2 = n;
2439 if (ea.addr_count == 0)
2440 ea.addr_count = 1;
2442 else
2444 ea.line1 = ea.line2;
2445 ea.line2 += n - 1;
2446 ++ea.addr_count;
2448 * Be vi compatible: no error message for out of range.
2450 if (ea.line2 > curbuf->b_ml.ml_line_count)
2451 ea.line2 = curbuf->b_ml.ml_line_count;
2456 * Check for flags: 'l', 'p' and '#'.
2458 if (ea.argt & EXFLAGS)
2459 get_flags(&ea);
2460 /* no arguments allowed */
2461 if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL
2462 && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0))
2464 errormsg = (char_u *)_(e_trailing);
2465 goto doend;
2468 if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL)
2470 errormsg = (char_u *)_(e_argreq);
2471 goto doend;
2474 #ifdef FEAT_EVAL
2476 * Skip the command when it's not going to be executed.
2477 * The commands like :if, :endif, etc. always need to be executed.
2478 * Also make an exception for commands that handle a trailing command
2479 * themselves.
2481 if (ea.skip)
2483 switch (ea.cmdidx)
2485 /* commands that need evaluation */
2486 case CMD_while:
2487 case CMD_endwhile:
2488 case CMD_for:
2489 case CMD_endfor:
2490 case CMD_if:
2491 case CMD_elseif:
2492 case CMD_else:
2493 case CMD_endif:
2494 case CMD_try:
2495 case CMD_catch:
2496 case CMD_finally:
2497 case CMD_endtry:
2498 case CMD_function:
2499 break;
2501 /* Commands that handle '|' themselves. Check: A command should
2502 * either have the TRLBAR flag, appear in this list or appear in
2503 * the list at ":help :bar". */
2504 case CMD_aboveleft:
2505 case CMD_and:
2506 case CMD_belowright:
2507 case CMD_botright:
2508 case CMD_browse:
2509 case CMD_call:
2510 case CMD_confirm:
2511 case CMD_delfunction:
2512 case CMD_djump:
2513 case CMD_dlist:
2514 case CMD_dsearch:
2515 case CMD_dsplit:
2516 case CMD_echo:
2517 case CMD_echoerr:
2518 case CMD_echomsg:
2519 case CMD_echon:
2520 case CMD_execute:
2521 case CMD_help:
2522 case CMD_hide:
2523 case CMD_ijump:
2524 case CMD_ilist:
2525 case CMD_isearch:
2526 case CMD_isplit:
2527 case CMD_keepalt:
2528 case CMD_keepjumps:
2529 case CMD_keepmarks:
2530 case CMD_leftabove:
2531 case CMD_let:
2532 case CMD_lockmarks:
2533 case CMD_match:
2534 case CMD_mzscheme:
2535 case CMD_perl:
2536 case CMD_psearch:
2537 case CMD_python:
2538 case CMD_return:
2539 case CMD_rightbelow:
2540 case CMD_ruby:
2541 case CMD_silent:
2542 case CMD_smagic:
2543 case CMD_snomagic:
2544 case CMD_substitute:
2545 case CMD_syntax:
2546 case CMD_tab:
2547 case CMD_tcl:
2548 case CMD_throw:
2549 case CMD_tilde:
2550 case CMD_topleft:
2551 case CMD_unlet:
2552 case CMD_verbose:
2553 case CMD_vertical:
2554 break;
2556 default: goto doend;
2559 #endif
2561 if (ea.argt & XFILE)
2563 if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL)
2564 goto doend;
2567 #ifdef FEAT_LISTCMDS
2569 * Accept buffer name. Cannot be used at the same time with a buffer
2570 * number. Don't do this for a user command.
2572 if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0
2573 # ifdef FEAT_USR_CMDS
2574 && !USER_CMDIDX(ea.cmdidx)
2575 # endif
2579 * :bdelete, :bwipeout and :bunload take several arguments, separated
2580 * by spaces: find next space (skipping over escaped characters).
2581 * The others take one argument: ignore trailing spaces.
2583 if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout
2584 || ea.cmdidx == CMD_bunload)
2585 p = skiptowhite_esc(ea.arg);
2586 else
2588 p = ea.arg + STRLEN(ea.arg);
2589 while (p > ea.arg && vim_iswhite(p[-1]))
2590 --p;
2592 ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE);
2593 if (ea.line2 < 0) /* failed */
2594 goto doend;
2595 ea.addr_count = 1;
2596 ea.arg = skipwhite(p);
2598 #endif
2601 * 6. switch on command name
2603 * The "ea" structure holds the arguments that can be used.
2605 ea.cmdlinep = cmdlinep;
2606 ea.getline = fgetline;
2607 ea.cookie = cookie;
2608 #ifdef FEAT_EVAL
2609 ea.cstack = cstack;
2610 #endif
2612 #ifdef FEAT_USR_CMDS
2613 if (USER_CMDIDX(ea.cmdidx))
2616 * Execute a user-defined command.
2618 do_ucmd(&ea);
2620 else
2621 #endif
2624 * Call the function to execute the command.
2626 ea.errmsg = NULL;
2627 (cmdnames[ea.cmdidx].cmd_func)(&ea);
2628 if (ea.errmsg != NULL)
2629 errormsg = (char_u *)_(ea.errmsg);
2632 #ifdef FEAT_EVAL
2634 * If the command just executed called do_cmdline(), any throw or ":return"
2635 * or ":finish" encountered there must also check the cstack of the still
2636 * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught
2637 * exception, or reanimate a returned function or finished script file and
2638 * return or finish it again.
2640 if (need_rethrow)
2641 do_throw(cstack);
2642 else if (check_cstack)
2644 if (source_finished(fgetline, cookie))
2645 do_finish(&ea, TRUE);
2646 else if (getline_equal(fgetline, cookie, get_func_line)
2647 && current_func_returned())
2648 do_return(&ea, TRUE, FALSE, NULL);
2650 need_rethrow = check_cstack = FALSE;
2651 #endif
2653 doend:
2654 if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */
2655 curwin->w_cursor.lnum = 1;
2657 if (errormsg != NULL && *errormsg != NUL && !did_emsg)
2659 if (sourcing)
2661 if (errormsg != IObuff)
2663 STRCPY(IObuff, errormsg);
2664 errormsg = IObuff;
2666 STRCAT(errormsg, ": ");
2667 STRNCAT(errormsg, *cmdlinep, IOSIZE - STRLEN(IObuff) - 1);
2669 emsg(errormsg);
2671 #ifdef FEAT_EVAL
2672 do_errthrow(cstack,
2673 (ea.cmdidx != CMD_SIZE
2674 # ifdef FEAT_USR_CMDS
2675 && !USER_CMDIDX(ea.cmdidx)
2676 # endif
2677 ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL);
2678 #endif
2680 if (verbose_save >= 0)
2681 p_verbose = verbose_save;
2682 #ifdef FEAT_AUTOCMD
2683 if (cmdmod.save_ei != NULL)
2685 /* Restore 'eventignore' to the value before ":noautocmd". */
2686 set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei,
2687 OPT_FREE, SID_NONE);
2688 free_string_option(cmdmod.save_ei);
2690 #endif
2692 cmdmod = save_cmdmod;
2694 if (did_silent > 0)
2696 /* messages could be enabled for a serious error, need to check if the
2697 * counters don't become negative */
2698 msg_silent -= did_silent;
2699 if (msg_silent < 0)
2700 msg_silent = 0;
2701 emsg_silent -= did_esilent;
2702 if (emsg_silent < 0)
2703 emsg_silent = 0;
2704 /* Restore msg_scroll, it's set by file I/O commands, even when no
2705 * message is actually displayed. */
2706 msg_scroll = save_msg_scroll;
2709 #ifdef HAVE_SANDBOX
2710 if (did_sandbox)
2711 --sandbox;
2712 #endif
2714 if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */
2715 ea.nextcmd = NULL;
2717 #ifdef FEAT_EVAL
2718 --ex_nesting_level;
2719 #endif
2721 return ea.nextcmd;
2723 #if (_MSC_VER == 1200)
2724 #pragma optimize( "", on )
2725 #endif
2728 * Check for an Ex command with optional tail.
2729 * If there is a match advance "pp" to the argument and return TRUE.
2732 checkforcmd(pp, cmd, len)
2733 char_u **pp; /* start of command */
2734 char *cmd; /* name of command */
2735 int len; /* required length */
2737 int i;
2739 for (i = 0; cmd[i] != NUL; ++i)
2740 if (cmd[i] != (*pp)[i])
2741 break;
2742 if (i >= len && !isalpha((*pp)[i]))
2744 *pp = skipwhite(*pp + i);
2745 return TRUE;
2747 return FALSE;
2751 * Find an Ex command by its name, either built-in or user.
2752 * Start of the name can be found at eap->cmd.
2753 * Returns pointer to char after the command name.
2754 * "full" is set to TRUE if the whole command name matched.
2755 * Returns NULL for an ambiguous user command.
2757 /*ARGSUSED*/
2758 static char_u *
2759 find_command(eap, full)
2760 exarg_T *eap;
2761 int *full;
2763 int len;
2764 char_u *p;
2765 int i;
2768 * Isolate the command and search for it in the command table.
2769 * Exceptions:
2770 * - the 'k' command can directly be followed by any character.
2771 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
2772 * but :sre[wind] is another command, as are :scrip[tnames],
2773 * :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
2774 * - the "d" command can directly be followed by 'l' or 'p' flag.
2776 p = eap->cmd;
2777 if (*p == 'k')
2779 eap->cmdidx = CMD_k;
2780 ++p;
2782 else if (p[0] == 's'
2783 && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r'
2784 && p[3] != 'i' && p[4] != 'p')
2785 || p[1] == 'g'
2786 || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
2787 || p[1] == 'I'
2788 || (p[1] == 'r' && p[2] != 'e')))
2790 eap->cmdidx = CMD_substitute;
2791 ++p;
2793 else
2795 while (ASCII_ISALPHA(*p))
2796 ++p;
2797 /* check for non-alpha command */
2798 if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
2799 ++p;
2800 len = (int)(p - eap->cmd);
2801 if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p'))
2803 /* Check for ":dl", ":dell", etc. to ":deletel": that's
2804 * :delete with the 'l' flag. Same for 'p'. */
2805 for (i = 0; i < len; ++i)
2806 if (eap->cmd[i] != "delete"[i])
2807 break;
2808 if (i == len - 1)
2810 --len;
2811 if (p[-1] == 'l')
2812 eap->flags |= EXFLAG_LIST;
2813 else
2814 eap->flags |= EXFLAG_PRINT;
2818 if (ASCII_ISLOWER(*eap->cmd))
2819 eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)];
2820 else
2821 eap->cmdidx = cmdidxs[26];
2823 for ( ; (int)eap->cmdidx < (int)CMD_SIZE;
2824 eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1))
2825 if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd,
2826 (size_t)len) == 0)
2828 #ifdef FEAT_EVAL
2829 if (full != NULL
2830 && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL)
2831 *full = TRUE;
2832 #endif
2833 break;
2836 #ifdef FEAT_USR_CMDS
2837 /* Look for a user defined command as a last resort */
2838 if (eap->cmdidx == CMD_SIZE && *eap->cmd >= 'A' && *eap->cmd <= 'Z')
2840 /* User defined commands may contain digits. */
2841 while (ASCII_ISALNUM(*p))
2842 ++p;
2843 p = find_ucmd(eap, p, full, NULL, NULL);
2845 #endif
2846 if (p == eap->cmd)
2847 eap->cmdidx = CMD_SIZE;
2850 return p;
2853 #ifdef FEAT_USR_CMDS
2855 * Search for a user command that matches "eap->cmd".
2856 * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
2857 * Return a pointer to just after the command.
2858 * Return NULL if there is no matching command.
2860 static char_u *
2861 find_ucmd(eap, p, full, xp, compl)
2862 exarg_T *eap;
2863 char_u *p; /* end of the command (possibly including count) */
2864 int *full; /* set to TRUE for a full match */
2865 expand_T *xp; /* used for completion, NULL otherwise */
2866 int *compl; /* completion flags or NULL */
2868 int len = (int)(p - eap->cmd);
2869 int j, k, matchlen = 0;
2870 ucmd_T *uc;
2871 int found = FALSE;
2872 int possible = FALSE;
2873 char_u *cp, *np; /* Point into typed cmd and test name */
2874 garray_T *gap;
2875 int amb_local = FALSE; /* Found ambiguous buffer-local command,
2876 only full match global is accepted. */
2879 * Look for buffer-local user commands first, then global ones.
2881 gap = &curbuf->b_ucmds;
2882 for (;;)
2884 for (j = 0; j < gap->ga_len; ++j)
2886 uc = USER_CMD_GA(gap, j);
2887 cp = eap->cmd;
2888 np = uc->uc_name;
2889 k = 0;
2890 while (k < len && *np != NUL && *cp++ == *np++)
2891 k++;
2892 if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k])))
2894 /* If finding a second match, the command is ambiguous. But
2895 * not if a buffer-local command wasn't a full match and a
2896 * global command is a full match. */
2897 if (k == len && found && *np != NUL)
2899 if (gap == &ucmds)
2900 return NULL;
2901 amb_local = TRUE;
2904 if (!found || (k == len && *np == NUL))
2906 /* If we matched up to a digit, then there could
2907 * be another command including the digit that we
2908 * should use instead.
2910 if (k == len)
2911 found = TRUE;
2912 else
2913 possible = TRUE;
2915 if (gap == &ucmds)
2916 eap->cmdidx = CMD_USER;
2917 else
2918 eap->cmdidx = CMD_USER_BUF;
2919 eap->argt = (long)uc->uc_argt;
2920 eap->useridx = j;
2922 # ifdef FEAT_CMDL_COMPL
2923 if (compl != NULL)
2924 *compl = uc->uc_compl;
2925 # ifdef FEAT_EVAL
2926 if (xp != NULL)
2928 xp->xp_arg = uc->uc_compl_arg;
2929 xp->xp_scriptID = uc->uc_scriptID;
2931 # endif
2932 # endif
2933 /* Do not search for further abbreviations
2934 * if this is an exact match. */
2935 matchlen = k;
2936 if (k == len && *np == NUL)
2938 if (full != NULL)
2939 *full = TRUE;
2940 amb_local = FALSE;
2941 break;
2947 /* Stop if we found a full match or searched all. */
2948 if (j < gap->ga_len || gap == &ucmds)
2949 break;
2950 gap = &ucmds;
2953 /* Only found ambiguous matches. */
2954 if (amb_local)
2956 if (xp != NULL)
2957 xp->xp_context = EXPAND_UNSUCCESSFUL;
2958 return NULL;
2961 /* The match we found may be followed immediately by a number. Move "p"
2962 * back to point to it. */
2963 if (found || possible)
2964 return p + (matchlen - len);
2965 return p;
2967 #endif
2969 #if defined(FEAT_EVAL) || defined(PROTO)
2970 static struct cmdmod
2972 char *name;
2973 int minlen;
2974 int has_count; /* :123verbose :3tab */
2975 } cmdmods[] = {
2976 {"aboveleft", 3, FALSE},
2977 {"belowright", 3, FALSE},
2978 {"botright", 2, FALSE},
2979 {"browse", 3, FALSE},
2980 {"confirm", 4, FALSE},
2981 {"hide", 3, FALSE},
2982 {"keepalt", 5, FALSE},
2983 {"keepjumps", 5, FALSE},
2984 {"keepmarks", 3, FALSE},
2985 {"leftabove", 5, FALSE},
2986 {"lockmarks", 3, FALSE},
2987 {"rightbelow", 6, FALSE},
2988 {"sandbox", 3, FALSE},
2989 {"silent", 3, FALSE},
2990 {"tab", 3, TRUE},
2991 {"topleft", 2, FALSE},
2992 {"verbose", 4, TRUE},
2993 {"vertical", 4, FALSE},
2997 * Return length of a command modifier (including optional count).
2998 * Return zero when it's not a modifier.
3001 modifier_len(cmd)
3002 char_u *cmd;
3004 int i, j;
3005 char_u *p = cmd;
3007 if (VIM_ISDIGIT(*cmd))
3008 p = skipwhite(skipdigits(cmd));
3009 for (i = 0; i < sizeof(cmdmods) / sizeof(struct cmdmod); ++i)
3011 for (j = 0; p[j] != NUL; ++j)
3012 if (p[j] != cmdmods[i].name[j])
3013 break;
3014 if (!isalpha(p[j]) && j >= cmdmods[i].minlen
3015 && (p == cmd || cmdmods[i].has_count))
3016 return j + (int)(p - cmd);
3018 return 0;
3022 * Return > 0 if an Ex command "name" exists.
3023 * Return 2 if there is an exact match.
3024 * Return 3 if there is an ambiguous match.
3027 cmd_exists(name)
3028 char_u *name;
3030 exarg_T ea;
3031 int full = FALSE;
3032 int i;
3033 int j;
3034 char_u *p;
3036 /* Check command modifiers. */
3037 for (i = 0; i < sizeof(cmdmods) / sizeof(struct cmdmod); ++i)
3039 for (j = 0; name[j] != NUL; ++j)
3040 if (name[j] != cmdmods[i].name[j])
3041 break;
3042 if (name[j] == NUL && j >= cmdmods[i].minlen)
3043 return (cmdmods[i].name[j] == NUL ? 2 : 1);
3046 /* Check built-in commands and user defined commands.
3047 * For ":2match" and ":3match" we need to skip the number. */
3048 ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3049 ea.cmdidx = (cmdidx_T)0;
3050 p = find_command(&ea, &full);
3051 if (p == NULL)
3052 return 3;
3053 if (vim_isdigit(*name) && ea.cmdidx != CMD_match)
3054 return 0;
3055 if (*skipwhite(p) != NUL)
3056 return 0; /* trailing garbage */
3057 return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1));
3059 #endif
3062 * This is all pretty much copied from do_one_cmd(), with all the extra stuff
3063 * we don't need/want deleted. Maybe this could be done better if we didn't
3064 * repeat all this stuff. The only problem is that they may not stay
3065 * perfectly compatible with each other, but then the command line syntax
3066 * probably won't change that much -- webb.
3068 char_u *
3069 set_one_cmd_context(xp, buff)
3070 expand_T *xp;
3071 char_u *buff; /* buffer for command string */
3073 char_u *p;
3074 char_u *cmd, *arg;
3075 int len = 0;
3076 exarg_T ea;
3077 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3078 int compl = EXPAND_NOTHING;
3079 #endif
3080 #ifdef FEAT_CMDL_COMPL
3081 int delim;
3082 #endif
3083 int forceit = FALSE;
3084 int usefilter = FALSE; /* filter instead of file name */
3086 ExpandInit(xp);
3087 xp->xp_pattern = buff;
3088 xp->xp_context = EXPAND_COMMANDS; /* Default until we get past command */
3089 ea.argt = 0;
3092 * 2. skip comment lines and leading space, colons or bars
3094 for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
3096 xp->xp_pattern = cmd;
3098 if (*cmd == NUL)
3099 return NULL;
3100 if (*cmd == '"') /* ignore comment lines */
3102 xp->xp_context = EXPAND_NOTHING;
3103 return NULL;
3107 * 3. parse a range specifier of the form: addr [,addr] [;addr] ..
3109 cmd = skip_range(cmd, &xp->xp_context);
3112 * 4. parse command
3114 xp->xp_pattern = cmd;
3115 if (*cmd == NUL)
3116 return NULL;
3117 if (*cmd == '"')
3119 xp->xp_context = EXPAND_NOTHING;
3120 return NULL;
3123 if (*cmd == '|' || *cmd == '\n')
3124 return cmd + 1; /* There's another command */
3127 * Isolate the command and search for it in the command table.
3128 * Exceptions:
3129 * - the 'k' command can directly be followed by any character, but
3130 * do accept "keepmarks", "keepalt" and "keepjumps".
3131 * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3133 if (*cmd == 'k' && cmd[1] != 'e')
3135 ea.cmdidx = CMD_k;
3136 p = cmd + 1;
3138 else
3140 p = cmd;
3141 while (ASCII_ISALPHA(*p) || *p == '*') /* Allow * wild card */
3142 ++p;
3143 /* check for non-alpha command */
3144 if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
3145 ++p;
3146 len = (int)(p - cmd);
3148 if (len == 0)
3150 xp->xp_context = EXPAND_UNSUCCESSFUL;
3151 return NULL;
3153 for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE;
3154 ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1))
3155 if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd, (size_t)len) == 0)
3156 break;
3158 #ifdef FEAT_USR_CMDS
3159 if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3161 while (ASCII_ISALNUM(*p) || *p == '*') /* Allow * wild card */
3162 ++p;
3163 len = (int)(p - cmd);
3165 #endif
3169 * If the cursor is touching the command, and it ends in an alpha-numeric
3170 * character, complete the command name.
3172 if (*p == NUL && ASCII_ISALNUM(p[-1]))
3173 return NULL;
3175 if (ea.cmdidx == CMD_SIZE)
3177 if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
3179 ea.cmdidx = CMD_substitute;
3180 p = cmd + 1;
3182 #ifdef FEAT_USR_CMDS
3183 else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
3185 ea.cmd = cmd;
3186 p = find_ucmd(&ea, p, NULL, xp,
3187 # if defined(FEAT_CMDL_COMPL)
3188 &compl
3189 # else
3190 NULL
3191 # endif
3193 if (p == NULL)
3194 ea.cmdidx = CMD_SIZE; /* ambiguous user command */
3196 #endif
3198 if (ea.cmdidx == CMD_SIZE)
3200 /* Not still touching the command and it was an illegal one */
3201 xp->xp_context = EXPAND_UNSUCCESSFUL;
3202 return NULL;
3205 xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */
3207 if (*p == '!') /* forced commands */
3209 forceit = TRUE;
3210 ++p;
3214 * 5. parse arguments
3216 #ifdef FEAT_USR_CMDS
3217 if (!USER_CMDIDX(ea.cmdidx))
3218 #endif
3219 ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt;
3221 arg = skipwhite(p);
3223 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
3225 if (*arg == '>') /* append */
3227 if (*++arg == '>')
3228 ++arg;
3229 arg = skipwhite(arg);
3231 else if (*arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */
3233 ++arg;
3234 usefilter = TRUE;
3238 if (ea.cmdidx == CMD_read)
3240 usefilter = forceit; /* :r! filter if forced */
3241 if (*arg == '!') /* :r !filter */
3243 ++arg;
3244 usefilter = TRUE;
3248 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
3250 while (*arg == *cmd) /* allow any number of '>' or '<' */
3251 ++arg;
3252 arg = skipwhite(arg);
3255 /* Does command allow "+command"? */
3256 if ((ea.argt & EDITCMD) && !usefilter && *arg == '+')
3258 /* Check if we're in the +command */
3259 p = arg + 1;
3260 arg = skip_cmd_arg(arg, FALSE);
3262 /* Still touching the command after '+'? */
3263 if (*arg == NUL)
3264 return p;
3266 /* Skip space(s) after +command to get to the real argument */
3267 arg = skipwhite(arg);
3271 * Check for '|' to separate commands and '"' to start comments.
3272 * Don't do this for ":read !cmd" and ":write !cmd".
3274 if ((ea.argt & TRLBAR) && !usefilter)
3276 p = arg;
3277 /* ":redir @" is not the start of a comment */
3278 if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
3279 p += 2;
3280 while (*p)
3282 if (*p == Ctrl_V)
3284 if (p[1] != NUL)
3285 ++p;
3287 else if ( (*p == '"' && !(ea.argt & NOTRLCOM))
3288 || *p == '|' || *p == '\n')
3290 if (*(p - 1) != '\\')
3292 if (*p == '|' || *p == '\n')
3293 return p + 1;
3294 return NULL; /* It's a comment */
3297 mb_ptr_adv(p);
3301 /* no arguments allowed */
3302 if (!(ea.argt & EXTRA) && *arg != NUL &&
3303 vim_strchr((char_u *)"|\"", *arg) == NULL)
3304 return NULL;
3306 /* Find start of last argument (argument just before cursor): */
3307 p = buff + STRLEN(buff);
3308 while (p != arg && *p != ' ' && *p != TAB)
3309 p--;
3310 if (*p == ' ' || *p == TAB)
3311 p++;
3312 xp->xp_pattern = p;
3314 if (ea.argt & XFILE)
3316 int c;
3317 int in_quote = FALSE;
3318 char_u *bow = NULL; /* Beginning of word */
3321 * Allow spaces within back-quotes to count as part of the argument
3322 * being expanded.
3324 xp->xp_pattern = skipwhite(arg);
3325 p = xp->xp_pattern;
3326 while (*p != NUL)
3328 #ifdef FEAT_MBYTE
3329 if (has_mbyte)
3330 c = mb_ptr2char(p);
3331 else
3332 #endif
3333 c = *p;
3334 if (c == '\\' && p[1] != NUL)
3335 ++p;
3336 else if (c == '`')
3338 if (!in_quote)
3340 xp->xp_pattern = p;
3341 bow = p + 1;
3343 in_quote = !in_quote;
3345 /* An argument can contain just about everything, except
3346 * characters that end the command and white space. */
3347 else if (c == '|' || c == '\n' || c == '"' || (vim_iswhite(c)
3348 #ifdef SPACE_IN_FILENAME
3349 && (!(ea.argt & NOSPC) || usefilter)
3350 #endif
3353 len = 0; /* avoid getting stuck when space is in 'isfname' */
3354 while (*p != NUL)
3356 #ifdef FEAT_MBYTE
3357 if (has_mbyte)
3358 c = mb_ptr2char(p);
3359 else
3360 #endif
3361 c = *p;
3362 if (c == '`' || vim_isfilec_or_wc(c))
3363 break;
3364 #ifdef FEAT_MBYTE
3365 if (has_mbyte)
3366 len = (*mb_ptr2len)(p);
3367 else
3368 #endif
3369 len = 1;
3370 mb_ptr_adv(p);
3372 if (in_quote)
3373 bow = p;
3374 else
3375 xp->xp_pattern = p;
3376 p -= len;
3378 mb_ptr_adv(p);
3382 * If we are still inside the quotes, and we passed a space, just
3383 * expand from there.
3385 if (bow != NULL && in_quote)
3386 xp->xp_pattern = bow;
3387 xp->xp_context = EXPAND_FILES;
3389 #ifndef BACKSLASH_IN_FILENAME
3390 /* For a shell command more chars need to be escaped. */
3391 if (usefilter || ea.cmdidx == CMD_bang)
3393 xp->xp_shell = TRUE;
3395 /* When still after the command name expand executables. */
3396 if (xp->xp_pattern == skipwhite(arg))
3397 xp->xp_context = EXPAND_SHELLCMD;
3399 #endif
3401 /* Check for environment variable */
3402 if (*xp->xp_pattern == '$'
3403 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3404 || *xp->xp_pattern == '%'
3405 #endif
3408 for (p = xp->xp_pattern + 1; *p != NUL; ++p)
3409 if (!vim_isIDc(*p))
3410 break;
3411 if (*p == NUL)
3413 xp->xp_context = EXPAND_ENV_VARS;
3414 ++xp->xp_pattern;
3415 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
3416 /* Avoid that the assignment uses EXPAND_FILES again. */
3417 if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
3418 compl = EXPAND_ENV_VARS;
3419 #endif
3425 * 6. switch on command name
3427 switch (ea.cmdidx)
3429 case CMD_cd:
3430 case CMD_chdir:
3431 case CMD_lcd:
3432 case CMD_lchdir:
3433 if (xp->xp_context == EXPAND_FILES)
3434 xp->xp_context = EXPAND_DIRECTORIES;
3435 break;
3436 case CMD_help:
3437 xp->xp_context = EXPAND_HELP;
3438 xp->xp_pattern = arg;
3439 break;
3441 /* Command modifiers: return the argument.
3442 * Also for commands with an argument that is a command. */
3443 case CMD_aboveleft:
3444 case CMD_argdo:
3445 case CMD_belowright:
3446 case CMD_botright:
3447 case CMD_browse:
3448 case CMD_bufdo:
3449 case CMD_confirm:
3450 case CMD_debug:
3451 case CMD_folddoclosed:
3452 case CMD_folddoopen:
3453 case CMD_hide:
3454 case CMD_keepalt:
3455 case CMD_keepjumps:
3456 case CMD_keepmarks:
3457 case CMD_leftabove:
3458 case CMD_lockmarks:
3459 case CMD_rightbelow:
3460 case CMD_sandbox:
3461 case CMD_silent:
3462 case CMD_tab:
3463 case CMD_topleft:
3464 case CMD_verbose:
3465 case CMD_vertical:
3466 case CMD_windo:
3467 return arg;
3469 #ifdef FEAT_CMDL_COMPL
3470 # ifdef FEAT_SEARCH_EXTRA
3471 case CMD_match:
3472 if (*arg == NUL || !ends_excmd(*arg))
3474 /* also complete "None" */
3475 set_context_in_echohl_cmd(xp, arg);
3476 arg = skipwhite(skiptowhite(arg));
3477 if (*arg != NUL)
3479 xp->xp_context = EXPAND_NOTHING;
3480 arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
3483 return find_nextcmd(arg);
3484 # endif
3487 * All completion for the +cmdline_compl feature goes here.
3490 # ifdef FEAT_USR_CMDS
3491 case CMD_command:
3492 /* Check for attributes */
3493 while (*arg == '-')
3495 arg++; /* Skip "-" */
3496 p = skiptowhite(arg);
3497 if (*p == NUL)
3499 /* Cursor is still in the attribute */
3500 p = vim_strchr(arg, '=');
3501 if (p == NULL)
3503 /* No "=", so complete attribute names */
3504 xp->xp_context = EXPAND_USER_CMD_FLAGS;
3505 xp->xp_pattern = arg;
3506 return NULL;
3509 /* For the -complete and -nargs attributes, we complete
3510 * their arguments as well.
3512 if (STRNICMP(arg, "complete", p - arg) == 0)
3514 xp->xp_context = EXPAND_USER_COMPLETE;
3515 xp->xp_pattern = p + 1;
3516 return NULL;
3518 else if (STRNICMP(arg, "nargs", p - arg) == 0)
3520 xp->xp_context = EXPAND_USER_NARGS;
3521 xp->xp_pattern = p + 1;
3522 return NULL;
3524 return NULL;
3526 arg = skipwhite(p);
3529 /* After the attributes comes the new command name */
3530 p = skiptowhite(arg);
3531 if (*p == NUL)
3533 xp->xp_context = EXPAND_USER_COMMANDS;
3534 xp->xp_pattern = arg;
3535 break;
3538 /* And finally comes a normal command */
3539 return skipwhite(p);
3541 case CMD_delcommand:
3542 xp->xp_context = EXPAND_USER_COMMANDS;
3543 xp->xp_pattern = arg;
3544 break;
3545 # endif
3547 case CMD_global:
3548 case CMD_vglobal:
3549 delim = *arg; /* get the delimiter */
3550 if (delim)
3551 ++arg; /* skip delimiter if there is one */
3553 while (arg[0] != NUL && arg[0] != delim)
3555 if (arg[0] == '\\' && arg[1] != NUL)
3556 ++arg;
3557 ++arg;
3559 if (arg[0] != NUL)
3560 return arg + 1;
3561 break;
3562 case CMD_and:
3563 case CMD_substitute:
3564 delim = *arg;
3565 if (delim)
3567 /* skip "from" part */
3568 ++arg;
3569 arg = skip_regexp(arg, delim, p_magic, NULL);
3571 /* skip "to" part */
3572 while (arg[0] != NUL && arg[0] != delim)
3574 if (arg[0] == '\\' && arg[1] != NUL)
3575 ++arg;
3576 ++arg;
3578 if (arg[0] != NUL) /* skip delimiter */
3579 ++arg;
3580 while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
3581 ++arg;
3582 if (arg[0] != NUL)
3583 return arg;
3584 break;
3585 case CMD_isearch:
3586 case CMD_dsearch:
3587 case CMD_ilist:
3588 case CMD_dlist:
3589 case CMD_ijump:
3590 case CMD_psearch:
3591 case CMD_djump:
3592 case CMD_isplit:
3593 case CMD_dsplit:
3594 arg = skipwhite(skipdigits(arg)); /* skip count */
3595 if (*arg == '/') /* Match regexp, not just whole words */
3597 for (++arg; *arg && *arg != '/'; arg++)
3598 if (*arg == '\\' && arg[1] != NUL)
3599 arg++;
3600 if (*arg)
3602 arg = skipwhite(arg + 1);
3604 /* Check for trailing illegal characters */
3605 if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
3606 xp->xp_context = EXPAND_NOTHING;
3607 else
3608 return arg;
3611 break;
3612 #ifdef FEAT_AUTOCMD
3613 case CMD_autocmd:
3614 return set_context_in_autocmd(xp, arg, FALSE);
3616 case CMD_doautocmd:
3617 return set_context_in_autocmd(xp, arg, TRUE);
3618 #endif
3619 case CMD_set:
3620 set_context_in_set_cmd(xp, arg, 0);
3621 break;
3622 case CMD_setglobal:
3623 set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
3624 break;
3625 case CMD_setlocal:
3626 set_context_in_set_cmd(xp, arg, OPT_LOCAL);
3627 break;
3628 case CMD_tag:
3629 case CMD_stag:
3630 case CMD_ptag:
3631 case CMD_ltag:
3632 case CMD_tselect:
3633 case CMD_stselect:
3634 case CMD_ptselect:
3635 case CMD_tjump:
3636 case CMD_stjump:
3637 case CMD_ptjump:
3638 if (*p_wop != NUL)
3639 xp->xp_context = EXPAND_TAGS_LISTFILES;
3640 else
3641 xp->xp_context = EXPAND_TAGS;
3642 xp->xp_pattern = arg;
3643 break;
3644 case CMD_augroup:
3645 xp->xp_context = EXPAND_AUGROUP;
3646 xp->xp_pattern = arg;
3647 break;
3648 #ifdef FEAT_SYN_HL
3649 case CMD_syntax:
3650 set_context_in_syntax_cmd(xp, arg);
3651 break;
3652 #endif
3653 #ifdef FEAT_EVAL
3654 case CMD_let:
3655 case CMD_if:
3656 case CMD_elseif:
3657 case CMD_while:
3658 case CMD_for:
3659 case CMD_echo:
3660 case CMD_echon:
3661 case CMD_execute:
3662 case CMD_echomsg:
3663 case CMD_echoerr:
3664 case CMD_call:
3665 case CMD_return:
3666 set_context_for_expression(xp, arg, ea.cmdidx);
3667 break;
3669 case CMD_unlet:
3670 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3671 arg = xp->xp_pattern + 1;
3672 xp->xp_context = EXPAND_USER_VARS;
3673 xp->xp_pattern = arg;
3674 break;
3676 case CMD_function:
3677 case CMD_delfunction:
3678 xp->xp_context = EXPAND_USER_FUNC;
3679 xp->xp_pattern = arg;
3680 break;
3682 case CMD_echohl:
3683 set_context_in_echohl_cmd(xp, arg);
3684 break;
3685 #endif
3686 case CMD_highlight:
3687 set_context_in_highlight_cmd(xp, arg);
3688 break;
3689 #ifdef FEAT_LISTCMDS
3690 case CMD_bdelete:
3691 case CMD_bwipeout:
3692 case CMD_bunload:
3693 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3694 arg = xp->xp_pattern + 1;
3695 /*FALLTHROUGH*/
3696 case CMD_buffer:
3697 case CMD_sbuffer:
3698 case CMD_checktime:
3699 xp->xp_context = EXPAND_BUFFERS;
3700 xp->xp_pattern = arg;
3701 break;
3702 #endif
3703 #ifdef FEAT_USR_CMDS
3704 case CMD_USER:
3705 case CMD_USER_BUF:
3706 if (compl != EXPAND_NOTHING)
3708 /* XFILE: file names are handled above */
3709 if (!(ea.argt & XFILE))
3711 # ifdef FEAT_MENU
3712 if (compl == EXPAND_MENUS)
3713 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3714 # endif
3715 if (compl == EXPAND_COMMANDS)
3716 return arg;
3717 if (compl == EXPAND_MAPPINGS)
3718 return set_context_in_map_cmd(xp, (char_u *)"map",
3719 arg, forceit, FALSE, FALSE, CMD_map);
3720 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
3721 arg = xp->xp_pattern + 1;
3722 xp->xp_pattern = arg;
3724 xp->xp_context = compl;
3726 break;
3727 #endif
3728 case CMD_map: case CMD_noremap:
3729 case CMD_nmap: case CMD_nnoremap:
3730 case CMD_vmap: case CMD_vnoremap:
3731 case CMD_omap: case CMD_onoremap:
3732 case CMD_imap: case CMD_inoremap:
3733 case CMD_cmap: case CMD_cnoremap:
3734 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3735 FALSE, FALSE, ea.cmdidx);
3736 case CMD_unmap:
3737 case CMD_nunmap:
3738 case CMD_vunmap:
3739 case CMD_ounmap:
3740 case CMD_iunmap:
3741 case CMD_cunmap:
3742 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3743 FALSE, TRUE, ea.cmdidx);
3744 case CMD_abbreviate: case CMD_noreabbrev:
3745 case CMD_cabbrev: case CMD_cnoreabbrev:
3746 case CMD_iabbrev: case CMD_inoreabbrev:
3747 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3748 TRUE, FALSE, ea.cmdidx);
3749 case CMD_unabbreviate:
3750 case CMD_cunabbrev:
3751 case CMD_iunabbrev:
3752 return set_context_in_map_cmd(xp, cmd, arg, forceit,
3753 TRUE, TRUE, ea.cmdidx);
3754 #ifdef FEAT_MENU
3755 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
3756 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
3757 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
3758 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
3759 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
3760 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
3761 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
3762 case CMD_tmenu: case CMD_tunmenu:
3763 case CMD_popup: case CMD_tearoff: case CMD_emenu:
3764 #ifdef FEAT_GUI_MACVIM
3765 case CMD_macmenu:
3766 #endif
3767 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
3768 #endif
3770 case CMD_colorscheme:
3771 xp->xp_context = EXPAND_COLORS;
3772 xp->xp_pattern = arg;
3773 break;
3775 case CMD_compiler:
3776 xp->xp_context = EXPAND_COMPILER;
3777 xp->xp_pattern = arg;
3778 break;
3780 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
3781 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
3782 case CMD_language:
3783 if (*skiptowhite(arg) == NUL)
3785 xp->xp_context = EXPAND_LANGUAGE;
3786 xp->xp_pattern = arg;
3788 else
3789 xp->xp_context = EXPAND_NOTHING;
3790 break;
3791 #endif
3793 #ifdef FEAT_GUI_MACVIM
3794 case CMD_macaction:
3795 xp->xp_context = EXPAND_MACACTION;
3796 xp->xp_pattern = arg;
3797 break;
3798 #endif
3801 #endif /* FEAT_CMDL_COMPL */
3803 default:
3804 break;
3806 return NULL;
3810 * skip a range specifier of the form: addr [,addr] [;addr] ..
3812 * Backslashed delimiters after / or ? will be skipped, and commands will
3813 * not be expanded between /'s and ?'s or after "'".
3815 * Also skip white space and ":" characters.
3816 * Returns the "cmd" pointer advanced to beyond the range.
3818 char_u *
3819 skip_range(cmd, ctx)
3820 char_u *cmd;
3821 int *ctx; /* pointer to xp_context or NULL */
3823 int delim;
3825 while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;", *cmd) != NULL)
3827 if (*cmd == '\'')
3829 if (*++cmd == NUL && ctx != NULL)
3830 *ctx = EXPAND_NOTHING;
3832 else if (*cmd == '/' || *cmd == '?')
3834 delim = *cmd++;
3835 while (*cmd != NUL && *cmd != delim)
3836 if (*cmd++ == '\\' && *cmd != NUL)
3837 ++cmd;
3838 if (*cmd == NUL && ctx != NULL)
3839 *ctx = EXPAND_NOTHING;
3841 if (*cmd != NUL)
3842 ++cmd;
3845 /* Skip ":" and white space. */
3846 while (*cmd == ':')
3847 cmd = skipwhite(cmd + 1);
3849 return cmd;
3853 * get a single EX address
3855 * Set ptr to the next character after the part that was interpreted.
3856 * Set ptr to NULL when an error is encountered.
3858 * Return MAXLNUM when no Ex address was found.
3860 static linenr_T
3861 get_address(ptr, skip, to_other_file)
3862 char_u **ptr;
3863 int skip; /* only skip the address, don't use it */
3864 int to_other_file; /* flag: may jump to other file */
3866 int c;
3867 int i;
3868 long n;
3869 char_u *cmd;
3870 pos_T pos;
3871 pos_T *fp;
3872 linenr_T lnum;
3874 cmd = skipwhite(*ptr);
3875 lnum = MAXLNUM;
3878 switch (*cmd)
3880 case '.': /* '.' - Cursor position */
3881 ++cmd;
3882 lnum = curwin->w_cursor.lnum;
3883 break;
3885 case '$': /* '$' - last line */
3886 ++cmd;
3887 lnum = curbuf->b_ml.ml_line_count;
3888 break;
3890 case '\'': /* ''' - mark */
3891 if (*++cmd == NUL)
3893 cmd = NULL;
3894 goto error;
3896 if (skip)
3897 ++cmd;
3898 else
3900 /* Only accept a mark in another file when it is
3901 * used by itself: ":'M". */
3902 fp = getmark(*cmd, to_other_file && cmd[1] == NUL);
3903 ++cmd;
3904 if (fp == (pos_T *)-1)
3905 /* Jumped to another file. */
3906 lnum = curwin->w_cursor.lnum;
3907 else
3909 if (check_mark(fp) == FAIL)
3911 cmd = NULL;
3912 goto error;
3914 lnum = fp->lnum;
3917 break;
3919 case '/':
3920 case '?': /* '/' or '?' - search */
3921 c = *cmd++;
3922 if (skip) /* skip "/pat/" */
3924 cmd = skip_regexp(cmd, c, (int)p_magic, NULL);
3925 if (*cmd == c)
3926 ++cmd;
3928 else
3930 pos = curwin->w_cursor; /* save curwin->w_cursor */
3932 * When '/' or '?' follows another address, start
3933 * from there.
3935 if (lnum != MAXLNUM)
3936 curwin->w_cursor.lnum = lnum;
3938 * Start a forward search at the end of the line.
3939 * Start a backward search at the start of the line.
3940 * This makes sure we never match in the current
3941 * line, and can match anywhere in the
3942 * next/previous line.
3944 if (c == '/')
3945 curwin->w_cursor.col = MAXCOL;
3946 else
3947 curwin->w_cursor.col = 0;
3948 searchcmdlen = 0;
3949 if (!do_search(NULL, c, cmd, 1L,
3950 SEARCH_HIS | SEARCH_MSG, NULL))
3952 curwin->w_cursor = pos;
3953 cmd = NULL;
3954 goto error;
3956 lnum = curwin->w_cursor.lnum;
3957 curwin->w_cursor = pos;
3958 /* adjust command string pointer */
3959 cmd += searchcmdlen;
3961 break;
3963 case '\\': /* "\?", "\/" or "\&", repeat search */
3964 ++cmd;
3965 if (*cmd == '&')
3966 i = RE_SUBST;
3967 else if (*cmd == '?' || *cmd == '/')
3968 i = RE_SEARCH;
3969 else
3971 EMSG(_(e_backslash));
3972 cmd = NULL;
3973 goto error;
3976 if (!skip)
3979 * When search follows another address, start from
3980 * there.
3982 if (lnum != MAXLNUM)
3983 pos.lnum = lnum;
3984 else
3985 pos.lnum = curwin->w_cursor.lnum;
3988 * Start the search just like for the above
3989 * do_search().
3991 if (*cmd != '?')
3992 pos.col = MAXCOL;
3993 else
3994 pos.col = 0;
3995 if (searchit(curwin, curbuf, &pos,
3996 *cmd == '?' ? BACKWARD : FORWARD,
3997 (char_u *)"", 1L, SEARCH_MSG,
3998 i, (linenr_T)0, NULL) != FAIL)
3999 lnum = pos.lnum;
4000 else
4002 cmd = NULL;
4003 goto error;
4006 ++cmd;
4007 break;
4009 default:
4010 if (VIM_ISDIGIT(*cmd)) /* absolute line number */
4011 lnum = getdigits(&cmd);
4014 for (;;)
4016 cmd = skipwhite(cmd);
4017 if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd))
4018 break;
4020 if (lnum == MAXLNUM)
4021 lnum = curwin->w_cursor.lnum; /* "+1" is same as ".+1" */
4022 if (VIM_ISDIGIT(*cmd))
4023 i = '+'; /* "number" is same as "+number" */
4024 else
4025 i = *cmd++;
4026 if (!VIM_ISDIGIT(*cmd)) /* '+' is '+1', but '+0' is not '+1' */
4027 n = 1;
4028 else
4029 n = getdigits(&cmd);
4030 if (i == '-')
4031 lnum -= n;
4032 else
4033 lnum += n;
4035 } while (*cmd == '/' || *cmd == '?');
4037 error:
4038 *ptr = cmd;
4039 return lnum;
4043 * Get flags from an Ex command argument.
4045 static void
4046 get_flags(eap)
4047 exarg_T *eap;
4049 while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL)
4051 if (*eap->arg == 'l')
4052 eap->flags |= EXFLAG_LIST;
4053 else if (*eap->arg == 'p')
4054 eap->flags |= EXFLAG_PRINT;
4055 else
4056 eap->flags |= EXFLAG_NR;
4057 eap->arg = skipwhite(eap->arg + 1);
4062 * Function called for command which is Not Implemented. NI!
4064 void
4065 ex_ni(eap)
4066 exarg_T *eap;
4068 if (!eap->skip)
4069 eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version");
4072 #ifdef HAVE_EX_SCRIPT_NI
4074 * Function called for script command which is Not Implemented. NI!
4075 * Skips over ":perl <<EOF" constructs.
4077 static void
4078 ex_script_ni(eap)
4079 exarg_T *eap;
4081 if (!eap->skip)
4082 ex_ni(eap);
4083 else
4084 vim_free(script_get(eap, eap->arg));
4086 #endif
4089 * Check range in Ex command for validity.
4090 * Return NULL when valid, error message when invalid.
4092 static char_u *
4093 invalid_range(eap)
4094 exarg_T *eap;
4096 if ( eap->line1 < 0
4097 || eap->line2 < 0
4098 || eap->line1 > eap->line2
4099 || ((eap->argt & RANGE)
4100 && !(eap->argt & NOTADR)
4101 && eap->line2 > curbuf->b_ml.ml_line_count
4102 #ifdef FEAT_DIFF
4103 + (eap->cmdidx == CMD_diffget)
4104 #endif
4106 return (char_u *)_(e_invrange);
4107 return NULL;
4111 * Correct the range for zero line number, if required.
4113 static void
4114 correct_range(eap)
4115 exarg_T *eap;
4117 if (!(eap->argt & ZEROR)) /* zero in range not allowed */
4119 if (eap->line1 == 0)
4120 eap->line1 = 1;
4121 if (eap->line2 == 0)
4122 eap->line2 = 1;
4126 #ifdef FEAT_QUICKFIX
4127 static char_u *skip_grep_pat __ARGS((exarg_T *eap));
4130 * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
4131 * pattern. Otherwise return eap->arg.
4133 static char_u *
4134 skip_grep_pat(eap)
4135 exarg_T *eap;
4137 char_u *p = eap->arg;
4139 if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
4140 || eap->cmdidx == CMD_vimgrepadd
4141 || eap->cmdidx == CMD_lvimgrepadd
4142 || grep_internal(eap->cmdidx)))
4144 p = skip_vimgrep_pat(p, NULL, NULL);
4145 if (p == NULL)
4146 p = eap->arg;
4148 return p;
4152 * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
4153 * in the command line, so that things like % get expanded.
4155 static char_u *
4156 replace_makeprg(eap, p, cmdlinep)
4157 exarg_T *eap;
4158 char_u *p;
4159 char_u **cmdlinep;
4161 char_u *new_cmdline;
4162 char_u *program;
4163 char_u *pos;
4164 char_u *ptr;
4165 int len;
4166 int i;
4169 * Don't do it when ":vimgrep" is used for ":grep".
4171 if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake
4172 || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4173 || eap->cmdidx == CMD_grepadd
4174 || eap->cmdidx == CMD_lgrepadd)
4175 && !grep_internal(eap->cmdidx))
4177 if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep
4178 || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd)
4180 if (*curbuf->b_p_gp == NUL)
4181 program = p_gp;
4182 else
4183 program = curbuf->b_p_gp;
4185 else
4187 if (*curbuf->b_p_mp == NUL)
4188 program = p_mp;
4189 else
4190 program = curbuf->b_p_mp;
4193 p = skipwhite(p);
4195 if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4197 /* replace $* by given arguments */
4198 i = 1;
4199 while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL)
4200 ++i;
4201 len = (int)STRLEN(p);
4202 new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1));
4203 if (new_cmdline == NULL)
4204 return NULL; /* out of memory */
4205 ptr = new_cmdline;
4206 while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL)
4208 i = (int)(pos - program);
4209 STRNCPY(ptr, program, i);
4210 STRCPY(ptr += i, p);
4211 ptr += len;
4212 program = pos + 2;
4214 STRCPY(ptr, program);
4216 else
4218 new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2));
4219 if (new_cmdline == NULL)
4220 return NULL; /* out of memory */
4221 STRCPY(new_cmdline, program);
4222 STRCAT(new_cmdline, " ");
4223 STRCAT(new_cmdline, p);
4225 msg_make(p);
4227 /* 'eap->cmd' is not set here, because it is not used at CMD_make */
4228 vim_free(*cmdlinep);
4229 *cmdlinep = new_cmdline;
4230 p = new_cmdline;
4232 return p;
4234 #endif
4237 * Expand file name in Ex command argument.
4238 * Return FAIL for failure, OK otherwise.
4241 expand_filename(eap, cmdlinep, errormsgp)
4242 exarg_T *eap;
4243 char_u **cmdlinep;
4244 char_u **errormsgp;
4246 int has_wildcards; /* need to expand wildcards */
4247 char_u *repl;
4248 int srclen;
4249 char_u *p;
4250 int n;
4251 int escaped;
4253 #ifdef FEAT_QUICKFIX
4254 /* Skip a regexp pattern for ":vimgrep[add] pat file..." */
4255 p = skip_grep_pat(eap);
4256 #else
4257 p = eap->arg;
4258 #endif
4261 * Decide to expand wildcards *before* replacing '%', '#', etc. If
4262 * the file name contains a wildcard it should not cause expanding.
4263 * (it will be expanded anyway if there is a wildcard before replacing).
4265 has_wildcards = mch_has_wildcard(p);
4266 while (*p != NUL)
4268 #ifdef FEAT_EVAL
4269 /* Skip over `=expr`, wildcards in it are not expanded. */
4270 if (p[0] == '`' && p[1] == '=')
4272 p += 2;
4273 (void)skip_expr(&p);
4274 if (*p == '`')
4275 ++p;
4276 continue;
4278 #endif
4280 * Quick check if this cannot be the start of a special string.
4281 * Also removes backslash before '%', '#' and '<'.
4283 if (vim_strchr((char_u *)"%#<", *p) == NULL)
4285 ++p;
4286 continue;
4290 * Try to find a match at this position.
4292 repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
4293 errormsgp, &escaped);
4294 if (*errormsgp != NULL) /* error detected */
4295 return FAIL;
4296 if (repl == NULL) /* no match found */
4298 p += srclen;
4299 continue;
4302 /* Wildcards won't be expanded below, the replacement is taken
4303 * literally. But do expand "~/file", "~user/file" and "$HOME/file". */
4304 if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
4306 char_u *l = repl;
4308 repl = expand_env_save(repl);
4309 vim_free(l);
4312 /* Need to escape white space et al. with a backslash.
4313 * Don't do this for:
4314 * - replacement that already has been escaped: "##"
4315 * - shell commands (may have to use quotes instead).
4316 * - non-unix systems when there is a single argument (spaces don't
4317 * separate arguments then).
4319 if (!eap->usefilter
4320 && !escaped
4321 && eap->cmdidx != CMD_bang
4322 && eap->cmdidx != CMD_make
4323 && eap->cmdidx != CMD_lmake
4324 && eap->cmdidx != CMD_grep
4325 && eap->cmdidx != CMD_lgrep
4326 && eap->cmdidx != CMD_grepadd
4327 && eap->cmdidx != CMD_lgrepadd
4328 #ifndef UNIX
4329 && !(eap->argt & NOSPC)
4330 #endif
4333 char_u *l;
4334 #ifdef BACKSLASH_IN_FILENAME
4335 /* Don't escape a backslash here, because rem_backslash() doesn't
4336 * remove it later. */
4337 static char_u *nobslash = (char_u *)" \t\"|";
4338 # define ESCAPE_CHARS nobslash
4339 #else
4340 # define ESCAPE_CHARS escape_chars
4341 #endif
4343 for (l = repl; *l; ++l)
4344 if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
4346 l = vim_strsave_escaped(repl, ESCAPE_CHARS);
4347 if (l != NULL)
4349 vim_free(repl);
4350 repl = l;
4352 break;
4356 /* For a shell command a '!' must be escaped. */
4357 if ((eap->usefilter || eap->cmdidx == CMD_bang)
4358 && vim_strpbrk(repl, (char_u *)"!&;()<>") != NULL)
4360 char_u *l;
4362 l = vim_strsave_escaped(repl, (char_u *)"!&;()<>");
4363 if (l != NULL)
4365 vim_free(repl);
4366 repl = l;
4367 /* For a sh-like shell escape "!" another time. */
4368 if (strstr((char *)p_sh, "sh") != NULL)
4370 l = vim_strsave_escaped(repl, (char_u *)"!");
4371 if (l != NULL)
4373 vim_free(repl);
4374 repl = l;
4380 p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4381 vim_free(repl);
4382 if (p == NULL)
4383 return FAIL;
4387 * One file argument: Expand wildcards.
4388 * Don't do this with ":r !command" or ":w !command".
4390 if ((eap->argt & NOSPC) && !eap->usefilter)
4393 * May do this twice:
4394 * 1. Replace environment variables.
4395 * 2. Replace any other wildcards, remove backslashes.
4397 for (n = 1; n <= 2; ++n)
4399 if (n == 2)
4401 #ifdef UNIX
4403 * Only for Unix we check for more than one file name.
4404 * For other systems spaces are considered to be part
4405 * of the file name.
4406 * Only check here if there is no wildcard, otherwise
4407 * ExpandOne() will check for errors. This allows
4408 * ":e `ls ve*.c`" on Unix.
4410 if (!has_wildcards)
4411 for (p = eap->arg; *p; ++p)
4413 /* skip escaped characters */
4414 if (p[1] && (*p == '\\' || *p == Ctrl_V))
4415 ++p;
4416 else if (vim_iswhite(*p))
4418 *errormsgp = (char_u *)_("E172: Only one file name allowed");
4419 return FAIL;
4422 #endif
4425 * Halve the number of backslashes (this is Vi compatible).
4426 * For Unix and OS/2, when wildcards are expanded, this is
4427 * done by ExpandOne() below.
4429 #if defined(UNIX) || defined(OS2)
4430 if (!has_wildcards)
4431 #endif
4432 backslash_halve(eap->arg);
4435 if (has_wildcards)
4437 if (n == 1)
4440 * First loop: May expand environment variables. This
4441 * can be done much faster with expand_env() than with
4442 * something else (e.g., calling a shell).
4443 * After expanding environment variables, check again
4444 * if there are still wildcards present.
4446 if (vim_strchr(eap->arg, '$') != NULL
4447 || vim_strchr(eap->arg, '~') != NULL)
4449 expand_env_esc(eap->arg, NameBuff, MAXPATHL,
4450 TRUE, TRUE, NULL);
4451 has_wildcards = mch_has_wildcard(NameBuff);
4452 p = NameBuff;
4454 else
4455 p = NULL;
4457 else /* n == 2 */
4459 expand_T xpc;
4461 ExpandInit(&xpc);
4462 xpc.xp_context = EXPAND_FILES;
4463 p = ExpandOne(&xpc, eap->arg, NULL,
4464 WILD_LIST_NOTFOUND|WILD_ADD_SLASH,
4465 WILD_EXPAND_FREE);
4466 if (p == NULL)
4467 return FAIL;
4469 if (p != NULL)
4471 (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
4472 p, cmdlinep);
4473 if (n == 2) /* p came from ExpandOne() */
4474 vim_free(p);
4479 return OK;
4483 * Replace part of the command line, keeping eap->cmd, eap->arg and
4484 * eap->nextcmd correct.
4485 * "src" points to the part that is to be replaced, of length "srclen".
4486 * "repl" is the replacement string.
4487 * Returns a pointer to the character after the replaced string.
4488 * Returns NULL for failure.
4490 static char_u *
4491 repl_cmdline(eap, src, srclen, repl, cmdlinep)
4492 exarg_T *eap;
4493 char_u *src;
4494 int srclen;
4495 char_u *repl;
4496 char_u **cmdlinep;
4498 int len;
4499 int i;
4500 char_u *new_cmdline;
4503 * The new command line is build in new_cmdline[].
4504 * First allocate it.
4505 * Careful: a "+cmd" argument may have been NUL terminated.
4507 len = (int)STRLEN(repl);
4508 i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3;
4509 if (eap->nextcmd != NULL)
4510 i += (int)STRLEN(eap->nextcmd);/* add space for next command */
4511 if ((new_cmdline = alloc((unsigned)i)) == NULL)
4512 return NULL; /* out of memory! */
4515 * Copy the stuff before the expanded part.
4516 * Copy the expanded stuff.
4517 * Copy what came after the expanded part.
4518 * Copy the next commands, if there are any.
4520 i = (int)(src - *cmdlinep); /* length of part before match */
4521 mch_memmove(new_cmdline, *cmdlinep, (size_t)i);
4523 mch_memmove(new_cmdline + i, repl, (size_t)len);
4524 i += len; /* remember the end of the string */
4525 STRCPY(new_cmdline + i, src + srclen);
4526 src = new_cmdline + i; /* remember where to continue */
4528 if (eap->nextcmd != NULL) /* append next command */
4530 i = (int)STRLEN(new_cmdline) + 1;
4531 STRCPY(new_cmdline + i, eap->nextcmd);
4532 eap->nextcmd = new_cmdline + i;
4534 eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4535 eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4536 if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command)
4537 eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4538 vim_free(*cmdlinep);
4539 *cmdlinep = new_cmdline;
4541 return src;
4545 * Check for '|' to separate commands and '"' to start comments.
4547 void
4548 separate_nextcmd(eap)
4549 exarg_T *eap;
4551 char_u *p;
4553 #ifdef FEAT_QUICKFIX
4554 p = skip_grep_pat(eap);
4555 #else
4556 p = eap->arg;
4557 #endif
4559 for ( ; *p; mb_ptr_adv(p))
4561 if (*p == Ctrl_V)
4563 if (eap->argt & (USECTRLV | XFILE))
4564 ++p; /* skip CTRL-V and next char */
4565 else
4566 /* remove CTRL-V and skip next char */
4567 STRMOVE(p, p + 1);
4568 if (*p == NUL) /* stop at NUL after CTRL-V */
4569 break;
4572 #ifdef FEAT_EVAL
4573 /* Skip over `=expr` when wildcards are expanded. */
4574 else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE))
4576 p += 2;
4577 (void)skip_expr(&p);
4579 #endif
4581 /* Check for '"': start of comment or '|': next command */
4582 /* :@" and :*" do not start a comment!
4583 * :redir @" doesn't either. */
4584 else if ((*p == '"' && !(eap->argt & NOTRLCOM)
4585 && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star)
4586 || p != eap->arg)
4587 && (eap->cmdidx != CMD_redir
4588 || p != eap->arg + 1 || p[-1] != '@'))
4589 || *p == '|' || *p == '\n')
4592 * We remove the '\' before the '|', unless USECTRLV is used
4593 * AND 'b' is present in 'cpoptions'.
4595 if ((vim_strchr(p_cpo, CPO_BAR) == NULL
4596 || !(eap->argt & USECTRLV)) && *(p - 1) == '\\')
4598 STRMOVE(p - 1, p); /* remove the '\' */
4599 --p;
4601 else
4603 eap->nextcmd = check_nextcmd(p);
4604 *p = NUL;
4605 break;
4610 if (!(eap->argt & NOTRLCOM)) /* remove trailing spaces */
4611 del_trailing_spaces(eap->arg);
4615 * get + command from ex argument
4617 static char_u *
4618 getargcmd(argp)
4619 char_u **argp;
4621 char_u *arg = *argp;
4622 char_u *command = NULL;
4624 if (*arg == '+') /* +[command] */
4626 ++arg;
4627 if (vim_isspace(*arg))
4628 command = dollar_command;
4629 else
4631 command = arg;
4632 arg = skip_cmd_arg(command, TRUE);
4633 if (*arg != NUL)
4634 *arg++ = NUL; /* terminate command with NUL */
4637 arg = skipwhite(arg); /* skip over spaces */
4638 *argp = arg;
4640 return command;
4644 * Find end of "+command" argument. Skip over "\ " and "\\".
4646 static char_u *
4647 skip_cmd_arg(p, rembs)
4648 char_u *p;
4649 int rembs; /* TRUE to halve the number of backslashes */
4651 while (*p && !vim_isspace(*p))
4653 if (*p == '\\' && p[1] != NUL)
4655 if (rembs)
4656 STRMOVE(p, p + 1);
4657 else
4658 ++p;
4660 mb_ptr_adv(p);
4662 return p;
4666 * Get "++opt=arg" argument.
4667 * Return FAIL or OK.
4669 static int
4670 getargopt(eap)
4671 exarg_T *eap;
4673 char_u *arg = eap->arg + 2;
4674 int *pp = NULL;
4675 #ifdef FEAT_MBYTE
4676 char_u *p;
4677 #endif
4679 /* ":edit ++[no]bin[ary] file" */
4680 if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0)
4682 if (*arg == 'n')
4684 arg += 2;
4685 eap->force_bin = FORCE_NOBIN;
4687 else
4688 eap->force_bin = FORCE_BIN;
4689 if (!checkforcmd(&arg, "binary", 3))
4690 return FAIL;
4691 eap->arg = skipwhite(arg);
4692 return OK;
4695 /* ":read ++edit file" */
4696 if (STRNCMP(arg, "edit", 4) == 0)
4698 eap->read_edit = TRUE;
4699 eap->arg = skipwhite(arg + 4);
4700 return OK;
4703 if (STRNCMP(arg, "ff", 2) == 0)
4705 arg += 2;
4706 pp = &eap->force_ff;
4708 else if (STRNCMP(arg, "fileformat", 10) == 0)
4710 arg += 10;
4711 pp = &eap->force_ff;
4713 #ifdef FEAT_MBYTE
4714 else if (STRNCMP(arg, "enc", 3) == 0)
4716 arg += 3;
4717 pp = &eap->force_enc;
4719 else if (STRNCMP(arg, "encoding", 8) == 0)
4721 arg += 8;
4722 pp = &eap->force_enc;
4724 else if (STRNCMP(arg, "bad", 3) == 0)
4726 arg += 3;
4727 pp = &eap->bad_char;
4729 #endif
4731 if (pp == NULL || *arg != '=')
4732 return FAIL;
4734 ++arg;
4735 *pp = (int)(arg - eap->cmd);
4736 arg = skip_cmd_arg(arg, FALSE);
4737 eap->arg = skipwhite(arg);
4738 *arg = NUL;
4740 #ifdef FEAT_MBYTE
4741 if (pp == &eap->force_ff)
4743 #endif
4744 if (check_ff_value(eap->cmd + eap->force_ff) == FAIL)
4745 return FAIL;
4746 #ifdef FEAT_MBYTE
4748 else if (pp == &eap->force_enc)
4750 /* Make 'fileencoding' lower case. */
4751 for (p = eap->cmd + eap->force_enc; *p != NUL; ++p)
4752 *p = TOLOWER_ASC(*p);
4754 else
4756 /* Check ++bad= argument. Must be a single-byte character, "keep" or
4757 * "drop". */
4758 p = eap->cmd + eap->bad_char;
4759 if (STRICMP(p, "keep") == 0)
4760 eap->bad_char = BAD_KEEP;
4761 else if (STRICMP(p, "drop") == 0)
4762 eap->bad_char = BAD_DROP;
4763 else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL)
4764 eap->bad_char = *p;
4765 else
4766 return FAIL;
4768 #endif
4770 return OK;
4774 * ":abbreviate" and friends.
4776 static void
4777 ex_abbreviate(eap)
4778 exarg_T *eap;
4780 do_exmap(eap, TRUE); /* almost the same as mapping */
4784 * ":map" and friends.
4786 static void
4787 ex_map(eap)
4788 exarg_T *eap;
4791 * If we are sourcing .exrc or .vimrc in current directory we
4792 * print the mappings for security reasons.
4794 if (secure)
4796 secure = 2;
4797 msg_outtrans(eap->cmd);
4798 msg_putchar('\n');
4800 do_exmap(eap, FALSE);
4804 * ":unmap" and friends.
4806 static void
4807 ex_unmap(eap)
4808 exarg_T *eap;
4810 do_exmap(eap, FALSE);
4814 * ":mapclear" and friends.
4816 static void
4817 ex_mapclear(eap)
4818 exarg_T *eap;
4820 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
4824 * ":abclear" and friends.
4826 static void
4827 ex_abclear(eap)
4828 exarg_T *eap;
4830 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
4833 #ifdef FEAT_AUTOCMD
4834 static void
4835 ex_autocmd(eap)
4836 exarg_T *eap;
4839 * Disallow auto commands from .exrc and .vimrc in current
4840 * directory for security reasons.
4842 if (secure)
4844 secure = 2;
4845 eap->errmsg = e_curdir;
4847 else if (eap->cmdidx == CMD_autocmd)
4848 do_autocmd(eap->arg, eap->forceit);
4849 else
4850 do_augroup(eap->arg, eap->forceit);
4854 * ":doautocmd": Apply the automatic commands to the current buffer.
4856 static void
4857 ex_doautocmd(eap)
4858 exarg_T *eap;
4860 (void)do_doautocmd(eap->arg, TRUE);
4861 do_modelines(0);
4863 #endif
4865 #ifdef FEAT_LISTCMDS
4867 * :[N]bunload[!] [N] [bufname] unload buffer
4868 * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4869 * :[N]bwipeout[!] [N] [bufname] delete buffer really
4871 static void
4872 ex_bunload(eap)
4873 exarg_T *eap;
4875 eap->errmsg = do_bufdel(
4876 eap->cmdidx == CMD_bdelete ? DOBUF_DEL
4877 : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE
4878 : DOBUF_UNLOAD, eap->arg,
4879 eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit);
4883 * :[N]buffer [N] to buffer N
4884 * :[N]sbuffer [N] to buffer N
4886 static void
4887 ex_buffer(eap)
4888 exarg_T *eap;
4890 if (*eap->arg)
4891 eap->errmsg = e_trailing;
4892 else
4894 if (eap->addr_count == 0) /* default is current buffer */
4895 goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4896 else
4897 goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4902 * :[N]bmodified [N] to next mod. buffer
4903 * :[N]sbmodified [N] to next mod. buffer
4905 static void
4906 ex_bmodified(eap)
4907 exarg_T *eap;
4909 goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4913 * :[N]bnext [N] to next buffer
4914 * :[N]sbnext [N] split and to next buffer
4916 static void
4917 ex_bnext(eap)
4918 exarg_T *eap;
4920 goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4924 * :[N]bNext [N] to previous buffer
4925 * :[N]bprevious [N] to previous buffer
4926 * :[N]sbNext [N] split and to previous buffer
4927 * :[N]sbprevious [N] split and to previous buffer
4929 static void
4930 ex_bprevious(eap)
4931 exarg_T *eap;
4933 goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4937 * :brewind to first buffer
4938 * :bfirst to first buffer
4939 * :sbrewind split and to first buffer
4940 * :sbfirst split and to first buffer
4942 static void
4943 ex_brewind(eap)
4944 exarg_T *eap;
4946 goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4950 * :blast to last buffer
4951 * :sblast split and to last buffer
4953 static void
4954 ex_blast(eap)
4955 exarg_T *eap;
4957 goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4959 #endif
4962 ends_excmd(c)
4963 int c;
4965 return (c == NUL || c == '|' || c == '"' || c == '\n');
4968 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \
4969 || defined(PROTO)
4971 * Return the next command, after the first '|' or '\n'.
4972 * Return NULL if not found.
4974 char_u *
4975 find_nextcmd(p)
4976 char_u *p;
4978 while (*p != '|' && *p != '\n')
4980 if (*p == NUL)
4981 return NULL;
4982 ++p;
4984 return (p + 1);
4986 #endif
4989 * Check if *p is a separator between Ex commands.
4990 * Return NULL if it isn't, (p + 1) if it is.
4992 char_u *
4993 check_nextcmd(p)
4994 char_u *p;
4996 p = skipwhite(p);
4997 if (*p == '|' || *p == '\n')
4998 return (p + 1);
4999 else
5000 return NULL;
5004 * - if there are more files to edit
5005 * - and this is the last window
5006 * - and forceit not used
5007 * - and not repeated twice on a row
5008 * return FAIL and give error message if 'message' TRUE
5009 * return OK otherwise
5011 static int
5012 check_more(message, forceit)
5013 int message; /* when FALSE check only, no messages */
5014 int forceit;
5016 int n = ARGCOUNT - curwin->w_arg_idx - 1;
5018 if (!forceit && only_one_window()
5019 && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0)
5021 if (message)
5023 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5024 if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL)
5026 char_u buff[IOSIZE];
5028 if (n == 1)
5029 STRCPY(buff, _("1 more file to edit. Quit anyway?"));
5030 else
5031 vim_snprintf((char *)buff, IOSIZE,
5032 _("%d more files to edit. Quit anyway?"), n);
5033 if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES)
5034 return OK;
5035 return FAIL;
5037 #endif
5038 if (n == 1)
5039 EMSG(_("E173: 1 more file to edit"));
5040 else
5041 EMSGN(_("E173: %ld more files to edit"), n);
5042 quitmore = 2; /* next try to quit is allowed */
5044 return FAIL;
5046 return OK;
5049 #ifdef FEAT_CMDL_COMPL
5051 * Function given to ExpandGeneric() to obtain the list of command names.
5053 /*ARGSUSED*/
5054 char_u *
5055 get_command_name(xp, idx)
5056 expand_T *xp;
5057 int idx;
5059 if (idx >= (int)CMD_SIZE)
5060 # ifdef FEAT_USR_CMDS
5061 return get_user_command_name(idx);
5062 # else
5063 return NULL;
5064 # endif
5065 return cmdnames[idx].cmd_name;
5067 #endif
5069 #if defined(FEAT_USR_CMDS) || defined(PROTO)
5070 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));
5071 static void uc_list __ARGS((char_u *name, size_t name_len));
5072 static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg));
5073 static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp));
5074 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));
5076 static int
5077 uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force)
5078 char_u *name;
5079 size_t name_len;
5080 char_u *rep;
5081 long argt;
5082 long def;
5083 int flags;
5084 int compl;
5085 char_u *compl_arg;
5086 int force;
5088 ucmd_T *cmd = NULL;
5089 char_u *p;
5090 int i;
5091 int cmp = 1;
5092 char_u *rep_buf = NULL;
5093 garray_T *gap;
5095 replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE);
5096 if (rep_buf == NULL)
5098 /* Can't replace termcodes - try using the string as is */
5099 rep_buf = vim_strsave(rep);
5101 /* Give up if out of memory */
5102 if (rep_buf == NULL)
5103 return FAIL;
5106 /* get address of growarray: global or in curbuf */
5107 if (flags & UC_BUFFER)
5109 gap = &curbuf->b_ucmds;
5110 if (gap->ga_itemsize == 0)
5111 ga_init2(gap, (int)sizeof(ucmd_T), 4);
5113 else
5114 gap = &ucmds;
5116 /* Search for the command in the already defined commands. */
5117 for (i = 0; i < gap->ga_len; ++i)
5119 size_t len;
5121 cmd = USER_CMD_GA(gap, i);
5122 len = STRLEN(cmd->uc_name);
5123 cmp = STRNCMP(name, cmd->uc_name, name_len);
5124 if (cmp == 0)
5126 if (name_len < len)
5127 cmp = -1;
5128 else if (name_len > len)
5129 cmp = 1;
5132 if (cmp == 0)
5134 if (!force)
5136 EMSG(_("E174: Command already exists: add ! to replace it"));
5137 goto fail;
5140 vim_free(cmd->uc_rep);
5141 cmd->uc_rep = 0;
5142 break;
5145 /* Stop as soon as we pass the name to add */
5146 if (cmp < 0)
5147 break;
5150 /* Extend the array unless we're replacing an existing command */
5151 if (cmp != 0)
5153 if (ga_grow(gap, 1) != OK)
5154 goto fail;
5155 if ((p = vim_strnsave(name, (int)name_len)) == NULL)
5156 goto fail;
5158 cmd = USER_CMD_GA(gap, i);
5159 mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T));
5161 ++gap->ga_len;
5163 cmd->uc_name = p;
5166 cmd->uc_rep = rep_buf;
5167 cmd->uc_argt = argt;
5168 cmd->uc_def = def;
5169 cmd->uc_compl = compl;
5170 #ifdef FEAT_EVAL
5171 cmd->uc_scriptID = current_SID;
5172 # ifdef FEAT_CMDL_COMPL
5173 cmd->uc_compl_arg = compl_arg;
5174 # endif
5175 #endif
5177 return OK;
5179 fail:
5180 vim_free(rep_buf);
5181 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5182 vim_free(compl_arg);
5183 #endif
5184 return FAIL;
5188 * List of names for completion for ":command" with the EXPAND_ flag.
5189 * Must be alphabetical for completion.
5191 static struct
5193 int expand;
5194 char *name;
5195 } command_complete[] =
5197 {EXPAND_AUGROUP, "augroup"},
5198 {EXPAND_BUFFERS, "buffer"},
5199 {EXPAND_COMMANDS, "command"},
5200 #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5201 {EXPAND_USER_DEFINED, "custom"},
5202 {EXPAND_USER_LIST, "customlist"},
5203 #endif
5204 {EXPAND_DIRECTORIES, "dir"},
5205 {EXPAND_ENV_VARS, "environment"},
5206 {EXPAND_EVENTS, "event"},
5207 {EXPAND_EXPRESSION, "expression"},
5208 {EXPAND_FILES, "file"},
5209 {EXPAND_FUNCTIONS, "function"},
5210 {EXPAND_HELP, "help"},
5211 {EXPAND_HIGHLIGHT, "highlight"},
5212 {EXPAND_MAPPINGS, "mapping"},
5213 {EXPAND_MENUS, "menu"},
5214 {EXPAND_SETTINGS, "option"},
5215 {EXPAND_SHELLCMD, "shellcmd"},
5216 {EXPAND_TAGS, "tag"},
5217 {EXPAND_TAGS_LISTFILES, "tag_listfiles"},
5218 {EXPAND_USER_VARS, "var"},
5219 {0, NULL}
5222 static void
5223 uc_list(name, name_len)
5224 char_u *name;
5225 size_t name_len;
5227 int i, j;
5228 int found = FALSE;
5229 ucmd_T *cmd;
5230 int len;
5231 long a;
5232 garray_T *gap;
5234 gap = &curbuf->b_ucmds;
5235 for (;;)
5237 for (i = 0; i < gap->ga_len; ++i)
5239 cmd = USER_CMD_GA(gap, i);
5240 a = (long)cmd->uc_argt;
5242 /* Skip commands which don't match the requested prefix */
5243 if (STRNCMP(name, cmd->uc_name, name_len) != 0)
5244 continue;
5246 /* Put out the title first time */
5247 if (!found)
5248 MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition"));
5249 found = TRUE;
5250 msg_putchar('\n');
5251 if (got_int)
5252 break;
5254 /* Special cases */
5255 msg_putchar(a & BANG ? '!' : ' ');
5256 msg_putchar(a & REGSTR ? '"' : ' ');
5257 msg_putchar(gap != &ucmds ? 'b' : ' ');
5258 msg_putchar(' ');
5260 msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D));
5261 len = (int)STRLEN(cmd->uc_name) + 4;
5263 do {
5264 msg_putchar(' ');
5265 ++len;
5266 } while (len < 16);
5268 len = 0;
5270 /* Arguments */
5271 switch ((int)(a & (EXTRA|NOSPC|NEEDARG)))
5273 case 0: IObuff[len++] = '0'; break;
5274 case (EXTRA): IObuff[len++] = '*'; break;
5275 case (EXTRA|NOSPC): IObuff[len++] = '?'; break;
5276 case (EXTRA|NEEDARG): IObuff[len++] = '+'; break;
5277 case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break;
5280 do {
5281 IObuff[len++] = ' ';
5282 } while (len < 5);
5284 /* Range */
5285 if (a & (RANGE|COUNT))
5287 if (a & COUNT)
5289 /* -count=N */
5290 sprintf((char *)IObuff + len, "%ldc", cmd->uc_def);
5291 len += (int)STRLEN(IObuff + len);
5293 else if (a & DFLALL)
5294 IObuff[len++] = '%';
5295 else if (cmd->uc_def >= 0)
5297 /* -range=N */
5298 sprintf((char *)IObuff + len, "%ld", cmd->uc_def);
5299 len += (int)STRLEN(IObuff + len);
5301 else
5302 IObuff[len++] = '.';
5305 do {
5306 IObuff[len++] = ' ';
5307 } while (len < 11);
5309 /* Completion */
5310 for (j = 0; command_complete[j].expand != 0; ++j)
5311 if (command_complete[j].expand == cmd->uc_compl)
5313 STRCPY(IObuff + len, command_complete[j].name);
5314 len += (int)STRLEN(IObuff + len);
5315 break;
5318 do {
5319 IObuff[len++] = ' ';
5320 } while (len < 21);
5322 IObuff[len] = '\0';
5323 msg_outtrans(IObuff);
5325 msg_outtrans_special(cmd->uc_rep, FALSE);
5326 #ifdef FEAT_EVAL
5327 if (p_verbose > 0)
5328 last_set_msg(cmd->uc_scriptID);
5329 #endif
5330 out_flush();
5331 ui_breakcheck();
5332 if (got_int)
5333 break;
5335 if (gap == &ucmds || i < gap->ga_len)
5336 break;
5337 gap = &ucmds;
5340 if (!found)
5341 MSG(_("No user-defined commands found"));
5344 static char_u *
5345 uc_fun_cmd()
5347 static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4,
5348 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60,
5349 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2,
5350 0xb9, 0x7f, 0};
5351 int i;
5353 for (i = 0; fcmd[i]; ++i)
5354 IObuff[i] = fcmd[i] - 0x40;
5355 IObuff[i] = 0;
5356 return IObuff;
5359 static int
5360 uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg)
5361 char_u *attr;
5362 size_t len;
5363 long *argt;
5364 long *def;
5365 int *flags;
5366 int *compl;
5367 char_u **compl_arg;
5369 char_u *p;
5371 if (len == 0)
5373 EMSG(_("E175: No attribute specified"));
5374 return FAIL;
5377 /* First, try the simple attributes (no arguments) */
5378 if (STRNICMP(attr, "bang", len) == 0)
5379 *argt |= BANG;
5380 else if (STRNICMP(attr, "buffer", len) == 0)
5381 *flags |= UC_BUFFER;
5382 else if (STRNICMP(attr, "register", len) == 0)
5383 *argt |= REGSTR;
5384 else if (STRNICMP(attr, "bar", len) == 0)
5385 *argt |= TRLBAR;
5386 else
5388 int i;
5389 char_u *val = NULL;
5390 size_t vallen = 0;
5391 size_t attrlen = len;
5393 /* Look for the attribute name - which is the part before any '=' */
5394 for (i = 0; i < (int)len; ++i)
5396 if (attr[i] == '=')
5398 val = &attr[i + 1];
5399 vallen = len - i - 1;
5400 attrlen = i;
5401 break;
5405 if (STRNICMP(attr, "nargs", attrlen) == 0)
5407 if (vallen == 1)
5409 if (*val == '0')
5410 /* Do nothing - this is the default */;
5411 else if (*val == '1')
5412 *argt |= (EXTRA | NOSPC | NEEDARG);
5413 else if (*val == '*')
5414 *argt |= EXTRA;
5415 else if (*val == '?')
5416 *argt |= (EXTRA | NOSPC);
5417 else if (*val == '+')
5418 *argt |= (EXTRA | NEEDARG);
5419 else
5420 goto wrong_nargs;
5422 else
5424 wrong_nargs:
5425 EMSG(_("E176: Invalid number of arguments"));
5426 return FAIL;
5429 else if (STRNICMP(attr, "range", attrlen) == 0)
5431 *argt |= RANGE;
5432 if (vallen == 1 && *val == '%')
5433 *argt |= DFLALL;
5434 else if (val != NULL)
5436 p = val;
5437 if (*def >= 0)
5439 two_count:
5440 EMSG(_("E177: Count cannot be specified twice"));
5441 return FAIL;
5444 *def = getdigits(&p);
5445 *argt |= (ZEROR | NOTADR);
5447 if (p != val + vallen || vallen == 0)
5449 invalid_count:
5450 EMSG(_("E178: Invalid default value for count"));
5451 return FAIL;
5455 else if (STRNICMP(attr, "count", attrlen) == 0)
5457 *argt |= (COUNT | ZEROR | RANGE | NOTADR);
5459 if (val != NULL)
5461 p = val;
5462 if (*def >= 0)
5463 goto two_count;
5465 *def = getdigits(&p);
5467 if (p != val + vallen)
5468 goto invalid_count;
5471 if (*def < 0)
5472 *def = 0;
5474 else if (STRNICMP(attr, "complete", attrlen) == 0)
5476 if (val == NULL)
5478 EMSG(_("E179: argument required for -complete"));
5479 return FAIL;
5482 if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg)
5483 == FAIL)
5484 return FAIL;
5486 else
5488 char_u ch = attr[len];
5489 attr[len] = '\0';
5490 EMSG2(_("E181: Invalid attribute: %s"), attr);
5491 attr[len] = ch;
5492 return FAIL;
5496 return OK;
5499 static void
5500 ex_command(eap)
5501 exarg_T *eap;
5503 char_u *name;
5504 char_u *end;
5505 char_u *p;
5506 long argt = 0;
5507 long def = -1;
5508 int flags = 0;
5509 int compl = EXPAND_NOTHING;
5510 char_u *compl_arg = NULL;
5511 int has_attr = (eap->arg[0] == '-');
5513 p = eap->arg;
5515 /* Check for attributes */
5516 while (*p == '-')
5518 ++p;
5519 end = skiptowhite(p);
5520 if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg)
5521 == FAIL)
5522 return;
5523 p = skipwhite(end);
5526 /* Get the name (if any) and skip to the following argument */
5527 name = p;
5528 if (ASCII_ISALPHA(*p))
5529 while (ASCII_ISALNUM(*p))
5530 ++p;
5531 if (!ends_excmd(*p) && !vim_iswhite(*p))
5533 EMSG(_("E182: Invalid command name"));
5534 return;
5536 end = p;
5538 /* If there is nothing after the name, and no attributes were specified,
5539 * we are listing commands
5541 p = skipwhite(end);
5542 if (!has_attr && ends_excmd(*p))
5544 uc_list(name, end - name);
5546 else if (!ASCII_ISUPPER(*name))
5548 EMSG(_("E183: User defined commands must start with an uppercase letter"));
5549 return;
5551 else
5552 uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
5553 eap->forceit);
5557 * ":comclear"
5558 * Clear all user commands, global and for current buffer.
5560 /*ARGSUSED*/
5561 void
5562 ex_comclear(eap)
5563 exarg_T *eap;
5565 uc_clear(&ucmds);
5566 uc_clear(&curbuf->b_ucmds);
5570 * Clear all user commands for "gap".
5572 void
5573 uc_clear(gap)
5574 garray_T *gap;
5576 int i;
5577 ucmd_T *cmd;
5579 for (i = 0; i < gap->ga_len; ++i)
5581 cmd = USER_CMD_GA(gap, i);
5582 vim_free(cmd->uc_name);
5583 vim_free(cmd->uc_rep);
5584 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5585 vim_free(cmd->uc_compl_arg);
5586 # endif
5588 ga_clear(gap);
5591 static void
5592 ex_delcommand(eap)
5593 exarg_T *eap;
5595 int i = 0;
5596 ucmd_T *cmd = NULL;
5597 int cmp = -1;
5598 garray_T *gap;
5600 gap = &curbuf->b_ucmds;
5601 for (;;)
5603 for (i = 0; i < gap->ga_len; ++i)
5605 cmd = USER_CMD_GA(gap, i);
5606 cmp = STRCMP(eap->arg, cmd->uc_name);
5607 if (cmp <= 0)
5608 break;
5610 if (gap == &ucmds || cmp == 0)
5611 break;
5612 gap = &ucmds;
5615 if (cmp != 0)
5617 EMSG2(_("E184: No such user-defined command: %s"), eap->arg);
5618 return;
5621 vim_free(cmd->uc_name);
5622 vim_free(cmd->uc_rep);
5623 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
5624 vim_free(cmd->uc_compl_arg);
5625 # endif
5627 --gap->ga_len;
5629 if (i < gap->ga_len)
5630 mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T));
5634 * split and quote args for <f-args>
5636 static char_u *
5637 uc_split_args(arg, lenp)
5638 char_u *arg;
5639 size_t *lenp;
5641 char_u *buf;
5642 char_u *p;
5643 char_u *q;
5644 int len;
5646 /* Precalculate length */
5647 p = arg;
5648 len = 2; /* Initial and final quotes */
5650 while (*p)
5652 if (p[0] == '\\' && p[1] == '\\')
5654 len += 2;
5655 p += 2;
5657 else if (p[0] == '\\' && vim_iswhite(p[1]))
5659 len += 1;
5660 p += 2;
5662 else if (*p == '\\' || *p == '"')
5664 len += 2;
5665 p += 1;
5667 else if (vim_iswhite(*p))
5669 p = skipwhite(p);
5670 if (*p == NUL)
5671 break;
5672 len += 3; /* "," */
5674 else
5676 ++len;
5677 ++p;
5681 buf = alloc(len + 1);
5682 if (buf == NULL)
5684 *lenp = 0;
5685 return buf;
5688 p = arg;
5689 q = buf;
5690 *q++ = '"';
5691 while (*p)
5693 if (p[0] == '\\' && p[1] == '\\')
5695 *q++ = '\\';
5696 *q++ = '\\';
5697 p += 2;
5699 else if (p[0] == '\\' && vim_iswhite(p[1]))
5701 *q++ = p[1];
5702 p += 2;
5704 else if (*p == '\\' || *p == '"')
5706 *q++ = '\\';
5707 *q++ = *p++;
5709 else if (vim_iswhite(*p))
5711 p = skipwhite(p);
5712 if (*p == NUL)
5713 break;
5714 *q++ = '"';
5715 *q++ = ',';
5716 *q++ = '"';
5718 else
5720 *q++ = *p++;
5723 *q++ = '"';
5724 *q = 0;
5726 *lenp = len;
5727 return buf;
5731 * Check for a <> code in a user command.
5732 * "code" points to the '<'. "len" the length of the <> (inclusive).
5733 * "buf" is where the result is to be added.
5734 * "split_buf" points to a buffer used for splitting, caller should free it.
5735 * "split_len" is the length of what "split_buf" contains.
5736 * Returns the length of the replacement, which has been added to "buf".
5737 * Returns -1 if there was no match, and only the "<" has been copied.
5739 static size_t
5740 uc_check_code(code, len, buf, cmd, eap, split_buf, split_len)
5741 char_u *code;
5742 size_t len;
5743 char_u *buf;
5744 ucmd_T *cmd; /* the user command we're expanding */
5745 exarg_T *eap; /* ex arguments */
5746 char_u **split_buf;
5747 size_t *split_len;
5749 size_t result = 0;
5750 char_u *p = code + 1;
5751 size_t l = len - 2;
5752 int quote = 0;
5753 enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER,
5754 ct_LT, ct_NONE } type = ct_NONE;
5756 if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-')
5758 quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
5759 p += 2;
5760 l -= 2;
5763 ++l;
5764 if (l <= 1)
5765 type = ct_NONE;
5766 else if (STRNICMP(p, "args>", l) == 0)
5767 type = ct_ARGS;
5768 else if (STRNICMP(p, "bang>", l) == 0)
5769 type = ct_BANG;
5770 else if (STRNICMP(p, "count>", l) == 0)
5771 type = ct_COUNT;
5772 else if (STRNICMP(p, "line1>", l) == 0)
5773 type = ct_LINE1;
5774 else if (STRNICMP(p, "line2>", l) == 0)
5775 type = ct_LINE2;
5776 else if (STRNICMP(p, "lt>", l) == 0)
5777 type = ct_LT;
5778 else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0)
5779 type = ct_REGISTER;
5781 switch (type)
5783 case ct_ARGS:
5784 /* Simple case first */
5785 if (*eap->arg == NUL)
5787 if (quote == 1)
5789 result = 2;
5790 if (buf != NULL)
5791 STRCPY(buf, "''");
5793 else
5794 result = 0;
5795 break;
5798 /* When specified there is a single argument don't split it.
5799 * Works for ":Cmd %" when % is "a b c". */
5800 if ((eap->argt & NOSPC) && quote == 2)
5801 quote = 1;
5803 switch (quote)
5805 case 0: /* No quoting, no splitting */
5806 result = STRLEN(eap->arg);
5807 if (buf != NULL)
5808 STRCPY(buf, eap->arg);
5809 break;
5810 case 1: /* Quote, but don't split */
5811 result = STRLEN(eap->arg) + 2;
5812 for (p = eap->arg; *p; ++p)
5814 if (*p == '\\' || *p == '"')
5815 ++result;
5818 if (buf != NULL)
5820 *buf++ = '"';
5821 for (p = eap->arg; *p; ++p)
5823 if (*p == '\\' || *p == '"')
5824 *buf++ = '\\';
5825 *buf++ = *p;
5827 *buf = '"';
5830 break;
5831 case 2: /* Quote and split (<f-args>) */
5832 /* This is hard, so only do it once, and cache the result */
5833 if (*split_buf == NULL)
5834 *split_buf = uc_split_args(eap->arg, split_len);
5836 result = *split_len;
5837 if (buf != NULL && result != 0)
5838 STRCPY(buf, *split_buf);
5840 break;
5842 break;
5844 case ct_BANG:
5845 result = eap->forceit ? 1 : 0;
5846 if (quote)
5847 result += 2;
5848 if (buf != NULL)
5850 if (quote)
5851 *buf++ = '"';
5852 if (eap->forceit)
5853 *buf++ = '!';
5854 if (quote)
5855 *buf = '"';
5857 break;
5859 case ct_LINE1:
5860 case ct_LINE2:
5861 case ct_COUNT:
5863 char num_buf[20];
5864 long num = (type == ct_LINE1) ? eap->line1 :
5865 (type == ct_LINE2) ? eap->line2 :
5866 (eap->addr_count > 0) ? eap->line2 : cmd->uc_def;
5867 size_t num_len;
5869 sprintf(num_buf, "%ld", num);
5870 num_len = STRLEN(num_buf);
5871 result = num_len;
5873 if (quote)
5874 result += 2;
5876 if (buf != NULL)
5878 if (quote)
5879 *buf++ = '"';
5880 STRCPY(buf, num_buf);
5881 buf += num_len;
5882 if (quote)
5883 *buf = '"';
5886 break;
5889 case ct_REGISTER:
5890 result = eap->regname ? 1 : 0;
5891 if (quote)
5892 result += 2;
5893 if (buf != NULL)
5895 if (quote)
5896 *buf++ = '\'';
5897 if (eap->regname)
5898 *buf++ = eap->regname;
5899 if (quote)
5900 *buf = '\'';
5902 break;
5904 case ct_LT:
5905 result = 1;
5906 if (buf != NULL)
5907 *buf = '<';
5908 break;
5910 default:
5911 /* Not recognized: just copy the '<' and return -1. */
5912 result = (size_t)-1;
5913 if (buf != NULL)
5914 *buf = '<';
5915 break;
5918 return result;
5921 static void
5922 do_ucmd(eap)
5923 exarg_T *eap;
5925 char_u *buf;
5926 char_u *p;
5927 char_u *q;
5929 char_u *start;
5930 char_u *end;
5931 size_t len, totlen;
5933 size_t split_len = 0;
5934 char_u *split_buf = NULL;
5935 ucmd_T *cmd;
5936 #ifdef FEAT_EVAL
5937 scid_T save_current_SID = current_SID;
5938 #endif
5940 if (eap->cmdidx == CMD_USER)
5941 cmd = USER_CMD(eap->useridx);
5942 else
5943 cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
5946 * Replace <> in the command by the arguments.
5948 buf = NULL;
5949 for (;;)
5951 p = cmd->uc_rep;
5952 q = buf;
5953 totlen = 0;
5954 while ((start = vim_strchr(p, '<')) != NULL
5955 && (end = vim_strchr(start + 1, '>')) != NULL)
5957 /* Include the '>' */
5958 ++end;
5960 /* Take everything up to the '<' */
5961 len = start - p;
5962 if (buf == NULL)
5963 totlen += len;
5964 else
5966 mch_memmove(q, p, len);
5967 q += len;
5970 len = uc_check_code(start, end - start, q, cmd, eap,
5971 &split_buf, &split_len);
5972 if (len == (size_t)-1)
5974 /* no match, continue after '<' */
5975 p = start + 1;
5976 len = 1;
5978 else
5979 p = end;
5980 if (buf == NULL)
5981 totlen += len;
5982 else
5983 q += len;
5985 if (buf != NULL) /* second time here, finished */
5987 STRCPY(q, p);
5988 break;
5991 totlen += STRLEN(p); /* Add on the trailing characters */
5992 buf = alloc((unsigned)(totlen + 1));
5993 if (buf == NULL)
5995 vim_free(split_buf);
5996 return;
6000 #ifdef FEAT_EVAL
6001 current_SID = cmd->uc_scriptID;
6002 #endif
6003 (void)do_cmdline(buf, eap->getline, eap->cookie,
6004 DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
6005 #ifdef FEAT_EVAL
6006 current_SID = save_current_SID;
6007 #endif
6008 vim_free(buf);
6009 vim_free(split_buf);
6012 # if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6013 static char_u *
6014 get_user_command_name(idx)
6015 int idx;
6017 return get_user_commands(NULL, idx - (int)CMD_SIZE);
6021 * Function given to ExpandGeneric() to obtain the list of user command names.
6023 /*ARGSUSED*/
6024 char_u *
6025 get_user_commands(xp, idx)
6026 expand_T *xp;
6027 int idx;
6029 if (idx < curbuf->b_ucmds.ga_len)
6030 return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name;
6031 idx -= curbuf->b_ucmds.ga_len;
6032 if (idx < ucmds.ga_len)
6033 return USER_CMD(idx)->uc_name;
6034 return NULL;
6038 * Function given to ExpandGeneric() to obtain the list of user command
6039 * attributes.
6041 /*ARGSUSED*/
6042 char_u *
6043 get_user_cmd_flags(xp, idx)
6044 expand_T *xp;
6045 int idx;
6047 static char *user_cmd_flags[] =
6048 {"bang", "bar", "buffer", "complete", "count",
6049 "nargs", "range", "register"};
6051 if (idx >= sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0]))
6052 return NULL;
6053 return (char_u *)user_cmd_flags[idx];
6057 * Function given to ExpandGeneric() to obtain the list of values for -nargs.
6059 /*ARGSUSED*/
6060 char_u *
6061 get_user_cmd_nargs(xp, idx)
6062 expand_T *xp;
6063 int idx;
6065 static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"};
6067 if (idx >= sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0]))
6068 return NULL;
6069 return (char_u *)user_cmd_nargs[idx];
6073 * Function given to ExpandGeneric() to obtain the list of values for -complete.
6075 /*ARGSUSED*/
6076 char_u *
6077 get_user_cmd_complete(xp, idx)
6078 expand_T *xp;
6079 int idx;
6081 return (char_u *)command_complete[idx].name;
6083 # endif /* FEAT_CMDL_COMPL */
6085 #endif /* FEAT_USR_CMDS */
6087 #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO)
6089 * Parse a completion argument "value[vallen]".
6090 * The detected completion goes in "*complp", argument type in "*argt".
6091 * When there is an argument, for function and user defined completion, it's
6092 * copied to allocated memory and stored in "*compl_arg".
6093 * Returns FAIL if something is wrong.
6096 parse_compl_arg(value, vallen, complp, argt, compl_arg)
6097 char_u *value;
6098 int vallen;
6099 int *complp;
6100 long *argt;
6101 char_u **compl_arg;
6103 char_u *arg = NULL;
6104 size_t arglen = 0;
6105 int i;
6106 int valend = vallen;
6108 /* Look for any argument part - which is the part after any ',' */
6109 for (i = 0; i < vallen; ++i)
6111 if (value[i] == ',')
6113 arg = &value[i + 1];
6114 arglen = vallen - i - 1;
6115 valend = i;
6116 break;
6120 for (i = 0; command_complete[i].expand != 0; ++i)
6122 if ((int)STRLEN(command_complete[i].name) == valend
6123 && STRNCMP(value, command_complete[i].name, valend) == 0)
6125 *complp = command_complete[i].expand;
6126 if (command_complete[i].expand == EXPAND_BUFFERS)
6127 *argt |= BUFNAME;
6128 else if (command_complete[i].expand == EXPAND_DIRECTORIES
6129 || command_complete[i].expand == EXPAND_FILES)
6130 *argt |= XFILE;
6131 break;
6135 if (command_complete[i].expand == 0)
6137 EMSG2(_("E180: Invalid complete value: %s"), value);
6138 return FAIL;
6141 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6142 if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
6143 && arg != NULL)
6144 # else
6145 if (arg != NULL)
6146 # endif
6148 EMSG(_("E468: Completion argument only allowed for custom completion"));
6149 return FAIL;
6152 # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
6153 if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
6154 && arg == NULL)
6156 EMSG(_("E467: Custom completion requires a function argument"));
6157 return FAIL;
6160 if (arg != NULL)
6161 *compl_arg = vim_strnsave(arg, (int)arglen);
6162 # endif
6163 return OK;
6165 #endif
6167 static void
6168 ex_colorscheme(eap)
6169 exarg_T *eap;
6171 if (load_colors(eap->arg) == FAIL)
6172 EMSG2(_("E185: Cannot find color scheme %s"), eap->arg);
6175 static void
6176 ex_highlight(eap)
6177 exarg_T *eap;
6179 if (*eap->arg == NUL && eap->cmd[2] == '!')
6180 MSG(_("Greetings, Vim user!"));
6181 do_highlight(eap->arg, eap->forceit, FALSE);
6186 * Call this function if we thought we were going to exit, but we won't
6187 * (because of an error). May need to restore the terminal mode.
6189 void
6190 not_exiting()
6192 exiting = FALSE;
6193 settmode(TMODE_RAW);
6197 * ":quit": quit current window, quit Vim if closed the last window.
6199 static void
6200 ex_quit(eap)
6201 exarg_T *eap;
6203 #ifdef FEAT_CMDWIN
6204 if (cmdwin_type != 0)
6206 cmdwin_result = Ctrl_C;
6207 return;
6209 #endif
6210 /* Don't quit while editing the command line. */
6211 if (text_locked())
6213 text_locked_msg();
6214 return;
6216 #ifdef FEAT_AUTOCMD
6217 if (curbuf_locked())
6218 return;
6219 #endif
6221 #ifdef FEAT_NETBEANS_INTG
6222 netbeansForcedQuit = eap->forceit;
6223 #endif
6226 * If there are more files or windows we won't exit.
6228 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6229 exiting = TRUE;
6230 if ((!P_HID(curbuf)
6231 && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE))
6232 || check_more(TRUE, eap->forceit) == FAIL
6233 || (only_one_window() && check_changed_any(eap->forceit)))
6235 not_exiting();
6237 else
6239 #ifdef FEAT_WINDOWS
6240 if (only_one_window()) /* quit last window */
6241 #endif
6242 getout(0);
6243 #ifdef FEAT_WINDOWS
6244 # ifdef FEAT_GUI
6245 need_mouse_correct = TRUE;
6246 # endif
6247 /* close window; may free buffer */
6248 win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit);
6249 #endif
6254 * ":cquit".
6256 /*ARGSUSED*/
6257 static void
6258 ex_cquit(eap)
6259 exarg_T *eap;
6261 getout(1); /* this does not always pass on the exit code to the Manx
6262 compiler. why? */
6266 * ":qall": try to quit all windows
6268 static void
6269 ex_quit_all(eap)
6270 exarg_T *eap;
6272 # ifdef FEAT_CMDWIN
6273 if (cmdwin_type != 0)
6275 if (eap->forceit)
6276 cmdwin_result = K_XF1; /* ex_window() takes care of this */
6277 else
6278 cmdwin_result = K_XF2;
6279 return;
6281 # endif
6283 /* Don't quit while editing the command line. */
6284 if (text_locked())
6286 text_locked_msg();
6287 return;
6289 #ifdef FEAT_AUTOCMD
6290 if (curbuf_locked())
6291 return;
6292 #endif
6294 exiting = TRUE;
6295 if (eap->forceit || !check_changed_any(FALSE))
6296 getout(0);
6297 not_exiting();
6300 #if defined(FEAT_WINDOWS) || defined(PROTO)
6302 * ":close": close current window, unless it is the last one
6304 static void
6305 ex_close(eap)
6306 exarg_T *eap;
6308 # ifdef FEAT_CMDWIN
6309 if (cmdwin_type != 0)
6310 cmdwin_result = K_IGNORE;
6311 else
6312 # endif
6313 if (!text_locked()
6314 #ifdef FEAT_AUTOCMD
6315 && !curbuf_locked()
6316 #endif
6318 ex_win_close(eap->forceit, curwin, NULL);
6321 # ifdef FEAT_QUICKFIX
6323 * ":pclose": Close any preview window.
6325 static void
6326 ex_pclose(eap)
6327 exarg_T *eap;
6329 win_T *win;
6331 for (win = firstwin; win != NULL; win = win->w_next)
6332 if (win->w_p_pvw)
6334 ex_win_close(eap->forceit, win, NULL);
6335 break;
6338 # endif
6341 * Close window "win" and take care of handling closing the last window for a
6342 * modified buffer.
6344 static void
6345 ex_win_close(forceit, win, tp)
6346 int forceit;
6347 win_T *win;
6348 tabpage_T *tp; /* NULL or the tab page "win" is in */
6350 int need_hide;
6351 buf_T *buf = win->w_buffer;
6353 need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
6354 if (need_hide && !P_HID(buf) && !forceit)
6356 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
6357 if ((p_confirm || cmdmod.confirm) && p_write)
6359 dialog_changed(buf, FALSE);
6360 if (buf_valid(buf) && bufIsChanged(buf))
6361 return;
6362 need_hide = FALSE;
6364 else
6365 # endif
6367 EMSG(_(e_nowrtmsg));
6368 return;
6372 # ifdef FEAT_GUI
6373 need_mouse_correct = TRUE;
6374 # endif
6376 /* free buffer when not hiding it or when it's a scratch buffer */
6377 if (tp == NULL)
6378 win_close(win, !need_hide && !P_HID(buf));
6379 else
6380 win_close_othertab(win, !need_hide && !P_HID(buf), tp);
6384 * ":tabclose": close current tab page, unless it is the last one.
6385 * ":tabclose N": close tab page N.
6387 static void
6388 ex_tabclose(eap)
6389 exarg_T *eap;
6391 tabpage_T *tp;
6393 # ifdef FEAT_CMDWIN
6394 if (cmdwin_type != 0)
6395 cmdwin_result = K_IGNORE;
6396 else
6397 # endif
6398 if (first_tabpage->tp_next == NULL)
6399 EMSG(_("E784: Cannot close last tab page"));
6400 else
6402 if (eap->addr_count > 0)
6404 tp = find_tabpage((int)eap->line2);
6405 if (tp == NULL)
6407 beep_flush();
6408 return;
6410 if (tp != curtab)
6412 tabpage_close_other(tp, eap->forceit);
6413 return;
6416 if (!text_locked()
6417 #ifdef FEAT_AUTOCMD
6418 && !curbuf_locked()
6419 #endif
6421 tabpage_close(eap->forceit);
6426 * ":tabonly": close all tab pages except the current one
6428 static void
6429 ex_tabonly(eap)
6430 exarg_T *eap;
6432 tabpage_T *tp;
6433 int done;
6435 # ifdef FEAT_CMDWIN
6436 if (cmdwin_type != 0)
6437 cmdwin_result = K_IGNORE;
6438 else
6439 # endif
6440 if (first_tabpage->tp_next == NULL)
6441 MSG(_("Already only one tab page"));
6442 else
6444 /* Repeat this up to a 1000 times, because autocommands may mess
6445 * up the lists. */
6446 for (done = 0; done < 1000; ++done)
6448 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6449 if (tp->tp_topframe != topframe)
6451 tabpage_close_other(tp, eap->forceit);
6452 /* if we failed to close it quit */
6453 if (valid_tabpage(tp))
6454 done = 1000;
6455 /* start over, "tp" is now invalid */
6456 break;
6458 if (first_tabpage->tp_next == NULL)
6459 break;
6465 * Close the current tab page.
6467 void
6468 tabpage_close(forceit)
6469 int forceit;
6471 /* First close all the windows but the current one. If that worked then
6472 * close the last window in this tab, that will close it. */
6473 if (lastwin != firstwin)
6474 close_others(TRUE, forceit);
6475 if (lastwin == firstwin)
6476 ex_win_close(forceit, curwin, NULL);
6477 # ifdef FEAT_GUI
6478 need_mouse_correct = TRUE;
6479 # endif
6483 * Close tab page "tp", which is not the current tab page.
6484 * Note that autocommands may make "tp" invalid.
6485 * Also takes care of the tab pages line disappearing when closing the
6486 * last-but-one tab page.
6488 void
6489 tabpage_close_other(tp, forceit)
6490 tabpage_T *tp;
6491 int forceit;
6493 int done = 0;
6494 win_T *wp;
6495 int h = tabline_height();
6497 /* Limit to 1000 windows, autocommands may add a window while we close
6498 * one. OK, so I'm paranoid... */
6499 while (++done < 1000)
6501 wp = tp->tp_firstwin;
6502 ex_win_close(forceit, wp, tp);
6504 /* Autocommands may delete the tab page under our fingers and we may
6505 * fail to close a window with a modified buffer. */
6506 if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
6507 break;
6510 redraw_tabline = TRUE;
6511 if (h != tabline_height())
6512 shell_new_rows();
6516 * ":only".
6518 static void
6519 ex_only(eap)
6520 exarg_T *eap;
6522 # ifdef FEAT_GUI
6523 need_mouse_correct = TRUE;
6524 # endif
6525 close_others(TRUE, eap->forceit);
6529 * ":all" and ":sall".
6530 * Also used for ":tab drop file ..." after setting the argument list.
6532 void
6533 ex_all(eap)
6534 exarg_T *eap;
6536 if (eap->addr_count == 0)
6537 eap->line2 = 9999;
6538 do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
6540 #endif /* FEAT_WINDOWS */
6542 static void
6543 ex_hide(eap)
6544 exarg_T *eap;
6546 if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL)
6547 eap->errmsg = e_invarg;
6548 else
6550 /* ":hide" or ":hide | cmd": hide current window */
6551 eap->nextcmd = check_nextcmd(eap->arg);
6552 #ifdef FEAT_WINDOWS
6553 if (!eap->skip)
6555 # ifdef FEAT_GUI
6556 need_mouse_correct = TRUE;
6557 # endif
6558 win_close(curwin, FALSE); /* don't free buffer */
6560 #endif
6565 * ":stop" and ":suspend": Suspend Vim.
6567 static void
6568 ex_stop(eap)
6569 exarg_T *eap;
6572 * Disallow suspending for "rvim".
6574 if (!check_restricted()
6575 #ifdef WIN3264
6577 * Check if external commands are allowed now.
6579 && can_end_termcap_mode(TRUE)
6580 #endif
6583 if (!eap->forceit)
6584 autowrite_all();
6585 windgoto((int)Rows - 1, 0);
6586 out_char('\n');
6587 out_flush();
6588 stoptermcap();
6589 out_flush(); /* needed for SUN to restore xterm buffer */
6590 #ifdef FEAT_TITLE
6591 mch_restore_title(3); /* restore window titles */
6592 #endif
6593 ui_suspend(); /* call machine specific function */
6594 #ifdef FEAT_TITLE
6595 maketitle();
6596 resettitle(); /* force updating the title */
6597 #endif
6598 starttermcap();
6599 scroll_start(); /* scroll screen before redrawing */
6600 redraw_later_clear();
6601 shell_resized(); /* may have resized window */
6606 * ":exit", ":xit" and ":wq": Write file and exit Vim.
6608 static void
6609 ex_exit(eap)
6610 exarg_T *eap;
6612 #ifdef FEAT_CMDWIN
6613 if (cmdwin_type != 0)
6615 cmdwin_result = Ctrl_C;
6616 return;
6618 #endif
6619 /* Don't quit while editing the command line. */
6620 if (text_locked())
6622 text_locked_msg();
6623 return;
6625 #ifdef FEAT_AUTOCMD
6626 if (curbuf_locked())
6627 return;
6628 #endif
6631 * if more files or windows we won't exit
6633 if (check_more(FALSE, eap->forceit) == OK && only_one_window())
6634 exiting = TRUE;
6635 if ( ((eap->cmdidx == CMD_wq
6636 || curbufIsChanged())
6637 && do_write(eap) == FAIL)
6638 || check_more(TRUE, eap->forceit) == FAIL
6639 || (only_one_window() && check_changed_any(eap->forceit)))
6641 not_exiting();
6643 else
6645 #ifdef FEAT_WINDOWS
6646 if (only_one_window()) /* quit last window, exit Vim */
6647 #endif
6648 getout(0);
6649 #ifdef FEAT_WINDOWS
6650 # ifdef FEAT_GUI
6651 need_mouse_correct = TRUE;
6652 # endif
6653 /* quit current window, may free buffer */
6654 win_close(curwin, !P_HID(curwin->w_buffer));
6655 #endif
6660 * ":print", ":list", ":number".
6662 static void
6663 ex_print(eap)
6664 exarg_T *eap;
6666 if (curbuf->b_ml.ml_flags & ML_EMPTY)
6667 EMSG(_(e_emptybuf));
6668 else
6670 for ( ;!got_int; ui_breakcheck())
6672 print_line(eap->line1,
6673 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
6674 || (eap->flags & EXFLAG_NR)),
6675 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST));
6676 if (++eap->line1 > eap->line2)
6677 break;
6678 out_flush(); /* show one line at a time */
6680 setpcmark();
6681 /* put cursor at last line */
6682 curwin->w_cursor.lnum = eap->line2;
6683 beginline(BL_SOL | BL_FIX);
6686 ex_no_reprint = TRUE;
6689 #ifdef FEAT_BYTEOFF
6690 static void
6691 ex_goto(eap)
6692 exarg_T *eap;
6694 goto_byte(eap->line2);
6696 #endif
6699 * ":shell".
6701 /*ARGSUSED*/
6702 static void
6703 ex_shell(eap)
6704 exarg_T *eap;
6706 do_shell(NULL, 0);
6709 #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \
6710 || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \
6711 || defined(FEAT_GUI_MSWIN) \
6712 || defined(FEAT_GUI_MAC) \
6713 || defined(PROTO) \
6714 || defined(FEAT_GUI_MACVIM)
6717 * Handle a file drop. The code is here because a drop is *nearly* like an
6718 * :args command, but not quite (we have a list of exact filenames, so we
6719 * don't want to (a) parse a command line, or (b) expand wildcards. So the
6720 * code is very similar to :args and hence needs access to a lot of the static
6721 * functions in this file.
6723 * The list should be allocated using alloc(), as should each item in the
6724 * list. This function takes over responsibility for freeing the list.
6726 * XXX The list is made into the argument list. This is freed using
6727 * FreeWild(), which does a series of vim_free() calls, unless the two defines
6728 * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a
6729 * routine _fnexplodefree() is used. This may cause problems, but as the drop
6730 * file functionality is (currently) not in EMX this is not presently a
6731 * problem.
6733 void
6734 handle_drop(filec, filev, split)
6735 int filec; /* the number of files dropped */
6736 char_u **filev; /* the list of files dropped */
6737 int split; /* force splitting the window */
6739 exarg_T ea;
6740 int save_msg_scroll = msg_scroll;
6742 /* Postpone this while editing the command line. */
6743 if (text_locked())
6744 return;
6745 #ifdef FEAT_AUTOCMD
6746 if (curbuf_locked())
6747 return;
6748 #endif
6749 /* When the screen is being updated we should not change buffers and
6750 * windows structures, it may cause freed memory to be used. */
6751 if (updating_screen)
6752 return;
6754 /* Check whether the current buffer is changed. If so, we will need
6755 * to split the current window or data could be lost.
6756 * We don't need to check if the 'hidden' option is set, as in this
6757 * case the buffer won't be lost.
6759 if (!P_HID(curbuf) && !split)
6761 ++emsg_off;
6762 split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE);
6763 --emsg_off;
6765 if (split)
6767 # ifdef FEAT_WINDOWS
6768 if (win_split(0, 0) == FAIL)
6769 return;
6770 # ifdef FEAT_SCROLLBIND
6771 curwin->w_p_scb = FALSE;
6772 # endif
6774 /* When splitting the window, create a new alist. Otherwise the
6775 * existing one is overwritten. */
6776 alist_unlink(curwin->w_alist);
6777 alist_new();
6778 # else
6779 return; /* can't split, always fail */
6780 # endif
6784 * Set up the new argument list.
6786 alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0);
6789 * Move to the first file.
6791 /* Fake up a minimal "next" command for do_argfile() */
6792 vim_memset(&ea, 0, sizeof(ea));
6793 ea.cmd = (char_u *)"next";
6794 do_argfile(&ea, 0);
6796 /* do_ecmd() may set need_start_insertmode, but since we never left Insert
6797 * mode that is not needed here. */
6798 need_start_insertmode = FALSE;
6800 /* Restore msg_scroll, otherwise a following command may cause scrolling
6801 * unexpectedly. The screen will be redrawn by the caller, thus
6802 * msg_scroll being set by displaying a message is irrelevant. */
6803 msg_scroll = save_msg_scroll;
6805 #endif
6808 * Clear an argument list: free all file names and reset it to zero entries.
6810 void
6811 alist_clear(al)
6812 alist_T *al;
6814 while (--al->al_ga.ga_len >= 0)
6815 vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname);
6816 ga_clear(&al->al_ga);
6820 * Init an argument list.
6822 void
6823 alist_init(al)
6824 alist_T *al;
6826 ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5);
6829 #if defined(FEAT_WINDOWS) || defined(PROTO)
6832 * Remove a reference from an argument list.
6833 * Ignored when the argument list is the global one.
6834 * If the argument list is no longer used by any window, free it.
6836 void
6837 alist_unlink(al)
6838 alist_T *al;
6840 if (al != &global_alist && --al->al_refcount <= 0)
6842 alist_clear(al);
6843 vim_free(al);
6847 # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO)
6849 * Create a new argument list and use it for the current window.
6851 void
6852 alist_new()
6854 curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T));
6855 if (curwin->w_alist == NULL)
6857 curwin->w_alist = &global_alist;
6858 ++global_alist.al_refcount;
6860 else
6862 curwin->w_alist->al_refcount = 1;
6863 alist_init(curwin->w_alist);
6866 # endif
6867 #endif
6869 #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO)
6871 * Expand the file names in the global argument list.
6872 * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
6873 * numbers to be re-used.
6875 void
6876 alist_expand(fnum_list, fnum_len)
6877 int *fnum_list;
6878 int fnum_len;
6880 char_u **old_arg_files;
6881 int old_arg_count;
6882 char_u **new_arg_files;
6883 int new_arg_file_count;
6884 char_u *save_p_su = p_su;
6885 int i;
6887 /* Don't use 'suffixes' here. This should work like the shell did the
6888 * expansion. Also, the vimrc file isn't read yet, thus the user
6889 * can't set the options. */
6890 p_su = empty_option;
6891 old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT));
6892 if (old_arg_files != NULL)
6894 for (i = 0; i < GARGCOUNT; ++i)
6895 old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname);
6896 old_arg_count = GARGCOUNT;
6897 if (expand_wildcards(old_arg_count, old_arg_files,
6898 &new_arg_file_count, &new_arg_files,
6899 EW_FILE|EW_NOTFOUND|EW_ADDSLASH) == OK
6900 && new_arg_file_count > 0)
6902 alist_set(&global_alist, new_arg_file_count, new_arg_files,
6903 TRUE, fnum_list, fnum_len);
6904 FreeWild(old_arg_count, old_arg_files);
6907 p_su = save_p_su;
6909 #endif
6912 * Set the argument list for the current window.
6913 * Takes over the allocated files[] and the allocated fnames in it.
6915 void
6916 alist_set(al, count, files, use_curbuf, fnum_list, fnum_len)
6917 alist_T *al;
6918 int count;
6919 char_u **files;
6920 int use_curbuf;
6921 int *fnum_list;
6922 int fnum_len;
6924 int i;
6926 alist_clear(al);
6927 if (ga_grow(&al->al_ga, count) == OK)
6929 for (i = 0; i < count; ++i)
6931 if (got_int)
6933 /* When adding many buffers this can take a long time. Allow
6934 * interrupting here. */
6935 while (i < count)
6936 vim_free(files[i++]);
6937 break;
6940 /* May set buffer name of a buffer previously used for the
6941 * argument list, so that it's re-used by alist_add. */
6942 if (fnum_list != NULL && i < fnum_len)
6943 buf_set_name(fnum_list[i], files[i]);
6945 alist_add(al, files[i], use_curbuf ? 2 : 1);
6946 ui_breakcheck();
6948 vim_free(files);
6950 else
6951 FreeWild(count, files);
6952 #ifdef FEAT_WINDOWS
6953 if (al == &global_alist)
6954 #endif
6955 arg_had_last = FALSE;
6959 * Add file "fname" to argument list "al".
6960 * "fname" must have been allocated and "al" must have been checked for room.
6962 void
6963 alist_add(al, fname, set_fnum)
6964 alist_T *al;
6965 char_u *fname;
6966 int set_fnum; /* 1: set buffer number; 2: re-use curbuf */
6968 if (fname == NULL) /* don't add NULL file names */
6969 return;
6970 #ifdef BACKSLASH_IN_FILENAME
6971 slash_adjust(fname);
6972 #endif
6973 AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
6974 if (set_fnum > 0)
6975 AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
6976 buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
6977 ++al->al_ga.ga_len;
6980 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
6982 * Adjust slashes in file names. Called after 'shellslash' was set.
6984 void
6985 alist_slash_adjust()
6987 int i;
6988 # ifdef FEAT_WINDOWS
6989 win_T *wp;
6990 tabpage_T *tp;
6991 # endif
6993 for (i = 0; i < GARGCOUNT; ++i)
6994 if (GARGLIST[i].ae_fname != NULL)
6995 slash_adjust(GARGLIST[i].ae_fname);
6996 # ifdef FEAT_WINDOWS
6997 FOR_ALL_TAB_WINDOWS(tp, wp)
6998 if (wp->w_alist != &global_alist)
6999 for (i = 0; i < WARGCOUNT(wp); ++i)
7000 if (WARGLIST(wp)[i].ae_fname != NULL)
7001 slash_adjust(WARGLIST(wp)[i].ae_fname);
7002 # endif
7004 #endif
7007 * ":preserve".
7009 /*ARGSUSED*/
7010 static void
7011 ex_preserve(eap)
7012 exarg_T *eap;
7014 curbuf->b_flags |= BF_PRESERVED;
7015 ml_preserve(curbuf, TRUE);
7019 * ":recover".
7021 static void
7022 ex_recover(eap)
7023 exarg_T *eap;
7025 /* Set recoverymode right away to avoid the ATTENTION prompt. */
7026 recoverymode = TRUE;
7027 if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE)
7028 && (*eap->arg == NUL
7029 || setfname(curbuf, eap->arg, NULL, TRUE) == OK))
7030 ml_recover();
7031 recoverymode = FALSE;
7035 * Command modifier used in a wrong way.
7037 static void
7038 ex_wrongmodifier(eap)
7039 exarg_T *eap;
7041 eap->errmsg = e_invcmd;
7044 #ifdef FEAT_WINDOWS
7046 * :sview [+command] file split window with new file, read-only
7047 * :split [[+command] file] split window with current or new file
7048 * :vsplit [[+command] file] split window vertically with current or new file
7049 * :new [[+command] file] split window with no or new file
7050 * :vnew [[+command] file] split vertically window with no or new file
7051 * :sfind [+command] file split window with file in 'path'
7053 * :tabedit open new Tab page with empty window
7054 * :tabedit [+command] file open new Tab page and edit "file"
7055 * :tabnew [[+command] file] just like :tabedit
7056 * :tabfind [+command] file open new Tab page and find "file"
7058 void
7059 ex_splitview(eap)
7060 exarg_T *eap;
7062 win_T *old_curwin = curwin;
7063 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7064 char_u *fname = NULL;
7065 # endif
7066 # ifdef FEAT_BROWSE
7067 int browse_flag = cmdmod.browse;
7068 # endif
7070 # ifndef FEAT_VERTSPLIT
7071 if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew)
7073 ex_ni(eap);
7074 return;
7076 # endif
7078 # ifdef FEAT_GUI
7079 need_mouse_correct = TRUE;
7080 # endif
7082 # ifdef FEAT_QUICKFIX
7083 /* A ":split" in the quickfix window works like ":new". Don't want two
7084 * quickfix windows. But it's OK when doing ":tab split". */
7085 if (bt_quickfix(curbuf) && cmdmod.tab == 0)
7087 if (eap->cmdidx == CMD_split)
7088 eap->cmdidx = CMD_new;
7089 # ifdef FEAT_VERTSPLIT
7090 if (eap->cmdidx == CMD_vsplit)
7091 eap->cmdidx = CMD_vnew;
7092 # endif
7094 # endif
7096 # ifdef FEAT_SEARCHPATH
7097 if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind)
7099 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg),
7100 FNAME_MESS, TRUE, curbuf->b_ffname);
7101 if (fname == NULL)
7102 goto theend;
7103 eap->arg = fname;
7105 # ifdef FEAT_BROWSE
7106 else
7107 # endif
7108 # endif
7109 # ifdef FEAT_BROWSE
7110 if (cmdmod.browse
7111 # ifdef FEAT_VERTSPLIT
7112 && eap->cmdidx != CMD_vnew
7113 # endif
7114 && eap->cmdidx != CMD_new)
7116 # ifdef FEAT_AUTOCMD
7117 if (
7118 # ifdef FEAT_GUI
7119 !gui.in_use &&
7120 # endif
7121 au_has_group((char_u *)"FileExplorer"))
7123 /* No browsing supported but we do have the file explorer:
7124 * Edit the directory. */
7125 if (*eap->arg == NUL || !mch_isdir(eap->arg))
7126 eap->arg = (char_u *)".";
7128 else
7129 # endif
7131 fname = do_browse(0, (char_u *)_("Edit File in new window"),
7132 eap->arg, NULL, NULL, NULL, curbuf);
7133 if (fname == NULL)
7134 goto theend;
7135 eap->arg = fname;
7138 cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */
7139 # endif
7142 * Either open new tab page or split the window.
7144 if (eap->cmdidx == CMD_tabedit
7145 || eap->cmdidx == CMD_tabfind
7146 || eap->cmdidx == CMD_tabnew)
7148 if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab
7149 : eap->addr_count == 0 ? 0
7150 : (int)eap->line2 + 1) != FAIL)
7152 do_exedit(eap, old_curwin);
7154 /* set the alternate buffer for the window we came from */
7155 if (curwin != old_curwin
7156 && win_valid(old_curwin)
7157 && old_curwin->w_buffer != curbuf
7158 && !cmdmod.keepalt)
7159 old_curwin->w_alt_fnum = curbuf->b_fnum;
7162 else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
7163 *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL)
7165 # ifdef FEAT_SCROLLBIND
7166 /* Reset 'scrollbind' when editing another file, but keep it when
7167 * doing ":split" without arguments. */
7168 if (*eap->arg != NUL
7169 # ifdef FEAT_BROWSE
7170 || cmdmod.browse
7171 # endif
7173 curwin->w_p_scb = FALSE;
7174 else
7175 do_check_scrollbind(FALSE);
7176 # endif
7177 do_exedit(eap, old_curwin);
7180 # ifdef FEAT_BROWSE
7181 cmdmod.browse = browse_flag;
7182 # endif
7184 # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE)
7185 theend:
7186 vim_free(fname);
7187 # endif
7191 * Open a new tab page.
7193 void
7194 tabpage_new()
7196 exarg_T ea;
7198 vim_memset(&ea, 0, sizeof(ea));
7199 ea.cmdidx = CMD_tabnew;
7200 ea.cmd = (char_u *)"tabn";
7201 ea.arg = (char_u *)"";
7202 ex_splitview(&ea);
7206 * :tabnext command
7208 static void
7209 ex_tabnext(eap)
7210 exarg_T *eap;
7212 switch (eap->cmdidx)
7214 case CMD_tabfirst:
7215 case CMD_tabrewind:
7216 goto_tabpage(1);
7217 break;
7218 case CMD_tablast:
7219 goto_tabpage(9999);
7220 break;
7221 case CMD_tabprevious:
7222 case CMD_tabNext:
7223 goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2);
7224 break;
7225 default: /* CMD_tabnext */
7226 goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2);
7227 break;
7232 * :tabmove command
7234 static void
7235 ex_tabmove(eap)
7236 exarg_T *eap;
7238 tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2);
7242 * :tabs command: List tabs and their contents.
7244 /*ARGSUSED*/
7245 static void
7246 ex_tabs(eap)
7247 exarg_T *eap;
7249 tabpage_T *tp;
7250 win_T *wp;
7251 int tabcount = 1;
7253 msg_start();
7254 msg_scroll = TRUE;
7255 for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next)
7257 msg_putchar('\n');
7258 vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++);
7259 msg_outtrans_attr(IObuff, hl_attr(HLF_T));
7260 out_flush(); /* output one line at a time */
7261 ui_breakcheck();
7263 if (tp == curtab)
7264 wp = firstwin;
7265 else
7266 wp = tp->tp_firstwin;
7267 for ( ; wp != NULL && !got_int; wp = wp->w_next)
7269 msg_putchar('\n');
7270 msg_putchar(wp == curwin ? '>' : ' ');
7271 msg_putchar(' ');
7272 msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
7273 msg_putchar(' ');
7274 if (buf_spname(wp->w_buffer) != NULL)
7275 STRCPY(IObuff, buf_spname(wp->w_buffer));
7276 else
7277 home_replace(wp->w_buffer, wp->w_buffer->b_fname,
7278 IObuff, IOSIZE, TRUE);
7279 msg_outtrans(IObuff);
7280 out_flush(); /* output one line at a time */
7281 ui_breakcheck();
7286 #endif /* FEAT_WINDOWS */
7289 * ":mode": Set screen mode.
7290 * If no argument given, just get the screen size and redraw.
7292 static void
7293 ex_mode(eap)
7294 exarg_T *eap;
7296 if (*eap->arg == NUL)
7297 shell_resized();
7298 else
7299 mch_screenmode(eap->arg);
7302 #ifdef FEAT_WINDOWS
7304 * ":resize".
7305 * set, increment or decrement current window height
7307 static void
7308 ex_resize(eap)
7309 exarg_T *eap;
7311 int n;
7312 win_T *wp = curwin;
7314 if (eap->addr_count > 0)
7316 n = eap->line2;
7317 for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next)
7321 #ifdef FEAT_GUI
7322 need_mouse_correct = TRUE;
7323 #endif
7324 n = atol((char *)eap->arg);
7325 #ifdef FEAT_VERTSPLIT
7326 if (cmdmod.split & WSP_VERT)
7328 if (*eap->arg == '-' || *eap->arg == '+')
7329 n += W_WIDTH(curwin);
7330 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7331 n = 9999;
7332 win_setwidth_win((int)n, wp);
7334 else
7335 #endif
7337 if (*eap->arg == '-' || *eap->arg == '+')
7338 n += curwin->w_height;
7339 else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */
7340 n = 9999;
7341 win_setheight_win((int)n, wp);
7344 #endif
7347 * ":find [+command] <file>" command.
7349 static void
7350 ex_find(eap)
7351 exarg_T *eap;
7353 #ifdef FEAT_SEARCHPATH
7354 char_u *fname;
7355 int count;
7357 fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS,
7358 TRUE, curbuf->b_ffname);
7359 if (eap->addr_count > 0)
7361 /* Repeat finding the file "count" times. This matters when it
7362 * appears several times in the path. */
7363 count = eap->line2;
7364 while (fname != NULL && --count > 0)
7366 vim_free(fname);
7367 fname = find_file_in_path(NULL, 0, FNAME_MESS,
7368 FALSE, curbuf->b_ffname);
7372 if (fname != NULL)
7374 eap->arg = fname;
7375 #endif
7376 do_exedit(eap, NULL);
7377 #ifdef FEAT_SEARCHPATH
7378 vim_free(fname);
7380 #endif
7384 * ":open" simulation: for now just work like ":visual".
7386 static void
7387 ex_open(eap)
7388 exarg_T *eap;
7390 regmatch_T regmatch;
7391 char_u *p;
7393 curwin->w_cursor.lnum = eap->line2;
7394 beginline(BL_SOL | BL_FIX);
7395 if (*eap->arg == '/')
7397 /* ":open /pattern/": put cursor in column found with pattern */
7398 ++eap->arg;
7399 p = skip_regexp(eap->arg, '/', p_magic, NULL);
7400 *p = NUL;
7401 regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0);
7402 if (regmatch.regprog != NULL)
7404 regmatch.rm_ic = p_ic;
7405 p = ml_get_curline();
7406 if (vim_regexec(&regmatch, p, (colnr_T)0))
7407 curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p);
7408 else
7409 EMSG(_(e_nomatch));
7410 vim_free(regmatch.regprog);
7412 /* Move to the NUL, ignore any other arguments. */
7413 eap->arg += STRLEN(eap->arg);
7415 check_cursor();
7417 eap->cmdidx = CMD_visual;
7418 do_exedit(eap, NULL);
7422 * ":edit", ":badd", ":visual".
7424 static void
7425 ex_edit(eap)
7426 exarg_T *eap;
7428 do_exedit(eap, NULL);
7432 * ":edit <file>" command and alikes.
7434 /*ARGSUSED*/
7435 void
7436 do_exedit(eap, old_curwin)
7437 exarg_T *eap;
7438 win_T *old_curwin; /* curwin before doing a split or NULL */
7440 int n;
7441 #ifdef FEAT_WINDOWS
7442 int need_hide;
7443 #endif
7444 int exmode_was = exmode_active;
7447 * ":vi" command ends Ex mode.
7449 if (exmode_active && (eap->cmdidx == CMD_visual
7450 || eap->cmdidx == CMD_view))
7452 exmode_active = FALSE;
7453 if (*eap->arg == NUL)
7455 /* Special case: ":global/pat/visual\NLvi-commands" */
7456 if (global_busy)
7458 int rd = RedrawingDisabled;
7459 int nwr = no_wait_return;
7460 int ms = msg_scroll;
7461 #ifdef FEAT_GUI
7462 int he = hold_gui_events;
7463 #endif
7465 if (eap->nextcmd != NULL)
7467 stuffReadbuff(eap->nextcmd);
7468 eap->nextcmd = NULL;
7471 if (exmode_was != EXMODE_VIM)
7472 settmode(TMODE_RAW);
7473 RedrawingDisabled = 0;
7474 no_wait_return = 0;
7475 need_wait_return = FALSE;
7476 msg_scroll = 0;
7477 #ifdef FEAT_GUI
7478 hold_gui_events = 0;
7479 #endif
7480 must_redraw = CLEAR;
7482 main_loop(FALSE, TRUE);
7484 RedrawingDisabled = rd;
7485 no_wait_return = nwr;
7486 msg_scroll = ms;
7487 #ifdef FEAT_GUI
7488 hold_gui_events = he;
7489 #endif
7491 return;
7495 if ((eap->cmdidx == CMD_new
7496 || eap->cmdidx == CMD_tabnew
7497 || eap->cmdidx == CMD_tabedit
7498 #ifdef FEAT_VERTSPLIT
7499 || eap->cmdidx == CMD_vnew
7500 #endif
7501 ) && *eap->arg == NUL)
7503 /* ":new" or ":tabnew" without argument: edit an new empty buffer */
7504 setpcmark();
7505 (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
7506 ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0));
7508 else if ((eap->cmdidx != CMD_split
7509 #ifdef FEAT_VERTSPLIT
7510 && eap->cmdidx != CMD_vsplit
7511 #endif
7513 || *eap->arg != NUL
7514 #ifdef FEAT_BROWSE
7515 || cmdmod.browse
7516 #endif
7519 #ifdef FEAT_AUTOCMD
7520 /* Can't edit another file when "curbuf_lock" is set. Only ":edit"
7521 * can bring us here, others are stopped earlier. */
7522 if (*eap->arg != NUL && curbuf_locked())
7523 return;
7524 #endif
7525 n = readonlymode;
7526 if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview)
7527 readonlymode = TRUE;
7528 else if (eap->cmdidx == CMD_enew)
7529 readonlymode = FALSE; /* 'readonly' doesn't make sense in an
7530 empty buffer */
7531 setpcmark();
7532 if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg),
7533 NULL, eap,
7534 /* ":edit" goes to first line if Vi compatible */
7535 (*eap->arg == NUL && eap->do_ecmd_lnum == 0
7536 && vim_strchr(p_cpo, CPO_GOTO1) != NULL)
7537 ? ECMD_ONE : eap->do_ecmd_lnum,
7538 (P_HID(curbuf) ? ECMD_HIDE : 0)
7539 + (eap->forceit ? ECMD_FORCEIT : 0)
7540 #ifdef FEAT_LISTCMDS
7541 + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 )
7542 #endif
7543 ) == FAIL)
7545 /* Editing the file failed. If the window was split, close it. */
7546 #ifdef FEAT_WINDOWS
7547 if (old_curwin != NULL)
7549 need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
7550 if (!need_hide || P_HID(curbuf))
7552 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7553 cleanup_T cs;
7555 /* Reset the error/interrupt/exception state here so that
7556 * aborting() returns FALSE when closing a window. */
7557 enter_cleanup(&cs);
7558 # endif
7559 # ifdef FEAT_GUI
7560 need_mouse_correct = TRUE;
7561 # endif
7562 win_close(curwin, !need_hide && !P_HID(curbuf));
7564 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7565 /* Restore the error/interrupt/exception state if not
7566 * discarded by a new aborting error, interrupt, or
7567 * uncaught exception. */
7568 leave_cleanup(&cs);
7569 # endif
7572 #endif
7574 else if (readonlymode && curbuf->b_nwindows == 1)
7576 /* When editing an already visited buffer, 'readonly' won't be set
7577 * but the previous value is kept. With ":view" and ":sview" we
7578 * want the file to be readonly, except when another window is
7579 * editing the same buffer. */
7580 curbuf->b_p_ro = TRUE;
7582 readonlymode = n;
7584 else
7586 if (eap->do_ecmd_cmd != NULL)
7587 do_cmdline_cmd(eap->do_ecmd_cmd);
7588 #ifdef FEAT_TITLE
7589 n = curwin->w_arg_idx_invalid;
7590 #endif
7591 check_arg_idx(curwin);
7592 #ifdef FEAT_TITLE
7593 if (n != curwin->w_arg_idx_invalid)
7594 maketitle();
7595 #endif
7598 #ifdef FEAT_WINDOWS
7600 * if ":split file" worked, set alternate file name in old window to new
7601 * file
7603 if (old_curwin != NULL
7604 && *eap->arg != NUL
7605 && curwin != old_curwin
7606 && win_valid(old_curwin)
7607 && old_curwin->w_buffer != curbuf
7608 && !cmdmod.keepalt)
7609 old_curwin->w_alt_fnum = curbuf->b_fnum;
7610 #endif
7612 ex_no_reprint = TRUE;
7615 #ifndef FEAT_GUI
7617 * ":gui" and ":gvim" when there is no GUI.
7619 static void
7620 ex_nogui(eap)
7621 exarg_T *eap;
7623 eap->errmsg = e_nogvim;
7625 #endif
7627 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
7628 static void
7629 ex_tearoff(eap)
7630 exarg_T *eap;
7632 gui_make_tearoff(eap->arg);
7634 #endif
7636 #if defined(FEAT_MENU) && (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK) \
7637 || defined(FEAT_GUI_MACVIM))
7638 static void
7639 ex_popup(eap)
7640 exarg_T *eap;
7642 gui_make_popup(eap->arg, eap->forceit);
7644 #endif
7646 /*ARGSUSED*/
7647 static void
7648 ex_swapname(eap)
7649 exarg_T *eap;
7651 if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL)
7652 MSG(_("No swap file"));
7653 else
7654 msg(curbuf->b_ml.ml_mfp->mf_fname);
7658 * ":syncbind" forces all 'scrollbind' windows to have the same relative
7659 * offset.
7660 * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>)
7662 /*ARGSUSED*/
7663 static void
7664 ex_syncbind(eap)
7665 exarg_T *eap;
7667 #ifdef FEAT_SCROLLBIND
7668 win_T *wp;
7669 long topline;
7670 long y;
7671 linenr_T old_linenr = curwin->w_cursor.lnum;
7673 setpcmark();
7676 * determine max topline
7678 if (curwin->w_p_scb)
7680 topline = curwin->w_topline;
7681 for (wp = firstwin; wp; wp = wp->w_next)
7683 if (wp->w_p_scb && wp->w_buffer)
7685 y = wp->w_buffer->b_ml.ml_line_count - p_so;
7686 if (topline > y)
7687 topline = y;
7690 if (topline < 1)
7691 topline = 1;
7693 else
7695 topline = 1;
7700 * set all scrollbind windows to the same topline
7702 wp = curwin;
7703 for (curwin = firstwin; curwin; curwin = curwin->w_next)
7705 if (curwin->w_p_scb)
7707 y = topline - curwin->w_topline;
7708 if (y > 0)
7709 scrollup(y, TRUE);
7710 else
7711 scrolldown(-y, TRUE);
7712 curwin->w_scbind_pos = topline;
7713 redraw_later(VALID);
7714 cursor_correct();
7715 #ifdef FEAT_WINDOWS
7716 curwin->w_redr_status = TRUE;
7717 #endif
7720 curwin = wp;
7721 if (curwin->w_p_scb)
7723 did_syncbind = TRUE;
7724 checkpcmark();
7725 if (old_linenr != curwin->w_cursor.lnum)
7727 char_u ctrl_o[2];
7729 ctrl_o[0] = Ctrl_O;
7730 ctrl_o[1] = 0;
7731 ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE);
7734 #endif
7738 static void
7739 ex_read(eap)
7740 exarg_T *eap;
7742 int i;
7743 int empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7744 linenr_T lnum;
7746 if (eap->usefilter) /* :r!cmd */
7747 do_bang(1, eap, FALSE, FALSE, TRUE);
7748 else
7750 if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL)
7751 return;
7753 #ifdef FEAT_BROWSE
7754 if (cmdmod.browse)
7756 char_u *browseFile;
7758 browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg,
7759 NULL, NULL, NULL, curbuf);
7760 if (browseFile != NULL)
7762 i = readfile(browseFile, NULL,
7763 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7764 vim_free(browseFile);
7766 else
7767 i = OK;
7769 else
7770 #endif
7771 if (*eap->arg == NUL)
7773 if (check_fname() == FAIL) /* check for no file name */
7774 return;
7775 i = readfile(curbuf->b_ffname, curbuf->b_fname,
7776 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7778 else
7780 if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL)
7781 (void)setaltfname(eap->arg, eap->arg, (linenr_T)1);
7782 i = readfile(eap->arg, NULL,
7783 eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0);
7786 if (i == FAIL)
7788 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7789 if (!aborting())
7790 #endif
7791 EMSG2(_(e_notopen), eap->arg);
7793 else
7795 if (empty && exmode_active)
7797 /* Delete the empty line that remains. Historically ex does
7798 * this but vi doesn't. */
7799 if (eap->line2 == 0)
7800 lnum = curbuf->b_ml.ml_line_count;
7801 else
7802 lnum = 1;
7803 if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK)
7805 ml_delete(lnum, FALSE);
7806 deleted_lines_mark(lnum, 1L);
7807 if (curwin->w_cursor.lnum > 1
7808 && curwin->w_cursor.lnum >= lnum)
7809 --curwin->w_cursor.lnum;
7812 redraw_curbuf_later(VALID);
7817 static char_u *prev_dir = NULL;
7819 #if defined(EXITFREE) || defined(PROTO)
7820 void
7821 free_cd_dir()
7823 vim_free(prev_dir);
7824 prev_dir = NULL;
7826 #endif
7830 * ":cd", ":lcd", ":chdir" and ":lchdir".
7832 void
7833 ex_cd(eap)
7834 exarg_T *eap;
7836 char_u *new_dir;
7837 char_u *tofree;
7839 new_dir = eap->arg;
7840 #if !defined(UNIX) && !defined(VMS)
7841 /* for non-UNIX ":cd" means: print current directory */
7842 if (*new_dir == NUL)
7843 ex_pwd(NULL);
7844 else
7845 #endif
7847 if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged()
7848 && !eap->forceit)
7850 EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)"));
7851 return;
7854 /* ":cd -": Change to previous directory */
7855 if (STRCMP(new_dir, "-") == 0)
7857 if (prev_dir == NULL)
7859 EMSG(_("E186: No previous directory"));
7860 return;
7862 new_dir = prev_dir;
7865 /* Save current directory for next ":cd -" */
7866 tofree = prev_dir;
7867 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7868 prev_dir = vim_strsave(NameBuff);
7869 else
7870 prev_dir = NULL;
7872 #if defined(UNIX) || defined(VMS)
7873 /* for UNIX ":cd" means: go to home directory */
7874 if (*new_dir == NUL)
7876 /* use NameBuff for home directory name */
7877 # ifdef VMS
7878 char_u *p;
7880 p = mch_getenv((char_u *)"SYS$LOGIN");
7881 if (p == NULL || *p == NUL) /* empty is the same as not set */
7882 NameBuff[0] = NUL;
7883 else
7884 vim_strncpy(NameBuff, p, MAXPATHL - 1);
7885 # else
7886 expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
7887 # endif
7888 new_dir = NameBuff;
7890 #endif
7891 if (new_dir == NULL || vim_chdir(new_dir))
7892 EMSG(_(e_failed));
7893 else
7895 vim_free(curwin->w_localdir);
7896 if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir)
7898 /* If still in global directory, need to remember current
7899 * directory as global directory. */
7900 if (globaldir == NULL && prev_dir != NULL)
7901 globaldir = vim_strsave(prev_dir);
7902 /* Remember this local directory for the window. */
7903 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7904 curwin->w_localdir = vim_strsave(NameBuff);
7906 else
7908 /* We are now in the global directory, no need to remember its
7909 * name. */
7910 vim_free(globaldir);
7911 globaldir = NULL;
7912 curwin->w_localdir = NULL;
7915 shorten_fnames(TRUE);
7917 /* Echo the new current directory if the command was typed. */
7918 if (KeyTyped)
7919 ex_pwd(eap);
7921 vim_free(tofree);
7926 * ":pwd".
7928 /*ARGSUSED*/
7929 static void
7930 ex_pwd(eap)
7931 exarg_T *eap;
7933 if (mch_dirname(NameBuff, MAXPATHL) == OK)
7935 #ifdef BACKSLASH_IN_FILENAME
7936 slash_adjust(NameBuff);
7937 #endif
7938 msg(NameBuff);
7940 else
7941 EMSG(_("E187: Unknown"));
7945 * ":=".
7947 static void
7948 ex_equal(eap)
7949 exarg_T *eap;
7951 smsg((char_u *)"%ld", (long)eap->line2);
7952 ex_may_print(eap);
7955 static void
7956 ex_sleep(eap)
7957 exarg_T *eap;
7959 int n;
7960 long len;
7962 if (cursor_valid())
7964 n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled;
7965 if (n >= 0)
7966 windgoto((int)n, curwin->w_wcol);
7969 len = eap->line2;
7970 switch (*eap->arg)
7972 case 'm': break;
7973 case NUL: len *= 1000L; break;
7974 default: EMSG2(_(e_invarg2), eap->arg); return;
7976 do_sleep(len);
7980 * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second.
7982 void
7983 do_sleep(msec)
7984 long msec;
7986 long done;
7988 cursor_on();
7989 out_flush();
7990 for (done = 0; !got_int && done < msec; done += 1000L)
7992 ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE);
7993 ui_breakcheck();
7997 static void
7998 do_exmap(eap, isabbrev)
7999 exarg_T *eap;
8000 int isabbrev;
8002 int mode;
8003 char_u *cmdp;
8005 cmdp = eap->cmd;
8006 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
8008 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
8009 eap->arg, mode, isabbrev))
8011 case 1: EMSG(_(e_invarg));
8012 break;
8013 case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap));
8014 break;
8019 * ":winsize" command (obsolete).
8021 static void
8022 ex_winsize(eap)
8023 exarg_T *eap;
8025 int w, h;
8026 char_u *arg = eap->arg;
8027 char_u *p;
8029 w = getdigits(&arg);
8030 arg = skipwhite(arg);
8031 p = arg;
8032 h = getdigits(&arg);
8033 if (*p != NUL && *arg == NUL)
8034 set_shellsize(w, h, TRUE);
8035 else
8036 EMSG(_("E465: :winsize requires two number arguments"));
8039 #ifdef FEAT_WINDOWS
8040 static void
8041 ex_wincmd(eap)
8042 exarg_T *eap;
8044 int xchar = NUL;
8045 char_u *p;
8047 if (*eap->arg == 'g' || *eap->arg == Ctrl_G)
8049 /* CTRL-W g and CTRL-W CTRL-G have an extra command character */
8050 if (eap->arg[1] == NUL)
8052 EMSG(_(e_invarg));
8053 return;
8055 xchar = eap->arg[1];
8056 p = eap->arg + 2;
8058 else
8059 p = eap->arg + 1;
8061 eap->nextcmd = check_nextcmd(p);
8062 p = skipwhite(p);
8063 if (*p != NUL && *p != '"' && eap->nextcmd == NULL)
8064 EMSG(_(e_invarg));
8065 else
8067 /* Pass flags on for ":vertical wincmd ]". */
8068 postponed_split_flags = cmdmod.split;
8069 postponed_split_tab = cmdmod.tab;
8070 do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar);
8071 postponed_split_flags = 0;
8072 postponed_split_tab = 0;
8075 #endif
8077 #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN)
8079 * ":winpos".
8081 static void
8082 ex_winpos(eap)
8083 exarg_T *eap;
8085 int x, y;
8086 char_u *arg = eap->arg;
8087 char_u *p;
8089 if (*arg == NUL)
8091 # if defined(FEAT_GUI) || defined(MSWIN)
8092 # ifdef FEAT_GUI
8093 if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL)
8094 # else
8095 if (mch_get_winpos(&x, &y) != FAIL)
8096 # endif
8098 sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y);
8099 msg(IObuff);
8101 else
8102 # endif
8103 EMSG(_("E188: Obtaining window position not implemented for this platform"));
8105 else
8107 x = getdigits(&arg);
8108 arg = skipwhite(arg);
8109 p = arg;
8110 y = getdigits(&arg);
8111 if (*p == NUL || *arg != NUL)
8113 EMSG(_("E466: :winpos requires two number arguments"));
8114 return;
8116 # ifdef FEAT_GUI
8117 if (gui.in_use)
8118 gui_mch_set_winpos(x, y);
8119 else if (gui.starting)
8121 /* Remember the coordinates for when the window is opened. */
8122 gui_win_x = x;
8123 gui_win_y = y;
8125 # ifdef HAVE_TGETENT
8126 else
8127 # endif
8128 # else
8129 # ifdef MSWIN
8130 mch_set_winpos(x, y);
8131 # endif
8132 # endif
8133 # ifdef HAVE_TGETENT
8134 if (*T_CWP)
8135 term_set_winpos(x, y);
8136 # endif
8139 #endif
8142 * Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
8144 static void
8145 ex_operators(eap)
8146 exarg_T *eap;
8148 oparg_T oa;
8150 clear_oparg(&oa);
8151 oa.regname = eap->regname;
8152 oa.start.lnum = eap->line1;
8153 oa.end.lnum = eap->line2;
8154 oa.line_count = eap->line2 - eap->line1 + 1;
8155 oa.motion_type = MLINE;
8156 #ifdef FEAT_VIRTUALEDIT
8157 virtual_op = FALSE;
8158 #endif
8159 if (eap->cmdidx != CMD_yank) /* position cursor for undo */
8161 setpcmark();
8162 curwin->w_cursor.lnum = eap->line1;
8163 beginline(BL_SOL | BL_FIX);
8166 switch (eap->cmdidx)
8168 case CMD_delete:
8169 oa.op_type = OP_DELETE;
8170 op_delete(&oa);
8171 break;
8173 case CMD_yank:
8174 oa.op_type = OP_YANK;
8175 (void)op_yank(&oa, FALSE, TRUE);
8176 break;
8178 default: /* CMD_rshift or CMD_lshift */
8179 if ((eap->cmdidx == CMD_rshift)
8180 #ifdef FEAT_RIGHTLEFT
8181 ^ curwin->w_p_rl
8182 #endif
8184 oa.op_type = OP_RSHIFT;
8185 else
8186 oa.op_type = OP_LSHIFT;
8187 op_shift(&oa, FALSE, eap->amount);
8188 break;
8190 #ifdef FEAT_VIRTUALEDIT
8191 virtual_op = MAYBE;
8192 #endif
8193 ex_may_print(eap);
8197 * ":put".
8199 static void
8200 ex_put(eap)
8201 exarg_T *eap;
8203 /* ":0put" works like ":1put!". */
8204 if (eap->line2 == 0)
8206 eap->line2 = 1;
8207 eap->forceit = TRUE;
8209 curwin->w_cursor.lnum = eap->line2;
8210 do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L,
8211 PUT_LINE|PUT_CURSLINE);
8215 * Handle ":copy" and ":move".
8217 static void
8218 ex_copymove(eap)
8219 exarg_T *eap;
8221 long n;
8223 n = get_address(&eap->arg, FALSE, FALSE);
8224 if (eap->arg == NULL) /* error detected */
8226 eap->nextcmd = NULL;
8227 return;
8229 get_flags(eap);
8232 * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
8234 if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count)
8236 EMSG(_(e_invaddr));
8237 return;
8240 if (eap->cmdidx == CMD_move)
8242 if (do_move(eap->line1, eap->line2, n) == FAIL)
8243 return;
8245 else
8246 ex_copy(eap->line1, eap->line2, n);
8247 u_clearline();
8248 beginline(BL_SOL | BL_FIX);
8249 ex_may_print(eap);
8253 * Print the current line if flags were given to the Ex command.
8255 static void
8256 ex_may_print(eap)
8257 exarg_T *eap;
8259 if (eap->flags != 0)
8261 print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
8262 (eap->flags & EXFLAG_LIST));
8263 ex_no_reprint = TRUE;
8268 * ":smagic" and ":snomagic".
8270 static void
8271 ex_submagic(eap)
8272 exarg_T *eap;
8274 int magic_save = p_magic;
8276 p_magic = (eap->cmdidx == CMD_smagic);
8277 do_sub(eap);
8278 p_magic = magic_save;
8282 * ":join".
8284 static void
8285 ex_join(eap)
8286 exarg_T *eap;
8288 curwin->w_cursor.lnum = eap->line1;
8289 if (eap->line1 == eap->line2)
8291 if (eap->addr_count >= 2) /* :2,2join does nothing */
8292 return;
8293 if (eap->line2 == curbuf->b_ml.ml_line_count)
8295 beep_flush();
8296 return;
8298 ++eap->line2;
8300 do_do_join(eap->line2 - eap->line1 + 1, !eap->forceit);
8301 beginline(BL_WHITE | BL_FIX);
8302 ex_may_print(eap);
8306 * ":[addr]@r" or ":[addr]*r": execute register
8308 static void
8309 ex_at(eap)
8310 exarg_T *eap;
8312 int c;
8314 curwin->w_cursor.lnum = eap->line2;
8316 #ifdef USE_ON_FLY_SCROLL
8317 dont_scroll = TRUE; /* disallow scrolling here */
8318 #endif
8320 /* get the register name. No name means to use the previous one */
8321 c = *eap->arg;
8322 if (c == NUL || (c == '*' && *eap->cmd == '*'))
8323 c = '@';
8324 /* Put the register in the typeahead buffer with the "silent" flag. */
8325 if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE)
8326 == FAIL)
8328 beep_flush();
8330 else
8332 int save_efr = exec_from_reg;
8334 exec_from_reg = TRUE;
8337 * Execute from the typeahead buffer.
8338 * Originally this didn't check for the typeahead buffer to be empty,
8339 * thus could read more Ex commands from stdin. It's not clear why,
8340 * it is certainly unexpected.
8342 while ((!stuff_empty() || typebuf.tb_len > 0) && vpeekc() == ':')
8343 (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
8345 exec_from_reg = save_efr;
8350 * ":!".
8352 static void
8353 ex_bang(eap)
8354 exarg_T *eap;
8356 do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE);
8360 * ":undo".
8362 /*ARGSUSED*/
8363 static void
8364 ex_undo(eap)
8365 exarg_T *eap;
8367 if (eap->addr_count == 1) /* :undo 123 */
8368 undo_time(eap->line2, FALSE, TRUE);
8369 else
8370 u_undo(1);
8374 * ":redo".
8376 /*ARGSUSED*/
8377 static void
8378 ex_redo(eap)
8379 exarg_T *eap;
8381 u_redo(1);
8385 * ":earlier" and ":later".
8387 /*ARGSUSED*/
8388 static void
8389 ex_later(eap)
8390 exarg_T *eap;
8392 long count = 0;
8393 int sec = FALSE;
8394 char_u *p = eap->arg;
8396 if (*p == NUL)
8397 count = 1;
8398 else if (isdigit(*p))
8400 count = getdigits(&p);
8401 switch (*p)
8403 case 's': ++p; sec = TRUE; break;
8404 case 'm': ++p; sec = TRUE; count *= 60; break;
8405 case 'h': ++p; sec = TRUE; count *= 60 * 60; break;
8409 if (*p != NUL)
8410 EMSG2(_(e_invarg2), eap->arg);
8411 else
8412 undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, FALSE);
8416 * ":redir": start/stop redirection.
8418 static void
8419 ex_redir(eap)
8420 exarg_T *eap;
8422 char *mode;
8423 char_u *fname;
8424 char_u *arg = eap->arg;
8426 if (STRICMP(eap->arg, "END") == 0)
8427 close_redir();
8428 else
8430 if (*arg == '>')
8432 ++arg;
8433 if (*arg == '>')
8435 ++arg;
8436 mode = "a";
8438 else
8439 mode = "w";
8440 arg = skipwhite(arg);
8442 close_redir();
8444 /* Expand environment variables and "~/". */
8445 fname = expand_env_save(arg);
8446 if (fname == NULL)
8447 return;
8448 #ifdef FEAT_BROWSE
8449 if (cmdmod.browse)
8451 char_u *browseFile;
8453 browseFile = do_browse(BROWSE_SAVE,
8454 (char_u *)_("Save Redirection"),
8455 fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf);
8456 if (browseFile == NULL)
8457 return; /* operation cancelled */
8458 vim_free(fname);
8459 fname = browseFile;
8460 eap->forceit = TRUE; /* since dialog already asked */
8462 #endif
8464 redir_fd = open_exfile(fname, eap->forceit, mode);
8465 vim_free(fname);
8467 #ifdef FEAT_EVAL
8468 else if (*arg == '@')
8470 /* redirect to a register a-z (resp. A-Z for appending) */
8471 close_redir();
8472 ++arg;
8473 if (ASCII_ISALPHA(*arg)
8474 # ifdef FEAT_CLIPBOARD
8475 || *arg == '*'
8476 || *arg == '+'
8477 # endif
8478 || *arg == '"')
8480 redir_reg = *arg++;
8481 if (*arg == '>' && arg[1] == '>') /* append */
8482 arg += 2;
8483 else
8485 /* Can use both "@a" and "@a>". */
8486 if (*arg == '>')
8487 arg++;
8488 /* Make register empty when not using @A-@Z and the
8489 * command is valid. */
8490 if (*arg == NUL && !isupper(redir_reg))
8491 write_reg_contents(redir_reg, (char_u *)"", -1, FALSE);
8494 if (*arg != NUL)
8496 redir_reg = 0;
8497 EMSG2(_(e_invarg2), eap->arg);
8500 else if (*arg == '=' && arg[1] == '>')
8502 int append;
8504 /* redirect to a variable */
8505 close_redir();
8506 arg += 2;
8508 if (*arg == '>')
8510 ++arg;
8511 append = TRUE;
8513 else
8514 append = FALSE;
8516 if (var_redir_start(skipwhite(arg), append) == OK)
8517 redir_vname = 1;
8519 #endif
8521 /* TODO: redirect to a buffer */
8523 else
8524 EMSG2(_(e_invarg2), eap->arg);
8527 /* Make sure redirection is not off. Can happen for cmdline completion
8528 * that indirectly invokes a command to catch its output. */
8529 if (redir_fd != NULL
8530 #ifdef FEAT_EVAL
8531 || redir_reg || redir_vname
8532 #endif
8534 redir_off = FALSE;
8538 * ":redraw": force redraw
8540 static void
8541 ex_redraw(eap)
8542 exarg_T *eap;
8544 int r = RedrawingDisabled;
8545 int p = p_lz;
8547 RedrawingDisabled = 0;
8548 p_lz = FALSE;
8549 update_topline();
8550 update_screen(eap->forceit ? CLEAR :
8551 #ifdef FEAT_VISUAL
8552 VIsual_active ? INVERTED :
8553 #endif
8555 #ifdef FEAT_TITLE
8556 if (need_maketitle)
8557 maketitle();
8558 #endif
8559 RedrawingDisabled = r;
8560 p_lz = p;
8562 /* Reset msg_didout, so that a message that's there is overwritten. */
8563 msg_didout = FALSE;
8564 msg_col = 0;
8566 out_flush();
8570 * ":redrawstatus": force redraw of status line(s)
8572 /*ARGSUSED*/
8573 static void
8574 ex_redrawstatus(eap)
8575 exarg_T *eap;
8577 #if defined(FEAT_WINDOWS)
8578 int r = RedrawingDisabled;
8579 int p = p_lz;
8581 RedrawingDisabled = 0;
8582 p_lz = FALSE;
8583 if (eap->forceit)
8584 status_redraw_all();
8585 else
8586 status_redraw_curbuf();
8587 update_screen(
8588 # ifdef FEAT_VISUAL
8589 VIsual_active ? INVERTED :
8590 # endif
8592 RedrawingDisabled = r;
8593 p_lz = p;
8594 out_flush();
8595 #endif
8598 static void
8599 close_redir()
8601 if (redir_fd != NULL)
8603 fclose(redir_fd);
8604 redir_fd = NULL;
8606 #ifdef FEAT_EVAL
8607 redir_reg = 0;
8608 if (redir_vname)
8610 var_redir_stop();
8611 redir_vname = 0;
8613 #endif
8616 #if defined(FEAT_SESSION) && defined(USE_CRNL)
8617 # define MKSESSION_NL
8618 static int mksession_nl = FALSE; /* use NL only in put_eol() */
8619 #endif
8622 * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession".
8624 static void
8625 ex_mkrc(eap)
8626 exarg_T *eap;
8628 FILE *fd;
8629 int failed = FALSE;
8630 char_u *fname;
8631 #ifdef FEAT_BROWSE
8632 char_u *browseFile = NULL;
8633 #endif
8634 #ifdef FEAT_SESSION
8635 int view_session = FALSE;
8636 int using_vdir = FALSE; /* using 'viewdir'? */
8637 char_u *viewFile = NULL;
8638 unsigned *flagp;
8639 #endif
8641 if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview)
8643 #ifdef FEAT_SESSION
8644 view_session = TRUE;
8645 #else
8646 ex_ni(eap);
8647 return;
8648 #endif
8651 #ifdef FEAT_SESSION
8652 did_lcd = FALSE;
8654 /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */
8655 if (eap->cmdidx == CMD_mkview
8656 && (*eap->arg == NUL
8657 || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL)))
8659 eap->forceit = TRUE;
8660 fname = get_view_file(*eap->arg);
8661 if (fname == NULL)
8662 return;
8663 viewFile = fname;
8664 using_vdir = TRUE;
8666 else
8667 #endif
8668 if (*eap->arg != NUL)
8669 fname = eap->arg;
8670 else if (eap->cmdidx == CMD_mkvimrc)
8671 fname = (char_u *)VIMRC_FILE;
8672 #ifdef FEAT_SESSION
8673 else if (eap->cmdidx == CMD_mksession)
8674 fname = (char_u *)SESSION_FILE;
8675 #endif
8676 else
8677 fname = (char_u *)EXRC_FILE;
8679 #ifdef FEAT_BROWSE
8680 if (cmdmod.browse)
8682 browseFile = do_browse(BROWSE_SAVE,
8683 # ifdef FEAT_SESSION
8684 eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") :
8685 eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") :
8686 # endif
8687 (char_u *)_("Save Setup"),
8688 fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL);
8689 if (browseFile == NULL)
8690 goto theend;
8691 fname = browseFile;
8692 eap->forceit = TRUE; /* since dialog already asked */
8694 #endif
8696 #if defined(FEAT_SESSION) && defined(vim_mkdir)
8697 /* When using 'viewdir' may have to create the directory. */
8698 if (using_vdir && !mch_isdir(p_vdir))
8699 vim_mkdir_emsg(p_vdir, 0755);
8700 #endif
8702 fd = open_exfile(fname, eap->forceit, WRITEBIN);
8703 if (fd != NULL)
8705 #ifdef FEAT_SESSION
8706 if (eap->cmdidx == CMD_mkview)
8707 flagp = &vop_flags;
8708 else
8709 flagp = &ssop_flags;
8710 #endif
8712 #ifdef MKSESSION_NL
8713 /* "unix" in 'sessionoptions': use NL line separator */
8714 if (view_session && (*flagp & SSOP_UNIX))
8715 mksession_nl = TRUE;
8716 #endif
8718 /* Write the version command for :mkvimrc */
8719 if (eap->cmdidx == CMD_mkvimrc)
8720 (void)put_line(fd, "version 6.0");
8722 #ifdef FEAT_SESSION
8723 if (eap->cmdidx == CMD_mksession)
8725 if (put_line(fd, "let SessionLoad = 1") == FAIL)
8726 failed = TRUE;
8729 if (eap->cmdidx != CMD_mkview)
8730 #endif
8732 /* Write setting 'compatible' first, because it has side effects.
8733 * For that same reason only do it when needed. */
8734 if (p_cp)
8735 (void)put_line(fd, "if !&cp | set cp | endif");
8736 else
8737 (void)put_line(fd, "if &cp | set nocp | endif");
8740 #ifdef FEAT_SESSION
8741 if (!view_session
8742 || (eap->cmdidx == CMD_mksession
8743 && (*flagp & SSOP_OPTIONS)))
8744 #endif
8745 failed |= (makemap(fd, NULL) == FAIL
8746 || makeset(fd, OPT_GLOBAL, FALSE) == FAIL);
8748 #ifdef FEAT_SESSION
8749 if (!failed && view_session)
8751 if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL)
8752 failed = TRUE;
8753 if (eap->cmdidx == CMD_mksession)
8755 char_u dirnow[MAXPATHL]; /* current directory */
8758 * Change to session file's dir.
8760 if (mch_dirname(dirnow, MAXPATHL) == FAIL
8761 || mch_chdir((char *)dirnow) != 0)
8762 *dirnow = NUL;
8763 if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR))
8765 if (vim_chdirfile(fname) == OK)
8766 shorten_fnames(TRUE);
8768 else if (*dirnow != NUL
8769 && (ssop_flags & SSOP_CURDIR) && globaldir != NULL)
8771 (void)mch_chdir((char *)globaldir);
8772 shorten_fnames(TRUE);
8775 failed |= (makeopens(fd, dirnow) == FAIL);
8777 /* restore original dir */
8778 if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR)
8779 || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL)))
8781 if (mch_chdir((char *)dirnow) != 0)
8782 EMSG(_(e_prev_dir));
8783 shorten_fnames(TRUE);
8786 else
8788 failed |= (put_view(fd, curwin, !using_vdir, flagp,
8789 -1) == FAIL);
8791 if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save")
8792 == FAIL)
8793 failed = TRUE;
8794 if (put_line(fd, "doautoall SessionLoadPost") == FAIL)
8795 failed = TRUE;
8796 if (eap->cmdidx == CMD_mksession)
8798 if (put_line(fd, "unlet SessionLoad") == FAIL)
8799 failed = TRUE;
8802 #endif
8803 if (put_line(fd, "\" vim: set ft=vim :") == FAIL)
8804 failed = TRUE;
8806 failed |= fclose(fd);
8808 if (failed)
8809 EMSG(_(e_write));
8810 #if defined(FEAT_EVAL) && defined(FEAT_SESSION)
8811 else if (eap->cmdidx == CMD_mksession)
8813 /* successful session write - set this_session var */
8814 char_u tbuf[MAXPATHL];
8816 if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK)
8817 set_vim_var_string(VV_THIS_SESSION, tbuf, -1);
8819 #endif
8820 #ifdef MKSESSION_NL
8821 mksession_nl = FALSE;
8822 #endif
8825 #ifdef FEAT_BROWSE
8826 theend:
8827 vim_free(browseFile);
8828 #endif
8829 #ifdef FEAT_SESSION
8830 vim_free(viewFile);
8831 #endif
8834 #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \
8835 || defined(PROTO)
8836 /*ARGSUSED*/
8838 vim_mkdir_emsg(name, prot)
8839 char_u *name;
8840 int prot;
8842 if (vim_mkdir(name, prot) != 0)
8844 EMSG2(_("E739: Cannot create directory: %s"), name);
8845 return FAIL;
8847 return OK;
8849 #endif
8852 * Open a file for writing for an Ex command, with some checks.
8853 * Return file descriptor, or NULL on failure.
8855 FILE *
8856 open_exfile(fname, forceit, mode)
8857 char_u *fname;
8858 int forceit;
8859 char *mode; /* "w" for create new file or "a" for append */
8861 FILE *fd;
8863 #ifdef UNIX
8864 /* with Unix it is possible to open a directory */
8865 if (mch_isdir(fname))
8867 EMSG2(_(e_isadir2), fname);
8868 return NULL;
8870 #endif
8871 if (!forceit && *mode != 'a' && vim_fexists(fname))
8873 EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname);
8874 return NULL;
8877 if ((fd = mch_fopen((char *)fname, mode)) == NULL)
8878 EMSG2(_("E190: Cannot open \"%s\" for writing"), fname);
8880 return fd;
8884 * ":mark" and ":k".
8886 static void
8887 ex_mark(eap)
8888 exarg_T *eap;
8890 pos_T pos;
8892 if (*eap->arg == NUL) /* No argument? */
8893 EMSG(_(e_argreq));
8894 else if (eap->arg[1] != NUL) /* more than one character? */
8895 EMSG(_(e_trailing));
8896 else
8898 pos = curwin->w_cursor; /* save curwin->w_cursor */
8899 curwin->w_cursor.lnum = eap->line2;
8900 beginline(BL_WHITE | BL_FIX);
8901 if (setmark(*eap->arg) == FAIL) /* set mark */
8902 EMSG(_("E191: Argument must be a letter or forward/backward quote"));
8903 curwin->w_cursor = pos; /* restore curwin->w_cursor */
8908 * Update w_topline, w_leftcol and the cursor position.
8910 void
8911 update_topline_cursor()
8913 check_cursor(); /* put cursor on valid line */
8914 update_topline();
8915 if (!curwin->w_p_wrap)
8916 validate_cursor();
8917 update_curswant();
8920 #ifdef FEAT_EX_EXTRA
8922 * ":normal[!] {commands}": Execute normal mode commands.
8924 static void
8925 ex_normal(eap)
8926 exarg_T *eap;
8928 int save_msg_scroll = msg_scroll;
8929 int save_restart_edit = restart_edit;
8930 int save_msg_didout = msg_didout;
8931 int save_State = State;
8932 tasave_T tabuf;
8933 int save_insertmode = p_im;
8934 int save_finish_op = finish_op;
8935 int save_opcount = opcount;
8936 #ifdef FEAT_MBYTE
8937 char_u *arg = NULL;
8938 int l;
8939 char_u *p;
8940 #endif
8942 if (ex_normal_lock > 0)
8944 EMSG(_(e_secure));
8945 return;
8947 if (ex_normal_busy >= p_mmd)
8949 EMSG(_("E192: Recursive use of :normal too deep"));
8950 return;
8952 ++ex_normal_busy;
8954 msg_scroll = FALSE; /* no msg scrolling in Normal mode */
8955 restart_edit = 0; /* don't go to Insert mode */
8956 p_im = FALSE; /* don't use 'insertmode' */
8958 #ifdef FEAT_MBYTE
8960 * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
8961 * this for the K_SPECIAL leading byte, otherwise special keys will not
8962 * work.
8964 if (has_mbyte)
8966 int len = 0;
8968 /* Count the number of characters to be escaped. */
8969 for (p = eap->arg; *p != NUL; ++p)
8971 # ifdef FEAT_GUI
8972 if (*p == CSI) /* leadbyte CSI */
8973 len += 2;
8974 # endif
8975 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
8976 if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */
8977 # ifdef FEAT_GUI
8978 || *p == CSI
8979 # endif
8981 len += 2;
8983 if (len > 0)
8985 arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1));
8986 if (arg != NULL)
8988 len = 0;
8989 for (p = eap->arg; *p != NUL; ++p)
8991 arg[len++] = *p;
8992 # ifdef FEAT_GUI
8993 if (*p == CSI)
8995 arg[len++] = KS_EXTRA;
8996 arg[len++] = (int)KE_CSI;
8998 # endif
8999 for (l = (*mb_ptr2len)(p) - 1; l > 0; --l)
9001 arg[len++] = *++p;
9002 if (*p == K_SPECIAL)
9004 arg[len++] = KS_SPECIAL;
9005 arg[len++] = KE_FILLER;
9007 # ifdef FEAT_GUI
9008 else if (*p == CSI)
9010 arg[len++] = KS_EXTRA;
9011 arg[len++] = (int)KE_CSI;
9013 # endif
9015 arg[len] = NUL;
9020 #endif
9023 * Save the current typeahead. This is required to allow using ":normal"
9024 * from an event handler and makes sure we don't hang when the argument
9025 * ends with half a command.
9027 save_typeahead(&tabuf);
9028 if (tabuf.typebuf_valid)
9031 * Repeat the :normal command for each line in the range. When no
9032 * range given, execute it just once, without positioning the cursor
9033 * first.
9037 if (eap->addr_count != 0)
9039 curwin->w_cursor.lnum = eap->line1++;
9040 curwin->w_cursor.col = 0;
9043 exec_normal_cmd(
9044 #ifdef FEAT_MBYTE
9045 arg != NULL ? arg :
9046 #endif
9047 eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE);
9049 while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
9052 /* Might not return to the main loop when in an event handler. */
9053 update_topline_cursor();
9055 /* Restore the previous typeahead. */
9056 restore_typeahead(&tabuf);
9058 --ex_normal_busy;
9059 msg_scroll = save_msg_scroll;
9060 restart_edit = save_restart_edit;
9061 p_im = save_insertmode;
9062 finish_op = save_finish_op;
9063 opcount = save_opcount;
9064 msg_didout |= save_msg_didout; /* don't reset msg_didout now */
9066 /* Restore the state (needed when called from a function executed for
9067 * 'indentexpr'). */
9068 State = save_State;
9069 #ifdef FEAT_MBYTE
9070 vim_free(arg);
9071 #endif
9075 * ":startinsert", ":startreplace" and ":startgreplace"
9077 static void
9078 ex_startinsert(eap)
9079 exarg_T *eap;
9081 if (eap->forceit)
9083 coladvance((colnr_T)MAXCOL);
9084 curwin->w_curswant = MAXCOL;
9085 curwin->w_set_curswant = FALSE;
9088 /* Ignore the command when already in Insert mode. Inserting an
9089 * expression register that invokes a function can do this. */
9090 if (State & INSERT)
9091 return;
9093 if (eap->cmdidx == CMD_startinsert)
9094 restart_edit = 'a';
9095 else if (eap->cmdidx == CMD_startreplace)
9096 restart_edit = 'R';
9097 else
9098 restart_edit = 'V';
9100 if (!eap->forceit)
9102 if (eap->cmdidx == CMD_startinsert)
9103 restart_edit = 'i';
9104 curwin->w_curswant = 0; /* avoid MAXCOL */
9109 * ":stopinsert"
9111 /*ARGSUSED*/
9112 static void
9113 ex_stopinsert(eap)
9114 exarg_T *eap;
9116 restart_edit = 0;
9117 stop_insert_mode = TRUE;
9119 #endif
9121 #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO)
9123 * Execute normal mode command "cmd".
9124 * "remap" can be REMAP_NONE or REMAP_YES.
9126 void
9127 exec_normal_cmd(cmd, remap, silent)
9128 char_u *cmd;
9129 int remap;
9130 int silent;
9132 oparg_T oa;
9135 * Stuff the argument into the typeahead buffer.
9136 * Execute normal_cmd() until there is no typeahead left.
9138 clear_oparg(&oa);
9139 finish_op = FALSE;
9140 ins_typebuf(cmd, remap, 0, TRUE, silent);
9141 while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0))
9142 && !got_int)
9144 update_topline_cursor();
9145 normal_cmd(&oa, FALSE); /* execute a Normal mode cmd */
9148 #endif
9150 #ifdef FEAT_FIND_ID
9151 static void
9152 ex_checkpath(eap)
9153 exarg_T *eap;
9155 find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L,
9156 eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
9157 (linenr_T)1, (linenr_T)MAXLNUM);
9160 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
9162 * ":psearch"
9164 static void
9165 ex_psearch(eap)
9166 exarg_T *eap;
9168 g_do_tagpreview = p_pvh;
9169 ex_findpat(eap);
9170 g_do_tagpreview = 0;
9172 #endif
9174 static void
9175 ex_findpat(eap)
9176 exarg_T *eap;
9178 int whole = TRUE;
9179 long n;
9180 char_u *p;
9181 int action;
9183 switch (cmdnames[eap->cmdidx].cmd_name[2])
9185 case 'e': /* ":psearch", ":isearch" and ":dsearch" */
9186 if (cmdnames[eap->cmdidx].cmd_name[0] == 'p')
9187 action = ACTION_GOTO;
9188 else
9189 action = ACTION_SHOW;
9190 break;
9191 case 'i': /* ":ilist" and ":dlist" */
9192 action = ACTION_SHOW_ALL;
9193 break;
9194 case 'u': /* ":ijump" and ":djump" */
9195 action = ACTION_GOTO;
9196 break;
9197 default: /* ":isplit" and ":dsplit" */
9198 action = ACTION_SPLIT;
9199 break;
9202 n = 1;
9203 if (vim_isdigit(*eap->arg)) /* get count */
9205 n = getdigits(&eap->arg);
9206 eap->arg = skipwhite(eap->arg);
9208 if (*eap->arg == '/') /* Match regexp, not just whole words */
9210 whole = FALSE;
9211 ++eap->arg;
9212 p = skip_regexp(eap->arg, '/', p_magic, NULL);
9213 if (*p)
9215 *p++ = NUL;
9216 p = skipwhite(p);
9218 /* Check for trailing illegal characters */
9219 if (!ends_excmd(*p))
9220 eap->errmsg = e_trailing;
9221 else
9222 eap->nextcmd = check_nextcmd(p);
9225 if (!eap->skip)
9226 find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg),
9227 whole, !eap->forceit,
9228 *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY,
9229 n, action, eap->line1, eap->line2);
9231 #endif
9233 #ifdef FEAT_WINDOWS
9235 # ifdef FEAT_QUICKFIX
9237 * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
9239 static void
9240 ex_ptag(eap)
9241 exarg_T *eap;
9243 g_do_tagpreview = p_pvh;
9244 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9248 * ":pedit"
9250 static void
9251 ex_pedit(eap)
9252 exarg_T *eap;
9254 win_T *curwin_save = curwin;
9256 g_do_tagpreview = p_pvh;
9257 prepare_tagpreview(TRUE);
9258 keep_help_flag = curwin_save->w_buffer->b_help;
9259 do_exedit(eap, NULL);
9260 keep_help_flag = FALSE;
9261 if (curwin != curwin_save && win_valid(curwin_save))
9263 /* Return cursor to where we were */
9264 validate_cursor();
9265 redraw_later(VALID);
9266 win_enter(curwin_save, TRUE);
9268 g_do_tagpreview = 0;
9270 # endif
9273 * ":stag", ":stselect" and ":stjump".
9275 static void
9276 ex_stag(eap)
9277 exarg_T *eap;
9279 postponed_split = -1;
9280 postponed_split_flags = cmdmod.split;
9281 postponed_split_tab = cmdmod.tab;
9282 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
9283 postponed_split_flags = 0;
9284 postponed_split_tab = 0;
9286 #endif
9289 * ":tag", ":tselect", ":tjump", ":tnext", etc.
9291 static void
9292 ex_tag(eap)
9293 exarg_T *eap;
9295 ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
9298 static void
9299 ex_tag_cmd(eap, name)
9300 exarg_T *eap;
9301 char_u *name;
9303 int cmd;
9305 switch (name[1])
9307 case 'j': cmd = DT_JUMP; /* ":tjump" */
9308 break;
9309 case 's': cmd = DT_SELECT; /* ":tselect" */
9310 break;
9311 case 'p': cmd = DT_PREV; /* ":tprevious" */
9312 break;
9313 case 'N': cmd = DT_PREV; /* ":tNext" */
9314 break;
9315 case 'n': cmd = DT_NEXT; /* ":tnext" */
9316 break;
9317 case 'o': cmd = DT_POP; /* ":pop" */
9318 break;
9319 case 'f': /* ":tfirst" */
9320 case 'r': cmd = DT_FIRST; /* ":trewind" */
9321 break;
9322 case 'l': cmd = DT_LAST; /* ":tlast" */
9323 break;
9324 default: /* ":tag" */
9325 #ifdef FEAT_CSCOPE
9326 if (p_cst && *eap->arg != NUL)
9328 do_cstag(eap);
9329 return;
9331 #endif
9332 cmd = DT_TAG;
9333 break;
9336 if (name[0] == 'l')
9338 #ifndef FEAT_QUICKFIX
9339 ex_ni(eap);
9340 return;
9341 #else
9342 cmd = DT_LTAG;
9343 #endif
9346 do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1,
9347 eap->forceit, TRUE);
9351 * Check "str" for starting with a special cmdline variable.
9352 * If found return one of the SPEC_ values and set "*usedlen" to the length of
9353 * the variable. Otherwise return -1 and "*usedlen" is unchanged.
9356 find_cmdline_var(src, usedlen)
9357 char_u *src;
9358 int *usedlen;
9360 int len;
9361 int i;
9362 static char *(spec_str[]) = {
9363 "%",
9364 #define SPEC_PERC 0
9365 "#",
9366 #define SPEC_HASH 1
9367 "<cword>", /* cursor word */
9368 #define SPEC_CWORD 2
9369 "<cWORD>", /* cursor WORD */
9370 #define SPEC_CCWORD 3
9371 "<cfile>", /* cursor path name */
9372 #define SPEC_CFILE 4
9373 "<sfile>", /* ":so" file name */
9374 #define SPEC_SFILE 5
9375 #ifdef FEAT_AUTOCMD
9376 "<afile>", /* autocommand file name */
9377 # define SPEC_AFILE 6
9378 "<abuf>", /* autocommand buffer number */
9379 # define SPEC_ABUF 7
9380 "<amatch>", /* autocommand match name */
9381 # define SPEC_AMATCH 8
9382 #endif
9383 #ifdef FEAT_CLIENTSERVER
9384 "<client>"
9385 # define SPEC_CLIENT 9
9386 #endif
9388 #define SPEC_COUNT (sizeof(spec_str) / sizeof(char *))
9390 for (i = 0; i < SPEC_COUNT; ++i)
9392 len = (int)STRLEN(spec_str[i]);
9393 if (STRNCMP(src, spec_str[i], len) == 0)
9395 *usedlen = len;
9396 return i;
9399 return -1;
9403 * Evaluate cmdline variables.
9405 * change '%' to curbuf->b_ffname
9406 * '#' to curwin->w_altfile
9407 * '<cword>' to word under the cursor
9408 * '<cWORD>' to WORD under the cursor
9409 * '<cfile>' to path name under the cursor
9410 * '<sfile>' to sourced file name
9411 * '<afile>' to file name for autocommand
9412 * '<abuf>' to buffer number for autocommand
9413 * '<amatch>' to matching name for autocommand
9415 * When an error is detected, "errormsg" is set to a non-NULL pointer (may be
9416 * "" for error without a message) and NULL is returned.
9417 * Returns an allocated string if a valid match was found.
9418 * Returns NULL if no match was found. "usedlen" then still contains the
9419 * number of characters to skip.
9421 char_u *
9422 eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped)
9423 char_u *src; /* pointer into commandline */
9424 char_u *srcstart; /* beginning of valid memory for src */
9425 int *usedlen; /* characters after src that are used */
9426 linenr_T *lnump; /* line number for :e command, or NULL */
9427 char_u **errormsg; /* pointer to error message */
9428 int *escaped; /* return value has escaped white space (can
9429 * be NULL) */
9431 int i;
9432 char_u *s;
9433 char_u *result;
9434 char_u *resultbuf = NULL;
9435 int resultlen;
9436 buf_T *buf;
9437 int valid = VALID_HEAD + VALID_PATH; /* assume valid result */
9438 int spec_idx;
9439 #ifdef FEAT_MODIFY_FNAME
9440 int skip_mod = FALSE;
9441 #endif
9443 #if defined(FEAT_AUTOCMD) || defined(FEAT_CLIENTSERVER)
9444 char_u strbuf[30];
9445 #endif
9447 *errormsg = NULL;
9448 if (escaped != NULL)
9449 *escaped = FALSE;
9452 * Check if there is something to do.
9454 spec_idx = find_cmdline_var(src, usedlen);
9455 if (spec_idx < 0) /* no match */
9457 *usedlen = 1;
9458 return NULL;
9462 * Skip when preceded with a backslash "\%" and "\#".
9463 * Note: In "\\%" the % is also not recognized!
9465 if (src > srcstart && src[-1] == '\\')
9467 *usedlen = 0;
9468 STRMOVE(src - 1, src); /* remove backslash */
9469 return NULL;
9473 * word or WORD under cursor
9475 if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD)
9477 resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ?
9478 (FIND_IDENT|FIND_STRING) : FIND_STRING);
9479 if (resultlen == 0)
9481 *errormsg = (char_u *)"";
9482 return NULL;
9487 * '#': Alternate file name
9488 * '%': Current file name
9489 * File name under the cursor
9490 * File name for autocommand
9491 * and following modifiers
9493 else
9495 switch (spec_idx)
9497 case SPEC_PERC: /* '%': current file */
9498 if (curbuf->b_fname == NULL)
9500 result = (char_u *)"";
9501 valid = 0; /* Must have ":p:h" to be valid */
9503 else
9504 #ifdef RISCOS
9505 /* Always use the full path for RISC OS if possible. */
9506 result = curbuf->b_ffname;
9507 if (result == NULL)
9508 result = curbuf->b_fname;
9509 #else
9510 result = curbuf->b_fname;
9511 #endif
9512 break;
9514 case SPEC_HASH: /* '#' or "#99": alternate file */
9515 if (src[1] == '#') /* "##": the argument list */
9517 result = arg_all();
9518 resultbuf = result;
9519 *usedlen = 2;
9520 if (escaped != NULL)
9521 *escaped = TRUE;
9522 #ifdef FEAT_MODIFY_FNAME
9523 skip_mod = TRUE;
9524 #endif
9525 break;
9527 s = src + 1;
9528 i = (int)getdigits(&s);
9529 *usedlen = (int)(s - src); /* length of what we expand */
9531 buf = buflist_findnr(i);
9532 if (buf == NULL)
9534 *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'");
9535 return NULL;
9537 if (lnump != NULL)
9538 *lnump = ECMD_LAST;
9539 if (buf->b_fname == NULL)
9541 result = (char_u *)"";
9542 valid = 0; /* Must have ":p:h" to be valid */
9544 else
9545 result = buf->b_fname;
9546 break;
9548 #ifdef FEAT_SEARCHPATH
9549 case SPEC_CFILE: /* file name under cursor */
9550 result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL);
9551 if (result == NULL)
9553 *errormsg = (char_u *)"";
9554 return NULL;
9556 resultbuf = result; /* remember allocated string */
9557 break;
9558 #endif
9560 #ifdef FEAT_AUTOCMD
9561 case SPEC_AFILE: /* file name for autocommand */
9562 result = autocmd_fname;
9563 if (result == NULL)
9565 *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\"");
9566 return NULL;
9568 result = shorten_fname1(result);
9569 break;
9571 case SPEC_ABUF: /* buffer number for autocommand */
9572 if (autocmd_bufnr <= 0)
9574 *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\"");
9575 return NULL;
9577 sprintf((char *)strbuf, "%d", autocmd_bufnr);
9578 result = strbuf;
9579 break;
9581 case SPEC_AMATCH: /* match name for autocommand */
9582 result = autocmd_match;
9583 if (result == NULL)
9585 *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\"");
9586 return NULL;
9588 break;
9590 #endif
9591 case SPEC_SFILE: /* file name for ":so" command */
9592 result = sourcing_name;
9593 if (result == NULL)
9595 *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\"");
9596 return NULL;
9598 break;
9599 #if defined(FEAT_CLIENTSERVER)
9600 case SPEC_CLIENT: /* Source of last submitted input */
9601 sprintf((char *)strbuf, PRINTF_HEX_LONG_U,
9602 (long_u)clientWindow);
9603 result = strbuf;
9604 break;
9605 #endif
9608 resultlen = (int)STRLEN(result); /* length of new string */
9609 if (src[*usedlen] == '<') /* remove the file name extension */
9611 ++*usedlen;
9612 #ifdef RISCOS
9613 if ((s = vim_strrchr(result, '/')) != NULL && s >= gettail(result))
9614 #else
9615 if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result))
9616 #endif
9617 resultlen = (int)(s - result);
9619 #ifdef FEAT_MODIFY_FNAME
9620 else if (!skip_mod)
9622 valid |= modify_fname(src, usedlen, &result, &resultbuf,
9623 &resultlen);
9624 if (result == NULL)
9626 *errormsg = (char_u *)"";
9627 return NULL;
9630 #endif
9633 if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH)
9635 if (valid != VALID_HEAD + VALID_PATH)
9636 /* xgettext:no-c-format */
9637 *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\"");
9638 else
9639 *errormsg = (char_u *)_("E500: Evaluates to an empty string");
9640 result = NULL;
9642 else
9643 result = vim_strnsave(result, resultlen);
9644 vim_free(resultbuf);
9645 return result;
9649 * Concatenate all files in the argument list, separated by spaces, and return
9650 * it in one allocated string.
9651 * Spaces and backslashes in the file names are escaped with a backslash.
9652 * Returns NULL when out of memory.
9654 static char_u *
9655 arg_all()
9657 int len;
9658 int idx;
9659 char_u *retval = NULL;
9660 char_u *p;
9663 * Do this loop two times:
9664 * first time: compute the total length
9665 * second time: concatenate the names
9667 for (;;)
9669 len = 0;
9670 for (idx = 0; idx < ARGCOUNT; ++idx)
9672 p = alist_name(&ARGLIST[idx]);
9673 if (p != NULL)
9675 if (len > 0)
9677 /* insert a space in between names */
9678 if (retval != NULL)
9679 retval[len] = ' ';
9680 ++len;
9682 for ( ; *p != NUL; ++p)
9684 if (*p == ' ' || *p == '\\')
9686 /* insert a backslash */
9687 if (retval != NULL)
9688 retval[len] = '\\';
9689 ++len;
9691 if (retval != NULL)
9692 retval[len] = *p;
9693 ++len;
9698 /* second time: break here */
9699 if (retval != NULL)
9701 retval[len] = NUL;
9702 break;
9705 /* allocate memory */
9706 retval = alloc(len + 1);
9707 if (retval == NULL)
9708 break;
9711 return retval;
9714 #if defined(FEAT_AUTOCMD) || defined(PROTO)
9716 * Expand the <sfile> string in "arg".
9718 * Returns an allocated string, or NULL for any error.
9720 char_u *
9721 expand_sfile(arg)
9722 char_u *arg;
9724 char_u *errormsg;
9725 int len;
9726 char_u *result;
9727 char_u *newres;
9728 char_u *repl;
9729 int srclen;
9730 char_u *p;
9732 result = vim_strsave(arg);
9733 if (result == NULL)
9734 return NULL;
9736 for (p = result; *p; )
9738 if (STRNCMP(p, "<sfile>", 7) != 0)
9739 ++p;
9740 else
9742 /* replace "<sfile>" with the sourced file name, and do ":" stuff */
9743 repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL);
9744 if (errormsg != NULL)
9746 if (*errormsg)
9747 emsg(errormsg);
9748 vim_free(result);
9749 return NULL;
9751 if (repl == NULL) /* no match (cannot happen) */
9753 p += srclen;
9754 continue;
9756 len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1;
9757 newres = alloc(len);
9758 if (newres == NULL)
9760 vim_free(repl);
9761 vim_free(result);
9762 return NULL;
9764 mch_memmove(newres, result, (size_t)(p - result));
9765 STRCPY(newres + (p - result), repl);
9766 len = (int)STRLEN(newres);
9767 STRCAT(newres, p + srclen);
9768 vim_free(repl);
9769 vim_free(result);
9770 result = newres;
9771 p = newres + len; /* continue after the match */
9775 return result;
9777 #endif
9779 #ifdef FEAT_SESSION
9780 static int ses_winsizes __ARGS((FILE *fd, int restore_size,
9781 win_T *tab_firstwin));
9782 static int ses_win_rec __ARGS((FILE *fd, frame_T *fr));
9783 static frame_T *ses_skipframe __ARGS((frame_T *fr));
9784 static int ses_do_frame __ARGS((frame_T *fr));
9785 static int ses_do_win __ARGS((win_T *wp));
9786 static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp));
9787 static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp));
9788 static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp));
9791 * Write openfile commands for the current buffers to an .exrc file.
9792 * Return FAIL on error, OK otherwise.
9794 static int
9795 makeopens(fd, dirnow)
9796 FILE *fd;
9797 char_u *dirnow; /* Current directory name */
9799 buf_T *buf;
9800 int only_save_windows = TRUE;
9801 int nr;
9802 int cnr = 1;
9803 int restore_size = TRUE;
9804 win_T *wp;
9805 char_u *sname;
9806 win_T *edited_win = NULL;
9807 int tabnr;
9808 win_T *tab_firstwin;
9809 frame_T *tab_topframe;
9810 int cur_arg_idx = 0;
9811 int next_arg_idx = 0;
9813 if (ssop_flags & SSOP_BUFFERS)
9814 only_save_windows = FALSE; /* Save ALL buffers */
9817 * Begin by setting the this_session variable, and then other
9818 * sessionable variables.
9820 #ifdef FEAT_EVAL
9821 if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL)
9822 return FAIL;
9823 if (ssop_flags & SSOP_GLOBALS)
9824 if (store_session_globals(fd) == FAIL)
9825 return FAIL;
9826 #endif
9829 * Close all windows but one.
9831 if (put_line(fd, "silent only") == FAIL)
9832 return FAIL;
9835 * Now a :cd command to the session directory or the current directory
9837 if (ssop_flags & SSOP_SESDIR)
9839 if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')")
9840 == FAIL)
9841 return FAIL;
9843 else if (ssop_flags & SSOP_CURDIR)
9845 sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow);
9846 if (sname == NULL
9847 || fputs("cd ", fd) < 0
9848 || ses_put_fname(fd, sname, &ssop_flags) == FAIL
9849 || put_eol(fd) == FAIL)
9851 vim_free(sname);
9852 return FAIL;
9854 vim_free(sname);
9858 * If there is an empty, unnamed buffer we will wipe it out later.
9859 * Remember the buffer number.
9861 if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL)
9862 return FAIL;
9863 if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL)
9864 return FAIL;
9865 if (put_line(fd, "endif") == FAIL)
9866 return FAIL;
9869 * Now save the current files, current buffer first.
9871 if (put_line(fd, "set shortmess=aoO") == FAIL)
9872 return FAIL;
9874 /* Now put the other buffers into the buffer list */
9875 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9877 if (!(only_save_windows && buf->b_nwindows == 0)
9878 && !(buf->b_help && !(ssop_flags & SSOP_HELP))
9879 && buf->b_fname != NULL
9880 && buf->b_p_bl)
9882 if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L
9883 : buf->b_wininfo->wi_fpos.lnum) < 0
9884 || ses_fname(fd, buf, &ssop_flags) == FAIL)
9885 return FAIL;
9889 /* the global argument list */
9890 if (ses_arglist(fd, "args", &global_alist.al_ga,
9891 !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL)
9892 return FAIL;
9894 if (ssop_flags & SSOP_RESIZE)
9896 /* Note: after the restore we still check it worked!*/
9897 if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0
9898 || put_eol(fd) == FAIL)
9899 return FAIL;
9900 #ifdef FEAT_FULLSCREEN
9901 /* fullscreen needs to be set after lines and columns */
9902 if (p_fullscreen)
9904 if (fprintf(fd, "set fullscreen") < 0 || put_eol(fd) == FAIL)
9905 return FAIL;
9907 #endif
9910 #ifdef FEAT_GUI
9911 if (gui.in_use && (ssop_flags & SSOP_WINPOS))
9913 int x, y;
9915 if (gui_mch_get_winpos(&x, &y) == OK)
9917 /* Note: after the restore we still check it worked!*/
9918 if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL)
9919 return FAIL;
9922 #endif
9925 * May repeat putting Windows for each tab, when "tabpages" is in
9926 * 'sessionoptions'.
9927 * Don't use goto_tabpage(), it may change directory and trigger
9928 * autocommands.
9930 tab_firstwin = firstwin; /* first window in tab page "tabnr" */
9931 tab_topframe = topframe;
9932 for (tabnr = 1; ; ++tabnr)
9934 int need_tabnew = FALSE;
9936 if ((ssop_flags & SSOP_TABPAGES))
9938 tabpage_T *tp = find_tabpage(tabnr);
9940 if (tp == NULL)
9941 break; /* done all tab pages */
9942 if (tp == curtab)
9944 tab_firstwin = firstwin;
9945 tab_topframe = topframe;
9947 else
9949 tab_firstwin = tp->tp_firstwin;
9950 tab_topframe = tp->tp_topframe;
9952 if (tabnr > 1)
9953 need_tabnew = TRUE;
9957 * Before creating the window layout, try loading one file. If this
9958 * is aborted we don't end up with a number of useless windows.
9959 * This may have side effects! (e.g., compressed or network file).
9961 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
9963 if (ses_do_win(wp)
9964 && wp->w_buffer->b_ffname != NULL
9965 && !wp->w_buffer->b_help
9966 #ifdef FEAT_QUICKFIX
9967 && !bt_nofile(wp->w_buffer)
9968 #endif
9971 if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0
9972 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL)
9973 return FAIL;
9974 need_tabnew = FALSE;
9975 if (!wp->w_arg_idx_invalid)
9976 edited_win = wp;
9977 break;
9981 /* If no file got edited create an empty tab page. */
9982 if (need_tabnew && put_line(fd, "tabnew") == FAIL)
9983 return FAIL;
9986 * Save current window layout.
9988 if (put_line(fd, "set splitbelow splitright") == FAIL)
9989 return FAIL;
9990 if (ses_win_rec(fd, tab_topframe) == FAIL)
9991 return FAIL;
9992 if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL)
9993 return FAIL;
9994 if (!p_spr && put_line(fd, "set nosplitright") == FAIL)
9995 return FAIL;
9998 * Check if window sizes can be restored (no windows omitted).
9999 * Remember the window number of the current window after restoring.
10001 nr = 0;
10002 for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp))
10004 if (ses_do_win(wp))
10005 ++nr;
10006 else
10007 restore_size = FALSE;
10008 if (curwin == wp)
10009 cnr = nr;
10012 /* Go to the first window. */
10013 if (put_line(fd, "wincmd t") == FAIL)
10014 return FAIL;
10017 * If more than one window, see if sizes can be restored.
10018 * First set 'winheight' and 'winwidth' to 1 to avoid the windows being
10019 * resized when moving between windows.
10020 * Do this before restoring the view, so that the topline and the
10021 * cursor can be set. This is done again below.
10023 if (put_line(fd, "set winheight=1 winwidth=1") == FAIL)
10024 return FAIL;
10025 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10026 return FAIL;
10029 * Restore the view of the window (options, file, cursor, etc.).
10031 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10033 if (!ses_do_win(wp))
10034 continue;
10035 if (put_view(fd, wp, wp != edited_win, &ssop_flags,
10036 cur_arg_idx) == FAIL)
10037 return FAIL;
10038 if (nr > 1 && put_line(fd, "wincmd w") == FAIL)
10039 return FAIL;
10040 next_arg_idx = wp->w_arg_idx;
10043 /* The argument index in the first tab page is zero, need to set it in
10044 * each window. For further tab pages it's the window where we do
10045 * "tabedit". */
10046 cur_arg_idx = next_arg_idx;
10049 * Restore cursor to the current window if it's not the first one.
10051 if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0
10052 || put_eol(fd) == FAIL))
10053 return FAIL;
10056 * Restore window sizes again after jumping around in windows, because
10057 * the current window has a minimum size while others may not.
10059 if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL)
10060 return FAIL;
10062 /* Don't continue in another tab page when doing only the current one
10063 * or when at the last tab page. */
10064 if (!(ssop_flags & SSOP_TABPAGES))
10065 break;
10068 if (ssop_flags & SSOP_TABPAGES)
10070 if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0
10071 || put_eol(fd) == FAIL)
10072 return FAIL;
10076 * Wipe out an empty unnamed buffer we started in.
10078 if (put_line(fd, "if exists('s:wipebuf')") == FAIL)
10079 return FAIL;
10080 if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL)
10081 return FAIL;
10082 if (put_line(fd, "endif") == FAIL)
10083 return FAIL;
10084 if (put_line(fd, "unlet! s:wipebuf") == FAIL)
10085 return FAIL;
10087 /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */
10088 if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s",
10089 p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL)
10090 return FAIL;
10093 * Lastly, execute the x.vim file if it exists.
10095 if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL
10096 || put_line(fd, "if file_readable(s:sx)") == FAIL
10097 || put_line(fd, " exe \"source \" . s:sx") == FAIL
10098 || put_line(fd, "endif") == FAIL)
10099 return FAIL;
10101 return OK;
10104 static int
10105 ses_winsizes(fd, restore_size, tab_firstwin)
10106 FILE *fd;
10107 int restore_size;
10108 win_T *tab_firstwin;
10110 int n = 0;
10111 win_T *wp;
10113 if (restore_size && (ssop_flags & SSOP_WINSIZE))
10115 for (wp = tab_firstwin; wp != NULL; wp = wp->w_next)
10117 if (!ses_do_win(wp))
10118 continue;
10119 ++n;
10121 /* restore height when not full height */
10122 if (wp->w_height + wp->w_status_height < topframe->fr_height
10123 && (fprintf(fd,
10124 "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)",
10125 n, (long)wp->w_height, Rows / 2, Rows) < 0
10126 || put_eol(fd) == FAIL))
10127 return FAIL;
10129 /* restore width when not full width */
10130 if (wp->w_width < Columns && (fprintf(fd,
10131 "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)",
10132 n, (long)wp->w_width, Columns / 2, Columns) < 0
10133 || put_eol(fd) == FAIL))
10134 return FAIL;
10137 else
10139 /* Just equalise window sizes */
10140 if (put_line(fd, "wincmd =") == FAIL)
10141 return FAIL;
10143 return OK;
10147 * Write commands to "fd" to recursively create windows for frame "fr",
10148 * horizontally and vertically split.
10149 * After the commands the last window in the frame is the current window.
10150 * Returns FAIL when writing the commands to "fd" fails.
10152 static int
10153 ses_win_rec(fd, fr)
10154 FILE *fd;
10155 frame_T *fr;
10157 frame_T *frc;
10158 int count = 0;
10160 if (fr->fr_layout != FR_LEAF)
10162 /* Find first frame that's not skipped and then create a window for
10163 * each following one (first frame is already there). */
10164 frc = ses_skipframe(fr->fr_child);
10165 if (frc != NULL)
10166 while ((frc = ses_skipframe(frc->fr_next)) != NULL)
10168 /* Make window as big as possible so that we have lots of room
10169 * to split. */
10170 if (put_line(fd, "wincmd _ | wincmd |") == FAIL
10171 || put_line(fd, fr->fr_layout == FR_COL
10172 ? "split" : "vsplit") == FAIL)
10173 return FAIL;
10174 ++count;
10177 /* Go back to the first window. */
10178 if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL
10179 ? "%dwincmd k" : "%dwincmd h", count) < 0
10180 || put_eol(fd) == FAIL))
10181 return FAIL;
10183 /* Recursively create frames/windows in each window of this column or
10184 * row. */
10185 frc = ses_skipframe(fr->fr_child);
10186 while (frc != NULL)
10188 ses_win_rec(fd, frc);
10189 frc = ses_skipframe(frc->fr_next);
10190 /* Go to next window. */
10191 if (frc != NULL && put_line(fd, "wincmd w") == FAIL)
10192 return FAIL;
10195 return OK;
10199 * Skip frames that don't contain windows we want to save in the Session.
10200 * Returns NULL when there none.
10202 static frame_T *
10203 ses_skipframe(fr)
10204 frame_T *fr;
10206 frame_T *frc;
10208 for (frc = fr; frc != NULL; frc = frc->fr_next)
10209 if (ses_do_frame(frc))
10210 break;
10211 return frc;
10215 * Return TRUE if frame "fr" has a window somewhere that we want to save in
10216 * the Session.
10218 static int
10219 ses_do_frame(fr)
10220 frame_T *fr;
10222 frame_T *frc;
10224 if (fr->fr_layout == FR_LEAF)
10225 return ses_do_win(fr->fr_win);
10226 for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next)
10227 if (ses_do_frame(frc))
10228 return TRUE;
10229 return FALSE;
10233 * Return non-zero if window "wp" is to be stored in the Session.
10235 static int
10236 ses_do_win(wp)
10237 win_T *wp;
10239 if (wp->w_buffer->b_fname == NULL
10240 #ifdef FEAT_QUICKFIX
10241 /* When 'buftype' is "nofile" can't restore the window contents. */
10242 || bt_nofile(wp->w_buffer)
10243 #endif
10245 return (ssop_flags & SSOP_BLANK);
10246 if (wp->w_buffer->b_help)
10247 return (ssop_flags & SSOP_HELP);
10248 return TRUE;
10252 * Write commands to "fd" to restore the view of a window.
10253 * Caller must make sure 'scrolloff' is zero.
10255 static int
10256 put_view(fd, wp, add_edit, flagp, current_arg_idx)
10257 FILE *fd;
10258 win_T *wp;
10259 int add_edit; /* add ":edit" command to view */
10260 unsigned *flagp; /* vop_flags or ssop_flags */
10261 int current_arg_idx; /* current argument index of the window, use
10262 * -1 if unknown */
10264 win_T *save_curwin;
10265 int f;
10266 int do_cursor;
10267 int did_next = FALSE;
10269 /* Always restore cursor position for ":mksession". For ":mkview" only
10270 * when 'viewoptions' contains "cursor". */
10271 do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR);
10274 * Local argument list.
10276 if (wp->w_alist == &global_alist)
10278 if (put_line(fd, "argglobal") == FAIL)
10279 return FAIL;
10281 else
10283 if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga,
10284 flagp == &vop_flags
10285 || !(*flagp & SSOP_CURDIR)
10286 || wp->w_localdir != NULL, flagp) == FAIL)
10287 return FAIL;
10290 /* Only when part of a session: restore the argument index. Some
10291 * arguments may have been deleted, check if the index is valid. */
10292 if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx <= WARGCOUNT(wp)
10293 && flagp == &ssop_flags)
10295 if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0
10296 || put_eol(fd) == FAIL)
10297 return FAIL;
10298 did_next = TRUE;
10301 /* Edit the file. Skip this when ":next" already did it. */
10302 if (add_edit && (!did_next || wp->w_arg_idx_invalid))
10305 * Load the file.
10307 if (wp->w_buffer->b_ffname != NULL
10308 #ifdef FEAT_QUICKFIX
10309 && !bt_nofile(wp->w_buffer)
10310 #endif
10314 * Editing a file in this buffer: use ":edit file".
10315 * This may have side effects! (e.g., compressed or network file).
10317 if (fputs("edit ", fd) < 0
10318 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10319 return FAIL;
10321 else
10323 /* No file in this buffer, just make it empty. */
10324 if (put_line(fd, "enew") == FAIL)
10325 return FAIL;
10326 #ifdef FEAT_QUICKFIX
10327 if (wp->w_buffer->b_ffname != NULL)
10329 /* The buffer does have a name, but it's not a file name. */
10330 if (fputs("file ", fd) < 0
10331 || ses_fname(fd, wp->w_buffer, flagp) == FAIL)
10332 return FAIL;
10334 #endif
10335 do_cursor = FALSE;
10340 * Local mappings and abbreviations.
10342 if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10343 && makemap(fd, wp->w_buffer) == FAIL)
10344 return FAIL;
10347 * Local options. Need to go to the window temporarily.
10348 * Store only local values when using ":mkview" and when ":mksession" is
10349 * used and 'sessionoptions' doesn't include "options".
10350 * Some folding options are always stored when "folds" is included,
10351 * otherwise the folds would not be restored correctly.
10353 save_curwin = curwin;
10354 curwin = wp;
10355 curbuf = curwin->w_buffer;
10356 if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS))
10357 f = makeset(fd, OPT_LOCAL,
10358 flagp == &vop_flags || !(*flagp & SSOP_OPTIONS));
10359 #ifdef FEAT_FOLDING
10360 else if (*flagp & SSOP_FOLDS)
10361 f = makefoldset(fd);
10362 #endif
10363 else
10364 f = OK;
10365 curwin = save_curwin;
10366 curbuf = curwin->w_buffer;
10367 if (f == FAIL)
10368 return FAIL;
10370 #ifdef FEAT_FOLDING
10372 * Save Folds when 'buftype' is empty and for help files.
10374 if ((*flagp & SSOP_FOLDS)
10375 && wp->w_buffer->b_ffname != NULL
10376 # ifdef FEAT_QUICKFIX
10377 && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help)
10378 # endif
10381 if (put_folds(fd, wp) == FAIL)
10382 return FAIL;
10384 #endif
10387 * Set the cursor after creating folds, since that moves the cursor.
10389 if (do_cursor)
10392 /* Restore the cursor line in the file and relatively in the
10393 * window. Don't use "G", it changes the jumplist. */
10394 if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)",
10395 (long)wp->w_cursor.lnum,
10396 (long)(wp->w_cursor.lnum - wp->w_topline),
10397 (long)wp->w_height / 2, (long)wp->w_height) < 0
10398 || put_eol(fd) == FAIL
10399 || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL
10400 || put_line(fd, "exe s:l") == FAIL
10401 || put_line(fd, "normal! zt") == FAIL
10402 || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0
10403 || put_eol(fd) == FAIL)
10404 return FAIL;
10405 /* Restore the cursor column and left offset when not wrapping. */
10406 if (wp->w_cursor.col == 0)
10408 if (put_line(fd, "normal! 0") == FAIL)
10409 return FAIL;
10411 else
10413 if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0)
10415 if (fprintf(fd,
10416 "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)",
10417 (long)wp->w_cursor.col,
10418 (long)(wp->w_cursor.col - wp->w_leftcol),
10419 (long)wp->w_width / 2, (long)wp->w_width) < 0
10420 || put_eol(fd) == FAIL
10421 || put_line(fd, "if s:c > 0") == FAIL
10422 || fprintf(fd,
10423 " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'",
10424 (long)wp->w_cursor.col) < 0
10425 || put_eol(fd) == FAIL
10426 || put_line(fd, "else") == FAIL
10427 || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0
10428 || put_eol(fd) == FAIL
10429 || put_line(fd, "endif") == FAIL)
10430 return FAIL;
10432 else
10434 if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0
10435 || put_eol(fd) == FAIL)
10436 return FAIL;
10442 * Local directory.
10444 if (wp->w_localdir != NULL)
10446 if (fputs("lcd ", fd) < 0
10447 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL
10448 || put_eol(fd) == FAIL)
10449 return FAIL;
10450 did_lcd = TRUE;
10453 return OK;
10457 * Write an argument list to the session file.
10458 * Returns FAIL if writing fails.
10460 static int
10461 ses_arglist(fd, cmd, gap, fullname, flagp)
10462 FILE *fd;
10463 char *cmd;
10464 garray_T *gap;
10465 int fullname; /* TRUE: use full path name */
10466 unsigned *flagp;
10468 int i;
10469 char_u buf[MAXPATHL];
10470 char_u *s;
10472 if (gap->ga_len == 0)
10473 return put_line(fd, "silent! argdel *");
10474 if (fputs(cmd, fd) < 0)
10475 return FAIL;
10476 for (i = 0; i < gap->ga_len; ++i)
10478 /* NULL file names are skipped (only happens when out of memory). */
10479 s = alist_name(&((aentry_T *)gap->ga_data)[i]);
10480 if (s != NULL)
10482 if (fullname)
10484 (void)vim_FullName(s, buf, MAXPATHL, FALSE);
10485 s = buf;
10487 if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL)
10488 return FAIL;
10491 return put_eol(fd);
10495 * Write a buffer name to the session file.
10496 * Also ends the line.
10497 * Returns FAIL if writing fails.
10499 static int
10500 ses_fname(fd, buf, flagp)
10501 FILE *fd;
10502 buf_T *buf;
10503 unsigned *flagp;
10505 char_u *name;
10507 /* Use the short file name if the current directory is known at the time
10508 * the session file will be sourced.
10509 * Don't do this for ":mkview", we don't know the current directory.
10510 * Don't do this after ":lcd", we don't keep track of what the current
10511 * directory is. */
10512 if (buf->b_sfname != NULL
10513 && flagp == &ssop_flags
10514 && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR))
10515 && !did_lcd)
10516 name = buf->b_sfname;
10517 else
10518 name = buf->b_ffname;
10519 if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL)
10520 return FAIL;
10521 return OK;
10525 * Write a file name to the session file.
10526 * Takes care of the "slash" option in 'sessionoptions' and escapes special
10527 * characters.
10528 * Returns FAIL if writing fails.
10530 static int
10531 ses_put_fname(fd, name, flagp)
10532 FILE *fd;
10533 char_u *name;
10534 unsigned *flagp;
10536 char_u *sname;
10537 int retval = OK;
10538 int c;
10540 sname = home_replace_save(NULL, name);
10541 if (sname != NULL)
10542 name = sname;
10543 while (*name != NUL)
10545 #ifdef FEAT_MBYTE
10547 int l;
10549 if (has_mbyte && (l = (*mb_ptr2len)(name)) > 1)
10551 /* copy a multibyte char */
10552 while (--l >= 0)
10554 if (putc(*name, fd) != *name)
10555 retval = FAIL;
10556 ++name;
10558 continue;
10561 #endif
10562 c = *name++;
10563 if (c == '\\' && (*flagp & SSOP_SLASH))
10564 /* change a backslash to a forward slash */
10565 c = '/';
10566 else if ((vim_strchr(escape_chars, c) != NULL
10567 #ifdef BACKSLASH_IN_FILENAME
10568 && c != '\\'
10569 #endif
10570 ) || c == '#' || c == '%')
10572 /* escape a special character with a backslash */
10573 if (putc('\\', fd) != '\\')
10574 retval = FAIL;
10576 if (putc(c, fd) != c)
10577 retval = FAIL;
10579 vim_free(sname);
10580 return retval;
10584 * ":loadview [nr]"
10586 static void
10587 ex_loadview(eap)
10588 exarg_T *eap;
10590 char_u *fname;
10592 fname = get_view_file(*eap->arg);
10593 if (fname != NULL)
10595 do_source(fname, FALSE, DOSO_NONE);
10596 vim_free(fname);
10601 * Get the name of the view file for the current buffer.
10603 static char_u *
10604 get_view_file(c)
10605 int c;
10607 int len = 0;
10608 char_u *p, *s;
10609 char_u *retval;
10610 char_u *sname;
10612 if (curbuf->b_ffname == NULL)
10614 EMSG(_(e_noname));
10615 return NULL;
10617 sname = home_replace_save(NULL, curbuf->b_ffname);
10618 if (sname == NULL)
10619 return NULL;
10622 * We want a file name without separators, because we're not going to make
10623 * a directory.
10624 * "normal" path separator -> "=+"
10625 * "=" -> "=="
10626 * ":" path separator -> "=-"
10628 for (p = sname; *p; ++p)
10629 if (*p == '=' || vim_ispathsep(*p))
10630 ++len;
10631 retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9));
10632 if (retval != NULL)
10634 STRCPY(retval, p_vdir);
10635 add_pathsep(retval);
10636 s = retval + STRLEN(retval);
10637 for (p = sname; *p; ++p)
10639 if (*p == '=')
10641 *s++ = '=';
10642 *s++ = '=';
10644 else if (vim_ispathsep(*p))
10646 *s++ = '=';
10647 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(RISCOS) \
10648 || defined(VMS)
10649 if (*p == ':')
10650 *s++ = '-';
10651 else
10652 #endif
10653 *s++ = '+';
10655 else
10656 *s++ = *p;
10658 *s++ = '=';
10659 *s++ = c;
10660 STRCPY(s, ".vim");
10663 vim_free(sname);
10664 return retval;
10667 #endif /* FEAT_SESSION */
10670 * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession".
10671 * Return FAIL for a write error.
10674 put_eol(fd)
10675 FILE *fd;
10677 if (
10678 #ifdef USE_CRNL
10680 # ifdef MKSESSION_NL
10681 !mksession_nl &&
10682 # endif
10683 (putc('\r', fd) < 0)) ||
10684 #endif
10685 (putc('\n', fd) < 0))
10686 return FAIL;
10687 return OK;
10691 * Write a line to "fd".
10692 * Return FAIL for a write error.
10695 put_line(fd, s)
10696 FILE *fd;
10697 char *s;
10699 if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
10700 return FAIL;
10701 return OK;
10704 #ifdef FEAT_VIMINFO
10706 * ":rviminfo" and ":wviminfo".
10708 static void
10709 ex_viminfo(eap)
10710 exarg_T *eap;
10712 char_u *save_viminfo;
10714 save_viminfo = p_viminfo;
10715 if (*p_viminfo == NUL)
10716 p_viminfo = (char_u *)"'100";
10717 if (eap->cmdidx == CMD_rviminfo)
10719 if (read_viminfo(eap->arg, TRUE, TRUE, eap->forceit) == FAIL)
10720 EMSG(_("E195: Cannot open viminfo file for reading"));
10722 else
10723 write_viminfo(eap->arg, eap->forceit);
10724 p_viminfo = save_viminfo;
10726 #endif
10728 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO)
10730 * Make a dialog message in "buff[IOSIZE]".
10731 * "format" must contain "%s".
10733 void
10734 dialog_msg(buff, format, fname)
10735 char_u *buff;
10736 char *format;
10737 char_u *fname;
10739 if (fname == NULL)
10740 fname = (char_u *)_("Untitled");
10741 vim_snprintf((char *)buff, IOSIZE, format, fname);
10743 #endif
10746 * ":behave {mswin,xterm}"
10748 static void
10749 ex_behave(eap)
10750 exarg_T *eap;
10752 if (STRCMP(eap->arg, "mswin") == 0)
10754 set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0);
10755 set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0);
10756 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0);
10757 set_option_value((char_u *)"keymodel", 0L,
10758 (char_u *)"startsel,stopsel", 0);
10760 else if (STRCMP(eap->arg, "xterm") == 0)
10762 set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0);
10763 set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0);
10764 set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0);
10765 set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0);
10767 else
10768 EMSG2(_(e_invarg2), eap->arg);
10771 #ifdef FEAT_AUTOCMD
10772 static int filetype_detect = FALSE;
10773 static int filetype_plugin = FALSE;
10774 static int filetype_indent = FALSE;
10777 * ":filetype [plugin] [indent] {on,off,detect}"
10778 * on: Load the filetype.vim file to install autocommands for file types.
10779 * off: Load the ftoff.vim file to remove all autocommands for file types.
10780 * plugin on: load filetype.vim and ftplugin.vim
10781 * plugin off: load ftplugof.vim
10782 * indent on: load filetype.vim and indent.vim
10783 * indent off: load indoff.vim
10785 static void
10786 ex_filetype(eap)
10787 exarg_T *eap;
10789 char_u *arg = eap->arg;
10790 int plugin = FALSE;
10791 int indent = FALSE;
10793 if (*eap->arg == NUL)
10795 /* Print current status. */
10796 smsg((char_u *)"filetype detection:%s plugin:%s indent:%s",
10797 filetype_detect ? "ON" : "OFF",
10798 filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF",
10799 filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF");
10800 return;
10803 /* Accept "plugin" and "indent" in any order. */
10804 for (;;)
10806 if (STRNCMP(arg, "plugin", 6) == 0)
10808 plugin = TRUE;
10809 arg = skipwhite(arg + 6);
10810 continue;
10812 if (STRNCMP(arg, "indent", 6) == 0)
10814 indent = TRUE;
10815 arg = skipwhite(arg + 6);
10816 continue;
10818 break;
10820 if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0)
10822 if (*arg == 'o' || !filetype_detect)
10824 source_runtime((char_u *)FILETYPE_FILE, TRUE);
10825 filetype_detect = TRUE;
10826 if (plugin)
10828 source_runtime((char_u *)FTPLUGIN_FILE, TRUE);
10829 filetype_plugin = TRUE;
10831 if (indent)
10833 source_runtime((char_u *)INDENT_FILE, TRUE);
10834 filetype_indent = TRUE;
10837 if (*arg == 'd')
10839 (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE);
10840 do_modelines(0);
10843 else if (STRCMP(arg, "off") == 0)
10845 if (plugin || indent)
10847 if (plugin)
10849 source_runtime((char_u *)FTPLUGOF_FILE, TRUE);
10850 filetype_plugin = FALSE;
10852 if (indent)
10854 source_runtime((char_u *)INDOFF_FILE, TRUE);
10855 filetype_indent = FALSE;
10858 else
10860 source_runtime((char_u *)FTOFF_FILE, TRUE);
10861 filetype_detect = FALSE;
10864 else
10865 EMSG2(_(e_invarg2), arg);
10869 * ":setfiletype {name}"
10871 static void
10872 ex_setfiletype(eap)
10873 exarg_T *eap;
10875 if (!did_filetype)
10876 set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL);
10878 #endif
10880 /*ARGSUSED*/
10881 static void
10882 ex_digraphs(eap)
10883 exarg_T *eap;
10885 #ifdef FEAT_DIGRAPHS
10886 if (*eap->arg != NUL)
10887 putdigraph(eap->arg);
10888 else
10889 listdigraphs();
10890 #else
10891 EMSG(_("E196: No digraphs in this version"));
10892 #endif
10895 static void
10896 ex_set(eap)
10897 exarg_T *eap;
10899 int flags = 0;
10901 if (eap->cmdidx == CMD_setlocal)
10902 flags = OPT_LOCAL;
10903 else if (eap->cmdidx == CMD_setglobal)
10904 flags = OPT_GLOBAL;
10905 #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE)
10906 if (cmdmod.browse && flags == 0)
10907 ex_options(eap);
10908 else
10909 #endif
10910 (void)do_set(eap->arg, flags);
10913 #ifdef FEAT_SEARCH_EXTRA
10915 * ":nohlsearch"
10917 /*ARGSUSED*/
10918 static void
10919 ex_nohlsearch(eap)
10920 exarg_T *eap;
10922 no_hlsearch = TRUE;
10923 redraw_all_later(SOME_VALID);
10927 * ":[N]match {group} {pattern}"
10928 * Sets nextcmd to the start of the next command, if any. Also called when
10929 * skipping commands to find the next command.
10931 static void
10932 ex_match(eap)
10933 exarg_T *eap;
10935 char_u *p;
10936 char_u *g = NULL;
10937 char_u *end;
10938 int c;
10939 int id;
10941 if (eap->line2 <= 3)
10942 id = eap->line2;
10943 else
10945 EMSG(e_invcmd);
10946 return;
10949 /* First clear any old pattern. */
10950 if (!eap->skip)
10951 match_delete(curwin, id, FALSE);
10953 if (ends_excmd(*eap->arg))
10954 end = eap->arg;
10955 else if ((STRNICMP(eap->arg, "none", 4) == 0
10956 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4]))))
10957 end = eap->arg + 4;
10958 else
10960 p = skiptowhite(eap->arg);
10961 if (!eap->skip)
10962 g = vim_strnsave(eap->arg, (int)(p - eap->arg));
10963 p = skipwhite(p);
10964 if (*p == NUL)
10966 /* There must be two arguments. */
10967 EMSG2(_(e_invarg2), eap->arg);
10968 return;
10970 end = skip_regexp(p + 1, *p, TRUE, NULL);
10971 if (!eap->skip)
10973 if (*end != NUL && !ends_excmd(*skipwhite(end + 1)))
10975 eap->errmsg = e_trailing;
10976 return;
10978 if (*end != *p)
10980 EMSG2(_(e_invarg2), p);
10981 return;
10984 c = *end;
10985 *end = NUL;
10986 match_add(curwin, g, p + 1, 10, id);
10987 vim_free(g);
10988 *end = c;
10991 eap->nextcmd = find_nextcmd(end);
10993 #endif
10995 #ifdef FEAT_CRYPT
10997 * ":X": Get crypt key
10999 /*ARGSUSED*/
11000 static void
11001 ex_X(eap)
11002 exarg_T *eap;
11004 (void)get_crypt_key(TRUE, TRUE);
11006 #endif
11008 #ifdef FEAT_FOLDING
11009 static void
11010 ex_fold(eap)
11011 exarg_T *eap;
11013 if (foldManualAllowed(TRUE))
11014 foldCreate(eap->line1, eap->line2);
11017 static void
11018 ex_foldopen(eap)
11019 exarg_T *eap;
11021 opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen,
11022 eap->forceit, FALSE);
11025 static void
11026 ex_folddo(eap)
11027 exarg_T *eap;
11029 linenr_T lnum;
11031 /* First set the marks for all lines closed/open. */
11032 for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
11033 if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed))
11034 ml_setmarked(lnum);
11036 /* Execute the command on the marked lines. */
11037 global_exe(eap->arg);
11038 ml_clearmarked(); /* clear rest of the marks */
11040 #endif