robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
244.7 KiB8493 linesraw
1// ex_docmd.c: functions for executing an Ex command line.
2
3#include <assert.h>
4#include <ctype.h>
5#include <inttypes.h>
6#include <limits.h>
7#include <signal.h>
8#include <stdbool.h>
9#include <stddef.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13#include <uv.h>
14
15#include "auto/config.h"
16#include "nvim/api/private/defs.h"
17#include "nvim/api/private/dispatch.h"
18#include "nvim/api/private/helpers.h"
19#include "nvim/api/ui.h"
20#include "nvim/api/vim.h"
21#include "nvim/api/vimscript.h"
22#include "nvim/arglist.h"
23#include "nvim/ascii_defs.h"
24#include "nvim/autocmd.h"
25#include "nvim/autocmd_defs.h"
26#include "nvim/buffer.h"
27#include "nvim/buffer_defs.h"
28#include "nvim/change.h"
29#include "nvim/channel.h"
30#include "nvim/charset.h"
31#include "nvim/clipboard.h"
32#include "nvim/cmdexpand.h"
33#include "nvim/cmdexpand_defs.h"
34#include "nvim/context.h"
35#include "nvim/cursor.h"
36#include "nvim/debugger.h"
37#include "nvim/dialog.h"
38#include "nvim/digraph.h"
39#include "nvim/drawscreen.h"
40#include "nvim/errors.h"
41#include "nvim/eval/fs.h"
42#include "nvim/eval/funcs.h"
43#include "nvim/eval/typval.h"
44#include "nvim/eval/typval_defs.h"
45#include "nvim/eval/userfunc.h"
46#include "nvim/eval/vars.h"
47#include "nvim/eval/window.h"
48#include "nvim/eval_defs.h"
49#include "nvim/event/loop.h"
50#include "nvim/event/multiqueue.h"
51#include "nvim/event/proc.h"
52#include "nvim/event/socket.h"
53#include "nvim/ex_cmds.h"
54#include "nvim/ex_cmds2.h"
55#include "nvim/ex_cmds_defs.h"
56#include "nvim/ex_docmd.h"
57#include "nvim/ex_eval.h"
58#include "nvim/ex_eval_defs.h"
59#include "nvim/ex_getln.h"
60#include "nvim/file_search.h"
61#include "nvim/fileio.h"
62#include "nvim/fold.h"
63#include "nvim/garray.h"
64#include "nvim/garray_defs.h"
65#include "nvim/gettext_defs.h"
66#include "nvim/globals.h"
67#include "nvim/highlight_defs.h"
68#include "nvim/highlight_group.h"
69#include "nvim/input.h"
70#include "nvim/insert.h"
71#include "nvim/keycodes.h"
72#include "nvim/lua/executor.h"
73#include "nvim/macros_defs.h"
74#include "nvim/main.h"
75#include "nvim/mark.h"
76#include "nvim/mark_defs.h"
77#include "nvim/mbyte.h"
78#include "nvim/memline.h"
79#include "nvim/memline_defs.h"
80#include "nvim/memory.h"
81#include "nvim/message.h"
82#include "nvim/mouse.h"
83#include "nvim/move.h"
84#include "nvim/msgpack_rpc/channel.h"
85#include "nvim/msgpack_rpc/server.h"
86#include "nvim/normal.h"
87#include "nvim/normal_defs.h"
88#include "nvim/option.h"
89#include "nvim/option_defs.h"
90#include "nvim/option_vars.h"
91#include "nvim/optionstr.h"
92#include "nvim/os/fs.h"
93#include "nvim/os/input.h"
94#include "nvim/os/os.h"
95#include "nvim/os/os_defs.h"
96#ifdef MSWIN
97# include "nvim/os/os_win_console.h"
98#endif
99#include "nvim/os/shell.h"
100#include "nvim/path.h"
101#include "nvim/plines.h"
102#include "nvim/popupmenu.h"
103#include "nvim/pos_defs.h"
104#include "nvim/profile.h"
105#include "nvim/quickfix.h"
106#include "nvim/regexp.h"
107#include "nvim/regexp_defs.h"
108#include "nvim/runtime.h"
109#include "nvim/runtime_defs.h"
110#include "nvim/search.h"
111#include "nvim/shada.h"
112#include "nvim/state.h"
113#include "nvim/state_defs.h"
114#include "nvim/statusline.h"
115#include "nvim/strings.h"
116#include "nvim/tag.h"
117#include "nvim/types_defs.h"
118#include "nvim/ui.h"
119#include "nvim/ui_client.h"
120#include "nvim/undo.h"
121#include "nvim/undo_defs.h"
122#include "nvim/usercmd.h"
123#include "nvim/vim_defs.h"
124#include "nvim/window.h"
125#include "nvim/winfloat.h"
126
127static const char e_ambiguous_use_of_user_defined_command[]
128  = N_("E464: Ambiguous use of user-defined command");
129static const char e_no_call_stack_to_substitute_for_stack[]
130  = N_("E489: No call stack to substitute for \"<stack>\"");
131static const char e_not_an_editor_command[]
132  = N_("E492: Not an editor command");
133static const char e_no_autocommand_file_name_to_substitute_for_afile[]
134  = N_("E495: No autocommand file name to substitute for \"<afile>\"");
135static const char e_no_autocommand_buffer_number_to_substitute_for_abuf[]
136  = N_("E496: No autocommand buffer number to substitute for \"<abuf>\"");
137static const char e_no_autocommand_match_name_to_substitute_for_amatch[]
138  = N_("E497: No autocommand match name to substitute for \"<amatch>\"");
139static const char e_no_source_file_name_to_substitute_for_sfile[]
140  = N_("E498: No :source file name to substitute for \"<sfile>\"");
141static const char e_no_line_number_to_use_for_slnum[]
142  = N_("E842: No line number to use for \"<slnum>\"");
143static const char e_no_line_number_to_use_for_sflnum[]
144  = N_("E961: No line number to use for \"<sflnum>\"");
145static const char e_no_script_file_name_to_substitute_for_script[]
146  = N_("E1274: No script file name to substitute for \"<script>\"");
147
148static int quitmore = 0;
149
150// Struct for storing a line inside a while/for loop
151typedef struct {
152  char *line;            // command line
153  linenr_T lnum;                // sourcing_lnum of the line
154} wcmd_T;
155
156#define FREE_WCMD(wcmd) xfree((wcmd)->line)
157
158/// Structure used to store info for line position in a while or for loop.
159/// This is required, because do_one_cmd() may invoke ex_function(), which
160/// reads more lines that may come from the while/for loop.
161struct loop_cookie {
162  garray_T *lines_gap;               // growarray with line info
163  int current_line;                     // last read line from growarray
164  int repeating;                        // true when looping a second time
165  // When "repeating" is false use "getline" and "cookie" to get lines
166  LineGetter lc_getline;
167  void *cookie;
168};
169
170// Struct to save a few things while debugging.  Used in do_cmdline() only.
171struct dbg_stuff {
172  int trylevel;
173  int force_abort;
174  except_T *caught_stack;
175  char *vv_exception;
176  char *vv_throwpoint;
177  int did_emsg;
178  int got_int;
179  bool did_throw;
180  int need_rethrow;
181  int check_cstack;
182  except_T *current_exception;
183};
184
185#include "ex_docmd.c.generated.h"
186
187// Declare cmdnames[].
188#include "ex_cmds_defs.generated.h"
189
190static char dollar_command[2] = { '$', 0 };
191
192static void save_dbg_stuff(struct dbg_stuff *dsp)
193{
194  dsp->trylevel = trylevel;
195  trylevel = 0;
196  dsp->force_abort = force_abort;
197  force_abort = false;
198  dsp->caught_stack = caught_stack;
199  caught_stack = NULL;
200  dsp->vv_exception = v_exception(NULL);
201  dsp->vv_throwpoint = v_throwpoint(NULL);
202
203  // Necessary for debugging an inactive ":catch", ":finally", ":endtry".
204  dsp->did_emsg = did_emsg;
205  did_emsg = false;
206  dsp->got_int = got_int;
207  got_int = false;
208  dsp->did_throw = did_throw;
209  did_throw = false;
210  dsp->need_rethrow = need_rethrow;
211  need_rethrow = false;
212  dsp->check_cstack = check_cstack;
213  check_cstack = false;
214  dsp->current_exception = current_exception;
215  current_exception = NULL;
216}
217
218static void restore_dbg_stuff(struct dbg_stuff *dsp)
219{
220  suppress_errthrow = false;
221  trylevel = dsp->trylevel;
222  force_abort = dsp->force_abort;
223  caught_stack = dsp->caught_stack;
224  v_exception(dsp->vv_exception);
225  v_throwpoint(dsp->vv_throwpoint);
226  did_emsg = dsp->did_emsg;
227  got_int = dsp->got_int;
228  did_throw = dsp->did_throw;
229  need_rethrow = dsp->need_rethrow;
230  check_cstack = dsp->check_cstack;
231  current_exception = dsp->current_exception;
232}
233
234/// Check if ffname differs from fnum.
235/// fnum is a buffer number. 0 == current buffer, 1-or-more must be a valid buffer ID.
236/// ffname is a full path to where a buffer lives on-disk or would live on-disk.
237static bool is_other_file(int fnum, char *ffname)
238{
239  if (fnum != 0) {
240    if (fnum == curbuf->b_fnum) {
241      return false;
242    }
243
244    return true;
245  }
246
247  if (ffname == NULL) {
248    return true;
249  }
250
251  if (*ffname == NUL) {
252    return false;
253  }
254
255  if (!curbuf->file_id_valid
256      && curbuf->b_sfname != NULL
257      && *curbuf->b_sfname != NUL) {
258    // This occurs with unsaved buffers. In which case `ffname`
259    // actually corresponds to curbuf->b_sfname
260    return !path_equal(ffname, curbuf->b_sfname, kPathCmpLiteral);
261  }
262
263  return otherfile(ffname);
264}
265
266/// Print the executed command for when 'verbose' is set.
267///
268/// @param lnum  if 0, only print the command.
269static void msg_verbose_cmd(linenr_T lnum, char *cmd)
270  FUNC_ATTR_NONNULL_ALL
271{
272  no_wait_return++;
273  verbose_enter_scroll();
274
275  if (lnum == 0) {
276    smsg(0, _("Executing: %s"), cmd);
277  } else {
278    smsg(0, _("line %" PRIdLINENR ": %s"), lnum, cmd);
279  }
280  if (msg_silent == 0) {
281    msg_puts("\n");   // don't overwrite this
282  }
283
284  verbose_leave_scroll();
285  no_wait_return--;
286}
287
288static int cmdline_call_depth = 0;  ///< recursiveness
289
290/// Start executing an Ex command line.
291///
292/// @return  FAIL if too recursive, OK otherwise.
293static int do_cmdline_start(void)
294{
295  assert(cmdline_call_depth >= 0);
296  // It's possible to create an endless loop with ":execute", catch that
297  // here.  The value of 200 allows nested function calls, ":source", etc.
298  // Allow 200 or 'maxfuncdepth', whatever is larger.
299  if (cmdline_call_depth >= 200 && cmdline_call_depth >= p_mfd) {
300    return FAIL;
301  }
302  cmdline_call_depth++;
303  start_batch_changes();
304  return OK;
305}
306
307/// End executing an Ex command line.
308static void do_cmdline_end(void)
309{
310  cmdline_call_depth--;
311  assert(cmdline_call_depth >= 0);
312  end_batch_changes();
313}
314
315/// Execute a simple command line.  Used for translated commands like "*".
316int do_cmdline_cmd(const char *cmd)
317{
318  return do_cmdline((char *)cmd, NULL, NULL, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
319}
320
321/// do_cmdline(): execute one Ex command line
322///
323/// 1. Execute "cmdline" when it is not NULL.
324///    If "cmdline" is NULL, or more lines are needed, fgetline() is used.
325/// 2. Split up in parts separated with '|'.
326///
327/// This function can be called recursively!
328///
329/// flags:
330///   DOCMD_VERBOSE  - The command will be included in the error message.
331///   DOCMD_NOWAIT   - Don't call wait_return() and friends.
332///   DOCMD_REPEAT   - Repeat execution until fgetline() returns NULL.
333///   DOCMD_KEYTYPED - Don't reset KeyTyped.
334///   DOCMD_EXCRESET - Reset the exception environment (used for debugging).
335///   DOCMD_KEEPLINE - Store first typed line (for repeating with ".").
336///
337/// @param cookie  argument for fgetline()
338///
339/// @return FAIL if cmdline could not be executed, OK otherwise
340int do_cmdline(char *cmdline, LineGetter fgetline, void *cookie, int flags)
341{
342  char *next_cmdline;                   // next cmd to execute
343  char *cmdline_copy = NULL;            // copy of cmd line
344  bool used_getline = false;            // used "fgetline" to obtain command
345  static int recursive = 0;             // recursive depth
346  bool msg_didout_before_start = false;
347  int count = 0;                        // line number count
348  bool did_inc = false;                 // incremented RedrawingDisabled
349  bool did_block = false;               // emitted cmdline_block event
350  int retval = OK;
351  cstack_T cstack = {                   // conditional stack
352    .cs_idx = -1,
353  };
354  garray_T lines_ga;                    // keep lines for ":while"/":for"
355  int current_line = 0;                 // active line in lines_ga
356  char *fname = NULL;                   // function or script name
357  linenr_T *breakpoint = NULL;          // ptr to breakpoint field in cookie
358  int *dbg_tick = NULL;                 // ptr to dbg_tick field in cookie
359  struct dbg_stuff debug_saved;         // saved things for debug mode
360  msglist_T *private_msg_list;
361
362  // "fgetline" and "cookie" passed to do_one_cmd()
363  char *(*cmd_getline)(int, void *, int, bool);
364  void *cmd_cookie;
365  struct loop_cookie cmd_loop_cookie;
366
367  // For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
368  // location for storing error messages to be converted to an exception.
369  // This ensures that the do_errthrow() call in do_one_cmd() does not
370  // combine the messages stored by an earlier invocation of do_one_cmd()
371  // with the command name of the later one.  This would happen when
372  // BufWritePost autocommands are executed after a write error.
373  msglist_T **saved_msg_list = msg_list;
374  msg_list = &private_msg_list;
375  private_msg_list = NULL;
376
377  if (do_cmdline_start() == FAIL) {
378    emsg(_(e_command_too_recursive));
379    // When converting to an exception, we do not include the command name
380    // since this is not an error of the specific command.
381    do_errthrow((cstack_T *)NULL, NULL);
382    msg_list = saved_msg_list;
383    return FAIL;
384  }
385
386  ga_init(&lines_ga, (int)sizeof(wcmd_T), 10);
387
388  void *real_cookie = getline_cookie(fgetline, cookie);
389
390  // Inside a function use a higher nesting level.
391  bool getline_is_func = getline_equal(fgetline, cookie, get_func_line);
392  if (getline_is_func && ex_nesting_level == func_level(real_cookie)) {
393    ex_nesting_level++;
394  }
395
396  // Get the function or script name and the address where the next breakpoint
397  // line and the debug tick for a function or script are stored.
398  if (getline_is_func) {
399    fname = func_name(real_cookie);
400    breakpoint = func_breakpoint(real_cookie);
401    dbg_tick = func_dbg_tick(real_cookie);
402  } else if (getline_equal(fgetline, cookie, getsourceline)) {
403    fname = SOURCING_NAME;
404    breakpoint = source_breakpoint(real_cookie);
405    dbg_tick = source_dbg_tick(real_cookie);
406  }
407
408  // Initialize "force_abort"  and "suppress_errthrow" at the top level.
409  if (!recursive) {
410    force_abort = false;
411    suppress_errthrow = false;
412  }
413
414  // If requested, store and reset the global values controlling the
415  // exception handling (used when debugging).  Otherwise clear it to avoid
416  // a bogus compiler warning when the optimizer uses inline functions...
417  if (flags & DOCMD_EXCRESET) {
418    save_dbg_stuff(&debug_saved);
419  } else {
420    CLEAR_FIELD(debug_saved);
421  }
422
423  int initial_trylevel = trylevel;
424
425  // "did_throw" will be set to true when an exception is being thrown.
426  did_throw = false;
427  // "did_emsg" will be set to true when emsg() is used, in which case we
428  // cancel the whole command line, and any if/endif or loop.
429  // If force_abort is set, we cancel everything.
430  did_emsg = false;
431
432  // KeyTyped is only set when calling vgetc().  Reset it here when not
433  // calling vgetc() (sourced command lines).
434  if (!(flags & DOCMD_KEYTYPED)
435      && !getline_equal(fgetline, cookie, getexline)) {
436    KeyTyped = false;
437  }
438
439  // Continue executing command lines:
440  // - when inside an ":if", ":while" or ":for"
441  // - for multiple commands on one line, separated with '|'
442  // - when repeating until there are no more lines (for ":source")
443  next_cmdline = cmdline;
444  do {
445    getline_is_func = getline_equal(fgetline, cookie, get_func_line);
446
447    // stop skipping cmds for an error msg after all endif/while/for
448    if (next_cmdline == NULL
449        && !force_abort
450        && cstack.cs_idx < 0
451        && !(getline_is_func
452             && func_has_abort(real_cookie))) {
453      did_emsg = false;
454    }
455
456    // 1. If repeating a line in a loop, get a line from lines_ga.
457    // 2. If no line given: Get an allocated line with fgetline().
458    // 3. If a line is given: Make a copy, so we can mess with it.
459
460    // 1. If repeating, get a previous line from lines_ga.
461    if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len) {
462      // Each '|' separated command is stored separately in lines_ga, to
463      // be able to jump to it.  Don't use next_cmdline now.
464      XFREE_CLEAR(cmdline_copy);
465
466      // Check if a function has returned or, unless it has an unclosed
467      // try conditional, aborted.
468      if (getline_is_func) {
469        if (do_profiling == PROF_YES) {
470          func_line_end(real_cookie);
471        }
472        if (func_has_ended(real_cookie)) {
473          retval = FAIL;
474          break;
475        }
476      } else if (do_profiling == PROF_YES
477                 && getline_equal(fgetline, cookie, getsourceline)) {
478        script_line_end();
479      }
480
481      // Check if a sourced file hit a ":finish" command.
482      if (source_finished(fgetline, cookie)) {
483        retval = FAIL;
484        break;
485      }
486
487      // If breakpoints have been added/deleted need to check for it.
488      if (breakpoint != NULL && dbg_tick != NULL
489          && *dbg_tick != debug_tick) {
490        *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline),
491                                          fname, SOURCING_LNUM);
492        *dbg_tick = debug_tick;
493      }
494
495      next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
496      SOURCING_LNUM = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;
497
498      // Did we encounter a breakpoint?
499      if (breakpoint != NULL && *breakpoint != 0 && *breakpoint <= SOURCING_LNUM) {
500        dbg_breakpoint(fname, SOURCING_LNUM);
501        // Find next breakpoint.
502        *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline),
503                                          fname, SOURCING_LNUM);
504        *dbg_tick = debug_tick;
505      }
506      if (do_profiling == PROF_YES) {
507        if (getline_is_func) {
508          func_line_start(real_cookie);
509        } else if (getline_equal(fgetline, cookie, getsourceline)) {
510          script_line_start();
511        }
512      }
513    }
514
515    // 2. If no line given, get an allocated line with fgetline().
516    if (next_cmdline == NULL) {
517      int indent = cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2;
518
519      if (count == 1 && getline_equal(fgetline, cookie, getexline)) {
520        if (ui_has(kUICmdline)) {
521          // Emit cmdline_block event for loop/conditional block.
522          ui_ext_cmdline_block_append(0, last_cmdline);
523          did_block = true;
524        }
525        // Need to set msg_didout for the first line after an ":if",
526        // otherwise the ":if" will be overwritten.
527        msg_didout = true;
528      }
529
530      if (fgetline == NULL || (next_cmdline = fgetline(':', cookie, indent, true)) == NULL) {
531        // Don't call wait_return() for aborted command line.  The NULL
532        // returned for the end of a sourced file or executed function
533        // doesn't do this.
534        if (KeyTyped && !(flags & DOCMD_REPEAT)) {
535          need_wait_return = false;
536        }
537        retval = FAIL;
538        break;
539      }
540      used_getline = true;
541
542      // Emit all but the first cmdline_block event immediately; waiting until after
543      // command execution would mess up event ordering with nested command lines.
544      if (ui_has(kUICmdline) && count > 0 && getline_equal(fgetline, cookie, getexline)) {
545        ui_ext_cmdline_block_append((size_t)indent, next_cmdline);
546      }
547
548      // Keep the first typed line.  Clear it when more lines are typed.
549      if (flags & DOCMD_KEEPLINE) {
550        xfree(repeat_cmdline);
551        if (count == 0) {
552          repeat_cmdline = xstrdup(next_cmdline);
553        } else {
554          repeat_cmdline = NULL;
555        }
556      }
557    } else if (cmdline_copy == NULL) {
558      // 3. Make a copy of the command so we can mess with it.
559      next_cmdline = xstrdup(next_cmdline);
560    }
561    cmdline_copy = next_cmdline;
562
563    int current_line_before = 0;
564    // Inside a while/for loop, and when the command looks like a ":while"
565    // or ":for", the line is stored, because we may need it later when
566    // looping.
567    //
568    // When there is a '|' and another command, it is stored separately,
569    // because we need to be able to jump back to it from an
570    // :endwhile/:endfor.
571    //
572    // Pass a different "fgetline" function to do_one_cmd() below,
573    // that it stores lines in or reads them from "lines_ga".  Makes it
574    // possible to define a function inside a while/for loop.
575    if ((cstack.cs_looplevel > 0 || has_loop_cmd(next_cmdline))) {
576      cmd_getline = get_loop_line;
577      cmd_cookie = (void *)&cmd_loop_cookie;
578      cmd_loop_cookie.lines_gap = &lines_ga;
579      cmd_loop_cookie.current_line = current_line;
580      cmd_loop_cookie.lc_getline = fgetline;
581      cmd_loop_cookie.cookie = cookie;
582      cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);
583
584      // Save the current line when encountering it the first time.
585      if (current_line == lines_ga.ga_len) {
586        store_loop_line(&lines_ga, next_cmdline);
587      }
588      current_line_before = current_line;
589    } else {
590      cmd_getline = fgetline;
591      cmd_cookie = cookie;
592    }
593
594    did_endif = false;
595
596    if (count++ == 0) {
597      // All output from the commands is put below each other, without
598      // waiting for a return. Don't do this when executing commands
599      // from a script or when being called recursive (e.g. for ":e
600      // +command file").
601      if (!(flags & DOCMD_NOWAIT) && !recursive) {
602        msg_didout_before_start = msg_didout;
603        msg_didany = false;         // no output yet
604        msg_start();
605        msg_scroll = true;          // put messages below each other
606        no_wait_return++;           // don't wait for return until finished
607        RedrawingDisabled++;
608        did_inc = true;
609      }
610    }
611
612    if ((p_verbose >= 15 && SOURCING_NAME != NULL) || p_verbose >= 16) {
613      msg_verbose_cmd(SOURCING_LNUM, cmdline_copy);
614    }
615
616    // 2. Execute one '|' separated command.
617    //    do_one_cmd() will return NULL if there is no trailing '|'.
618    //    "cmdline_copy" can change, e.g. for '%' and '#' expansion.
619    recursive++;
620    next_cmdline = do_one_cmd(&cmdline_copy, flags, &cstack, cmd_getline, cmd_cookie);
621    recursive--;
622
623    if (cmd_cookie == (void *)&cmd_loop_cookie) {
624      // Use "current_line" from "cmd_loop_cookie", it may have been
625      // incremented when defining a function.
626      current_line = cmd_loop_cookie.current_line;
627    }
628
629    if (next_cmdline == NULL) {
630      XFREE_CLEAR(cmdline_copy);
631
632      // If the command was typed, remember it for the ':' register.
633      // Do this AFTER executing the command to make :@: work.
634      if (getline_equal(fgetline, cookie, getexline) && new_last_cmdline != NULL) {
635        xfree(last_cmdline);
636        last_cmdline = new_last_cmdline;
637        new_last_cmdline = NULL;
638      }
639    } else {
640      // need to copy the command after the '|' to cmdline_copy, for the
641      // next do_one_cmd()
642      STRMOVE(cmdline_copy, next_cmdline);
643      next_cmdline = cmdline_copy;
644    }
645
646    // reset did_emsg for a function that is not aborted by an error
647    if (did_emsg && !force_abort
648        && getline_equal(fgetline, cookie, get_func_line)
649        && !func_has_abort(real_cookie)) {
650      did_emsg = false;
651    }
652
653    if (cstack.cs_looplevel > 0) {
654      current_line++;
655
656      // An ":endwhile", ":endfor" and ":continue" is handled here.
657      // If we were executing commands, jump back to the ":while" or
658      // ":for".
659      // If we were not executing commands, decrement cs_looplevel.
660      if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP)) {
661        cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);
662
663        // Jump back to the matching ":while" or ":for".  Be careful
664        // not to use a cs_line[] from an entry that isn't a ":while"
665        // or ":for": It would make "current_line" invalid and can
666        // cause a crash.
667        if (!did_emsg && !got_int && !did_throw
668            && cstack.cs_idx >= 0
669            && (cstack.cs_flags[cstack.cs_idx]
670                & (CSF_WHILE | CSF_FOR))
671            && cstack.cs_line[cstack.cs_idx] >= 0
672            && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE)) {
673          current_line = cstack.cs_line[cstack.cs_idx];
674          // remember we jumped there
675          cstack.cs_lflags |= CSL_HAD_LOOP;
676          line_breakcheck();                    // check if CTRL-C typed
677
678          // Check for the next breakpoint at or after the ":while"
679          // or ":for".
680          if (breakpoint != NULL && lines_ga.ga_len > current_line) {
681            *breakpoint = dbg_find_breakpoint(getline_equal(fgetline, cookie, getsourceline), fname,
682                                              ((wcmd_T *)lines_ga.ga_data)[current_line].lnum - 1);
683            *dbg_tick = debug_tick;
684          }
685        } else {
686          // can only get here with ":endwhile" or ":endfor"
687          if (cstack.cs_idx >= 0) {
688            rewind_conditionals(&cstack, cstack.cs_idx - 1,
689                                CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
690          }
691        }
692      } else if (cstack.cs_lflags & CSL_HAD_LOOP) {
693        // For a ":while" or ":for" we need to remember the line number.
694        cstack.cs_lflags &= ~CSL_HAD_LOOP;
695        cstack.cs_line[cstack.cs_idx] = current_line_before;
696      }
697    }
698
699    // When not inside any ":while" loop, clear remembered lines.
700    if (cstack.cs_looplevel == 0) {
701      if (!GA_EMPTY(&lines_ga)) {
702        SOURCING_LNUM = ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
703        GA_DEEP_CLEAR(&lines_ga, wcmd_T, FREE_WCMD);
704      }
705      current_line = 0;
706    }
707
708    // A ":finally" makes did_emsg, got_int and did_throw pending for
709    // being restored at the ":endtry".  Reset them here and set the
710    // ACTIVE and FINALLY flags, so that the finally clause gets executed.
711    // This includes the case where a missing ":endif", ":endwhile" or
712    // ":endfor" was detected by the ":finally" itself.
713    if (cstack.cs_lflags & CSL_HAD_FINA) {
714      cstack.cs_lflags &= ~CSL_HAD_FINA;
715      report_make_pending((cstack.cs_pending[cstack.cs_idx]
716                           & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW)),
717                          did_throw ? current_exception : NULL);
718      did_emsg = got_int = did_throw = false;
719      cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
720    }
721
722    // Update global "trylevel" for recursive calls to do_cmdline() from
723    // within this loop.
724    trylevel = initial_trylevel + cstack.cs_trylevel;
725
726    // If the outermost try conditional (across function calls and sourced
727    // files) is aborted because of an error, an interrupt, or an uncaught
728    // exception, cancel everything.  If it is left normally, reset
729    // force_abort to get the non-EH compatible abortion behavior for
730    // the rest of the script.
731    if (trylevel == 0 && !did_emsg && !got_int && !did_throw) {
732      force_abort = false;
733    }
734
735    // Convert an interrupt to an exception if appropriate.
736    do_intthrow(&cstack);
737
738    // Continue executing command lines when:
739    // - no CTRL-C typed, no aborting error, no exception thrown or try
740    //   conditionals need to be checked for executing finally clauses or
741    //   catching an interrupt exception
742    // - didn't get an error message or lines are not typed
743    // - there is a command after '|', inside a :if, :while, :for or :try, or
744    //   looping for ":source" command or function call.
745  } while (!((got_int || (did_emsg && force_abort) || did_throw)
746             && cstack.cs_trylevel == 0)
747           && !(did_emsg
748                // Keep going when inside try/catch, so that the error can be
749                // deal with, except when it is a syntax error, it may cause
750                // the :endtry to be missed.
751                && (cstack.cs_trylevel == 0 || did_emsg_syntax)
752                && used_getline
753                && getline_equal(fgetline, cookie, getexline))
754           && (next_cmdline != NULL
755               || cstack.cs_idx >= 0
756               || (flags & DOCMD_REPEAT)));
757
758  xfree(cmdline_copy);
759  did_emsg_syntax = false;
760  GA_DEEP_CLEAR(&lines_ga, wcmd_T, FREE_WCMD);
761
762  if (cstack.cs_idx >= 0) {
763    // If a sourced file or executed function ran to its end, report the
764    // unclosed conditional.
765    if (!got_int && !did_throw && !aborting()
766        && ((getline_equal(fgetline, cookie, getsourceline)
767             && !source_finished(fgetline, cookie))
768            || (getline_equal(fgetline, cookie, get_func_line)
769                && !func_has_ended(real_cookie)))) {
770      if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) {
771        emsg(_(e_endtry));
772      } else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) {
773        emsg(_(e_endwhile));
774      } else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) {
775        emsg(_(e_endfor));
776      } else {
777        emsg(_(e_endif));
778      }
779    }
780
781    // Reset "trylevel" in case of a ":finish" or ":return" or a missing
782    // ":endtry" in a sourced file or executed function.  If the try
783    // conditional is in its finally clause, ignore anything pending.
784    // If it is in a catch clause, finish the caught exception.
785    // Also cleanup any "cs_forinfo" structures.
786    do {
787      int idx = cleanup_conditionals(&cstack, 0, true);
788
789      if (idx >= 0) {
790        idx--;              // remove try block not in its finally clause
791      }
792      rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
793                          &cstack.cs_looplevel);
794    } while (cstack.cs_idx >= 0);
795    trylevel = initial_trylevel;
796  }
797
798  // If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory
799  // lack was reported above and the error message is to be converted to an
800  // exception, do this now after rewinding the cstack.
801  do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line) ? "endfunction" : NULL);
802
803  if (trylevel == 0) {
804    // When an exception is being thrown out of the outermost try
805    // conditional, discard the uncaught exception, disable the conversion
806    // of interrupts or errors to exceptions, and ensure that no more
807    // commands are executed.
808    if (did_throw) {
809      handle_did_throw();
810    } else if (got_int || (did_emsg && force_abort)) {
811      // On an interrupt or an aborting error not converted to an exception,
812      // disable the conversion of errors to exceptions.  (Interrupts are not
813      // converted any more, here.) This enables also the interrupt message
814      // when force_abort is set and did_emsg unset in case of an interrupt
815      // from a finally clause after an error.
816      suppress_errthrow = true;
817    }
818  }
819
820  // The current cstack will be freed when do_cmdline() returns.  An uncaught
821  // exception will have to be rethrown in the previous cstack.  If a function
822  // has just returned or a script file was just finished and the previous
823  // cstack belongs to the same function or, respectively, script file, it
824  // will have to be checked for finally clauses to be executed due to the
825  // ":return" or ":finish".  This is done in do_one_cmd().
826  if (did_throw) {
827    need_rethrow = true;
828  }
829  if ((getline_equal(fgetline, cookie, getsourceline)
830       && ex_nesting_level > source_level(real_cookie))
831      || (getline_equal(fgetline, cookie, get_func_line)
832          && ex_nesting_level > func_level(real_cookie) + 1)) {
833    if (!did_throw) {
834      check_cstack = true;
835    }
836  } else {
837    // When leaving a function, reduce nesting level.
838    if (getline_equal(fgetline, cookie, get_func_line)) {
839      ex_nesting_level--;
840    }
841    // Go to debug mode when returning from a function in which we are
842    // single-stepping.
843    if ((getline_equal(fgetline, cookie, getsourceline)
844         || getline_equal(fgetline, cookie, get_func_line))
845        && ex_nesting_level + 1 <= debug_break_level) {
846      do_debug(getline_equal(fgetline, cookie, getsourceline)
847               ? _("End of sourced file")
848               : _("End of function"));
849    }
850  }
851
852  // Restore the exception environment (done after returning from the
853  // debugger).
854  if (flags & DOCMD_EXCRESET) {
855    restore_dbg_stuff(&debug_saved);
856  }
857
858  msg_list = saved_msg_list;
859
860  // Cleanup if "cs_emsg_silent_list" remains.
861  if (cstack.cs_emsg_silent_list != NULL) {
862    eslist_T *temp;
863    for (eslist_T *elem = cstack.cs_emsg_silent_list; elem != NULL; elem = temp) {
864      temp = elem->next;
865      xfree(elem);
866    }
867  }
868
869  // If there was too much output to fit on the command line, ask the user to
870  // hit return before redrawing the screen. With the ":global" command we do
871  // this only once after the command is finished.
872  if (did_inc) {
873    RedrawingDisabled--;
874    no_wait_return--;
875    msg_scroll = false;
876
877    // When just finished an ":if"-":else" which was typed, no need to
878    // wait for hit-return.  Also for an error situation.
879    if (retval == FAIL
880        || (did_endif && KeyTyped && !did_emsg)) {
881      need_wait_return = false;
882      msg_didany = false;               // don't wait when restarting edit
883    } else if (need_wait_return) {
884      // The msg_start() above clears msg_didout. The wait_return() we do
885      // here should not overwrite the command that may be shown before
886      // doing that.
887      msg_didout |= msg_didout_before_start;
888      wait_return(false);
889    }
890  }
891
892  if (did_block) {
893    ui_ext_cmdline_block_leave();
894  }
895
896  did_endif = false;    // in case do_cmdline used recursively
897
898  do_cmdline_end();
899  return retval;
900}
901
902/// Handle when "did_throw" is set after executing commands.
903void handle_did_throw(void)
904{
905  assert(current_exception != NULL);
906  char *p = NULL;
907  msglist_T *messages = NULL;
908  ESTACK_CHECK_DECLARATION;
909
910  // If the uncaught exception is a user exception, report it as an
911  // error.  If it is an error exception, display the saved error
912  // message now.  For an interrupt exception, do nothing; the
913  // interrupt message is given elsewhere.
914  switch (current_exception->type) {
915  case ET_USER:
916    vim_snprintf(IObuff, IOSIZE,
917                 _("E605: Exception not caught: %s"),
918                 current_exception->value);
919    p = xstrdup(IObuff);
920    break;
921  case ET_ERROR:
922    messages = current_exception->messages;
923    current_exception->messages = NULL;
924    break;
925  case ET_INTERRUPT:
926    break;
927  }
928
929  estack_push(ETYPE_EXCEPT, current_exception->throw_name, current_exception->throw_lnum);
930  ESTACK_CHECK_SETUP;
931  current_exception->throw_name = NULL;
932
933  discard_current_exception();              // uses IObuff if 'verbose'
934
935  // If "silent!" is active the uncaught exception is not fatal.
936  if (emsg_silent == 0) {
937    suppress_errthrow = true;
938    force_abort = true;
939  }
940
941  if (messages != NULL) {
942    do {
943      msglist_T *next = messages->next;
944      emsg_multiline(messages->msg, "emsg", HLF_E, messages->multiline);
945      xfree(messages->msg);
946      xfree(messages->sfile);
947      xfree(messages);
948      messages = next;
949    } while (messages != NULL);
950  } else if (p != NULL) {
951    emsg(p);
952    xfree(p);
953  }
954  xfree(SOURCING_NAME);
955  ESTACK_CHECK_NOW;
956  estack_pop();
957}
958
959/// Obtain a line when inside a ":while" or ":for" loop.
960static char *get_loop_line(int c, void *cookie, int indent, bool do_concat)
961{
962  struct loop_cookie *cp = (struct loop_cookie *)cookie;
963
964  if (cp->current_line + 1 >= cp->lines_gap->ga_len) {
965    if (cp->repeating) {
966      return NULL;              // trying to read past ":endwhile"/":endfor"
967    }
968    char *line;
969    // First time inside the ":while"/":for": get line normally.
970    if (cp->lc_getline == NULL) {
971      line = getcmdline(c, 0, indent, do_concat);
972    } else {
973      line = cp->lc_getline(c, cp->cookie, indent, do_concat);
974    }
975    if (line != NULL) {
976      store_loop_line(cp->lines_gap, line);
977      cp->current_line++;
978    }
979
980    return line;
981  }
982
983  KeyTyped = false;
984  cp->current_line++;
985  wcmd_T *wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line;
986  SOURCING_LNUM = wp->lnum;
987  return xstrdup(wp->line);
988}
989
990/// Store a line in "gap" so that a ":while" loop can execute it again.
991static void store_loop_line(garray_T *gap, char *line)
992{
993  wcmd_T *p = GA_APPEND_VIA_PTR(wcmd_T, gap);
994  p->line = xstrdup(line);
995  p->lnum = SOURCING_LNUM;
996}
997
998/// If "fgetline" is get_loop_line(), return true if the getline it uses equals
999/// "func".  * Otherwise return true when "fgetline" equals "func".
1000///
1001/// @param cookie  argument for fgetline()
1002bool getline_equal(LineGetter fgetline, void *cookie, LineGetter func)
1003{
1004  // When "fgetline" is "get_loop_line()" use the "cookie" to find the
1005  // function that's originally used to obtain the lines.  This may be
1006  // nested several levels.
1007  LineGetter gp = fgetline;
1008  struct loop_cookie *cp = (struct loop_cookie *)cookie;
1009  while (gp == get_loop_line) {
1010    gp = cp->lc_getline;
1011    cp = cp->cookie;
1012  }
1013  return gp == func;
1014}
1015
1016/// If "fgetline" is get_loop_line(), return the cookie used by the original
1017/// getline function.  Otherwise return "cookie".
1018///
1019/// @param cookie  argument for fgetline()
1020void *getline_cookie(LineGetter fgetline, void *cookie)
1021{
1022  // When "fgetline" is "get_loop_line()" use the "cookie" to find the
1023  // cookie that's originally used to obtain the lines.  This may be nested
1024  // several levels.
1025  LineGetter gp = fgetline;
1026  struct loop_cookie *cp = (struct loop_cookie *)cookie;
1027  while (gp == get_loop_line) {
1028    gp = cp->lc_getline;
1029    cp = cp->cookie;
1030  }
1031  return cp;
1032}
1033
1034/// Helper function to apply an offset for buffer commands, i.e. ":bdelete",
1035/// ":bwipeout", etc.
1036///
1037/// @return  the buffer number.
1038static int compute_buffer_local_count(cmd_addr_T addr_type, linenr_T lnum, int offset)
1039{
1040  int count = offset;
1041
1042  buf_T *buf = firstbuf;
1043  while (buf->b_next != NULL && buf->b_fnum < lnum) {
1044    buf = buf->b_next;
1045  }
1046  while (count != 0) {
1047    count += (count < 0) ? 1 : -1;
1048    buf_T *nextbuf = (offset < 0) ? buf->b_prev : buf->b_next;
1049    if (nextbuf == NULL) {
1050      break;
1051    }
1052    buf = nextbuf;
1053    if (addr_type == ADDR_LOADED_BUFFERS) {
1054      // skip over unloaded buffers
1055      while (buf->b_ml.ml_mfp == NULL) {
1056        nextbuf = (offset < 0) ? buf->b_prev : buf->b_next;
1057        if (nextbuf == NULL) {
1058          break;
1059        }
1060        buf = nextbuf;
1061      }
1062    }
1063  }
1064  // we might have gone too far, last buffer is not loaded
1065  if (addr_type == ADDR_LOADED_BUFFERS) {
1066    while (buf->b_ml.ml_mfp == NULL) {
1067      buf_T *nextbuf = (offset >= 0) ? buf->b_prev : buf->b_next;
1068      if (nextbuf == NULL) {
1069        break;
1070      }
1071      buf = nextbuf;
1072    }
1073  }
1074  return buf->b_fnum;
1075}
1076
1077/// @return  the window number of "win" or,
1078///          the number of windows if "win" is NULL
1079static int current_win_nr(const win_T *win, exarg_T *cmdarg)
1080  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1081{
1082  // Whether to also match hidden / non-focusable windows (in current tab).
1083  bool nonnr = cmdarg != NULL && cmdarg->cmdidx != CMD_quit;
1084  int nr = 0;
1085
1086  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1087    // only include non-hidden and focusable windows
1088    // (so ui2 windows are excluded)
1089    bool include_this = nonnr || win_has_winnr(wp, curtab);
1090    nr += include_this;
1091
1092    if (wp == win) {
1093      // same as in win_id2win()
1094      if (!include_this) {
1095        return 0;
1096      }
1097      break;
1098    }
1099  }
1100  return nr;
1101}
1102
1103static int current_tab_nr(tabpage_T *tab)
1104{
1105  int nr = 0;
1106
1107  FOR_ALL_TABS(tp) {
1108    nr++;
1109    if (tp == tab) {
1110      break;
1111    }
1112  }
1113  return nr;
1114}
1115
1116#define CURRENT_WIN_NR current_win_nr(curwin, NULL)
1117#define LAST_WIN_NR(cmdarg) current_win_nr(NULL, (cmdarg))
1118#define CURRENT_TAB_NR current_tab_nr(curtab)
1119#define LAST_TAB_NR current_tab_nr(NULL)
1120
1121/// Figure out the address type for ":wincmd".
1122static void get_wincmd_addr_type(const char *arg, exarg_T *eap)
1123{
1124  switch (*arg) {
1125  case 'S':
1126  case Ctrl_S:
1127  case 's':
1128  case Ctrl_N:
1129  case 'n':
1130  case 'j':
1131  case Ctrl_J:
1132  case 'k':
1133  case Ctrl_K:
1134  case 'T':
1135  case Ctrl_R:
1136  case 'r':
1137  case 'R':
1138  case 'K':
1139  case 'J':
1140  case '+':
1141  case '-':
1142  case Ctrl__:
1143  case '_':
1144  case '|':
1145  case ']':
1146  case Ctrl_RSB:
1147  case 'g':
1148  case Ctrl_G:
1149  case Ctrl_V:
1150  case 'v':
1151  case 'h':
1152  case Ctrl_H:
1153  case 'l':
1154  case Ctrl_L:
1155  case 'H':
1156  case 'L':
1157  case '>':
1158  case '<':
1159  case '}':
1160  case 'f':
1161  case 'F':
1162  case Ctrl_F:
1163  case 'i':
1164  case Ctrl_I:
1165  case 'd':
1166  case Ctrl_D:
1167    // window size or any count
1168    eap->addr_type = ADDR_OTHER;
1169    break;
1170
1171  case Ctrl_HAT:
1172  case '^':
1173    // buffer number
1174    eap->addr_type = ADDR_BUFFERS;
1175    break;
1176
1177  case Ctrl_Q:
1178  case 'q':
1179  case Ctrl_C:
1180  case 'c':
1181  case Ctrl_O:
1182  case 'o':
1183  case Ctrl_W:
1184  case 'w':
1185  case 'W':
1186  case 'x':
1187  case Ctrl_X:
1188    // window number
1189    eap->addr_type = ADDR_WINDOWS;
1190    break;
1191
1192  case Ctrl_Z:
1193  case 'z':
1194  case 'P':
1195  case 't':
1196  case Ctrl_T:
1197  case 'b':
1198  case Ctrl_B:
1199  case 'p':
1200  case Ctrl_P:
1201  case '=':
1202  case CAR:
1203    // no count
1204    eap->addr_type = ADDR_NONE;
1205    break;
1206  }
1207}
1208
1209/// Skip colons and trailing whitespace, returning a pointer to the first
1210/// non-colon, non-whitespace character.
1211//
1212/// @param skipleadingwhite Skip leading whitespace too
1213static char *skip_colon_white(const char *p, bool skipleadingwhite)
1214{
1215  if (skipleadingwhite) {
1216    p = skipwhite(p);
1217  }
1218
1219  while (*p == ':') {
1220    p = skipwhite(p + 1);
1221  }
1222
1223  return (char *)p;
1224}
1225
1226/// Set the addr type for command
1227///
1228/// @param p pointer to character after command name in cmdline
1229void set_cmd_addr_type(exarg_T *eap, char *p)
1230{
1231  // ea.addr_type for user commands is set by find_ucmd
1232  if (IS_USER_CMDIDX(eap->cmdidx)) {
1233    return;
1234  }
1235  if (eap->cmdidx != CMD_SIZE) {
1236    eap->addr_type = cmdnames[(int)eap->cmdidx].cmd_addr_type;
1237  } else {
1238    eap->addr_type = ADDR_LINES;
1239  }
1240  // :wincmd range depends on the argument
1241  if (eap->cmdidx == CMD_wincmd && p != NULL) {
1242    get_wincmd_addr_type(skipwhite(p), eap);
1243  }
1244  // :.cc in quickfix window uses line number
1245  if ((eap->cmdidx == CMD_cc || eap->cmdidx == CMD_ll) && bt_quickfix(curbuf)) {
1246    eap->addr_type = ADDR_OTHER;
1247  }
1248}
1249
1250/// Get default range number for command based on its address type
1251linenr_T get_cmd_default_range(exarg_T *eap)
1252{
1253  switch (eap->addr_type) {
1254  case ADDR_LINES:
1255  case ADDR_OTHER:
1256    // Default is the cursor line number.  Avoid using an invalid
1257    // line number though.
1258    return MIN(curwin->w_cursor.lnum, curbuf->b_ml.ml_line_count);
1259    break;
1260  case ADDR_WINDOWS:
1261    return CURRENT_WIN_NR;
1262    break;
1263  case ADDR_ARGUMENTS:
1264    return MIN(curwin->w_arg_idx + 1, ARGCOUNT);
1265    break;
1266  case ADDR_LOADED_BUFFERS:
1267  case ADDR_BUFFERS:
1268    return curbuf->b_fnum;
1269    break;
1270  case ADDR_TABS:
1271    return CURRENT_TAB_NR;
1272    break;
1273  case ADDR_TABS_RELATIVE:
1274  case ADDR_UNSIGNED:
1275    return 1;
1276    break;
1277  case ADDR_QUICKFIX:
1278    return (linenr_T)qf_get_cur_idx(eap);
1279    break;
1280  case ADDR_QUICKFIX_VALID:
1281    return qf_get_cur_valid_idx(eap);
1282    break;
1283  default:
1284    return 0;
1285    // Will give an error later if a range is found.
1286    break;
1287  }
1288}
1289
1290/// Set default command range for -range=% based on the addr type of the command
1291void set_cmd_dflall_range(exarg_T *eap)
1292{
1293  buf_T *buf;
1294
1295  eap->line1 = 1;
1296  switch (eap->addr_type) {
1297  case ADDR_LINES:
1298  case ADDR_OTHER:
1299    eap->line2 = curbuf->b_ml.ml_line_count;
1300    break;
1301  case ADDR_LOADED_BUFFERS:
1302    buf = firstbuf;
1303    while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) {
1304      buf = buf->b_next;
1305    }
1306    eap->line1 = buf->b_fnum;
1307    buf = lastbuf;
1308    while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) {
1309      buf = buf->b_prev;
1310    }
1311    eap->line2 = buf->b_fnum;
1312    break;
1313  case ADDR_BUFFERS:
1314    eap->line1 = firstbuf->b_fnum;
1315    eap->line2 = lastbuf->b_fnum;
1316    break;
1317  case ADDR_WINDOWS:
1318    eap->line2 = LAST_WIN_NR(eap);
1319    break;
1320  case ADDR_TABS:
1321    eap->line2 = LAST_TAB_NR;
1322    break;
1323  case ADDR_TABS_RELATIVE:
1324    eap->line2 = 1;
1325    break;
1326  case ADDR_ARGUMENTS:
1327    if (ARGCOUNT == 0) {
1328      eap->line1 = eap->line2 = 0;
1329    } else {
1330      eap->line2 = ARGCOUNT;
1331    }
1332    break;
1333  case ADDR_QUICKFIX_VALID:
1334    eap->line2 = (linenr_T)qf_get_valid_size(eap);
1335    if (eap->line2 == 0) {
1336      eap->line2 = 1;
1337    }
1338    break;
1339  case ADDR_NONE:
1340  case ADDR_UNSIGNED:
1341  case ADDR_QUICKFIX:
1342    iemsg(_("INTERNAL: Cannot use EX_DFLALL "
1343            "with ADDR_NONE, ADDR_UNSIGNED or ADDR_QUICKFIX"));
1344    break;
1345  }
1346}
1347
1348static void parse_register(exarg_T *eap)
1349{
1350  // Accept numbered register only when no count allowed (:put)
1351  if ((eap->argt & EX_REGSTR)
1352      && *eap->arg != NUL
1353      // Do not allow register = for user commands
1354      && (!IS_USER_CMDIDX(eap->cmdidx) || *eap->arg != '=')
1355      && !((eap->argt & EX_COUNT) && ascii_isdigit(*eap->arg))) {
1356    if (valid_yank_reg(*eap->arg,
1357                       (!IS_USER_CMDIDX(eap->cmdidx)
1358                        && eap->cmdidx != CMD_put && eap->cmdidx != CMD_iput))) {
1359      eap->regname = (uint8_t)(*eap->arg++);
1360      // for '=' register: accept the rest of the line as an expression
1361      if (eap->arg[-1] == '=' && eap->arg[0] != NUL) {
1362        if (!eap->skip) {
1363          set_expr_line(xstrdup(eap->arg));
1364        }
1365        eap->arg += strlen(eap->arg);
1366      }
1367      eap->arg = skipwhite(eap->arg);
1368    }
1369  }
1370}
1371
1372// Change line1 and line2 of Ex command to use count
1373void set_cmd_count(exarg_T *eap, linenr_T count, bool validate)
1374{
1375  if (eap->addr_type != ADDR_LINES) {  // e.g. :buffer 2, :sleep 3
1376    eap->line2 = count;
1377    if (eap->addr_count == 0) {
1378      eap->addr_count = 1;
1379    }
1380  } else {
1381    eap->line1 = eap->line2;
1382    if (eap->line2 >= INT32_MAX - (count - 1)) {
1383      eap->line2 = INT32_MAX;
1384    } else {
1385      eap->line2 += count - 1;
1386    }
1387    eap->addr_count++;
1388    // Be vi compatible: no error message for out of range.
1389    if (validate && eap->line2 > curbuf->b_ml.ml_line_count) {
1390      eap->line2 = curbuf->b_ml.ml_line_count;
1391    }
1392  }
1393}
1394
1395static int parse_count(exarg_T *eap, const char **errormsg, bool validate)
1396{
1397  // Check for a count.  When accepting a EX_BUFNAME, don't use "123foo" as a
1398  // count, it's a buffer name.
1399  char *p;
1400
1401  if ((eap->argt & EX_COUNT) && ascii_isdigit(*eap->arg)
1402      && (!(eap->argt & EX_BUFNAME) || *(p = skipdigits(eap->arg + 1)) == NUL
1403          || ascii_iswhite(*p))) {
1404    linenr_T n = getdigits_int32(&eap->arg, false, INT32_MAX);
1405    eap->arg = skipwhite(eap->arg);
1406
1407    if (eap->args != NULL) {
1408      assert(eap->argc > 0 && eap->arg >= eap->args[0]);
1409      // If eap->arg is still pointing to the first argument, just make eap->args[0] point to the
1410      // same location. This is needed for usecases like vim.cmd.sleep('10m'). If eap->arg is
1411      // pointing outside the first argument, shift arguments by 1.
1412      if (eap->arg < eap->args[0] + eap->arglens[0]) {
1413        eap->arglens[0] -= (size_t)(eap->arg - eap->args[0]);
1414        eap->args[0] = eap->arg;
1415      } else {
1416        shift_cmd_args(eap);
1417      }
1418    }
1419
1420    if (n <= 0 && (eap->argt & EX_ZEROR) == 0) {
1421      if (errormsg != NULL) {
1422        *errormsg = _(e_zerocount);
1423      }
1424      return FAIL;
1425    }
1426    set_cmd_count(eap, n, validate);
1427  }
1428
1429  return OK;
1430}
1431
1432/// Check if command is not implemented
1433bool is_cmd_ni(cmdidx_T cmdidx)
1434{
1435  return !IS_USER_CMDIDX(cmdidx) && (cmdnames[cmdidx].cmd_func == ex_ni
1436                                     || cmdnames[cmdidx].cmd_func == ex_script_ni);
1437}
1438
1439// Find the command name after skipping range specifiers.
1440static char *find_excmd_after_range(exarg_T *eap)
1441{
1442  // Save location after command modifiers.
1443  char *cmd = eap->cmd;
1444  eap->cmd = skip_range(eap->cmd, NULL);
1445  char *p = find_ex_command(eap, NULL);
1446  eap->cmd = cmd;  // Restore original position for address parsing
1447  return p;
1448}
1449
1450// Set the forceit flag based on the presence of '!' after the command.
1451static bool parse_bang(const exarg_T *eap, char **p)
1452{
1453  if (**p == '!'
1454      && eap->cmdidx != CMD_substitute
1455      && eap->cmdidx != CMD_smagic
1456      && eap->cmdidx != CMD_snomagic) {
1457    (*p)++;
1458    return true;
1459  }
1460  return false;
1461}
1462
1463/// Check if command expects expression arguments that need special parsing
1464bool cmd_has_expr_args(cmdidx_T cmdidx)
1465{
1466  return cmdidx == CMD_execute
1467         || cmdidx == CMD_echo
1468         || cmdidx == CMD_echon
1469         || cmdidx == CMD_echomsg
1470         || cmdidx == CMD_echoerr;
1471}
1472
1473/// Parse command line and return information about the first command.
1474/// If parsing is done successfully, need to free cmod_filter_pat and cmod_filter_regmatch.regprog
1475/// after calling, usually done using undo_cmdmod() or execute_cmd().
1476///
1477/// @param cmdline Command line string
1478/// @param[out] eap Ex command arguments
1479/// @param[out] cmod Command modifiers
1480/// @param[out] errormsg Error message, if any
1481/// @param skipmods Skip modifiers, nextcmd, register and count. Keep leading
1482///                 whitespace of the arguments.
1483///
1484/// @return Success or failure
1485bool parse_cmdline(char **cmdline, exarg_T *eap, cmdmod_T *cmod, const char **errormsg,
1486                   bool skipmods)
1487{
1488  char *after_modifier = NULL;
1489  bool retval = false;
1490  // parsing the command range may require moving the cursor
1491  const pos_T save_cursor = curwin->w_cursor;
1492  // parsing the command range may set the last search pattern
1493  save_last_search_pattern();
1494
1495  // Initialize cmod
1496  CLEAR_POINTER(cmod);
1497
1498  // Initialize eap
1499  *eap = (exarg_T){
1500    .line1 = 1,
1501    .line2 = 1,
1502    .cmd = *cmdline,
1503    .cmdlinep = cmdline,
1504    .ea_getline = NULL,
1505    .cookie = NULL,
1506  };
1507
1508  char *orig_cmd = eap->cmd;
1509  // If parse command modifiers failed but modifiers were passed, continue
1510  int result = skipmods ? OK : parse_command_modifiers(eap, errormsg, cmod, false);
1511  after_modifier = eap->cmd;
1512  if (result == FAIL && after_modifier == orig_cmd) {
1513    goto end;
1514  }
1515
1516  // We need the command name to know what kind of range it uses.
1517  char *p = find_excmd_after_range(eap);
1518  if (p == NULL) {
1519    *errormsg = _(e_ambiguous_use_of_user_defined_command);
1520    goto end;
1521  }
1522
1523  // Set command address type and parse command range
1524  set_cmd_addr_type(eap, p);
1525  if (parse_cmd_address(eap, errormsg, true) == FAIL) {
1526    goto end;
1527  }
1528
1529  // Skip colon and whitespace
1530  eap->cmd = skip_colon_white(eap->cmd, true);
1531  // Fail if command is a comment
1532  if (*eap->cmd == '"') {
1533    goto end;
1534  }
1535  // Fail only if: empty command AND no range AND no modifier
1536  if (*eap->cmd == NUL && eap->addr_count == 0 && after_modifier == *cmdline) {
1537    goto end;
1538  }
1539
1540  // Allow range-only (:1) or modifier-only (:aboveleft) commands.
1541  if (*eap->cmd == NUL && eap->cmdidx == CMD_SIZE) {
1542    eap->arg = eap->cmd;
1543    if (eap->addr_count > 0) {
1544      eap->argt = EX_RANGE;
1545    } else {
1546      eap->argt = 0;
1547      eap->addr_type = ADDR_NONE;
1548    }
1549    retval = true;
1550    goto end;
1551  }
1552
1553  // Fail if command is invalid
1554  if (eap->cmdidx == CMD_SIZE) {
1555    xstrlcpy(IObuff, _(e_not_an_editor_command), IOSIZE);
1556    // If the modifier was parsed OK the error must be in the following command
1557    char *cmdname = after_modifier ? after_modifier : *cmdline;
1558    append_command(cmdname);
1559    *errormsg = IObuff;
1560    goto end;
1561  }
1562
1563  // Correctly set 'forceit' for commands
1564  eap->forceit = parse_bang(eap, &p);
1565
1566  // Parse arguments.
1567  if (!IS_USER_CMDIDX(eap->cmdidx)) {
1568    eap->argt = cmdnames[(int)eap->cmdidx].cmd_argt;
1569  }
1570  if (skipmods) {
1571    // Only skip the space before the arguments, the rest belongs to them.
1572    eap->arg = p + (*p == ' ');
1573  } else {
1574    // Skip to start of argument.
1575    // Don't do this for the ":!" command, because ":!! -l" needs the space.
1576    eap->arg = eap->cmdidx == CMD_bang ? p : skipwhite(p);
1577  }
1578
1579  // Don't treat ":r! filter" like a bang
1580  if (eap->cmdidx == CMD_read && eap->forceit) {
1581    eap->forceit = false;  // :r! filter
1582  }
1583
1584  // Check for '|' to separate commands and '"' to start comments.
1585  // Don't do this for ":read !cmd" and ":write !cmd".
1586  if (!skipmods && (eap->argt & EX_TRLBAR)) {
1587    separate_nextcmd(eap);
1588  } else if (!skipmods && cmd_has_expr_args(eap->cmdidx)) {
1589    // For commands without EX_TRLBAR, check for '|' separator
1590    // by skipping over expressions (including string literals)
1591    char *arg = eap->arg;
1592    while (*arg != NUL && *arg != '|' && *arg != '\n') {
1593      char *start = arg;
1594      emsg_skip++;
1595      skip_expr(&arg, NULL);
1596      emsg_skip--;
1597      // If skip_expr didn't advance, move forward to avoid infinite loop
1598      if (arg == start) {
1599        arg++;
1600      }
1601    }
1602    if (*arg == '|' || *arg == '\n') {
1603      eap->nextcmd = check_nextcmd(arg);
1604      *arg = NUL;
1605    }
1606  }
1607  // Fail if command doesn't support bang but is used with a bang
1608  if (!(eap->argt & EX_BANG) && eap->forceit) {
1609    *errormsg = _(e_nobang);
1610    goto end;
1611  }
1612  // Fail if command doesn't support a range but it is given a range
1613  if (!(eap->argt & EX_RANGE) && eap->addr_count > 0) {
1614    *errormsg = _(e_norange);
1615    goto end;
1616  }
1617  // Set default range for command if required
1618  if ((eap->argt & EX_DFLALL) && eap->addr_count == 0) {
1619    set_cmd_dflall_range(eap);
1620  }
1621
1622  // Parse register and count
1623  if (!skipmods) {
1624    parse_register(eap);
1625    if (parse_count(eap, errormsg, false) == FAIL) {
1626      goto end;
1627    }
1628  }
1629
1630  // Remove leading whitespace and colon from next command
1631  if (eap->nextcmd) {
1632    eap->nextcmd = skip_colon_white(eap->nextcmd, true);
1633  }
1634
1635  // Set the "magic" values (characters that get treated specially)
1636  eap->magic.file = eap->argt & EX_XFILE;
1637  eap->magic.bar = eap->argt & EX_TRLBAR;
1638
1639  retval = true;
1640end:
1641  if (!retval) {
1642    undo_cmdmod(cmod);
1643  }
1644  curwin->w_cursor = save_cursor;
1645  restore_last_search_pattern();
1646  return retval;
1647}
1648
1649// Shift Ex-command arguments to the right.
1650static void shift_cmd_args(exarg_T *eap)
1651{
1652  assert(eap->args != NULL && eap->argc > 0);
1653
1654  char **oldargs = eap->args;
1655  size_t *oldarglens = eap->arglens;
1656
1657  eap->argc--;
1658  eap->args = eap->argc > 0 ? xcalloc(eap->argc, sizeof(char *)) : NULL;
1659  eap->arglens = eap->argc > 0 ? xcalloc(eap->argc, sizeof(size_t)) : NULL;
1660
1661  for (size_t i = 0; i < eap->argc; i++) {
1662    eap->args[i] = oldargs[i + 1];
1663    eap->arglens[i] = oldarglens[i + 1];
1664  }
1665
1666  // If there are no arguments, make eap->arg point to the end of string.
1667  eap->arg = (eap->argc > 0 ? eap->args[0] : (oldargs[0] + oldarglens[0]));
1668
1669  xfree(oldargs);
1670  xfree(oldarglens);
1671}
1672
1673static int execute_cmd0(int *retv, exarg_T *eap, const char **errormsg, bool preview)
1674{
1675  // If filename expansion is enabled, expand filenames
1676  if (eap->argt & EX_XFILE) {
1677    if (expand_filename(eap, eap->cmdlinep, errormsg) == FAIL) {
1678      return FAIL;
1679    }
1680  }
1681
1682  // Accept buffer name.  Cannot be used at the same time with a buffer
1683  // number.  Don't do this for a user command.
1684  if ((eap->argt & EX_BUFNAME) && *eap->arg != NUL && eap->addr_count == 0
1685      && !IS_USER_CMDIDX(eap->cmdidx)) {
1686    if (eap->args == NULL) {
1687      // If argument positions are not specified, search the argument for the buffer name.
1688      // :bdelete, :bwipeout and :bunload take several arguments, separated by spaces:
1689      // find next space (skipping over escaped characters).
1690      // The others take one argument: ignore trailing spaces.
1691      char *p;
1692
1693      if (eap->cmdidx == CMD_bdelete || eap->cmdidx == CMD_bwipeout
1694          || eap->cmdidx == CMD_bunload) {
1695        p = skiptowhite_esc(eap->arg);
1696      } else {
1697        p = eap->arg + strlen(eap->arg);
1698        while (p > eap->arg && ascii_iswhite(p[-1])) {
1699          p--;
1700        }
1701      }
1702      eap->line2 = buflist_findpat(eap->arg, p, (eap->argt & EX_BUFUNL) != 0,
1703                                   false, false);
1704      eap->addr_count = 1;
1705      eap->arg = skipwhite(p);
1706    } else {
1707      // If argument positions are specified, just use the first argument
1708      eap->line2 = buflist_findpat(eap->args[0],
1709                                   eap->args[0] + eap->arglens[0],
1710                                   (eap->argt & EX_BUFUNL) != 0, false, false);
1711      eap->addr_count = 1;
1712      shift_cmd_args(eap);
1713    }
1714    if (eap->line2 < 0) {  // failed
1715      return FAIL;
1716    }
1717  }
1718
1719  // The :try command saves the emsg_silent flag, reset it here when
1720  // ":silent! try" was used, it should only apply to :try itself.
1721  if (eap->cmdidx == CMD_try && cmdmod.cmod_did_esilent > 0) {
1722    emsg_silent -= cmdmod.cmod_did_esilent;
1723    emsg_silent = MAX(emsg_silent, 0);
1724    cmdmod.cmod_did_esilent = 0;
1725  }
1726
1727  // Execute the command
1728  if (IS_USER_CMDIDX(eap->cmdidx)) {
1729    // Execute a user-defined command.
1730    *retv = do_ucmd(eap, preview);
1731  } else {
1732    // Call the function to execute the builtin command or the preview callback.
1733    eap->errmsg = NULL;
1734    if (preview) {
1735      *retv = (cmdnames[eap->cmdidx].cmd_preview_func)(eap, cmdpreview_get_ns(),
1736                                                       cmdpreview_get_bufnr());
1737    } else {
1738      (cmdnames[eap->cmdidx].cmd_func)(eap);
1739    }
1740    if (eap->errmsg != NULL) {
1741      *errormsg = eap->errmsg;
1742    }
1743  }
1744
1745  return OK;
1746}
1747
1748/// Execute an Ex command using parsed command line information.
1749/// Does not do any validation of the Ex command arguments.
1750///
1751/// @param eap Ex-command arguments
1752/// @param cmod Command modifiers
1753/// @param preview Execute command preview callback instead of actual command
1754int execute_cmd(exarg_T *eap, cmdmod_T *cmod, bool preview)
1755{
1756  int retv = 0;
1757  if (do_cmdline_start() == FAIL) {
1758    emsg(_(e_command_too_recursive));
1759    return retv;
1760  }
1761
1762  const char *errormsg = NULL;
1763
1764  cmdmod_T save_cmdmod = cmdmod;
1765  cmdmod = *cmod;
1766
1767  // Apply command modifiers
1768  apply_cmdmod(&cmdmod);
1769
1770  if (!MODIFIABLE(curbuf) && (eap->argt & EX_MODIFY)
1771      // allow :put in terminals
1772      && !(curbuf->terminal && (eap->cmdidx == CMD_put || eap->cmdidx == CMD_iput))) {
1773    errormsg = _(e_modifiable);
1774    goto end;
1775  }
1776  if (!IS_USER_CMDIDX(eap->cmdidx)) {
1777    if (text_locked() && !(eap->argt & EX_LOCK_OK)) {
1778      // Command not allowed when text is locked
1779      errormsg = _(get_text_locked_msg());
1780      goto end;
1781    }
1782  }
1783  // Disallow editing another buffer when "curbuf->b_ro_locked" is set.
1784  // Do allow ":checktime" (it is postponed).
1785  // Do allow ":edit" (check for an argument later).
1786  // Do allow ":file" with no arguments
1787  if (!(eap->argt & EX_BUFLOCK_OK)
1788      && eap->cmdidx != CMD_checktime
1789      && eap->cmdidx != CMD_edit
1790      && !(eap->cmdidx == CMD_file && *eap->arg == NUL)
1791      && !IS_USER_CMDIDX(eap->cmdidx)
1792      && curbuf_locked()) {
1793    goto end;
1794  }
1795
1796  correct_range(eap);
1797  if (eap->cmdidx == CMD_SIZE && eap->addr_count > 0) {
1798    errormsg = ex_range_without_command(eap);
1799    goto end;
1800  }
1801
1802  if (((eap->argt & EX_WHOLEFOLD) || eap->addr_count >= 2) && !global_busy
1803      && eap->addr_type == ADDR_LINES) {
1804    // Put the first line at the start of a closed fold, put the last line
1805    // at the end of a closed fold.
1806    hasFolding(curwin, eap->line1, &eap->line1, NULL);
1807    hasFolding(curwin, eap->line2, NULL, &eap->line2);
1808  }
1809
1810  // Use first argument as count when possible
1811  if (parse_count(eap, &errormsg, true) == FAIL) {
1812    goto end;
1813  }
1814
1815  cstack_T cstack = { .cs_idx = -1 };
1816  eap->cstack = &cstack;
1817
1818  // Execute the command
1819  execute_cmd0(&retv, eap, &errormsg, preview);
1820
1821end:
1822  if (errormsg != NULL && *errormsg != NUL) {
1823    emsg(errormsg);
1824  }
1825
1826  // Undo command modifiers
1827  undo_cmdmod(&cmdmod);
1828  cmdmod = save_cmdmod;
1829
1830  do_cmdline_end();
1831  return retv;
1832}
1833
1834static void profile_cmd(const exarg_T *eap, cstack_T *cstack, LineGetter fgetline, void *cookie)
1835{
1836  // Count this line for profiling if skip is true.
1837  if (do_profiling == PROF_YES
1838      && (!eap->skip || cstack->cs_idx == 0
1839          || (cstack->cs_idx > 0
1840              && (cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE)))) {
1841    bool skip = did_emsg || got_int || did_throw;
1842
1843    if (eap->cmdidx == CMD_catch) {
1844      skip = !skip && !(cstack->cs_idx >= 0
1845                        && (cstack->cs_flags[cstack->cs_idx] & CSF_THROWN)
1846                        && !(cstack->cs_flags[cstack->cs_idx] & CSF_CAUGHT));
1847    } else if (eap->cmdidx == CMD_else || eap->cmdidx == CMD_elseif) {
1848      skip = skip || !(cstack->cs_idx >= 0
1849                       && !(cstack->cs_flags[cstack->cs_idx]
1850                            & (CSF_ACTIVE | CSF_TRUE)));
1851    } else if (eap->cmdidx == CMD_finally) {
1852      skip = false;
1853    } else if (eap->cmdidx != CMD_endif
1854               && eap->cmdidx != CMD_endfor
1855               && eap->cmdidx != CMD_endtry
1856               && eap->cmdidx != CMD_endwhile) {
1857      skip = eap->skip;
1858    }
1859
1860    if (!skip) {
1861      if (getline_equal(fgetline, cookie, get_func_line)) {
1862        func_line_exec(getline_cookie(fgetline, cookie));
1863      } else if (getline_equal(fgetline, cookie, getsourceline)) {
1864        script_line_exec();
1865      }
1866    }
1867  }
1868}
1869
1870static bool skip_cmd(const exarg_T *eap)
1871{
1872  // Skip the command when it's not going to be executed.
1873  // The commands like :if, :endif, etc. always need to be executed.
1874  // Also make an exception for commands that handle a trailing command
1875  // themselves.
1876  if (eap->skip) {
1877    switch (eap->cmdidx) {
1878    // commands that need evaluation
1879    case CMD_while:
1880    case CMD_endwhile:
1881    case CMD_for:
1882    case CMD_endfor:
1883    case CMD_if:
1884    case CMD_elseif:
1885    case CMD_else:
1886    case CMD_endif:
1887    case CMD_try:
1888    case CMD_catch:
1889    case CMD_finally:
1890    case CMD_endtry:
1891    case CMD_function:
1892      break;
1893
1894    // commands that read a block of lines
1895    case CMD_append:
1896    case CMD_change:
1897    case CMD_insert:
1898    case CMD_loadkeymap:
1899      break;
1900
1901    // Commands that handle '|' themselves.  Check: A command should
1902    // either have the EX_TRLBAR flag, appear in this list or appear in
1903    // the list at ":help :bar".
1904    case CMD_aboveleft:
1905    case CMD_and:
1906    case CMD_belowright:
1907    case CMD_botright:
1908    case CMD_browse:
1909    case CMD_call:
1910    case CMD_confirm:
1911    case CMD_const:
1912    case CMD_delfunction:
1913    case CMD_djump:
1914    case CMD_dlist:
1915    case CMD_dsearch:
1916    case CMD_dsplit:
1917    case CMD_echo:
1918    case CMD_echoerr:
1919    case CMD_echomsg:
1920    case CMD_echon:
1921    case CMD_eval:
1922    case CMD_execute:
1923    case CMD_filter:
1924    case CMD_help:
1925    case CMD_hide:
1926    case CMD_horizontal:
1927    case CMD_ijump:
1928    case CMD_ilist:
1929    case CMD_isearch:
1930    case CMD_isplit:
1931    case CMD_keepalt:
1932    case CMD_keepjumps:
1933    case CMD_keepmarks:
1934    case CMD_keeppatterns:
1935    case CMD_leftabove:
1936    case CMD_let:
1937    case CMD_lockmarks:
1938    case CMD_lockvar:
1939    case CMD_lua:
1940    case CMD_match:
1941    case CMD_mzscheme:
1942    case CMD_noautocmd:
1943    case CMD_noswapfile:
1944    case CMD_perl:
1945    case CMD_psearch:
1946    case CMD_python:
1947    case CMD_py3:
1948    case CMD_python3:
1949    case CMD_pythonx:
1950    case CMD_pyx:
1951    case CMD_return:
1952    case CMD_rightbelow:
1953    case CMD_ruby:
1954    case CMD_silent:
1955    case CMD_smagic:
1956    case CMD_snomagic:
1957    case CMD_substitute:
1958    case CMD_syntax:
1959    case CMD_tab:
1960    case CMD_tcl:
1961    case CMD_throw:
1962    case CMD_tilde:
1963    case CMD_topleft:
1964    case CMD_unlet:
1965    case CMD_unlockvar:
1966    case CMD_verbose:
1967    case CMD_vertical:
1968    case CMD_wincmd:
1969      break;
1970
1971    default:
1972      return true;
1973    }
1974  }
1975  return false;
1976}
1977
1978/// Execute one Ex command.
1979///
1980/// If "flags" has DOCMD_VERBOSE, the command will be included in the error
1981/// message.
1982///
1983/// 1. skip comment lines and leading space
1984/// 2. handle command modifiers
1985/// 3. skip over the range to find the command
1986/// 4. parse the range
1987/// 5. parse the command
1988/// 6. parse arguments
1989/// 7. switch on command name
1990///
1991/// Note: "fgetline" can be NULL.
1992///
1993/// This function may be called recursively!
1994///
1995/// @param cookie  argument for fgetline()
1996static char *do_one_cmd(char **cmdlinep, int flags, cstack_T *cstack, LineGetter fgetline,
1997                        void *cookie)
1998{
1999  const char *errormsg = NULL;  // error message
2000  const int save_reg_executing = reg_executing;
2001  const bool save_pending_end_reg_executing = pending_end_reg_executing;
2002
2003  exarg_T ea = {
2004    .line1 = 1,
2005    .line2 = 1,
2006  };
2007  ex_nesting_level++;
2008
2009  // When the last file has not been edited :q has to be typed twice.
2010  if (quitmore
2011      // avoid that a function call in 'statusline' does this
2012      && !getline_equal(fgetline, cookie, get_func_line)
2013      // avoid that an autocommand, e.g. QuitPre, does this
2014      && !getline_equal(fgetline, cookie, getnextac)) {
2015    quitmore--;
2016  }
2017
2018  // Reset browse, confirm, etc..  They are restored when returning, for
2019  // recursive calls.
2020  cmdmod_T save_cmdmod = cmdmod;
2021
2022  // "#!anything" is handled like a comment.
2023  if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!') {
2024    goto doend;
2025  }
2026
2027  // 1. Skip comment lines and leading white space and colons.
2028  // 2. Handle command modifiers.
2029
2030  // The "ea" structure holds the arguments that can be used.
2031  ea.cmd = *cmdlinep;
2032  ea.cmdlinep = cmdlinep;
2033  ea.ea_getline = fgetline;
2034  ea.cookie = cookie;
2035  ea.cstack = cstack;
2036
2037  if (parse_command_modifiers(&ea, &errormsg, &cmdmod, false) == FAIL) {
2038    goto doend;
2039  }
2040  apply_cmdmod(&cmdmod);
2041
2042  char *after_modifier = ea.cmd;
2043
2044  ea.skip = (did_emsg
2045             || got_int
2046             || did_throw
2047             || (cstack->cs_idx >= 0
2048                 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)));
2049
2050  // 3. Skip over the range to find the command. Let "p" point to after it.
2051  //
2052  // We need the command to know what kind of range it uses.
2053  char *p = find_excmd_after_range(&ea);
2054  profile_cmd(&ea, cstack, fgetline, cookie);
2055
2056  if (!exiting) {
2057    // May go to debug mode.  If this happens and the ">quit" debug command is
2058    // used, throw an interrupt exception and skip the next command.
2059    dbg_check_breakpoint(&ea);
2060  }
2061  if (!ea.skip && got_int) {
2062    ea.skip = true;
2063    do_intthrow(cstack);
2064  }
2065
2066  // 4. Parse a range specifier of the form: addr [,addr] [;addr] ..
2067  //
2068  // where 'addr' is:
2069  //
2070  // %          (entire file)
2071  // $  [+-NUM]
2072  // 'x [+-NUM] (where x denotes a currently defined mark)
2073  // .  [+-NUM]
2074  // [+-NUM]..
2075  // NUM
2076  //
2077  // The ea.cmd pointer is updated to point to the first character following the
2078  // range spec. If an initial address is found, but no second, the upper bound
2079  // is equal to the lower.
2080  set_cmd_addr_type(&ea, p);
2081
2082  if (parse_cmd_address(&ea, &errormsg, false) == FAIL) {
2083    goto doend;
2084  }
2085
2086  // 5. Parse the command.
2087
2088  // Skip ':' and any white space
2089  ea.cmd = skip_colon_white(ea.cmd, true);
2090
2091  // If we got a line, but no command, then go to the line.
2092  // If we find a '|' or '\n' we set ea.nextcmd.
2093  if (*ea.cmd == NUL || *ea.cmd == '"'
2094      || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL) {
2095    // strange vi behaviour:
2096    // ":3"     jumps to line 3
2097    // ":3|..." prints line 3
2098    // ":|"     prints current line
2099    if (ea.skip) {  // skip this if inside :if
2100      goto doend;
2101    }
2102    assert(errormsg == NULL);
2103    errormsg = ex_range_without_command(&ea);
2104    goto doend;
2105  }
2106
2107  // If this looks like an undefined user command and there are CmdUndefined
2108  // autocommands defined, trigger the matching autocommands.
2109  if (p != NULL && ea.cmdidx == CMD_SIZE && !ea.skip
2110      && ASCII_ISUPPER(*ea.cmd)
2111      && has_event(EVENT_CMDUNDEFINED)) {
2112    char *cmdname = ea.cmd;
2113    while (ASCII_ISALNUM(*cmdname)) {
2114      cmdname++;
2115    }
2116    cmdname = xmemdupz(ea.cmd, (size_t)(cmdname - ea.cmd));
2117    int ret = apply_autocmds(EVENT_CMDUNDEFINED, cmdname, cmdname, true, NULL);
2118    xfree(cmdname);
2119    // If the autocommands did something and didn't cause an error, try
2120    // finding the command again.
2121    p = (ret && !aborting()) ? find_ex_command(&ea, NULL) : ea.cmd;
2122  }
2123
2124  if (p == NULL) {
2125    if (!ea.skip) {
2126      errormsg = _(e_ambiguous_use_of_user_defined_command);
2127    }
2128    goto doend;
2129  }
2130
2131  // Check for wrong commands.
2132  if (ea.cmdidx == CMD_SIZE) {
2133    if (!ea.skip) {
2134      xstrlcpy(IObuff, _(e_not_an_editor_command), IOSIZE);
2135      // If the modifier was parsed OK the error must be in the following
2136      // command
2137      char *cmdname = after_modifier ? after_modifier : *cmdlinep;
2138      if (!(flags & DOCMD_VERBOSE)) {
2139        append_command(cmdname);
2140      }
2141      errormsg = IObuff;
2142      did_emsg_syntax = true;
2143      verify_command(cmdname);
2144    }
2145    goto doend;
2146  }
2147
2148  // set when Not Implemented
2149  const int ni = is_cmd_ni(ea.cmdidx);
2150
2151  // Determine if command has forceit flag ('!')
2152  ea.forceit = parse_bang(&ea, &p);
2153
2154  // 6. Parse arguments.  Then check for errors.
2155  if (!IS_USER_CMDIDX(ea.cmdidx)) {
2156    ea.argt = cmdnames[(int)ea.cmdidx].cmd_argt;
2157  }
2158
2159  if (!ea.skip) {
2160    if (sandbox != 0 && !(ea.argt & EX_SBOXOK)) {
2161      // Command not allowed in sandbox.
2162      errormsg = _(e_sandbox);
2163      goto doend;
2164    }
2165    if (!MODIFIABLE(curbuf) && (ea.argt & EX_MODIFY)
2166        // allow :put in terminals
2167        && !(curbuf->terminal && (ea.cmdidx == CMD_put || ea.cmdidx == CMD_iput))) {
2168      // Command not allowed in non-'modifiable' buffer
2169      errormsg = _(e_modifiable);
2170      goto doend;
2171    }
2172
2173    if (!IS_USER_CMDIDX(ea.cmdidx)) {
2174      if (text_locked() && !(ea.argt & EX_LOCK_OK)) {
2175        // Command not allowed when text is locked
2176        errormsg = _(get_text_locked_msg());
2177        goto doend;
2178      }
2179    }
2180
2181    // Disallow editing another buffer when "curbuf->b_ro_locked" is set.
2182    // Do allow ":checktime" (it is postponed).
2183    // Do allow ":edit" (check for an argument later).
2184    // Do allow ":file" with no arguments (check for an argument later).
2185    if (!(ea.argt & EX_BUFLOCK_OK)
2186        && ea.cmdidx != CMD_checktime
2187        && ea.cmdidx != CMD_edit
2188        && ea.cmdidx != CMD_file
2189        && !IS_USER_CMDIDX(ea.cmdidx)
2190        && curbuf_locked()) {
2191      goto doend;
2192    }
2193
2194    if (!ni && !(ea.argt & EX_RANGE) && ea.addr_count > 0) {
2195      // no range allowed
2196      errormsg = _(e_norange);
2197      goto doend;
2198    }
2199  }
2200
2201  if (!ni && !(ea.argt & EX_BANG) && ea.forceit) {  // no <!> allowed
2202    errormsg = _(e_nobang);
2203    goto doend;
2204  }
2205
2206  // Don't complain about the range if it is not used
2207  // (could happen if line_count is accidentally set to 0).
2208  if (!ea.skip && !ni && (ea.argt & EX_RANGE)) {
2209    // If the range is backwards, ask for confirmation and, if given, swap
2210    // ea.line1 & ea.line2 so it's forwards again.
2211    // When global command is busy, don't ask, will fail below.
2212    if (!global_busy && ea.line1 > ea.line2) {
2213      if (msg_silent == 0) {
2214        if ((flags & DOCMD_VERBOSE) || silent_mode) {
2215          errormsg = _("E493: Backwards range given");
2216          goto doend;
2217        }
2218        if (ask_yesno(_("Backwards range given, OK to swap")) != 'y') {
2219          goto doend;
2220        }
2221      }
2222      linenr_T lnum = ea.line1;
2223      ea.line1 = ea.line2;
2224      ea.line2 = lnum;
2225    }
2226    if ((errormsg = invalid_range(&ea)) != NULL) {
2227      goto doend;
2228    }
2229  }
2230
2231  if ((ea.addr_type == ADDR_OTHER) && ea.addr_count == 0) {
2232    // default is 1, not cursor
2233    ea.line2 = 1;
2234  }
2235
2236  correct_range(&ea);
2237
2238  if (((ea.argt & EX_WHOLEFOLD) || ea.addr_count >= 2) && !global_busy
2239      && ea.addr_type == ADDR_LINES) {
2240    // Put the first line at the start of a closed fold, put the last line
2241    // at the end of a closed fold.
2242    hasFolding(curwin, ea.line1, &ea.line1, NULL);
2243    hasFolding(curwin, ea.line2, NULL, &ea.line2);
2244  }
2245
2246  // For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg'
2247  // option here, so things like % get expanded.
2248  p = replace_makeprg(&ea, p, cmdlinep);
2249  if (p == NULL) {
2250    goto doend;
2251  }
2252
2253  // Skip to start of argument.
2254  // Don't do this for the ":!" command, because ":!! -l" needs the space.
2255  ea.arg = ea.cmdidx == CMD_bang ? p : skipwhite(p);
2256
2257  // ":file" cannot be run with an argument when "curbuf->b_ro_locked" is set
2258  if (ea.cmdidx == CMD_file && *ea.arg != NUL && curbuf_locked()) {
2259    goto doend;
2260  }
2261
2262  // Check for "++opt=val" argument.
2263  // Must be first, allow ":w ++enc=utf8 !cmd"
2264  if (ea.argt & EX_ARGOPT) {
2265    while (ea.arg[0] == '+' && ea.arg[1] == '+') {
2266      if (getargopt(&ea) == FAIL && !ni) {
2267        errormsg = _(e_invarg);
2268        goto doend;
2269      }
2270    }
2271  }
2272
2273  if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) {
2274    if (*ea.arg == '>') {                       // append
2275      if (*++ea.arg != '>') {                   // typed wrong
2276        errormsg = _("E494: Use w or w>>");
2277        goto doend;
2278      }
2279      ea.arg = skipwhite(ea.arg + 1);
2280      ea.append = true;
2281    } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) {  // :w !filter
2282      ea.arg++;
2283      ea.usefilter = true;
2284    }
2285  } else if (ea.cmdidx == CMD_read) {
2286    if (ea.forceit) {
2287      ea.usefilter = true;                      // :r! filter if ea.forceit
2288      ea.forceit = false;
2289    } else if (*ea.arg == '!') {              // :r !filter
2290      ea.arg++;
2291      ea.usefilter = true;
2292    }
2293  } else if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) {
2294    ea.amount = 1;
2295    while (*ea.arg == *ea.cmd) {                // count number of '>' or '<'
2296      ea.arg++;
2297      ea.amount++;
2298    }
2299    ea.arg = skipwhite(ea.arg);
2300  }
2301
2302  // Check for "+command" argument, before checking for next command.
2303  // Don't do this for ":read !cmd" and ":write !cmd".
2304  if ((ea.argt & EX_CMDARG) && !ea.usefilter) {
2305    ea.do_ecmd_cmd = getargcmd(&ea.arg);
2306  }
2307
2308  // Check for '|' to separate commands and '"' to start comments.
2309  // Don't do this for ":read !cmd" and ":write !cmd".
2310  if ((ea.argt & EX_TRLBAR) && !ea.usefilter) {
2311    separate_nextcmd(&ea);
2312  } else if (ea.cmdidx == CMD_bang
2313             || ea.cmdidx == CMD_terminal
2314             || ea.cmdidx == CMD_global
2315             || ea.cmdidx == CMD_vglobal
2316             || ea.usefilter) {
2317    // Check for <newline> to end a shell command.
2318    // Also do this for ":read !cmd", ":write !cmd" and ":global".
2319    // Any others?
2320    for (char *s = ea.arg; *s; s++) {
2321      // Remove one backslash before a newline.
2322      if (*s == '\\' && s[1] == '\n') {
2323        STRMOVE(s, s + 1);
2324      } else if (*s == '\n') {
2325        ea.nextcmd = s + 1;
2326        *s = NUL;
2327        break;
2328      }
2329    }
2330  }
2331
2332  if ((ea.argt & EX_DFLALL) && ea.addr_count == 0) {
2333    set_cmd_dflall_range(&ea);
2334  }
2335
2336  // Parse register and count
2337  parse_register(&ea);
2338  if (parse_count(&ea, &errormsg, true) == FAIL) {
2339    goto doend;
2340  }
2341
2342  // Check for flags: 'l', 'p' and '#'.
2343  if (ea.argt & EX_FLAGS) {
2344    get_flags(&ea);
2345  }
2346  if (!ni && !(ea.argt & EX_EXTRA) && *ea.arg != NUL
2347      && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & EX_TRLBAR) == 0)) {
2348    // no arguments allowed but there is something
2349    errormsg = ex_errmsg(e_trailing_arg, ea.arg);
2350    goto doend;
2351  }
2352
2353  if (!ni && (ea.argt & EX_NEEDARG) && *ea.arg == NUL) {
2354    errormsg = _(e_argreq);
2355    goto doend;
2356  }
2357
2358  if (skip_cmd(&ea)) {
2359    goto doend;
2360  }
2361
2362  // 7. Execute the command.
2363  int retv = 0;
2364  if (execute_cmd0(&retv, &ea, &errormsg, false) == FAIL) {
2365    goto doend;
2366  }
2367
2368  // If the command just executed called do_cmdline(), any throw or ":return"
2369  // or ":finish" encountered there must also check the cstack of the still
2370  // active do_cmdline() that called this do_one_cmd().  Rethrow an uncaught
2371  // exception, or reanimate a returned function or finished script file and
2372  // return or finish it again.
2373  if (need_rethrow) {
2374    do_throw(cstack);
2375  } else if (check_cstack) {
2376    if (source_finished(fgetline, cookie)) {
2377      do_finish(&ea, true);
2378    } else if (getline_equal(fgetline, cookie, get_func_line)
2379               && current_func_returned()) {
2380      do_return(&ea, true, false, NULL);
2381    }
2382  }
2383  need_rethrow = check_cstack = false;
2384
2385doend:
2386  // can happen with zero line number
2387  if (curwin->w_cursor.lnum == 0) {
2388    curwin->w_cursor.lnum = 1;
2389    curwin->w_cursor.col = 0;
2390  }
2391
2392  if (errormsg != NULL && *errormsg != NUL && !did_emsg) {
2393    if (flags & DOCMD_VERBOSE) {
2394      if (errormsg != IObuff) {
2395        xstrlcpy(IObuff, errormsg, IOSIZE);
2396        errormsg = IObuff;
2397      }
2398      append_command(*ea.cmdlinep);
2399    }
2400    emsg(errormsg);
2401  }
2402  do_errthrow(cstack,
2403              (ea.cmdidx != CMD_SIZE
2404               && !IS_USER_CMDIDX(ea.cmdidx)) ? cmdnames[(int)ea.cmdidx].cmd_name : NULL);
2405
2406  undo_cmdmod(&cmdmod);
2407  cmdmod = save_cmdmod;
2408  reg_executing = save_reg_executing;
2409  pending_end_reg_executing = save_pending_end_reg_executing;
2410
2411  if (ea.nextcmd && *ea.nextcmd == NUL) {       // not really a next command
2412    ea.nextcmd = NULL;
2413  }
2414
2415  ex_nesting_level--;
2416  xfree(ea.cmdline_tofree);
2417
2418  return ea.nextcmd;
2419}
2420
2421static char ex_error_buf[MSG_BUF_LEN];
2422
2423/// @return an error message with argument included.
2424/// Uses a static buffer, only the last error will be kept.
2425/// "msg" will be translated, caller should use N_().
2426char *ex_errmsg(const char *const msg, ...)
2427  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PRINTF(1, 2)
2428{
2429  va_list ap;
2430  va_start(ap, msg);
2431  vim_vsnprintf(ex_error_buf, MSG_BUF_LEN, _(msg), ap);
2432  va_end(ap);
2433  return ex_error_buf;
2434}
2435
2436/// Handle a range without a command.
2437/// Returns an error message on failure.
2438static char *ex_range_without_command(exarg_T *eap)
2439{
2440  char *errormsg = NULL;
2441
2442  if (*eap->cmd == '|') {
2443    eap->cmdidx = CMD_print;
2444    eap->argt = EX_RANGE | EX_COUNT | EX_TRLBAR;
2445    if ((errormsg = invalid_range(eap)) == NULL) {
2446      correct_range(eap);
2447      ex_print(eap);
2448    }
2449  } else if (eap->addr_count != 0) {
2450    eap->line2 = MIN(eap->line2, curbuf->b_ml.ml_line_count);
2451
2452    if (eap->line2 < 0) {
2453      errormsg = _(e_invrange);
2454    } else {
2455      if (eap->line2 == 0) {
2456        curwin->w_cursor.lnum = 1;
2457      } else {
2458        curwin->w_cursor.lnum = eap->line2;
2459      }
2460      beginline(BL_SOL | BL_FIX);
2461    }
2462  }
2463  return errormsg;
2464}
2465
2466/// Parse and skip over command modifiers:
2467/// - update eap->cmd
2468/// - store flags in "cmod".
2469///
2470/// @param skip_only      if false, undo_cmdmod() must be called later to free
2471///                       any cmod_filter_pat and cmod_filter_regmatch.regprog.
2472/// @param[out] errormsg  potential error message.
2473///
2474/// Call apply_cmdmod() to get the side effects of the modifiers:
2475/// - Increment "sandbox" for ":sandbox"
2476/// - set p_verbose for ":verbose"
2477/// - set msg_silent for ":silent"
2478/// - set 'eventignore' to "all" for ":noautocmd"
2479///
2480/// @return  FAIL when the command is not to be executed.
2481int parse_command_modifiers(exarg_T *eap, const char **errormsg, cmdmod_T *cmod, bool skip_only)
2482{
2483  char *orig_cmd = eap->cmd;
2484  char *cmd_start = NULL;
2485  bool has_visual_range = false;
2486  CLEAR_POINTER(cmod);
2487
2488  if (strncmp(eap->cmd, "'<,'>", 5) == 0) {
2489    // The automatically inserted Visual area range is skipped, so that
2490    // typing ":cmdmod cmd" in Visual mode works without having to move the
2491    // range to after the modifiers. The command will be "'<,'>cmdmod cmd",
2492    // parse "cmdmod cmd" and then put back "'<,'>" before "cmd" below.
2493    // Only skip '<,'>' if there's a command after it
2494    const char *p = skipwhite(eap->cmd + 5);
2495    if (*p != NUL && *p != '|') {
2496      eap->cmd += 5;
2497      cmd_start = eap->cmd;
2498      has_visual_range = true;
2499    }
2500  }
2501
2502  // Repeat until no more command modifiers are found.
2503  while (true) {
2504    while (*eap->cmd == ' '
2505           || *eap->cmd == '\t'
2506           || *eap->cmd == ':') {
2507      eap->cmd++;
2508    }
2509
2510    // ignore comment and empty lines
2511    if (*eap->cmd == '"') {
2512      // a comment ends at a NL
2513      eap->nextcmd = vim_strchr(eap->cmd, '\n');
2514      if (eap->nextcmd != NULL) {
2515        eap->nextcmd++;
2516      }
2517      return FAIL;
2518    }
2519    if (*eap->cmd == '\n') {
2520      eap->nextcmd = eap->cmd + 1;
2521      return FAIL;
2522    }
2523    if (*eap->cmd == NUL) {
2524      return FAIL;
2525    }
2526
2527    char *p = skip_range(eap->cmd, NULL);
2528    switch (*p) {
2529    // When adding an entry, also modify cmdmods[]
2530    case 'a':
2531      if (!checkforcmd(&eap->cmd, "aboveleft", 3)) {
2532        break;
2533      }
2534      cmod->cmod_split |= WSP_ABOVE;
2535      continue;
2536
2537    case 'b':
2538      if (checkforcmd(&eap->cmd, "belowright", 3)) {
2539        cmod->cmod_split |= WSP_BELOW;
2540        continue;
2541      }
2542      if (checkforcmd(&eap->cmd, "browse", 3)) {
2543        cmod->cmod_flags |= CMOD_BROWSE;
2544        continue;
2545      }
2546      if (!checkforcmd(&eap->cmd, "botright", 2)) {
2547        break;
2548      }
2549      cmod->cmod_split |= WSP_BOT;
2550      continue;
2551
2552    case 'c':
2553      if (!checkforcmd(&eap->cmd, "confirm", 4)) {
2554        break;
2555      }
2556      cmod->cmod_flags |= CMOD_CONFIRM;
2557      continue;
2558
2559    case 'k':
2560      if (checkforcmd(&eap->cmd, "keepmarks", 3)) {
2561        cmod->cmod_flags |= CMOD_KEEPMARKS;
2562        continue;
2563      }
2564      if (checkforcmd(&eap->cmd, "keepalt", 5)) {
2565        cmod->cmod_flags |= CMOD_KEEPALT;
2566        continue;
2567      }
2568      if (checkforcmd(&eap->cmd, "keeppatterns", 5)) {
2569        cmod->cmod_flags |= CMOD_KEEPPATTERNS;
2570        continue;
2571      }
2572      if (!checkforcmd(&eap->cmd, "keepjumps", 5)) {
2573        break;
2574      }
2575      cmod->cmod_flags |= CMOD_KEEPJUMPS;
2576      continue;
2577
2578    case 'f': {  // only accept ":filter {pat} cmd"
2579      char *reg_pat;
2580
2581      if (!checkforcmd(&p, "filter", 4) || *p == NUL || ends_excmd(*p)) {
2582        break;
2583      }
2584      if (*p == '!') {
2585        cmod->cmod_filter_force = true;
2586        p = skipwhite(p + 1);
2587        if (*p == NUL || ends_excmd(*p)) {
2588          break;
2589        }
2590      }
2591      if (skip_only) {
2592        p = skip_vimgrep_pat(p, NULL, NULL);
2593      } else {
2594        // NOTE: This puts a NUL after the pattern.
2595        p = skip_vimgrep_pat(p, &reg_pat, NULL);
2596      }
2597      if (p == NULL || *p == NUL) {
2598        break;
2599      }
2600      if (!skip_only) {
2601        cmod->cmod_filter_pat = xstrdup(reg_pat);
2602        cmod->cmod_filter_regmatch.regprog = vim_regcomp(reg_pat, RE_MAGIC);
2603        if (cmod->cmod_filter_regmatch.regprog == NULL) {
2604          break;
2605        }
2606      }
2607      eap->cmd = p;
2608      continue;
2609    }
2610
2611    case 'h':
2612      if (checkforcmd(&eap->cmd, "horizontal", 3)) {
2613        cmod->cmod_split |= WSP_HOR;
2614        continue;
2615      }
2616      // ":hide" and ":hide | cmd" are not modifiers
2617      if (p != eap->cmd || !checkforcmd(&p, "hide", 3)
2618          || *p == NUL || ends_excmd(*p)) {
2619        break;
2620      }
2621      eap->cmd = p;
2622      cmod->cmod_flags |= CMOD_HIDE;
2623      continue;
2624
2625    case 'l':
2626      if (checkforcmd(&eap->cmd, "lockmarks", 3)) {
2627        cmod->cmod_flags |= CMOD_LOCKMARKS;
2628        continue;
2629      }
2630
2631      if (!checkforcmd(&eap->cmd, "leftabove", 5)) {
2632        break;
2633      }
2634      cmod->cmod_split |= WSP_ABOVE;
2635      continue;
2636
2637    case 'n':
2638      if (checkforcmd(&eap->cmd, "noautocmd", 3)) {
2639        cmod->cmod_flags |= CMOD_NOAUTOCMD;
2640        continue;
2641      }
2642      if (!checkforcmd(&eap->cmd, "noswapfile", 3)) {
2643        break;
2644      }
2645      cmod->cmod_flags |= CMOD_NOSWAPFILE;
2646      continue;
2647
2648    case 'r':
2649      if (!checkforcmd(&eap->cmd, "rightbelow", 6)) {
2650        break;
2651      }
2652      cmod->cmod_split |= WSP_BELOW;
2653      continue;
2654
2655    case 's':
2656      if (checkforcmd(&eap->cmd, "sandbox", 3)) {
2657        cmod->cmod_flags |= CMOD_SANDBOX;
2658        continue;
2659      }
2660      if (!checkforcmd(&eap->cmd, "silent", 3)) {
2661        break;
2662      }
2663      cmod->cmod_flags |= CMOD_SILENT;
2664      if (*eap->cmd == '!' && !ascii_iswhite(eap->cmd[-1])) {
2665        // ":silent!", but not "silent !cmd"
2666        eap->cmd = skipwhite(eap->cmd + 1);
2667        cmod->cmod_flags |= CMOD_ERRSILENT;
2668      }
2669      continue;
2670
2671    case 't':
2672      if (checkforcmd(&p, "tab", 3)) {
2673        if (!skip_only) {
2674          int tabnr = (int)get_address(eap, &eap->cmd, ADDR_TABS, eap->skip, skip_only,
2675                                       false, 1, errormsg);
2676          if (eap->cmd == NULL) {
2677            return false;
2678          }
2679
2680          if (tabnr == MAXLNUM) {
2681            cmod->cmod_tab = tabpage_index(curtab) + 1;
2682          } else {
2683            if (tabnr < 0 || tabnr > LAST_TAB_NR) {
2684              *errormsg = _(e_invrange);
2685              return false;
2686            }
2687            cmod->cmod_tab = tabnr + 1;
2688          }
2689        }
2690        eap->cmd = p;
2691        continue;
2692      }
2693      if (!checkforcmd(&eap->cmd, "topleft", 2)) {
2694        break;
2695      }
2696      cmod->cmod_split |= WSP_TOP;
2697      continue;
2698
2699    case 'u':
2700      if (!checkforcmd(&eap->cmd, "unsilent", 3)) {
2701        break;
2702      }
2703      cmod->cmod_flags |= CMOD_UNSILENT;
2704      continue;
2705
2706    case 'v':
2707      if (checkforcmd(&eap->cmd, "vertical", 4)) {
2708        cmod->cmod_split |= WSP_VERT;
2709        continue;
2710      }
2711      if (!checkforcmd(&p, "verbose", 4)) {
2712        break;
2713      }
2714      if (ascii_isdigit(*eap->cmd)) {
2715        // zero means not set, one is verbose == 0, etc.
2716        cmod->cmod_verbose = atoi(eap->cmd) + 1;
2717      } else {
2718        cmod->cmod_verbose = 2;  // default: verbose == 1
2719      }
2720      eap->cmd = p;
2721      continue;
2722    }
2723    break;
2724  }
2725
2726  if (has_visual_range) {
2727    if (eap->cmd > cmd_start) {
2728      // Move the '<,'> range to after the modifiers and insert a colon.
2729      // Since the modifiers have been parsed put the colon on top of the
2730      // space: "'<,'>mod cmd" -> "mod:'<,'>cmd
2731      // Put eap->cmd after the colon.
2732      memmove(cmd_start - 5, cmd_start, (size_t)(eap->cmd - cmd_start));
2733      eap->cmd -= 5;
2734      memmove(eap->cmd - 1, ":'<,'>", 6);
2735    } else {
2736      // No modifiers, move the pointer back.
2737      eap->cmd = orig_cmd;
2738    }
2739  }
2740
2741  return OK;
2742}
2743
2744/// Apply the command modifiers.  Saves current state in "cmdmod", call
2745/// undo_cmdmod() later.
2746void apply_cmdmod(cmdmod_T *cmod)
2747{
2748  if ((cmod->cmod_flags & CMOD_SANDBOX) && !cmod->cmod_did_sandbox) {
2749    sandbox++;
2750    cmod->cmod_did_sandbox = true;
2751  }
2752  if (cmod->cmod_verbose > 0) {
2753    if (cmod->cmod_verbose_save == 0) {
2754      cmod->cmod_verbose_save = p_verbose + 1;
2755    }
2756    p_verbose = cmod->cmod_verbose - 1;
2757  }
2758
2759  if ((cmod->cmod_flags & (CMOD_SILENT | CMOD_UNSILENT))
2760      && cmod->cmod_save_msg_silent == 0) {
2761    cmod->cmod_save_msg_silent = msg_silent + 1;
2762    cmod->cmod_save_msg_scroll = msg_scroll;
2763  }
2764  if (cmod->cmod_flags & CMOD_SILENT) {
2765    msg_silent++;
2766  }
2767  if (cmod->cmod_flags & CMOD_UNSILENT) {
2768    msg_silent = 0;
2769  }
2770
2771  if (cmod->cmod_flags & CMOD_ERRSILENT) {
2772    emsg_silent++;
2773    cmod->cmod_did_esilent++;
2774  }
2775
2776  if ((cmod->cmod_flags & CMOD_NOAUTOCMD) && cmod->cmod_save_ei == NULL) {
2777    // Set 'eventignore' to "all".
2778    // First save the existing option value for restoring it later.
2779    cmod->cmod_save_ei = xstrdup(p_ei);
2780    set_option_direct(kOptEventignore, STATIC_CSTR_AS_OBJ("all"), 0, SID_NONE);
2781  }
2782}
2783
2784/// Undo and free contents of "cmod".
2785void undo_cmdmod(cmdmod_T *cmod)
2786  FUNC_ATTR_NONNULL_ALL
2787{
2788  if (cmod->cmod_verbose_save > 0) {
2789    p_verbose = cmod->cmod_verbose_save - 1;
2790    cmod->cmod_verbose_save = 0;
2791  }
2792
2793  if (cmod->cmod_did_sandbox) {
2794    sandbox--;
2795    cmod->cmod_did_sandbox = false;
2796  }
2797
2798  if (cmod->cmod_save_ei != NULL) {
2799    // Restore 'eventignore' to the value before ":noautocmd".
2800    set_option_direct(kOptEventignore, CSTR_AS_OBJ(cmod->cmod_save_ei), 0, SID_NONE);
2801    free_string_option(cmod->cmod_save_ei);
2802    cmod->cmod_save_ei = NULL;
2803  }
2804
2805  xfree(cmod->cmod_filter_pat);
2806  vim_regfree(cmod->cmod_filter_regmatch.regprog);
2807
2808  if (cmod->cmod_save_msg_silent > 0) {
2809    // messages could be enabled for a serious error, need to check if the
2810    // counters don't become negative
2811    if (!did_emsg || msg_silent > cmod->cmod_save_msg_silent - 1) {
2812      msg_silent = cmod->cmod_save_msg_silent - 1;
2813    }
2814    emsg_silent -= cmod->cmod_did_esilent;
2815    emsg_silent = MAX(emsg_silent, 0);
2816    // Restore msg_scroll, it's set by file I/O commands, even when no
2817    // message is actually displayed.
2818    msg_scroll = cmod->cmod_save_msg_scroll;
2819
2820    // "silent reg" or "silent echo x" inside "redir" leaves msg_col
2821    // somewhere in the line.  Put it back in the first column.
2822    if (redirecting()) {
2823      msg_col = 0;
2824    }
2825
2826    cmod->cmod_save_msg_silent = 0;
2827    cmod->cmod_did_esilent = 0;
2828  }
2829}
2830
2831/// Parse the address range, if any, in "eap".
2832/// May set the last search pattern, unless "silent" is true.
2833///
2834/// @return  FAIL and set "errormsg" or return OK.
2835int parse_cmd_address(exarg_T *eap, const char **errormsg, bool silent)
2836  FUNC_ATTR_NONNULL_ALL
2837{
2838  int address_count = 1;
2839  linenr_T lnum;
2840  bool need_check_cursor = false;
2841  int ret = FAIL;
2842
2843  // Repeat for all ',' or ';' separated addresses.
2844  while (true) {
2845    eap->line1 = eap->line2;
2846    eap->line2 = get_cmd_default_range(eap);
2847    eap->cmd = skipwhite(eap->cmd);
2848    lnum = get_address(eap, &eap->cmd, eap->addr_type, eap->skip, silent,
2849                       eap->addr_count == 0, address_count++, errormsg);
2850    if (eap->cmd == NULL) {  // error detected
2851      goto theend;
2852    }
2853    if (lnum == MAXLNUM) {
2854      if (*eap->cmd == '%') {  // '%' - all lines
2855        eap->cmd++;
2856        switch (eap->addr_type) {
2857        case ADDR_LINES:
2858        case ADDR_OTHER:
2859          eap->line1 = 1;
2860          eap->line2 = curbuf->b_ml.ml_line_count;
2861          break;
2862        case ADDR_LOADED_BUFFERS: {
2863          buf_T *buf = firstbuf;
2864
2865          while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) {
2866            buf = buf->b_next;
2867          }
2868          eap->line1 = buf->b_fnum;
2869          buf = lastbuf;
2870          while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) {
2871            buf = buf->b_prev;
2872          }
2873          eap->line2 = buf->b_fnum;
2874          break;
2875        }
2876        case ADDR_BUFFERS:
2877          eap->line1 = firstbuf->b_fnum;
2878          eap->line2 = lastbuf->b_fnum;
2879          break;
2880        case ADDR_WINDOWS:
2881        case ADDR_TABS:
2882          if (IS_USER_CMDIDX(eap->cmdidx)) {
2883            eap->line1 = 1;
2884            eap->line2 = eap->addr_type == ADDR_WINDOWS
2885                         ? LAST_WIN_NR(false) : LAST_TAB_NR;
2886          } else {
2887            // there is no Vim command which uses '%' and
2888            // ADDR_WINDOWS or ADDR_TABS
2889            *errormsg = _(e_invrange);
2890            goto theend;
2891          }
2892          break;
2893        case ADDR_TABS_RELATIVE:
2894        case ADDR_UNSIGNED:
2895        case ADDR_QUICKFIX:
2896          *errormsg = _(e_invrange);
2897          goto theend;
2898        case ADDR_ARGUMENTS:
2899          if (ARGCOUNT == 0) {
2900            eap->line1 = eap->line2 = 0;
2901          } else {
2902            eap->line1 = 1;
2903            eap->line2 = ARGCOUNT;
2904          }
2905          break;
2906        case ADDR_QUICKFIX_VALID:
2907          eap->line1 = 1;
2908          eap->line2 = (linenr_T)qf_get_valid_size(eap);
2909          if (eap->line2 == 0) {
2910            eap->line2 = 1;
2911          }
2912          break;
2913        case ADDR_NONE:
2914          // Will give an error later if a range is found.
2915          break;
2916        }
2917        eap->addr_count++;
2918      } else if (*eap->cmd == '*') {
2919        // '*' - visual area
2920        if (eap->addr_type != ADDR_LINES) {
2921          *errormsg = _(e_invrange);
2922          goto theend;
2923        }
2924
2925        eap->cmd++;
2926        if (!eap->skip) {
2927          fmark_T *fm = mark_get_visual(curbuf, '<');
2928          if (!mark_check(fm, errormsg)) {
2929            goto theend;
2930          }
2931          assert(fm != NULL);
2932          eap->line1 = fm->mark.lnum;
2933          fm = mark_get_visual(curbuf, '>');
2934          if (!mark_check(fm, errormsg)) {
2935            goto theend;
2936          }
2937          assert(fm != NULL);
2938          eap->line2 = fm->mark.lnum;
2939          eap->addr_count++;
2940        }
2941      }
2942    } else {
2943      eap->line2 = lnum;
2944    }
2945    eap->addr_count++;
2946
2947    if (*eap->cmd == ';') {
2948      if (!eap->skip) {
2949        curwin->w_cursor.lnum = eap->line2;
2950
2951        // Don't leave the cursor on an illegal line or column, but do
2952        // accept zero as address, so 0;/PATTERN/ works correctly
2953        // (where zero usually means to use the first line).
2954        // Check the cursor position before returning.
2955        if (eap->line2 > 0) {
2956          check_cursor(curwin);
2957        } else {
2958          check_cursor_col(curwin);
2959        }
2960        need_check_cursor = true;
2961      }
2962    } else if (*eap->cmd != ',') {
2963      break;
2964    }
2965    eap->cmd++;
2966  }
2967
2968  // One address given: set start and end lines.
2969  if (eap->addr_count == 1) {
2970    eap->line1 = eap->line2;
2971    // ... but only implicit: really no address given
2972    if (lnum == MAXLNUM) {
2973      eap->addr_count = 0;
2974    }
2975  }
2976  ret = OK;
2977
2978theend:
2979  if (need_check_cursor) {
2980    check_cursor(curwin);
2981  }
2982  return ret;
2983}
2984
2985/// Check for an Ex command with optional tail.
2986/// If there is a match advance "pp" to the argument and return true.
2987///
2988/// @param pp   start of command
2989/// @param cmd  name of command
2990/// @param len  required length
2991bool checkforcmd(char **pp, const char *cmd, int len)
2992{
2993  int i;
2994
2995  for (i = 0; cmd[i] != NUL; i++) {
2996    if (cmd[i] != (*pp)[i]) {
2997      break;
2998    }
2999  }
3000  if (i >= len && !ASCII_ISALPHA((*pp)[i])) {
3001    *pp = skipwhite(*pp + i);
3002    return true;
3003  }
3004  return false;
3005}
3006
3007/// Append "cmd" to the error message in IObuff.
3008/// Takes care of limiting the length and handling 0xa0, which would be
3009/// invisible otherwise.
3010static void append_command(const char *cmd)
3011{
3012  size_t len = strlen(IObuff);
3013  const char *s = cmd;
3014  char *d;
3015
3016  if (len > IOSIZE - 100) {
3017    // Not enough space, truncate and put in "...".
3018    d = IObuff + IOSIZE - 100;
3019    d -= utf_head_off(IObuff, d);
3020    STRCPY(d, "...");
3021  }
3022  xstrlcat(IObuff, ": ", IOSIZE);
3023  d = IObuff + strlen(IObuff);
3024  while (*s != NUL && d - IObuff + 5 < IOSIZE) {
3025    if ((uint8_t)s[0] == 0xc2 && (uint8_t)s[1] == 0xa0) {
3026      s += 2;
3027      STRCPY(d, "<a0>");
3028      d += 4;
3029    } else if (d - IObuff + utfc_ptr2len(s) + 1 >= IOSIZE) {
3030      break;
3031    } else {
3032      mb_copy_char(&s, &d);
3033    }
3034  }
3035  *d = NUL;
3036}
3037
3038/// Return true and set "*idx" if "p" points to a one letter command.
3039/// - The 'k' command can directly be followed by any character
3040///          but :keepa[lt] is another command, as are :keepj[umps],
3041///          :kee[pmarks] and :keepp[atterns].
3042/// - The 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
3043///          but :sre[wind] is another command, as are :scr[iptnames],
3044///          :scs[cope], :sim[alt], :sig[ns] and :sil[ent].
3045static int one_letter_cmd(const char *p, cmdidx_T *idx)
3046{
3047  if (p[0] == 'k'
3048      && (p[1] != 'e' || (p[1] == 'e' && p[2] != 'e'))) {
3049    *idx = CMD_k;
3050    return true;
3051  }
3052  if (p[0] == 's'
3053      && ((p[1] == 'c'
3054           && (p[2] == NUL
3055               || (p[2] != 's' && p[2] != 'r'
3056                   && (p[3] == NUL
3057                       || (p[3] != 'i' && p[4] != 'p')))))
3058          || p[1] == 'g'
3059          || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g')
3060          || p[1] == 'I'
3061          || (p[1] == 'r' && p[2] != 'e'))) {
3062    *idx = CMD_substitute;
3063    return true;
3064  }
3065  return false;
3066}
3067
3068/// Find an Ex command by its name, either built-in or user.
3069/// Start of the name can be found at eap->cmd.
3070/// Sets eap->cmdidx and returns a pointer to char after the command name.
3071/// "full" is set to true if the whole command name matched.
3072///
3073/// @return  NULL for an ambiguous user command.
3074char *find_ex_command(exarg_T *eap, int *full)
3075  FUNC_ATTR_NONNULL_ARG(1)
3076{
3077  // Isolate the command and search for it in the command table.
3078  char *p = eap->cmd;
3079  if (one_letter_cmd(p, &eap->cmdidx)) {
3080    p++;
3081    if (full != NULL) {
3082      *full = true;
3083    }
3084  } else {
3085    while (ASCII_ISALPHA(*p)) {
3086      p++;
3087    }
3088    // for python 3.x support ":py3", ":python3", ":py3file", etc.
3089    if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y') {
3090      while (ASCII_ISALNUM(*p)) {
3091        p++;
3092      }
3093    }
3094
3095    // check for non-alpha command
3096    if (p == eap->cmd && vim_strchr("@!=><&~#", (uint8_t)(*p)) != NULL) {
3097      p++;
3098    }
3099    int len = (int)(p - eap->cmd);
3100    // The "d" command can directly be followed by 'l' or 'p' flag.
3101    if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p')) {
3102      // Check for ":dl", ":dell", etc. to ":deletel": that's
3103      // :delete with the 'l' flag.  Same for 'p'.
3104      int i;
3105      for (i = 0; i < len; i++) {
3106        if (eap->cmd[i] != "delete"[i]) {
3107          break;
3108        }
3109      }
3110      if (i == len - 1) {
3111        len--;
3112        if (p[-1] == 'l') {
3113          eap->flags |= EXFLAG_LIST;
3114        } else {
3115          eap->flags |= EXFLAG_PRINT;
3116        }
3117      }
3118    }
3119
3120    if (ASCII_ISLOWER(eap->cmd[0])) {
3121      const int c1 = (uint8_t)eap->cmd[0];
3122      const int c2 = len == 1 ? NUL : eap->cmd[1];
3123
3124      if (command_count != CMD_SIZE) {
3125        iemsg(_("E943: Command table needs to be updated, run 'make'"));
3126        getout(1);
3127      }
3128
3129      // Use a precomputed index for fast look-up in cmdnames[]
3130      // taking into account the first 2 letters of eap->cmd.
3131      eap->cmdidx = cmdidxs1[CHAR_ORD_LOW(c1)];
3132      if (ASCII_ISLOWER(c2)) {
3133        eap->cmdidx += cmdidxs2[CHAR_ORD_LOW(c1)][CHAR_ORD_LOW(c2)];
3134      }
3135    } else if (ASCII_ISUPPER(eap->cmd[0])) {
3136      eap->cmdidx = CMD_Next;
3137    } else {
3138      eap->cmdidx = CMD_bang;
3139    }
3140    assert(eap->cmdidx >= 0);
3141
3142    if (len == 3 && strncmp("def", eap->cmd, 3) == 0) {
3143      // Make :def an unknown command to avoid confusing behavior. #23149
3144      eap->cmdidx = CMD_SIZE;
3145    }
3146
3147    for (; (int)eap->cmdidx < CMD_SIZE;
3148         eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1)) {
3149      if (strncmp(cmdnames[(int)eap->cmdidx].cmd_name, eap->cmd,
3150                  (size_t)len) == 0) {
3151        if (full != NULL
3152            && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL) {
3153          *full = true;
3154        }
3155        break;
3156      }
3157    }
3158
3159    // Look for a user defined command as a last resort.
3160    if ((eap->cmdidx == CMD_SIZE)
3161        && *eap->cmd >= 'A' && *eap->cmd <= 'Z') {
3162      // User defined commands may contain digits.
3163      while (ASCII_ISALNUM(*p)) {
3164        p++;
3165      }
3166      p = find_ucmd(eap, p, full, NULL, NULL);
3167    }
3168    if (p == eap->cmd) {
3169      eap->cmdidx = CMD_SIZE;
3170    }
3171  }
3172
3173  // Force ":ho" to be unresolved.  Without this, find_ex_command()
3174  // matches it to CMD_horizontal (the only "ho*" entry), which makes
3175  // fullcommand("ho") return "horizontal" even though ":ho" cannot be
3176  // used as the modifier (cmdmods[] requires 3 chars, "hor").
3177  if (eap->cmdidx == CMD_horizontal && p - eap->cmd == 2) {
3178    eap->cmdidx = CMD_SIZE;
3179  }
3180
3181  return p;
3182}
3183
3184static struct cmdmod {
3185  char *name;
3186  int minlen;
3187  int has_count;            // :123verbose  :3tab
3188} cmdmods[] = {
3189  { "aboveleft", 3, false },
3190  { "belowright", 3, false },
3191  { "botright", 2, false },
3192  { "browse", 3, false },
3193  { "confirm", 4, false },
3194  { "filter", 4, false },
3195  { "hide", 3, false },
3196  { "horizontal", 3, false },
3197  { "keepalt", 5, false },
3198  { "keepjumps", 5, false },
3199  { "keepmarks", 3, false },
3200  { "keeppatterns", 5, false },
3201  { "leftabove", 5, false },
3202  { "lockmarks", 3, false },
3203  { "noautocmd", 3, false },
3204  { "noswapfile", 3, false },
3205  { "rightbelow", 6, false },
3206  { "sandbox", 3, false },
3207  { "silent", 3, false },
3208  { "tab", 3, true },
3209  { "topleft", 2, false },
3210  { "unsilent", 3, false },
3211  { "verbose", 4, true },
3212  { "vertical", 4, false },
3213};
3214
3215/// @return  length of a command modifier (including optional count) or,
3216///          zero when it's not a modifier.
3217int modifier_len(char *cmd)
3218{
3219  char *p = cmd;
3220
3221  if (ascii_isdigit(*cmd)) {
3222    p = skipwhite(skipdigits(cmd + 1));
3223  }
3224  for (int i = 0; i < (int)ARRAY_SIZE(cmdmods); i++) {
3225    // cmdmod_info_tab[] is sorted by name: once the first letter is past
3226    // the command's first letter no later entry can match.
3227    if (cmdmods[i].name[0] > *p) {
3228      break;
3229    }
3230    int j;
3231    for (j = 0; p[j] != NUL; j++) {
3232      if (p[j] != cmdmods[i].name[j]) {
3233        break;
3234      }
3235    }
3236    if (j >= cmdmods[i].minlen
3237        && !ASCII_ISALPHA(p[j])
3238        && (p == cmd || cmdmods[i].has_count)) {
3239      return j + (int)(p - cmd);
3240    }
3241  }
3242  return 0;
3243}
3244
3245/// @return  > 0 if an Ex command "name" exists or,
3246///            2 if there is an exact match or,
3247///            3 if there is an ambiguous match.
3248int cmd_exists(const char *const name)
3249{
3250  // Check command modifiers.
3251  for (int i = 0; i < (int)ARRAY_SIZE(cmdmods); i++) {
3252    int j;
3253    for (j = 0; name[j] != NUL; j++) {
3254      if (name[j] != cmdmods[i].name[j]) {
3255        break;
3256      }
3257    }
3258    if (name[j] == NUL && j >= cmdmods[i].minlen) {
3259      return cmdmods[i].name[j] == NUL ? 2 : 1;
3260    }
3261  }
3262
3263  // Check built-in commands and user defined commands.
3264  // For ":2match" and ":3match" we need to skip the number.
3265  exarg_T ea;
3266  ea.cmd = (char *)((*name == '2' || *name == '3') ? name + 1 : name);
3267  ea.cmdidx = 0;
3268  ea.flags = 0;
3269  int full = false;
3270  char *p = find_ex_command(&ea, &full);
3271  if (p == NULL) {
3272    return 3;
3273  }
3274  if (ascii_isdigit(*name) && ea.cmdidx != CMD_match) {
3275    return 0;
3276  }
3277  if (*skipwhite(p) != NUL) {
3278    return 0;           // trailing garbage
3279  }
3280  return ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1);
3281}
3282
3283/// "fullcommand" function
3284void f_fullcommand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3285{
3286  char *name = (char *)tv_get_string(&argvars[0]);
3287
3288  rettv->v_type = VAR_STRING;
3289  rettv->vval.v_string = NULL;
3290
3291  while (*name == ':') {
3292    name++;
3293  }
3294  name = skip_range(name, NULL);
3295
3296  exarg_T ea;
3297  ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
3298  ea.cmdidx = 0;
3299  ea.flags = 0;
3300  char *p = find_ex_command(&ea, NULL);
3301  if (p == NULL || ea.cmdidx == CMD_SIZE) {
3302    return;
3303  }
3304
3305  rettv->vval.v_string = xstrdup(IS_USER_CMDIDX(ea.cmdidx)
3306                                 ? get_user_command_name(ea.useridx, ea.cmdidx)
3307                                 : cmdnames[ea.cmdidx].cmd_name);
3308}
3309
3310cmdidx_T excmd_get_cmdidx(const char *cmd, size_t len)
3311{
3312  if (len == 3 && strncmp("def", cmd, 3) == 0) {
3313    // Make :def an unknown command to avoid confusing behavior. #23149
3314    return CMD_SIZE;
3315  }
3316
3317  cmdidx_T idx;
3318
3319  if (!one_letter_cmd(cmd, &idx)) {
3320    for (idx = 0; (int)idx < CMD_SIZE; idx = (cmdidx_T)((int)idx + 1)) {
3321      if (strncmp(cmdnames[(int)idx].cmd_name, cmd, len) == 0) {
3322        break;
3323      }
3324    }
3325  }
3326
3327  return idx;
3328}
3329
3330uint32_t excmd_get_argt(cmdidx_T idx)
3331{
3332  return cmdnames[(int)idx].cmd_argt;
3333}
3334
3335/// Skip a range specifier of the form: addr [,addr] [;addr] ..
3336///
3337/// Backslashed delimiters after / or ? will be skipped, and commands will
3338/// not be expanded between /'s and ?'s or after "'".
3339///
3340/// Also skip white space and ":" characters.
3341///
3342/// @param ctx  pointer to xp_context or NULL
3343///
3344/// @return the "cmd" pointer advanced to beyond the range.
3345char *skip_range(const char *cmd, int *ctx)
3346{
3347  while (vim_strchr(" \t0123456789.$%'/?-+,;\\", (uint8_t)(*cmd)) != NULL) {
3348    if (*cmd == '\\') {
3349      if (cmd[1] == '?' || cmd[1] == '/' || cmd[1] == '&') {
3350        cmd++;
3351      } else {
3352        break;
3353      }
3354    } else if (*cmd == '\'') {
3355      if (*++cmd == NUL && ctx != NULL) {
3356        *ctx = EXPAND_NOTHING;
3357      }
3358    } else if (*cmd == '/' || *cmd == '?') {
3359      unsigned delim = (unsigned)(*cmd++);
3360      while (*cmd != NUL && *cmd != (char)delim) {
3361        if (*cmd++ == '\\' && *cmd != NUL) {
3362          cmd++;
3363        }
3364      }
3365      if (*cmd == NUL && ctx != NULL) {
3366        *ctx = EXPAND_NOTHING;
3367      }
3368    }
3369    if (*cmd != NUL) {
3370      cmd++;
3371    }
3372  }
3373
3374  // Skip ":" and white space.
3375  cmd = skip_colon_white(cmd, false);
3376
3377  // Skip "*" used for Visual range.
3378  if (*cmd == '*') {
3379    cmd = skipwhite(cmd + 1);
3380  }
3381
3382  return (char *)cmd;
3383}
3384
3385static const char *addr_error(cmd_addr_T addr_type)
3386{
3387  if (addr_type == ADDR_NONE) {
3388    return _(e_norange);
3389  } else {
3390    return _(e_invrange);
3391  }
3392}
3393
3394/// Gets a single EX address.
3395///
3396/// Sets ptr to the next character after the part that was interpreted.
3397/// Sets ptr to NULL when an error is encountered (stored in `errormsg`).
3398/// May set the last used search pattern.
3399///
3400/// @param skip           only skip the address, don't use it
3401/// @param silent         no errors or side effects
3402/// @param to_other_file  flag: may jump to other file
3403/// @param address_count  1 for first, >1 after comma
3404/// @param errormsg       Error message, if any
3405///
3406/// @return               MAXLNUM when no Ex address was found.
3407linenr_T get_address(exarg_T *eap, char **ptr, cmd_addr_T addr_type, bool skip, bool silent,
3408                     int to_other_file, int address_count, const char **errormsg)
3409  FUNC_ATTR_NONNULL_ARG(2, 8)
3410{
3411  int c;
3412  int i;
3413  linenr_T n;
3414  pos_T pos;
3415  buf_T *buf;
3416
3417  char *cmd = skipwhite(*ptr);
3418  linenr_T lnum = MAXLNUM;
3419  do {
3420    switch (*cmd) {
3421    case '.':                               // '.' - Cursor position
3422      cmd++;
3423      switch (addr_type) {
3424      case ADDR_LINES:
3425      case ADDR_OTHER:
3426        lnum = curwin->w_cursor.lnum;
3427        break;
3428      case ADDR_WINDOWS:
3429        lnum = CURRENT_WIN_NR;
3430        break;
3431      case ADDR_ARGUMENTS:
3432        lnum = curwin->w_arg_idx + 1;
3433        break;
3434      case ADDR_LOADED_BUFFERS:
3435      case ADDR_BUFFERS:
3436        lnum = curbuf->b_fnum;
3437        break;
3438      case ADDR_TABS:
3439        lnum = CURRENT_TAB_NR;
3440        break;
3441      case ADDR_NONE:
3442      case ADDR_TABS_RELATIVE:
3443      case ADDR_UNSIGNED:
3444        *errormsg = addr_error(addr_type);
3445        cmd = NULL;
3446        goto error;
3447        break;
3448      case ADDR_QUICKFIX:
3449        lnum = (linenr_T)qf_get_cur_idx(eap);
3450        break;
3451      case ADDR_QUICKFIX_VALID:
3452        lnum = qf_get_cur_valid_idx(eap);
3453        break;
3454      }
3455      break;
3456
3457    case '$':                               // '$' - last line
3458      cmd++;
3459      switch (addr_type) {
3460      case ADDR_LINES:
3461      case ADDR_OTHER:
3462        lnum = curbuf->b_ml.ml_line_count;
3463        break;
3464      case ADDR_WINDOWS:
3465        lnum = LAST_WIN_NR(eap);
3466        break;
3467      case ADDR_ARGUMENTS:
3468        lnum = ARGCOUNT;
3469        break;
3470      case ADDR_LOADED_BUFFERS:
3471        buf = lastbuf;
3472        while (buf->b_ml.ml_mfp == NULL) {
3473          if (buf->b_prev == NULL) {
3474            break;
3475          }
3476          buf = buf->b_prev;
3477        }
3478        lnum = buf->b_fnum;
3479        break;
3480      case ADDR_BUFFERS:
3481        lnum = lastbuf->b_fnum;
3482        break;
3483      case ADDR_TABS:
3484        lnum = LAST_TAB_NR;
3485        break;
3486      case ADDR_NONE:
3487      case ADDR_TABS_RELATIVE:
3488      case ADDR_UNSIGNED:
3489        *errormsg = addr_error(addr_type);
3490        cmd = NULL;
3491        goto error;
3492        break;
3493      case ADDR_QUICKFIX:
3494        lnum = (linenr_T)qf_get_size(eap);
3495        if (lnum == 0) {
3496          lnum = 1;
3497        }
3498        break;
3499      case ADDR_QUICKFIX_VALID:
3500        lnum = (linenr_T)qf_get_valid_size(eap);
3501        if (lnum == 0) {
3502          lnum = 1;
3503        }
3504        break;
3505      }
3506      break;
3507
3508    case '\'':                              // ''' - mark
3509      if (*++cmd == NUL) {
3510        cmd = NULL;
3511        goto error;
3512      }
3513      if (addr_type != ADDR_LINES) {
3514        *errormsg = addr_error(addr_type);
3515        cmd = NULL;
3516        goto error;
3517      }
3518      if (skip) {
3519        cmd++;
3520      } else {
3521        // Only accept a mark in another file when it is
3522        // used by itself: ":'M".
3523        MarkGet flag = to_other_file && cmd[1] == NUL ? kMarkAll : kMarkBufLocal;
3524        fmark_T *fm = mark_get(curbuf, curwin, NULL, flag, *cmd);
3525        cmd++;
3526        if (fm != NULL && fm->fnum != curbuf->handle) {
3527          mark_move_to(fm, 0);
3528          // Jumped to another file.
3529          lnum = curwin->w_cursor.lnum;
3530        } else {
3531          if (!mark_check(fm, errormsg)) {
3532            cmd = NULL;
3533            goto error;
3534          }
3535          assert(fm != NULL);
3536          lnum = fm->mark.lnum;
3537        }
3538      }
3539      break;
3540
3541    case '/':
3542    case '?':                           // '/' or '?' - search
3543      c = (uint8_t)(*cmd++);
3544      if (addr_type != ADDR_LINES) {
3545        *errormsg = addr_error(addr_type);
3546        cmd = NULL;
3547        goto error;
3548      }
3549      if (skip) {                       // skip "/pat/"
3550        cmd = skip_regexp(cmd, c, p_magic);
3551        if (*cmd == c) {
3552          cmd++;
3553        }
3554      } else {
3555        int flags;
3556
3557        pos = curwin->w_cursor;  // save curwin->w_cursor
3558
3559        // When '/' or '?' follows another address, start from
3560        // there.
3561        if (lnum > 0 && lnum != MAXLNUM) {
3562          curwin->w_cursor.lnum
3563            = lnum > curbuf->b_ml.ml_line_count ? curbuf->b_ml.ml_line_count : lnum;
3564        }
3565
3566        // Start a forward search at the end of the line (unless
3567        // before the first line).
3568        // Start a backward search at the start of the line.
3569        // This makes sure we never match in the current
3570        // line, and can match anywhere in the
3571        // next/previous line.
3572        curwin->w_cursor.col = (c == '/' && curwin->w_cursor.lnum > 0) ? MAXCOL : 0;
3573        Search.cmdlen = 0;
3574        flags = silent ? SEARCH_KEEP : SEARCH_HIS | SEARCH_MSG;
3575        if (!do_search(NULL, c, c, cmd, strlen(cmd), 1, flags, p_magic, NULL)) {
3576          curwin->w_cursor = pos;
3577          cmd = NULL;
3578          goto error;
3579        }
3580        lnum = curwin->w_cursor.lnum;
3581        curwin->w_cursor = pos;
3582        // adjust command string pointer
3583        cmd += Search.cmdlen;
3584      }
3585      break;
3586
3587    case '\\':                      // "\?", "\/" or "\&", repeat search
3588      cmd++;
3589      if (addr_type != ADDR_LINES) {
3590        *errormsg = addr_error(addr_type);
3591        cmd = NULL;
3592        goto error;
3593      }
3594      if (*cmd == '&') {
3595        i = RE_SUBST;
3596      } else if (*cmd == '?' || *cmd == '/') {
3597        i = RE_SEARCH;
3598      } else {
3599        *errormsg = _(e_backslash);
3600        cmd = NULL;
3601        goto error;
3602      }
3603
3604      if (!skip) {
3605        // When search follows another address, start from there.
3606        pos.lnum = (lnum != MAXLNUM) ? lnum : curwin->w_cursor.lnum;
3607        // Start the search just like for the above do_search().
3608        pos.col = (*cmd != '?') ? MAXCOL : 0;
3609        pos.coladd = 0;
3610        if (searchit(curwin, curbuf, &pos, NULL,
3611                     *cmd == '?' ? BACKWARD : FORWARD,
3612                     "", 0, 1, SEARCH_MSG, i, p_magic, NULL) != FAIL) {
3613          lnum = pos.lnum;
3614        } else {
3615          cmd = NULL;
3616          goto error;
3617        }
3618      }
3619      cmd++;
3620      break;
3621
3622    default:
3623      if (ascii_isdigit(*cmd)) {                // absolute line number
3624        lnum = (linenr_T)getdigits(&cmd, false, 0);
3625      }
3626    }
3627
3628    while (true) {
3629      cmd = skipwhite(cmd);
3630      if (*cmd != '-' && *cmd != '+' && !ascii_isdigit(*cmd)) {
3631        break;
3632      }
3633
3634      if (lnum == MAXLNUM) {
3635        switch (addr_type) {
3636        case ADDR_LINES:
3637        case ADDR_OTHER:
3638          // "+1" is same as ".+1"
3639          lnum = curwin->w_cursor.lnum;
3640          break;
3641        case ADDR_WINDOWS:
3642          lnum = CURRENT_WIN_NR;
3643          break;
3644        case ADDR_ARGUMENTS:
3645          lnum = curwin->w_arg_idx + 1;
3646          break;
3647        case ADDR_LOADED_BUFFERS:
3648        case ADDR_BUFFERS:
3649          lnum = curbuf->b_fnum;
3650          break;
3651        case ADDR_TABS:
3652          lnum = CURRENT_TAB_NR;
3653          break;
3654        case ADDR_TABS_RELATIVE:
3655          lnum = 1;
3656          break;
3657        case ADDR_QUICKFIX:
3658          lnum = (linenr_T)qf_get_cur_idx(eap);
3659          break;
3660        case ADDR_QUICKFIX_VALID:
3661          lnum = qf_get_cur_valid_idx(eap);
3662          break;
3663        case ADDR_NONE:
3664        case ADDR_UNSIGNED:
3665          lnum = 0;
3666          break;
3667        }
3668      }
3669
3670      if (ascii_isdigit(*cmd)) {
3671        i = '+';                        // "number" is same as "+number"
3672      } else {
3673        i = (uint8_t)(*cmd++);
3674      }
3675      if (!ascii_isdigit(*cmd)) {       // '+' is '+1'
3676        n = 1;
3677      } else {
3678        // "number", "+number" or "-number"
3679        n = getdigits_int32(&cmd, false, MAXLNUM);
3680        if (n == MAXLNUM) {
3681          *errormsg = _(e_line_number_out_of_range);
3682          cmd = NULL;
3683          goto error;
3684        }
3685      }
3686
3687      if (addr_type == ADDR_TABS_RELATIVE) {
3688        *errormsg = _(e_invrange);
3689        cmd = NULL;
3690        goto error;
3691      } else if (addr_type == ADDR_LOADED_BUFFERS || addr_type == ADDR_BUFFERS) {
3692        lnum = compute_buffer_local_count(addr_type, lnum, (i == '-') ? -1 * n : n);
3693      } else {
3694        // Relative line addressing: need to adjust for lines in a
3695        // closed fold after the first address.
3696        if (addr_type == ADDR_LINES && (i == '-' || i == '+')
3697            && address_count >= 2) {
3698          hasFolding(curwin, lnum, NULL, &lnum);
3699        }
3700        if (i == '-') {
3701          lnum -= n;
3702        } else {
3703          if (lnum >= 0 && n >= INT32_MAX - lnum) {
3704            *errormsg = _(e_line_number_out_of_range);
3705            cmd = NULL;
3706            goto error;
3707          }
3708          lnum += n;
3709        }
3710      }
3711    }
3712  } while (*cmd == '/' || *cmd == '?');
3713
3714error:
3715  *ptr = cmd;
3716  return lnum;
3717}
3718
3719/// Get flags from an Ex command argument.
3720static void get_flags(exarg_T *eap)
3721{
3722  while (vim_strchr("lp#", (uint8_t)(*eap->arg)) != NULL) {
3723    if (*eap->arg == 'l') {
3724      eap->flags |= EXFLAG_LIST;
3725    } else if (*eap->arg == 'p') {
3726      eap->flags |= EXFLAG_PRINT;
3727    } else {
3728      eap->flags |= EXFLAG_NR;
3729    }
3730    eap->arg = skipwhite(eap->arg + 1);
3731  }
3732}
3733
3734/// Stub function for command which is Not Implemented. NI!
3735void ex_ni(exarg_T *eap)
3736{
3737  if (!eap->skip) {
3738    eap->errmsg = _("E319: The command is not available in this version");
3739  }
3740}
3741
3742/// Stub function for script command which is Not Implemented. NI!
3743/// Skips over ":perl <<EOF" constructs.
3744static void ex_script_ni(exarg_T *eap)
3745{
3746  if (!eap->skip) {
3747    ex_ni(eap);
3748  } else {
3749    size_t len;
3750    xfree(script_get(eap, &len));
3751  }
3752}
3753
3754/// Check range in Ex command for validity.
3755///
3756/// @return  NULL when valid, error message when invalid.
3757char *invalid_range(exarg_T *eap)
3758{
3759  buf_T *buf;
3760  if (eap->line1 < 0 || eap->line2 < 0 || eap->line1 > eap->line2) {
3761    return _(e_invrange);
3762  }
3763
3764  if (eap->argt & EX_RANGE) {
3765    switch (eap->addr_type) {
3766    case ADDR_LINES:
3767      if (eap->line2 >
3768          (curbuf->b_ml.ml_line_count
3769           + (eap->cmdidx == CMD_diffget || eap->cmdidx == CMD_diffput))) {
3770        return _(e_invrange);
3771      }
3772      break;
3773    case ADDR_ARGUMENTS:
3774      // add 1 if ARGCOUNT is 0
3775      if (eap->line2 > ARGCOUNT + (!ARGCOUNT)) {
3776        return _(e_invrange);
3777      }
3778      break;
3779    case ADDR_BUFFERS:
3780      // Only a boundary check, not whether the buffers actually
3781      // exist.
3782      if (eap->line1 < 1 || eap->line2 > get_highest_fnum()) {
3783        return _(e_invrange);
3784      }
3785      break;
3786    case ADDR_LOADED_BUFFERS:
3787      buf = firstbuf;
3788      while (buf->b_ml.ml_mfp == NULL) {
3789        if (buf->b_next == NULL) {
3790          return _(e_invrange);
3791        }
3792        buf = buf->b_next;
3793      }
3794      if (eap->line1 < buf->b_fnum) {
3795        return _(e_invrange);
3796      }
3797      buf = lastbuf;
3798      while (buf->b_ml.ml_mfp == NULL) {
3799        if (buf->b_prev == NULL) {
3800          return _(e_invrange);
3801        }
3802        buf = buf->b_prev;
3803      }
3804      if (eap->line2 > buf->b_fnum) {
3805        return _(e_invrange);
3806      }
3807      break;
3808    case ADDR_WINDOWS:
3809      if (eap->line2 > LAST_WIN_NR(eap)) {
3810        return _(e_invrange);
3811      }
3812      break;
3813    case ADDR_TABS:
3814      if (eap->line2 > LAST_TAB_NR) {
3815        return _(e_invrange);
3816      }
3817      break;
3818    case ADDR_TABS_RELATIVE:
3819    case ADDR_OTHER:
3820      // Any range is OK.
3821      break;
3822    case ADDR_QUICKFIX:
3823      assert(eap->line2 >= 0);
3824      // No error for value that is too big, will use the last entry.
3825      if (eap->line2 <= 0) {
3826        if (eap->addr_count == 0) {
3827          return _(e_no_errors);
3828        }
3829        return _(e_invrange);
3830      }
3831      break;
3832    case ADDR_QUICKFIX_VALID:
3833      if ((eap->line2 != 1 && (size_t)eap->line2 > qf_get_valid_size(eap))
3834          || eap->line2 < 0) {
3835        return _(e_invrange);
3836      }
3837      break;
3838    case ADDR_UNSIGNED:
3839    case ADDR_NONE:
3840      // Will give an error elsewhere.
3841      break;
3842    }
3843  }
3844  return NULL;
3845}
3846
3847/// Correct the range for zero line number, if required.
3848static void correct_range(exarg_T *eap)
3849{
3850  if (!(eap->argt & EX_ZEROR)) {  // zero in range not allowed
3851    if (eap->line1 == 0) {
3852      eap->line1 = 1;
3853    }
3854    if (eap->line2 == 0) {
3855      eap->line2 = 1;
3856    }
3857  }
3858}
3859
3860/// For a ":vimgrep" or ":vimgrepadd" command return a pointer past the
3861/// pattern.  Otherwise return eap->arg.
3862static char *skip_grep_pat(exarg_T *eap)
3863{
3864  char *p = eap->arg;
3865
3866  if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep
3867                    || eap->cmdidx == CMD_vimgrepadd
3868                    || eap->cmdidx == CMD_lvimgrepadd
3869                    || grep_internal(eap->cmdidx))) {
3870    p = skip_vimgrep_pat(p, NULL, NULL);
3871    if (p == NULL) {
3872      p = eap->arg;
3873    }
3874  }
3875  return p;
3876}
3877
3878/// For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option
3879/// in the command line, so that things like % get expanded.
3880char *replace_makeprg(exarg_T *eap, char *arg, char **cmdlinep)
3881{
3882  bool isgrep = eap->cmdidx == CMD_grep
3883                || eap->cmdidx == CMD_lgrep
3884                || eap->cmdidx == CMD_grepadd
3885                || eap->cmdidx == CMD_lgrepadd;
3886
3887  // Don't do it when ":vimgrep" is used for ":grep".
3888  if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake || isgrep)
3889      && !grep_internal(eap->cmdidx)) {
3890    const char *program = isgrep ? (*curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp)
3891                                 : (*curbuf->b_p_mp == NUL ? p_mp : curbuf->b_p_mp);
3892
3893    arg = skipwhite(arg);
3894
3895    char *new_cmdline;
3896    // Replace $* by given arguments
3897    if ((new_cmdline = strrep(program, "$*", arg)) == NULL) {
3898      // No $* in arg, build "<makeprg> <arg>" instead
3899      new_cmdline = xmalloc(strlen(program) + strlen(arg) + 2);
3900      STRCPY(new_cmdline, program);
3901      strcat(new_cmdline, " ");
3902      strcat(new_cmdline, arg);
3903    }
3904
3905    msg_make(arg);
3906
3907    // 'eap->cmd' is not set here, because it is not used at CMD_make
3908    xfree(*cmdlinep);
3909    *cmdlinep = new_cmdline;
3910    arg = new_cmdline;
3911  }
3912  return arg;
3913}
3914
3915/// Expand file name in Ex command argument.
3916/// When an error is detected, "errormsgp" is set to a non-NULL pointer.
3917///
3918/// @return  FAIL for failure, OK otherwise.
3919int expand_filename(exarg_T *eap, char **cmdlinep, const char **errormsgp)
3920{
3921  // Skip a regexp pattern for ":vimgrep[add] pat file..."
3922  char *p = skip_grep_pat(eap);
3923
3924  // Decide to expand wildcards *before* replacing '%', '#', etc.  If
3925  // the file name contains a wildcard it should not cause expanding.
3926  // (it will be expanded anyway if there is a wildcard before replacing).
3927  bool has_wildcards = path_has_wildcard(p, true);
3928  while (*p != NUL) {
3929    // Skip over `=expr`, wildcards in it are not expanded.
3930    if (p[0] == '`' && p[1] == '=') {
3931      p += 2;
3932      skip_expr(&p, NULL);
3933      if (*p == '`') {
3934        p++;
3935      }
3936      continue;
3937    }
3938    // Quick check if this cannot be the start of a special string.
3939    // Also removes backslash before '%', '#' and '<'.
3940    if (vim_strchr("%#<", (uint8_t)(*p)) == NULL) {
3941      p++;
3942      continue;
3943    }
3944
3945    // Try to find a match at this position.
3946    size_t srclen;
3947    int escaped;
3948    char *repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
3949                           errormsgp, &escaped, true);
3950    if (*errormsgp != NULL) {           // error detected
3951      return FAIL;
3952    }
3953    if (repl == NULL) {                 // no match found
3954      p += srclen;
3955      continue;
3956    }
3957
3958    // Wildcards won't be expanded below, the replacement is taken
3959    // literally.  But do expand "~/file", "~user/file" and "$HOME/file".
3960    if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL) {
3961      char *l = repl;
3962
3963      repl = expand_env_save(repl);
3964      xfree(l);
3965    }
3966
3967    // Need to escape white space et al. with a backslash.
3968    // Don't do this for:
3969    // - replacement that already has been escaped: "##"
3970    // - shell commands (may have to use quotes instead).
3971    if (!eap->usefilter
3972        && !escaped
3973        && eap->cmdidx != CMD_bang
3974        && eap->cmdidx != CMD_grep
3975        && eap->cmdidx != CMD_grepadd
3976        && eap->cmdidx != CMD_lgrep
3977        && eap->cmdidx != CMD_lgrepadd
3978        && eap->cmdidx != CMD_lmake
3979        && eap->cmdidx != CMD_make
3980        && eap->cmdidx != CMD_terminal
3981        && !(eap->argt & EX_NOSPC)) {
3982      char *l;
3983#ifdef BACKSLASH_IN_FILENAME
3984      // Don't escape a backslash here, because rem_backslash() doesn't
3985      // remove it later.
3986      static char *nobslash = " \t\"|";
3987# define ESCAPE_CHARS nobslash
3988#else
3989# define ESCAPE_CHARS escape_chars
3990#endif
3991
3992      for (l = repl; *l; l++) {
3993        if (vim_strchr(ESCAPE_CHARS, (uint8_t)(*l)) != NULL) {
3994          l = vim_strsave_escaped(repl, ESCAPE_CHARS);
3995          xfree(repl);
3996          repl = l;
3997          break;
3998        }
3999      }
4000    }
4001
4002    // For a shell command a '!' must be escaped.
4003    if ((eap->usefilter
4004         || eap->cmdidx == CMD_bang
4005         || eap->cmdidx == CMD_terminal)
4006        && strpbrk(repl, "!") != NULL) {
4007      char *l = vim_strsave_escaped(repl, "!");
4008      xfree(repl);
4009      repl = l;
4010    }
4011
4012    p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
4013    xfree(repl);
4014  }
4015
4016  // One file argument: Expand wildcards.
4017  // Don't do this with ":r !command" or ":w !command".
4018  if ((eap->argt & EX_NOSPC) && !eap->usefilter) {
4019    // Replace environment variables.
4020    if (has_wildcards) {
4021      // May expand environment variables.  This
4022      // can be done much faster with expand_env() than with
4023      // something else (e.g., calling a shell).
4024      // After expanding environment variables, check again
4025      // if there are still wildcards present.
4026      if (vim_strchr(eap->arg, '$') != NULL
4027          || vim_strchr(eap->arg, '~') != NULL) {
4028        expand_env_esc(eap->arg, NameBuff, MAXPATHL, (char *)(" \t" PATH_ESC_WILDCARDS), true,
4029                       NULL);
4030        has_wildcards = path_has_wildcard(NameBuff, true);
4031        p = NameBuff;
4032      } else {
4033        p = NULL;
4034      }
4035      if (p != NULL) {
4036        repl_cmdline(eap, eap->arg, strlen(eap->arg), p, cmdlinep);
4037      }
4038    }
4039
4040    // Halve the number of backslashes (this is Vi compatible).
4041    // For Unix, when wildcards are expanded, this is
4042    // done by ExpandOne() below.
4043#ifdef UNIX
4044    if (!has_wildcards) {
4045      backslash_halve(eap->arg);
4046    }
4047#else
4048    backslash_halve(eap->arg);
4049#endif
4050
4051    if (has_wildcards) {
4052      expand_T xpc;
4053      int options = WILD_LIST_NOTFOUND | WILD_NOERROR | WILD_ADD_SLASH;
4054
4055      ExpandInit(&xpc);
4056      xpc.xp_context = EXPAND_FILES;
4057      if (p_wic) {
4058        options += WILD_ICASE;
4059      }
4060      p = ExpandOne(&xpc, eap->arg, NULL, options, WILD_EXPAND_FREE);
4061      if (p == NULL) {
4062        return FAIL;
4063      }
4064      repl_cmdline(eap, eap->arg, strlen(eap->arg), p, cmdlinep);
4065      xfree(p);
4066    } else {
4067      TO_SLASH(eap->arg);
4068    }
4069  }
4070  return OK;
4071}
4072
4073/// Replace part of the command line, keeping eap->cmd, eap->arg, eap->args and
4074/// eap->nextcmd correct.
4075/// "src" points to the part that is to be replaced, of length "srclen".
4076/// "repl" is the replacement string.
4077///
4078/// @return  a pointer to the character after the replaced string.
4079static char *repl_cmdline(exarg_T *eap, char *src, size_t srclen, char *repl, char **cmdlinep)
4080{
4081  // The new command line is build in new_cmdline[].
4082  // First allocate it.
4083  // Careful: a "+cmd" argument may have been NUL terminated.
4084  size_t len = strlen(repl);
4085  size_t i = (size_t)(src - *cmdlinep) + strlen(src + srclen) + len + 3;
4086  if (eap->nextcmd != NULL) {
4087    i += strlen(eap->nextcmd);    // add space for next command
4088  }
4089  char *new_cmdline = xmalloc(i);
4090  size_t offset = (size_t)(src - *cmdlinep);
4091
4092  // Copy the stuff before the expanded part.
4093  // Copy the expanded stuff.
4094  // Copy what came after the expanded part.
4095  // Copy the next commands, if there are any.
4096  i = offset;   // length of part before match
4097  memmove(new_cmdline, *cmdlinep, i);
4098
4099  memmove(new_cmdline + i, repl, len);
4100  i += len;                             // remember the end of the string
4101  STRCPY(new_cmdline + i, src + srclen);
4102  src = new_cmdline + i;                // remember where to continue
4103
4104  if (eap->nextcmd != NULL) {           // append next command
4105    i = strlen(new_cmdline) + 1;
4106    STRCPY(new_cmdline + i, eap->nextcmd);
4107    eap->nextcmd = new_cmdline + i;
4108  }
4109  eap->cmd = new_cmdline + (eap->cmd - *cmdlinep);
4110  eap->arg = new_cmdline + (eap->arg - *cmdlinep);
4111
4112  for (size_t j = 0; j < eap->argc; j++) {
4113    if (offset >= (size_t)(eap->args[j] - *cmdlinep)) {
4114      // If replaced text is after or in the same position as the argument,
4115      // the argument's position relative to the beginning of the cmdline stays the same.
4116      eap->args[j] = new_cmdline + (eap->args[j] - *cmdlinep);
4117    } else {
4118      // Otherwise, argument gets shifted alongside the replaced text.
4119      // The amount of the shift is equal to the difference of the old and new string length.
4120      eap->args[j] = new_cmdline + ((eap->args[j] - *cmdlinep) + (ptrdiff_t)(len - srclen));
4121    }
4122  }
4123
4124  if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command) {
4125    eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep);
4126  }
4127  xfree(*cmdlinep);
4128  *cmdlinep = new_cmdline;
4129
4130  return src;
4131}
4132
4133/// Check for '|' to separate commands and '"' to start comments.
4134void separate_nextcmd(exarg_T *eap)
4135{
4136  char *p = skip_grep_pat(eap);
4137
4138  for (; *p; MB_PTR_ADV(p)) {
4139    if (*p == Ctrl_V) {
4140      if (eap->argt & (EX_CTRLV | EX_XFILE)) {
4141        p++;  // skip CTRL-V and next char
4142      } else {
4143        // remove CTRL-V and skip next char
4144        STRMOVE(p, p + 1);
4145      }
4146      if (*p == NUL) {  // stop at NUL after CTRL-V
4147        break;
4148      }
4149    } else if (p[0] == '`' && p[1] == '=' && (eap->argt & EX_XFILE)) {
4150      // Skip over `=expr` when wildcards are expanded.
4151      p += 2;
4152      skip_expr(&p, NULL);
4153      if (*p == NUL) {  // stop at NUL after CTRL-V
4154        break;
4155      }
4156    } else if (
4157               // Check for '"': start of comment or '|': next command
4158               // :@" does not start a comment!
4159               // :redir @" doesn't either.
4160               (*p == '"'
4161                && !(eap->argt & EX_NOTRLCOM)
4162                && (eap->cmdidx != CMD_at || p != eap->arg)
4163                && (eap->cmdidx != CMD_redir
4164                    || p != eap->arg + 1 || p[-1] != '@'))
4165               || (*p == '|'
4166                   && eap->cmdidx != CMD_append
4167                   && eap->cmdidx != CMD_change
4168                   && eap->cmdidx != CMD_insert)
4169               || *p == '\n') {
4170      // We remove the '\' before the '|', unless EX_CTRLV is used
4171      // AND 'b' is present in 'cpoptions'.
4172      if ((vim_strchr(p_cpo, kCpoBar) == NULL
4173           || !(eap->argt & EX_CTRLV)) && *(p - 1) == '\\') {
4174        STRMOVE(p - 1, p);  // remove the '\'
4175        p--;
4176      } else {
4177        eap->nextcmd = check_nextcmd(p);
4178        *p = NUL;
4179        break;
4180      }
4181    }
4182  }
4183
4184  if (!(eap->argt & EX_NOTRLCOM)) {  // remove trailing spaces
4185    del_trailing_spaces(eap->arg);
4186  }
4187}
4188
4189/// get + command from ex argument
4190char *getargcmd(char **argp)
4191{
4192  char *arg = *argp;
4193  char *command = NULL;
4194
4195  if (*arg == '+') {        // +[command]
4196    arg++;
4197    if (ascii_isspace(*arg) || *arg == NUL) {
4198      command = dollar_command;
4199    } else {
4200      command = arg;
4201      arg = skip_cmd_arg(command, true);
4202      if (*arg != NUL) {
4203        *arg++ = NUL;                   // terminate command with NUL
4204      }
4205    }
4206
4207    arg = skipwhite(arg);       // skip over spaces
4208    *argp = arg;
4209  }
4210  return command;
4211}
4212
4213/// Find end of "+command" argument.  Skip over "\ " and "\\".
4214///
4215/// @param rembs  true to halve the number of backslashes
4216char *skip_cmd_arg(char *p, bool rembs)
4217{
4218  while (*p && !ascii_isspace(*p)) {
4219    if (*p == '\\' && p[1] != NUL) {
4220      if (rembs) {
4221        STRMOVE(p, p + 1);
4222      } else {
4223        p++;
4224      }
4225    }
4226    MB_PTR_ADV(p);
4227  }
4228  return p;
4229}
4230
4231int get_bad_opt(const char *p, exarg_T *eap)
4232  FUNC_ATTR_NONNULL_ALL
4233{
4234  if (STRICMP(p, "keep") == 0) {
4235    eap->bad_char = BAD_KEEP;
4236  } else if (STRICMP(p, "drop") == 0) {
4237    eap->bad_char = BAD_DROP;
4238  } else if (MB_BYTE2LEN((uint8_t)(*p)) == 1 && p[1] == NUL) {
4239    eap->bad_char = (uint8_t)(*p);
4240  } else {
4241    return FAIL;
4242  }
4243  return OK;
4244}
4245
4246/// Function given to ExpandGeneric() to obtain the list of bad= names.
4247static char *get_bad_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
4248{
4249  // Note: Keep this in sync with get_bad_opt().
4250  static char *(p_bad_values[]) = {
4251    "?",
4252    "keep",
4253    "drop",
4254  };
4255
4256  if (idx < (int)ARRAY_SIZE(p_bad_values)) {
4257    return p_bad_values[idx];
4258  }
4259  return NULL;
4260}
4261
4262/// Get "++opt=arg" argument.
4263///
4264/// @return  FAIL or OK.
4265int getargopt(exarg_T *eap)
4266{
4267  char *arg = eap->arg + 2;
4268  int *pp = NULL;
4269  int bad_char_idx;
4270
4271  // Note: Keep this in sync with get_argopt_name.
4272
4273  // ":edit ++[no]bin[ary] file"
4274  if (strncmp(arg, "bin", 3) == 0 || strncmp(arg, "nobin", 5) == 0) {
4275    if (*arg == 'n') {
4276      arg += 2;
4277      eap->force_bin = FORCE_NOBIN;
4278    } else {
4279      eap->force_bin = FORCE_BIN;
4280    }
4281    if (!checkforcmd(&arg, "binary", 3)) {
4282      return FAIL;
4283    }
4284    eap->arg = skipwhite(arg);
4285    return OK;
4286  }
4287
4288  // ":read ++edit file"
4289  if (strncmp(arg, "edit", 4) == 0 && !ASCII_ISALPHA(arg[4])) {
4290    eap->read_edit = true;
4291    eap->arg = skipwhite(arg + 4);
4292    return OK;
4293  }
4294
4295  // ":write ++p foo/bar/file
4296  if (arg[0] == 'p' && !ASCII_ISALPHA(arg[1])) {
4297    eap->mkdir_p = true;
4298    eap->arg = skipwhite(arg + 1);
4299    return OK;
4300  }
4301
4302  if (strncmp(arg, "ff", 2) == 0) {
4303    arg += 2;
4304    pp = &eap->force_ff;
4305  } else if (strncmp(arg, "fileformat", 10) == 0) {
4306    arg += 10;
4307    pp = &eap->force_ff;
4308  } else if (strncmp(arg, "enc", 3) == 0) {
4309    if (strncmp(arg, "encoding", 8) == 0) {
4310      arg += 8;
4311    } else {
4312      arg += 3;
4313    }
4314    pp = &eap->force_enc;
4315  } else if (strncmp(arg, "bad", 3) == 0) {
4316    arg += 3;
4317    pp = &bad_char_idx;
4318  }
4319
4320  if (pp == NULL || *arg != '=') {
4321    return FAIL;
4322  }
4323
4324  arg++;
4325  *pp = (int)(arg - eap->cmd);
4326  arg = skip_cmd_arg(arg, false);
4327  eap->arg = skipwhite(arg);
4328  *arg = NUL;
4329
4330  if (pp == &eap->force_ff) {
4331    if (check_ff_value(eap->cmd + eap->force_ff) == FAIL) {
4332      return FAIL;
4333    }
4334    eap->force_ff = (uint8_t)eap->cmd[eap->force_ff];
4335  } else if (pp == &eap->force_enc) {
4336    // Make 'fileencoding' lower case.
4337    for (char *p = eap->cmd + eap->force_enc; *p != NUL; p++) {
4338      *p = (char)TOLOWER_ASC(*p);
4339    }
4340  } else {
4341    // Check ++bad= argument.  Must be a single-byte character, "keep" or
4342    // "drop".
4343    if (get_bad_opt(eap->cmd + bad_char_idx, eap) == FAIL) {
4344      return FAIL;
4345    }
4346  }
4347
4348  return OK;
4349}
4350
4351/// Function given to ExpandGeneric() to obtain the list of ++opt names.
4352static char *get_argopt_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
4353{
4354  // Note: Keep this in sync with getargopt().
4355  static char *(p_opt_values[]) = {
4356    "fileformat=",
4357    "encoding=",
4358    "binary",
4359    "nobinary",
4360    "bad=",
4361    "edit",
4362    "p",
4363  };
4364
4365  if (idx < (int)ARRAY_SIZE(p_opt_values)) {
4366    return p_opt_values[idx];
4367  }
4368  return NULL;
4369}
4370
4371/// Command-line expansion for ++opt=name.
4372int expand_argopt(char *pat, expand_T *xp, regmatch_T *rmp, char ***matches, int *numMatches)
4373{
4374  if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern - 1) == '=') {
4375    CompleteListItemGetter cb = NULL;
4376
4377    char *name_end = xp->xp_pattern - 1;
4378    if (name_end - xp->xp_line >= 2
4379        && strncmp(name_end - 2, "ff", 2) == 0) {
4380      cb = get_fileformat_name;
4381    } else if (name_end - xp->xp_line >= 10
4382               && strncmp(name_end - 10, "fileformat", 10) == 0) {
4383      cb = get_fileformat_name;
4384    } else if (name_end - xp->xp_line >= 3
4385               && strncmp(name_end - 3, "enc", 3) == 0) {
4386      cb = get_encoding_name;
4387    } else if (name_end - xp->xp_line >= 8
4388               && strncmp(name_end - 8, "encoding", 8) == 0) {
4389      cb = get_encoding_name;
4390    } else if (name_end - xp->xp_line >= 3
4391               && strncmp(name_end - 3, "bad", 3) == 0) {
4392      cb = get_bad_name;
4393    }
4394
4395    if (cb != NULL) {
4396      ExpandGeneric(pat, xp, rmp, matches, numMatches, cb, false);
4397      return OK;
4398    }
4399    return FAIL;
4400  }
4401
4402  // Special handling of "ff" which acts as a short form of
4403  // "fileformat", as "ff" is not a substring of it.
4404  if (xp->xp_pattern_len == 2
4405      && strncmp(xp->xp_pattern, "ff", xp->xp_pattern_len) == 0) {
4406    *matches = xmalloc(sizeof(char *));
4407    *numMatches = 1;
4408    (*matches)[0] = xstrdup("fileformat=");
4409    return OK;
4410  }
4411
4412  ExpandGeneric(pat, xp, rmp, matches, numMatches, get_argopt_name, false);
4413  return OK;
4414}
4415
4416/// Handle the argument for a tabpage related ex command.
4417/// When an error is encountered then eap->errmsg is set.
4418///
4419/// @return  a tabpage number.
4420static int get_tabpage_arg(exarg_T *eap)
4421{
4422  int tab_number = 0;
4423  int unaccept_arg0 = (eap->cmdidx == CMD_tabmove) ? 0 : 1;
4424
4425  if (eap->arg && *eap->arg != NUL) {
4426    char *p = eap->arg;
4427    int relative = 0;  // argument +N/-N means: go to N places to the
4428                       // right/left relative to the current position.
4429
4430    if (*p == '-') {
4431      relative = -1;
4432      p++;
4433    } else if (*p == '+') {
4434      relative = 1;
4435      p++;
4436    }
4437
4438    char *p_save = p;
4439    tab_number = (int)getdigits(&p, false, tab_number);
4440
4441    if (relative == 0) {
4442      if (strcmp(p, "$") == 0) {
4443        tab_number = LAST_TAB_NR;
4444      } else if (strcmp(p, "#") == 0) {
4445        if (valid_tabpage(lastused_tabpage)) {
4446          tab_number = tabpage_index(lastused_tabpage);
4447        } else {
4448          eap->errmsg = ex_errmsg(e_invargval, eap->arg);
4449          tab_number = 0;
4450          goto theend;
4451        }
4452      } else if (p == p_save || *p_save == '-' || *p != NUL
4453                 || tab_number > LAST_TAB_NR) {
4454        // No numbers as argument.
4455        eap->errmsg = ex_errmsg(e_invarg2, eap->arg);
4456        goto theend;
4457      }
4458    } else {
4459      if (*p_save == NUL) {
4460        tab_number = 1;
4461      } else if (p == p_save || *p_save == '-' || *p != NUL || tab_number == 0) {
4462        // No numbers as argument.
4463        eap->errmsg = ex_errmsg(e_invarg2, eap->arg);
4464        goto theend;
4465      }
4466      tab_number = tab_number * relative + tabpage_index(curtab);
4467      if (!unaccept_arg0 && relative == -1) {
4468        tab_number--;
4469      }
4470    }
4471    if (tab_number < unaccept_arg0 || tab_number > LAST_TAB_NR) {
4472      eap->errmsg = ex_errmsg(e_invarg2, eap->arg);
4473    }
4474  } else if (eap->addr_count > 0) {
4475    if (unaccept_arg0 && eap->line2 == 0) {
4476      eap->errmsg = _(e_invrange);
4477      tab_number = 0;
4478    } else {
4479      tab_number = (int)eap->line2;
4480      if (!unaccept_arg0) {
4481        char *cmdp = eap->cmd;
4482        while (--cmdp > *eap->cmdlinep
4483               && (ascii_iswhite(*cmdp) || ascii_isdigit(*cmdp))) {}
4484        if (*cmdp == '-') {
4485          tab_number--;
4486          if (tab_number < unaccept_arg0) {
4487            eap->errmsg = _(e_invrange);
4488          }
4489        }
4490      }
4491    }
4492  } else {
4493    switch (eap->cmdidx) {
4494    case CMD_tabnext:
4495      tab_number = tabpage_index(curtab) + 1;
4496      if (tab_number > LAST_TAB_NR) {
4497        tab_number = 1;
4498      }
4499      break;
4500    case CMD_tabmove:
4501      tab_number = LAST_TAB_NR;
4502      break;
4503    default:
4504      tab_number = tabpage_index(curtab);
4505    }
4506  }
4507
4508theend:
4509  return tab_number;
4510}
4511
4512static void ex_autocmd(exarg_T *eap)
4513{
4514  // Disallow autocommands in secure mode.
4515  if (secure) {
4516    secure = 2;
4517    eap->errmsg = _(e_curdir);
4518  } else if (eap->cmdidx == CMD_autocmd) {
4519    do_autocmd(eap, eap->arg, eap->forceit);
4520  } else {
4521    do_augroup(eap->arg, eap->forceit);
4522  }
4523}
4524
4525/// ":doautocmd": Apply the automatic commands to the current buffer.
4526static void ex_doautocmd(exarg_T *eap)
4527{
4528  char *arg = eap->arg;
4529  int call_do_modelines = check_nomodeline(&arg);
4530  bool did_aucmd;
4531
4532  do_doautocmd(arg, false, &did_aucmd);
4533  // Only when there is no <nomodeline>.
4534  if (call_do_modelines && did_aucmd) {
4535    do_modelines(0);
4536  }
4537}
4538
4539/// :[N]bunload[!] [N] [bufname] unload buffer
4540/// :[N]bdelete[!] [N] [bufname] delete buffer from buffer list
4541/// :[N]bwipeout[!] [N] [bufname] delete buffer really
4542static void ex_bunload(exarg_T *eap)
4543{
4544  eap->errmsg = do_bufdel(eap->cmdidx == CMD_bdelete
4545                          ? DOBUF_DEL
4546                          : eap->cmdidx == CMD_bwipeout
4547                          ? DOBUF_WIPE
4548                          : DOBUF_UNLOAD,
4549                          eap->arg, eap->addr_count, (int)eap->line1, (int)eap->line2,
4550                          eap->forceit);
4551}
4552
4553/// :[N]buffer [N]       to buffer N
4554/// :[N]sbuffer [N]      to buffer N
4555static void ex_buffer(exarg_T *eap)
4556{
4557  do_exbuffer(eap);
4558}
4559
4560/// ":buffer" command and alike.
4561static void do_exbuffer(exarg_T *eap)
4562{
4563  if (*eap->arg) {
4564    eap->errmsg = ex_errmsg(e_trailing_arg, eap->arg);
4565  } else {
4566    if (eap->addr_count == 0) {  // default is current buffer
4567      goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0);
4568    } else {
4569      goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2);
4570    }
4571    if (eap->do_ecmd_cmd != NULL) {
4572      do_cmdline_cmd(eap->do_ecmd_cmd);
4573    }
4574  }
4575}
4576
4577/// :[N]bmodified [N]    to next mod. buffer
4578/// :[N]sbmodified [N]   to next mod. buffer
4579static void ex_bmodified(exarg_T *eap)
4580{
4581  goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2);
4582  if (eap->do_ecmd_cmd != NULL) {
4583    do_cmdline_cmd(eap->do_ecmd_cmd);
4584  }
4585}
4586
4587/// :[N]bnext [N]        to next buffer
4588/// :[N]sbnext [N]       split and to next buffer
4589static void ex_bnext(exarg_T *eap)
4590{
4591  goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2);
4592  if (eap->do_ecmd_cmd != NULL) {
4593    do_cmdline_cmd(eap->do_ecmd_cmd);
4594  }
4595}
4596
4597/// :[N]bNext [N]        to previous buffer
4598/// :[N]bprevious [N]    to previous buffer
4599/// :[N]sbNext [N]       split and to previous buffer
4600/// :[N]sbprevious [N]   split and to previous buffer
4601static void ex_bprevious(exarg_T *eap)
4602{
4603  goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2);
4604  if (eap->do_ecmd_cmd != NULL) {
4605    do_cmdline_cmd(eap->do_ecmd_cmd);
4606  }
4607}
4608
4609/// :brewind             to first buffer
4610/// :bfirst              to first buffer
4611/// :sbrewind            split and to first buffer
4612/// :sbfirst             split and to first buffer
4613static void ex_brewind(exarg_T *eap)
4614{
4615  goto_buffer(eap, DOBUF_FIRST, FORWARD, 0);
4616  if (eap->do_ecmd_cmd != NULL) {
4617    do_cmdline_cmd(eap->do_ecmd_cmd);
4618  }
4619}
4620
4621/// :blast               to last buffer
4622/// :sblast              split and to last buffer
4623static void ex_blast(exarg_T *eap)
4624{
4625  goto_buffer(eap, DOBUF_LAST, BACKWARD, 0);
4626  if (eap->do_ecmd_cmd != NULL) {
4627    do_cmdline_cmd(eap->do_ecmd_cmd);
4628  }
4629}
4630
4631int ends_excmd(int c) FUNC_ATTR_CONST
4632{
4633  return c == NUL || c == '|' || c == '"' || c == '\n';
4634}
4635
4636/// @return  the next command, after the first '|' or '\n' or,
4637///          NULL if not found.
4638char *find_nextcmd(const char *p)
4639{
4640  while (*p != '|' && *p != '\n') {
4641    if (*p == NUL) {
4642      return NULL;
4643    }
4644    p++;
4645  }
4646  return (char *)p + 1;
4647}
4648
4649/// Check if *p is a separator between Ex commands, skipping over white space.
4650///
4651/// @return  NULL if it isn't, the following character if it is.
4652char *check_nextcmd(char *p)
4653{
4654  char *s = skipwhite(p);
4655
4656  if (*s == '|' || *s == '\n') {
4657    return s + 1;
4658  }
4659  return NULL;
4660}
4661
4662/// - if there are more files to edit
4663/// - and this is the last window
4664/// - and forceit not used
4665/// - and not repeated twice on a row
4666///
4667/// @param   message  when false check only, no messages
4668///
4669/// @return  FAIL and give error message if 'message' true, return OK otherwise
4670static int check_more(bool message, bool forceit)
4671{
4672  int n = ARGCOUNT - curwin->w_arg_idx - 1;
4673
4674  if (!forceit && only_one_window()
4675      && ARGCOUNT > 1 && !arg_had_last && n > 0 && quitmore == 0) {
4676    if (message) {
4677      if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && curbuf->b_fname != NULL) {
4678        char buff[DIALOG_MSG_SIZE];
4679
4680        vim_snprintf(buff, DIALOG_MSG_SIZE,
4681                     NGETTEXT("%d more file to edit.  Quit anyway?",
4682                              "%d more files to edit.  Quit anyway?", n), n);
4683        if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) {
4684          return OK;
4685        }
4686        return FAIL;
4687      }
4688      semsg(NGETTEXT("E173: %d more file to edit",
4689                     "E173: %d more files to edit", n), n);
4690      quitmore = 2;                 // next try to quit is allowed
4691    }
4692    return FAIL;
4693  }
4694  return OK;
4695}
4696
4697/// Function given to ExpandGeneric() to obtain the list of command names.
4698char *get_command_name(expand_T *xp, int idx)
4699{
4700  if (idx >= CMD_SIZE) {
4701    return expand_user_command_name(idx);
4702  }
4703  return cmdnames[idx].cmd_name;
4704}
4705
4706static void ex_colorscheme(exarg_T *eap)
4707{
4708  if (*eap->arg == NUL) {
4709    char *expr = xstrdup("g:colors_name");
4710
4711    emsg_off++;
4712    char *p = eval_to_string(expr, false, false);
4713    emsg_off--;
4714    xfree(expr);
4715
4716    msg_ext_set_kind("list_cmd");
4717    if (p != NULL) {
4718      msg(p, 0);
4719      xfree(p);
4720    } else {
4721      msg("default", 0);
4722    }
4723  } else if (load_colors(eap->arg) == FAIL) {
4724    semsg(_("E185: Cannot find color scheme '%s'"), eap->arg);
4725  }
4726}
4727
4728static void ex_highlight(exarg_T *eap)
4729{
4730  if (*eap->arg == NUL && eap->cmd[2] == '!') {
4731    msg(_("Greetings, Vim user!"), 0);
4732  }
4733  do_highlight(eap->arg, eap->forceit, false);
4734}
4735
4736/// Call this function if we thought we were going to exit, but we won't
4737/// (because of an error).  May need to restore the terminal mode.
4738void not_exiting(bool save_exiting)
4739{
4740  exiting = save_exiting;
4741  set_vim_var_string(VV_EXITREASON, NULL, -1);
4742}
4743
4744bool before_quit_autocmds(win_T *wp, bool quit_all, bool forceit)
4745{
4746  // Set v:exitreason if not already set (e.g. by :restart).
4747  if (*get_vim_var_str(VV_EXITREASON) == NUL) {
4748    set_vim_var_string(VV_EXITREASON, S_LEN("quit"));
4749  }
4750  apply_autocmds_win(EVENT_QUITPRE, NULL, NULL, false, wp->w_buffer, wp);
4751
4752  // Bail out when autocommands closed the window.
4753  // Refuse to quit when the buffer in the last window is being closed (can
4754  // only happen in autocommands).
4755  if (!win_valid(wp)
4756      || curbuf_locked()
4757      || (wp->w_buffer->b_nwindows == 1 && wp->w_buffer->b_locked > 0)) {
4758    set_vim_var_string(VV_EXITREASON, NULL, -1);
4759    return true;
4760  }
4761
4762  if (quit_all
4763      || (check_more(false, forceit) == OK && only_one_window())) {
4764    apply_autocmds(EVENT_EXITPRE, NULL, NULL, false, curbuf);
4765    // Refuse to quit when locked or when the window was closed or the
4766    // buffer in the last window is being closed (can only happen in
4767    // autocommands).
4768    if (!win_valid(wp)
4769        || curbuf_locked()
4770        || (curbuf->b_nwindows == 1 && curbuf->b_locked > 0)) {
4771      set_vim_var_string(VV_EXITREASON, NULL, -1);
4772      return true;
4773    }
4774  }
4775
4776  return false;
4777}
4778
4779/// ":quit": quit current window, quit Vim if the last window is closed.
4780/// ":{nr}quit": quit window {nr}
4781static void ex_quit(exarg_T *eap)
4782{
4783  // Don't quit while editing the command line.
4784  if (text_locked()) {
4785    text_locked_msg();
4786    return;
4787  }
4788
4789  win_T *wp;
4790
4791  if (eap->addr_count > 0) {
4792    linenr_T wnr = eap->line2;
4793
4794    for (wp = firstwin; wp->w_next != NULL; wp = wp->w_next) {
4795      if (--wnr <= 0) {
4796        break;
4797      }
4798    }
4799  } else {
4800    wp = curwin;
4801  }
4802
4803  // Refuse to quit when locked.
4804  if (curbuf_locked()) {
4805    return;
4806  }
4807
4808  // Trigger QuitPre and maybe ExitPre
4809  if (before_quit_autocmds(wp, false, eap->forceit)) {
4810    return;
4811  }
4812
4813  bool save_exiting = exiting;
4814  // If there is only one relevant window we will exit.
4815  if (check_more(false, eap->forceit) == OK && only_one_window()) {
4816    exiting = true;
4817  }
4818  if ((!buf_hide(wp->w_buffer)
4819       && check_changed(wp->w_buffer, (p_awa ? CCGD_AW : 0)
4820                        | (eap->forceit ? CCGD_FORCEIT : 0)
4821                        | CCGD_EXCMD))
4822      || check_more(true, eap->forceit) == FAIL
4823      || (only_one_window() && check_changed_any(eap->forceit, true))) {
4824    not_exiting(save_exiting);
4825  } else {
4826    // quit last window
4827    // Note: only_one_window() returns true, even so a help window is
4828    // still open. In that case only quit, if no address has been
4829    // specified. Example:
4830    // :h|wincmd w|1q     - don't quit
4831    // :h|wincmd w|q      - quit
4832    if (only_one_window() && (ONE_WINDOW || eap->addr_count == 0)) {
4833      getout(0);
4834    }
4835    not_exiting(save_exiting);
4836    // close window; may free buffer
4837    win_close(wp, !buf_hide(wp->w_buffer) || eap->forceit, eap->forceit);
4838  }
4839}
4840
4841/// ":cquit".
4842static void ex_cquit(exarg_T *eap)
4843  FUNC_ATTR_NORETURN
4844{
4845  // this does not always pass on the exit code to the Manx compiler. why?
4846  int status = eap->addr_count > 0 ? (int)eap->line2 : EXIT_FAILURE;
4847  ui_call_error_exit(status);
4848  getout(status);
4849}
4850
4851/// Do preparations for "qall" and "wqall".
4852/// Returns FAIL when quitting should be aborted.
4853int before_quit_all(exarg_T *eap)
4854{
4855  // Don't quit while editing the command line.
4856  if (text_locked()) {
4857    text_locked_msg();
4858    return FAIL;
4859  }
4860
4861  if (before_quit_autocmds(curwin, true, eap->forceit)) {
4862    return FAIL;
4863  }
4864
4865  return OK;
4866}
4867
4868/// ":qall": try to quit all windows
4869static void ex_quitall(exarg_T *eap)
4870{
4871  if (before_quit_all(eap) == FAIL) {
4872    return;
4873  }
4874  bool save_exiting = exiting;
4875  exiting = true;
4876  if (eap->forceit || !check_changed_any(false, false)) {
4877    getout(0);
4878  }
4879  not_exiting(save_exiting);
4880}
4881
4882/// ":exmode": Enter interactive Ex mode.
4883static void ex_exmode(exarg_T *eap)
4884{
4885  if (silent_mode) {
4886    return;
4887  }
4888  if (ex_normal_busy > 0 || global_busy) {
4889    // Ex mode cannot run inside ":normal" or ":global"; discard the rest of the command.
4890    flush_buffers(FLUSH_TYPEAHEAD);
4891    return;
4892  }
4893  typval_T args[] = { { .v_type = VAR_UNKNOWN } };
4894  nlua_call_typval("vim._core.exmode", "open", args, NULL);
4895}
4896
4897/// ":restart": restart the Nvim server (using ":qall!").
4898/// ":restart +cmd": restart the Nvim server using ":cmd".
4899/// ":restart +cmd <command>": restart the Nvim server using ":cmd" and runs <command> in the new server.
4900static void ex_restart(exarg_T *eap)
4901{
4902  if (!eap->forceit) {
4903    dict_T *extra_d = tv_dict_alloc();  // Pass +cmd in the `extra` param of nlua_call_excmd.
4904    tv_dict_add_str(extra_d, S_LEN("quit_cmd"), eap->do_ecmd_cmd ? eap->do_ecmd_cmd : "");
4905    typval_T extra_tv = { .v_type = VAR_DICT, .vval.v_dict = extra_d };
4906    nlua_call_excmd("vim._core.server", "ex_session_restart", eap, &cmdmod, &extra_tv);
4907    tv_clear(&extra_tv);
4908    return;
4909  }
4910
4911  const char *startreason = "restart!";
4912  char *quit_cmd = (eap->do_ecmd_cmd) ? eap->do_ecmd_cmd : "qall";
4913  char *after_cmd = eap->arg;
4914
4915  // XXX: "+:::" is how ex_session_restart() signals that it (recursively) called :restart.
4916  if (strequal(quit_cmd, ":::")) {
4917    startreason = "restart";
4918    if (eap->argc > 1) {
4919      eap->args[1][eap->arglens[1]] = NUL;
4920      quit_cmd = eap->args[1];
4921      after_cmd = eap->argc > 2 ? eap->args[2] : "";
4922    } else {
4923      semsg(e_restart_failed_cmd_no_quit, quit_cmd);
4924      return;
4925    }
4926  }
4927
4928  Error err = ERROR_INIT;
4929  const bool no_ui = !ui_active();
4930  const char *exepath = get_vim_var_str(VV_PROGPATH);
4931  const list_T *l = get_vim_var_list(VV_ARGV);
4932  int argc = tv_list_len(l);
4933
4934  char **argv = xcalloc((size_t)argc + 3, sizeof(char *));
4935  size_t i = 0;
4936  const char *listen_arg = NULL;  // --listen arg given by user, if any.
4937
4938  // Build args to start the new Nvim, based on the current v:argv.
4939  for (const listitem_T *li = l->lv_first; li != NULL; li = li->li_next) {
4940    const char *arg = tv_get_string(TV_LIST_ITEM_TV(li));
4941    // Drop "-- [files…]". Usually isn't wanted. User can :mksession instead.
4942    if (i > 0 && strequal(arg, "--")) {
4943      break;
4944    }
4945    // Drop "-S [file]". It conflicts with :restart and usually isn't wanted for :restart!
4946    if (i > 0 && strequal(arg, "-S")) {
4947      if (li->li_next != NULL) {
4948        const char *next_arg = tv_get_string(TV_LIST_ITEM_TV(li->li_next));
4949        if (next_arg[0] != '-') {
4950          li = li->li_next;
4951        }
4952      }
4953      continue;
4954    }
4955    // Drop "-s <scriptfile>": skip the scriptfile arg too.
4956    if (i > 0 && strequal(arg, "-s")) {
4957      li = li->li_next;
4958      continue;
4959    }
4960    // The address after --listen may be in use by the current server.
4961    if (i > 0 && strequal(arg, "--listen")) {
4962      const listitem_T *next_li = li->li_next;
4963      if (next_li != NULL) {
4964        const char *addr = tv_get_string(TV_LIST_ITEM_TV(next_li));
4965        if (strstr(addr, ":") || strstr(addr, "/") || strstr(addr, "\\")) {
4966          XFREE_CLEAR(listen_arg);
4967          listen_arg = TO_SLASH_SAVE(addr);
4968#ifdef MSWIN
4969          // On Windows, don't pass --listen to new server (named pipe can't be reused immediately).
4970          // Instead pass the address via RPC; new server rebinds after startup.
4971          li = next_li;
4972          continue;
4973#endif
4974        }
4975      }
4976    }
4977    // Replace `--embed` OR `--headless` with `--embed` or `--embed --headless` once.
4978    // Drop stdin ("-") argument.
4979    if (i == 0
4980        || (!strequal(arg, "--embed") && !strequal(arg, "--headless") && !strequal(arg, "-"))) {
4981      argv[i++] = xstrdup(arg);
4982      if (i == 1) {
4983        argv[i++] = xstrdup("--embed");
4984        // Without --headless, embed waits for UI to attach.
4985        // Only add --headless when there is no UI.
4986        if (no_ui) {
4987          argv[i++] = xstrdup("--headless");
4988        }
4989      }
4990    }
4991  }
4992
4993#ifdef MSWIN
4994  // On Windows, --listen is omitted from child argv because the named pipe can't be reused immediately.
4995  // Recover the canonical address from the Lua module state (set by the previous rebind_after_restart() call),
4996  // and keep the current listener alive (new server reclaims it).
4997  if (listen_arg == NULL) {
4998    Error lua_err = ERROR_INIT;
4999    Object rv = NLUA_EXEC_STATIC("return require('vim._core.server').restart_canonical_addr",
5000                                 (Array)ARRAY_DICT_INIT, kRetObject, NULL, &lua_err);
5001    if (!ERROR_SET(&lua_err) && rv.type == kObjectTypeString && rv.data.string.size > 0) {
5002      listen_arg = xstrdup(rv.data.string.data);
5003    }
5004    api_free_object(rv);
5005    api_clear_error(&lua_err);
5006  }
5007  bool server_stopped = false;
5008#else
5009  // Stop listening on the --listen address so that the new server can listen.
5010  bool server_stopped = listen_arg ? server_stop(listen_arg, true) : false;
5011#endif
5012
5013  dict_T *env = create_environment(NULL, false, false, false, NULL);
5014  tv_dict_add_str(env, S_LEN(ENV_STARTREASON), startreason);
5015
5016  CallbackReader on_err = CALLBACK_READER_INIT;
5017#ifdef MSWIN
5018  // On Windows, don't forward stderr as it won't work after the current server exits.
5019  on_err.fwd_err = false;
5020#else
5021  // On Unix, stderr fd is inherited, so it works even after the current server exits.
5022  on_err.fwd_err = true;
5023#endif
5024  bool detach = true;
5025  varnumber_T exit_status;
5026
5027  Channel *channel = channel_job_start(argv, exepath,
5028                                       CALLBACK_READER_INIT, on_err, CALLBACK_NONE,
5029                                       false, true, true, detach, kChannelStdinPipe,
5030                                       globaldir, 0, 0, env, &exit_status);
5031  if (!channel) {
5032    emsg("cannot create a channel job");
5033    goto fail_1;
5034  }
5035
5036  // Prevent new server from self-exiting when the channel closes.
5037  ArenaMem result_mem = NULL;
5038  MAXSIZE_TEMP_ARRAY(detach_args, 1);
5039  ADD_C(detach_args, BOOLEAN_OBJ(true));
5040  rpc_send_call(channel->id, "nvim__chan_set_detach", detach_args, &result_mem, &err);
5041  if (ERROR_SET(&err)) {
5042    goto fail_2;
5043  }
5044  arena_mem_free(result_mem);
5045  result_mem = NULL;
5046
5047  if (*after_cmd != NUL) {
5048    // Execute [command] on new server on UIEnter.
5049    MAXSIZE_TEMP_DICT(autocmd_opts, 3);
5050    PUT_C(autocmd_opts, "once", BOOLEAN_OBJ(true));
5051    PUT_C(autocmd_opts, "nested", BOOLEAN_OBJ(true));
5052    PUT_C(autocmd_opts, "command", CSTR_AS_OBJ(after_cmd));
5053    MAXSIZE_TEMP_ARRAY(autocmd_args, 2);
5054    ADD_C(autocmd_args, CSTR_AS_OBJ("UIEnter"));
5055    ADD_C(autocmd_args, DICT_OBJ(autocmd_opts));
5056    rpc_send_call(channel->id, "nvim_create_autocmd", autocmd_args, &result_mem, &err);
5057    if (ERROR_SET(&err)) {
5058      goto fail_2;
5059    }
5060    arena_mem_free(result_mem);
5061    result_mem = NULL;
5062  }
5063
5064  // Get the new server's initial address. On Windows this is the temporary self-generated address.
5065  MAXSIZE_TEMP_ARRAY(servername_args, 1);
5066  ADD_C(servername_args, CSTR_AS_OBJ("servername"));
5067  Object result = rpc_send_call(channel->id, "nvim_get_vvar", servername_args, &result_mem, &err);
5068  if (ERROR_SET(&err)) {
5069    goto fail_2;
5070  }
5071  if (result.type != kObjectTypeString || result.data.string.size == 0) {
5072    emsg("restart failed: could not get listen address from new server");
5073    goto fail_2;
5074  }
5075  // New server's self-generated address.
5076  char *listen_addr = xmemdupz(result.data.string.data, result.data.string.size);
5077  arena_mem_free(result_mem);
5078  result_mem = NULL;
5079
5080#ifdef MSWIN
5081  if (listen_arg != NULL) {
5082    // Tell the new server to reclaim the canonical --listen address once the old listener exits,
5083    // then retire the bootstrap address after all UIs have reattached (or timeout).
5084    MAXSIZE_TEMP_ARRAY(lua_args, 2);
5085    ADD_C(lua_args,
5086          CSTR_AS_OBJ("return require('vim._core.server').rebind_after_restart(...)"));
5087    MAXSIZE_TEMP_ARRAY(handoff_params, 3);
5088    ADD_C(handoff_params, CSTR_AS_OBJ(listen_arg));
5089    ADD_C(handoff_params, INTEGER_OBJ((Integer)ui_active()));
5090    ADD_C(lua_args, ARRAY_OBJ(handoff_params));
5091    rpc_send_call(channel->id, "nvim_exec_lua", lua_args, &result_mem, &err);
5092    if (ERROR_SET(&err)) {
5093      goto fail_2;
5094    }
5095    arena_mem_free(result_mem);
5096    result_mem = NULL;
5097  }
5098#endif
5099
5100  // Send restart event with new listen address to all UIs.
5101  ui_call_restart(cstr_as_string(listen_addr));
5102  ui_flush();
5103  xfree(listen_addr);
5104
5105  set_vim_var_string(VV_EXITREASON, startreason, -1);
5106
5107  char *quit_cmd_copy = NULL;
5108
5109  // Prepend "confirm " to cmd if :confirm is used
5110  if (cmdmod.cmod_flags & CMOD_CONFIRM) {
5111    quit_cmd_copy = concat_str("confirm ", quit_cmd);
5112    quit_cmd = quit_cmd_copy;
5113  }
5114  // Try to quit.
5115  nvim_command(cstr_as_string(quit_cmd), &err);
5116
5117  if (ERROR_SET(&err)) {
5118    emsg(err.msg);  // Could not exit
5119    api_clear_error(&err);
5120  } else if (!exiting) {
5121    semsg(e_restart_failed_cmd_no_quit, quit_cmd);
5122  }
5123  xfree(quit_cmd_copy);
5124
5125fail_2:
5126  set_vim_var_string(VV_EXITREASON, NULL, -1);
5127  if (ERROR_SET(&err)) {
5128    emsg(err.msg);
5129    api_clear_error(&err);
5130  }
5131  arena_mem_free(result_mem);
5132  result_mem = NULL;
5133
5134#ifndef MSWIN
5135  // Before killing the new server, close its stderr to avoid polluting the current UI.
5136  MAXSIZE_TEMP_ARRAY(chanclose_expr_args, 1);
5137  ADD_C(chanclose_expr_args, CSTR_AS_OBJ("chanclose(v:stderr)"));
5138  rpc_send_call(channel->id, "nvim_eval", chanclose_expr_args, &result_mem, &err);
5139  api_clear_error(&err);
5140  arena_mem_free(result_mem);
5141#endif
5142
5143  // Kill the new Nvim server.
5144  proc_stop(&channel->stream.proc);
5145  if (proc_wait(&channel->stream.proc, -1, NULL) < 0) {
5146    emsg("killing new nvim server failed");
5147  }
5148
5149fail_1:
5150  // Restart listening on the --listen address.
5151  if (server_stopped && server_start(listen_arg) != 0) {
5152    semsg("couldn't resume listening on %s", listen_arg);
5153  }
5154  XFREE_CLEAR(listen_arg);
5155}
5156
5157/// ":close": close current window, unless it is the last one
5158static void ex_close(exarg_T *eap)
5159{
5160  if (!text_locked() && !curbuf_locked()) {
5161    win_T *win;
5162    if (eap->addr_count == 0) {
5163      win = curwin;
5164    } else {
5165      win = win_find_nr((int)eap->line2, curtab);
5166      if (win == NULL) {
5167        win = lastwin;
5168      }
5169    }
5170    ex_win_close(eap->forceit, win, NULL);
5171  }
5172}
5173
5174/// ":pclose": Close any preview window.
5175static void ex_pclose(exarg_T *eap)
5176{
5177  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
5178    if (win->w_p_pvw) {
5179      ex_win_close(eap->forceit, win, NULL);
5180      break;
5181    }
5182  }
5183
5184  win_float_close(kWinPreview);
5185}
5186
5187/// Close window "win" and take care of handling closing the last window for a
5188/// modified buffer.
5189///
5190/// @param tp  NULL or the tab page "win" is in, if different from "curtab"
5191void ex_win_close(int forceit, win_T *win, tabpage_T *tp)
5192{
5193  assert(tp == NULL || tp != curtab);
5194
5195  // Never close the autocommand window.
5196  if (is_ctx_win(win)) {
5197    emsg(_(e_autocmd_close));
5198    return;
5199  }
5200  if (!win->w_floating && window_layout_locked(CMD_close)) {
5201    return;
5202  }
5203
5204  buf_T *buf = win->w_buffer;
5205
5206  bool need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
5207  if (need_hide && !buf_hide(buf) && !forceit) {
5208    if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) {
5209      bufref_T bufref;
5210      set_bufref(&bufref, buf);
5211      dialog_changed(buf, false);
5212      if (bufref_valid(&bufref) && bufIsChanged(buf)) {
5213        return;
5214      }
5215      need_hide = false;
5216    } else {
5217      no_write_message();
5218      return;
5219    }
5220  }
5221
5222  // free buffer when not hiding it or when it's a scratch buffer
5223  if (tp == NULL) {
5224    win_close(win, !need_hide && !buf_hide(buf), forceit);
5225  } else {
5226    win_close_othertab(win, !need_hide && !buf_hide(buf), tp, forceit);
5227  }
5228}
5229
5230/// ":tabclose": close current tab page, unless it is the last one.
5231/// ":tabclose N": close tab page N.
5232static void ex_tabclose(exarg_T *eap)
5233{
5234  if (first_tabpage->tp_next == NULL) {
5235    emsg(_("E784: Cannot close last tab page"));
5236    return;
5237  }
5238
5239  if (window_layout_locked(CMD_tabclose)) {
5240    return;
5241  }
5242
5243  int tab_number = get_tabpage_arg(eap);
5244  if (eap->errmsg != NULL) {
5245    return;
5246  }
5247
5248  tabpage_T *tp = find_tabpage(tab_number);
5249  if (tp == NULL) {
5250    beep_flush();
5251    return;
5252  }
5253  if (tp != curtab) {
5254    tabpage_close_other(tp, eap->forceit);
5255    return;
5256  } else if (!text_locked() && !curbuf_locked()) {
5257    tabpage_close(eap->forceit);
5258  }
5259}
5260
5261/// ":tabonly": close all tab pages except the current one
5262static void ex_tabonly(exarg_T *eap)
5263{
5264  if (first_tabpage->tp_next == NULL) {
5265    msg(_("Already only one tab page"), 0);
5266    return;
5267  }
5268
5269  if (window_layout_locked(CMD_tabonly)) {
5270    return;
5271  }
5272
5273  int tab_number = get_tabpage_arg(eap);
5274  if (eap->errmsg != NULL) {
5275    return;
5276  }
5277
5278  goto_tabpage(tab_number);
5279  // Repeat this up to a 1000 times, because autocommands may
5280  // mess up the lists.
5281  for (int done = 0; done < 1000; done++) {
5282    FOR_ALL_TABS(tp) {
5283      if (tp->tp_topframe != topframe) {
5284        tabpage_close_other(tp, eap->forceit);
5285        // if we failed to close it quit
5286        if (valid_tabpage(tp)) {
5287          done = 1000;
5288        }
5289        // start over, "tp" is now invalid
5290        break;
5291      }
5292    }
5293    assert(first_tabpage);
5294    if (first_tabpage->tp_next == NULL) {
5295      break;
5296    }
5297  }
5298}
5299
5300/// Close the current tab page.
5301void tabpage_close(int forceit)
5302{
5303  int done = 0;
5304
5305  if (window_layout_locked(CMD_tabclose)) {
5306    return;
5307  }
5308
5309  trigger_tabclosedpre(curtab);
5310  curtab->tp_did_tabclosedpre = true;
5311  tabpage_T *const save_curtab = curtab;
5312
5313  // First close all the windows but the current one.  If that worked then
5314  // close the last window in this tab, that will close it.
5315  while (curwin->w_floating && ++done < 1000) {
5316    ex_win_close(forceit, curwin, NULL);
5317  }
5318  if (done == 1000) {
5319    return;
5320  }
5321
5322  if (!ONE_WINDOW) {
5323    close_others(true, forceit, true);
5324  }
5325  if (ONE_WINDOW) {
5326    ex_win_close(forceit, curwin, NULL);
5327  }
5328  if (curtab == save_curtab) {
5329    // When closing the tab page failed, reset tp_did_tabclosedpre so that
5330    // TabClosedPre behaves consistently on next :close vs :tabclose.
5331    curtab->tp_did_tabclosedpre = false;
5332  }
5333}
5334
5335/// Close tab page "tp", which is not the current tab page.
5336/// Note that autocommands may make "tp" invalid.
5337/// Also takes care of the tab pages line disappearing when closing the
5338/// last-but-one tab page.
5339void tabpage_close_other(tabpage_T *tp, int forceit)
5340{
5341  int done = 0;
5342  char prev_idx[NUMBUFLEN];
5343
5344  assert(tp != curtab);
5345
5346  if (window_layout_locked(CMD_SIZE)) {
5347    return;
5348  }
5349
5350  trigger_tabclosedpre(tp);
5351  tp->tp_did_tabclosedpre = true;
5352
5353  // Limit to 1000 windows, autocommands may add a window while we close
5354  // one.  OK, so I'm paranoid...
5355  while (++done < 1000) {
5356    snprintf(prev_idx, sizeof(prev_idx), "%i", tabpage_index(tp));
5357    win_T *wp = tp->tp_lastwin;
5358
5359    // Autocommands (including TabClosedPre above) may change the current tab page,
5360    // abort a `:tabonly` (etc) if we're now on the tab we're trying to close
5361    if (tp == curtab) {
5362      done = 1000;
5363      break;
5364    }
5365    ex_win_close(forceit, wp, tp);
5366
5367    // Autocommands may delete the tab page under our fingers.
5368    if (!valid_tabpage(tp)) {
5369      break;
5370    }
5371
5372    // We may fail to close a window with a modified buffer.
5373    if (tp->tp_lastwin == wp) {
5374      done = 1000;
5375      break;
5376    }
5377  }
5378  if (done >= 1000) {
5379    // When closing the tab page failed, reset tp_did_tabclosedpre so that
5380    // TabClosedPre behaves consistently on next :close vs :tabclose.
5381    tp->tp_did_tabclosedpre = false;
5382    return;
5383  }
5384}
5385
5386/// ":only".
5387static void ex_only(exarg_T *eap)
5388{
5389  if (window_layout_locked(CMD_only)) {
5390    return;
5391  }
5392
5393  if (eap->addr_count > 0) {
5394    win_T *wp;
5395    linenr_T wnr = eap->line2;
5396    for (wp = firstwin; --wnr > 0;) {
5397      if (wp->w_next == NULL) {
5398        break;
5399      }
5400      wp = wp->w_next;
5401    }
5402    if (wp != curwin) {
5403      win_goto(wp);
5404    }
5405  }
5406  close_others(true, eap->forceit, false);
5407}
5408
5409static void ex_hide(exarg_T *eap)
5410{
5411  // ":hide" or ":hide | cmd": hide current window
5412  if (eap->skip) {
5413    return;
5414  }
5415
5416  win_T *win;
5417  if (eap->addr_count == 0) {
5418    win = curwin;
5419  } else {
5420    win = win_find_nr((int)eap->line2, curtab);
5421    if (win == NULL) {
5422      win = lastwin;
5423    }
5424  }
5425
5426  if (!win->w_floating && window_layout_locked(CMD_hide)) {
5427    return;
5428  }
5429
5430  win_close(win, false, eap->forceit);  // don't free buffer
5431}
5432
5433/// ":stop" and ":suspend": Suspend Vim.
5434static void ex_stop(exarg_T *eap)
5435{
5436  if (!eap->forceit) {
5437    autowrite_all();
5438  }
5439  may_trigger_vim_suspend_resume(true);
5440  ui_call_suspend();
5441  ui_flush();
5442}
5443
5444/// ":exit", ":xit" and ":wq": Write file and quit the current window.
5445static void ex_exit(exarg_T *eap)
5446{
5447  // Don't quit while editing the command line.
5448  if (text_locked()) {
5449    text_locked_msg();
5450    return;
5451  }
5452
5453  bool save_exiting = exiting;
5454  // we plan to exit if there is only one relevant window
5455  if (check_more(false, eap->forceit) == OK && only_one_window()) {
5456    exiting = true;
5457  }
5458  // Write the buffer for ":wq" or when it was changed.
5459  // Trigger QuitPre and ExitPre.
5460  // Check if we can exit now, after autocommands have changed things.
5461  if (((eap->cmdidx == CMD_wq || curbufIsChanged()) && do_write(eap) == FAIL)
5462      || before_quit_autocmds(curwin, false, eap->forceit)
5463      || check_more(true, eap->forceit) == FAIL
5464      || (only_one_window() && check_changed_any(eap->forceit, false))) {
5465    not_exiting(save_exiting);
5466  } else {
5467    if (only_one_window()) {
5468      // quit last window, exit Vim
5469      getout(0);
5470    }
5471    not_exiting(save_exiting);
5472    // Quit current window, may free the buffer.
5473    win_close(curwin, !buf_hide(curwin->w_buffer), eap->forceit);
5474  }
5475}
5476
5477/// ":print", ":list", ":number".
5478static void ex_print(exarg_T *eap)
5479{
5480  if (curbuf->b_ml.ml_flags & ML_EMPTY) {
5481    emsg(_(e_empty_buffer));
5482  } else {
5483    for (linenr_T line = eap->line1; line <= eap->line2 && !got_int; os_breakcheck()) {
5484      print_line(line,
5485                 (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound
5486                  || (eap->flags & EXFLAG_NR)),
5487                 eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST),
5488                 line == eap->line1);
5489      line++;
5490    }
5491    setpcmark();
5492    // put cursor at last line
5493    curwin->w_cursor.lnum = eap->line2;
5494    beginline(BL_SOL | BL_FIX);
5495  }
5496}
5497
5498static void ex_goto(exarg_T *eap)
5499{
5500  goto_byte(eap->line2);
5501}
5502
5503/// ":preserve".
5504static void ex_preserve(exarg_T *eap)
5505{
5506  ml_preserve(curbuf, true, true);
5507}
5508
5509/// ":recover".
5510static void ex_recover(exarg_T *eap)
5511{
5512  // Set recoverymode right away to avoid the ATTENTION prompt.
5513  recoverymode = true;
5514  if (!check_changed(curbuf, (p_awa ? CCGD_AW : 0)
5515                     | CCGD_MULTWIN
5516                     | (eap->forceit ? CCGD_FORCEIT : 0)
5517                     | CCGD_EXCMD)
5518
5519      && (*eap->arg == NUL
5520          || setfname(curbuf, eap->arg, NULL, true) == OK)) {
5521    ml_recover(true);
5522  }
5523  recoverymode = false;
5524}
5525
5526/// Command modifier used in a wrong way.
5527static void ex_wrongmodifier(exarg_T *eap)
5528{
5529  eap->errmsg = _(e_invcmd);
5530}
5531
5532/// Call 'findfunc' to obtain a list of file names.
5533static list_T *call_findfunc(char *pat, BoolVarValue cmdcomplete)
5534{
5535  const sctx_T saved_sctx = current_sctx;
5536
5537  typval_T args[3];
5538  args[0].v_type = VAR_STRING;
5539  args[0].vval.v_string = pat;
5540  args[1].v_type = VAR_BOOL;
5541  args[1].vval.v_bool = cmdcomplete;
5542  args[2].v_type = VAR_UNKNOWN;
5543
5544  // Lock the text to prevent weird things from happening.  Also disallow
5545  // switching to another window, it should not be needed and may end up in
5546  // Insert mode in another buffer.
5547  textlock++;
5548
5549  sctx_T *ctx = get_option_sctx(kOptFindfunc);
5550  if (ctx != NULL) {
5551    current_sctx = *ctx;
5552  }
5553
5554  Callback *cb = get_findfunc();
5555  typval_T rettv;
5556  int retval = callback_call(cb, 2, args, &rettv);
5557
5558  current_sctx = saved_sctx;
5559
5560  textlock--;
5561
5562  list_T *retlist = NULL;
5563
5564  if (retval == OK) {
5565    if (rettv.v_type == VAR_LIST) {
5566      retlist = tv_list_copy(NULL, rettv.vval.v_list, false, get_copyID());
5567    } else {
5568      emsg(_(e_invalid_return_type_from_findfunc));
5569    }
5570
5571    tv_clear(&rettv);
5572  }
5573
5574  return retlist;
5575}
5576
5577/// Find file names matching "pat" using 'findfunc' and return it in "files".
5578/// Used for expanding the :find, :sfind and :tabfind command argument.
5579/// Returns OK on success and FAIL otherwise.
5580int expand_findfunc(expand_T *xp, char *pat, char ***files, int *numMatches)
5581{
5582  *numMatches = 0;
5583  *files = NULL;
5584
5585  list_T *l = call_findfunc(pat, kBoolVarTrue);
5586  if (l == NULL) {
5587    return FAIL;
5588  }
5589
5590  int len = tv_list_len(l);
5591  if (len == 0) {  // empty List
5592    tv_list_free(l);
5593    return FAIL;
5594  }
5595
5596  expand_process_user_list(l, files, numMatches, xp);
5597  tv_list_free(l);
5598
5599  return OK;
5600}
5601
5602/// Use 'findfunc' to find file 'findarg'.  The 'count' argument is used to find
5603/// the n'th matching file.
5604static char *findfunc_find_file(char *findarg, size_t findarg_len, int count)
5605{
5606  char *ret_fname = NULL;
5607
5608  const char cc = findarg[findarg_len];
5609  findarg[findarg_len] = NUL;
5610
5611  list_T *fname_list = call_findfunc(findarg, kBoolVarFalse);
5612  int fname_count = tv_list_len(fname_list);
5613
5614  if (fname_count == 0) {
5615    semsg(_(e_cant_find_file_str_in_path), findarg);
5616  } else {
5617    if (count > fname_count) {
5618      semsg(_(e_no_more_file_str_found_in_path), findarg);
5619    } else {
5620      const listitem_T *li = tv_list_find(fname_list, count - 1);
5621      if (li != NULL) {
5622        const typval_T *tv = TV_LIST_ITEM_TV(li);
5623        if (tv->v_type == VAR_STRING && tv->vval.v_string != NULL) {
5624          ret_fname = xstrdup(tv->vval.v_string);
5625        } else if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) {
5626          ret_fname = tv_dict_get_string(tv->vval.v_dict, "word", true);
5627        }
5628      }
5629    }
5630  }
5631
5632  if (fname_list != NULL) {
5633    tv_list_free(fname_list);
5634  }
5635
5636  findarg[findarg_len] = cc;
5637
5638  TO_SLASH(ret_fname);
5639  return ret_fname;
5640}
5641
5642void free_findfunc_option(void)
5643{
5644  callback_free(&p_ffu);
5645}
5646
5647/// Mark the global 'findfunc' callback with "copyID" so that it is not
5648/// garbage collected.
5649bool set_ref_in_findfunc(int copyID)
5650{
5651  return set_ref_in_callback(&p_ffu, copyID, NULL, NULL);
5652}
5653
5654static void set_browse_edit_arg(exarg_T *eap)
5655{
5656  if ((cmdmod.cmod_flags & CMOD_BROWSE) && *eap->arg == NUL
5657      && (eap->cmdidx == CMD_edit
5658          || eap->cmdidx == CMD_split
5659          || eap->cmdidx == CMD_vsplit
5660          || eap->cmdidx == CMD_tabedit
5661          || eap->cmdidx == CMD_tabnew)) {
5662    eap->arg = ".";
5663  }
5664}
5665
5666/// :sview [+command] file       split window with new file, read-only
5667/// :split [[+command] file]     split window with current or new file
5668/// :vsplit [[+command] file]    split window vertically with current or new file
5669/// :new [[+command] file]       split window with no or new file
5670/// :vnew [[+command] file]      split vertically window with no or new file
5671/// :sfind [+command] file       split window with file in 'path'
5672///
5673/// :tabedit                     open new Tab page with empty window
5674/// :tabedit [+command] file     open new Tab page and edit "file"
5675/// :tabnew [[+command] file]    just like :tabedit
5676/// :tabfind [+command] file     open new Tab page and find "file"
5677void ex_splitview(exarg_T *eap)
5678{
5679  set_browse_edit_arg(eap);
5680  win_T *old_curwin = curwin;
5681  char *fname = NULL;
5682  const bool use_tab = eap->cmdidx == CMD_tabedit
5683                       || eap->cmdidx == CMD_tabfind
5684                       || eap->cmdidx == CMD_tabnew;
5685
5686  // A ":split" in the quickfix window works like ":new".  Don't want two
5687  // quickfix windows.  But it's OK when doing ":tab split".
5688  if (bt_quickfix(curbuf) && cmdmod.cmod_tab == 0) {
5689    if (eap->cmdidx == CMD_split) {
5690      eap->cmdidx = CMD_new;
5691    }
5692    if (eap->cmdidx == CMD_vsplit) {
5693      eap->cmdidx = CMD_vnew;
5694    }
5695  }
5696
5697  if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind) {
5698    if (get_findfunc()->type != kCallbackNone) {
5699      fname = findfunc_find_file(eap->arg, strlen(eap->arg),
5700                                 eap->addr_count > 0 ? eap->line2 : 1);
5701    } else {
5702      char *file_to_find = NULL;
5703      char *search_ctx = NULL;
5704      fname = find_file_in_path(eap->arg, strlen(eap->arg), FNAME_MESS, true,
5705                                curbuf->b_ffname, &file_to_find, &search_ctx);
5706      xfree(file_to_find);
5707      vim_findfile_cleanup(search_ctx);
5708    }
5709    if (fname == NULL) {
5710      goto theend;
5711    }
5712    eap->arg = fname;
5713  }
5714
5715  // Either open new tab page or split the window.
5716  if (use_tab) {
5717    if (win_new_tabpage(cmdmod.cmod_tab != 0 ? cmdmod.cmod_tab : eap->addr_count == 0
5718                        ? 0 : (int)eap->line2 + 1, eap->arg, true, NULL)) {
5719      do_exedit(eap, old_curwin);
5720      apply_autocmds(EVENT_TABNEWENTERED, NULL, NULL, false, curbuf);
5721
5722      // set the alternate buffer for the window we came from
5723      if (curwin != old_curwin
5724          && win_valid(old_curwin)
5725          && old_curwin->w_buffer != curbuf
5726          && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
5727        old_curwin->w_alt_fnum = curbuf->b_fnum;
5728      }
5729    }
5730  } else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0,
5731                       *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL) {
5732    // Reset 'scrollbind' when editing another file, but keep it when
5733    // doing ":split" without arguments.
5734    if (*eap->arg != NUL) {
5735      RESET_BINDING(curwin);
5736    } else {
5737      do_check_scrollbind(false);
5738    }
5739    do_exedit(eap, old_curwin);
5740  }
5741
5742theend:
5743  xfree(fname);
5744}
5745
5746/// Open a new tab page.
5747void tabpage_new(void)
5748{
5749  exarg_T ea = {
5750    .cmdidx = CMD_tabnew,
5751    .cmd = "tabn",
5752    .arg = "",
5753  };
5754  ex_splitview(&ea);
5755}
5756
5757/// :tabnext command
5758static void ex_tabnext(exarg_T *eap)
5759{
5760  int tab_number;
5761
5762  switch (eap->cmdidx) {
5763  case CMD_tabfirst:
5764  case CMD_tabrewind:
5765    goto_tabpage(1);
5766    break;
5767  case CMD_tablast:
5768    goto_tabpage(9999);
5769    break;
5770  case CMD_tabprevious:
5771  case CMD_tabNext:
5772    if (eap->arg && *eap->arg != NUL) {
5773      char *p = eap->arg;
5774      char *p_save = p;
5775      tab_number = (int)getdigits(&p, false, 0);
5776      if (p == p_save || *p_save == '-' || *p_save == '+' || *p != NUL
5777          || tab_number == 0) {
5778        // No numbers as argument.
5779        eap->errmsg = ex_errmsg(e_invarg2, eap->arg);
5780        return;
5781      }
5782    } else {
5783      if (eap->addr_count == 0) {
5784        tab_number = 1;
5785      } else {
5786        tab_number = (int)eap->line2;
5787        if (tab_number < 1) {
5788          eap->errmsg = _(e_invrange);
5789          return;
5790        }
5791      }
5792    }
5793    goto_tabpage(-tab_number);
5794    break;
5795  default:       // CMD_tabnext
5796    tab_number = get_tabpage_arg(eap);
5797    if (eap->errmsg == NULL) {
5798      goto_tabpage(tab_number);
5799    }
5800    break;
5801  }
5802}
5803
5804/// :tabmove command
5805static void ex_tabmove(exarg_T *eap)
5806{
5807  int tab_number = get_tabpage_arg(eap);
5808  if (eap->errmsg == NULL) {
5809    tabpage_move(tab_number);
5810  }
5811}
5812
5813/// :tabs command: List tabs and their contents.
5814static void ex_tabs(exarg_T *eap)
5815{
5816  int tabcount = 1;
5817
5818  msg_ext_set_kind("list_cmd");
5819  msg_start();
5820  msg_scroll = true;
5821
5822  win_T *lastused_win = valid_tabpage(lastused_tabpage)
5823                        ? lastused_tabpage->tp_curwin
5824                        : NULL;
5825
5826  FOR_ALL_TABS(tp) {
5827    if (got_int) {
5828      break;
5829    }
5830
5831    if (msg_col > 0) {
5832      msg_putchar('\n');
5833    }
5834    vim_snprintf(IObuff, IOSIZE, _("Tab page %d"), tabcount++);
5835    msg_outtrans(IObuff, HLF_T, false);
5836    os_breakcheck();
5837
5838    FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
5839      if (got_int) {
5840        break;
5841      } else if (!wp->w_config.focusable || wp->w_config.hide) {
5842        continue;
5843      }
5844
5845      msg_putchar('\n');
5846      msg_putchar(wp == curwin ? '>' : wp == lastused_win ? '#' : ' ');
5847      msg_putchar(' ');
5848      msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' ');
5849      msg_putchar(' ');
5850      if (buf_spname(wp->w_buffer) != NULL) {
5851        xstrlcpy(IObuff, buf_spname(wp->w_buffer), IOSIZE);
5852      } else {
5853        home_replace(wp->w_buffer, wp->w_buffer->b_fname, IObuff, IOSIZE, true);
5854      }
5855      msg_outtrans(IObuff, 0, false);
5856      os_breakcheck();
5857    }
5858  }
5859}
5860
5861/// ":detach"
5862///
5863/// Detaches the current UI.
5864///
5865/// ":%detach" detaches all UIs _except_ the current UI.
5866static void ex_detach(exarg_T *eap)
5867{
5868  Channel *chan = find_channel(current_ui);
5869  if (!chan) {
5870    emsg(_(e_noui));
5871    return;
5872  }
5873
5874  if (eap && eap->forceit) {
5875    chan->detach = true;
5876    msg(_("Nvim will continue running if the UI disconnects"), 0);
5877    return;
5878  }
5879
5880  if (eap && eap->addr_count > 0) {
5881    // ":%detach" detaches every UI except the current one.
5882    if (eap->line1 != 1 || eap->line2 != curbuf->b_ml.ml_line_count) {
5883      emsg(_(e_invrange));
5884      return;
5885    }
5886
5887    size_t n = ui_detach_others(current_ui);
5888    if (n == 0) {
5889      msg(_("No other UIs are attached"), 0);
5890    } else {
5891      smsg(0, _("Detached %d non-current UIs"), (int)n);
5892    }
5893    ILOG("%%detach current_ui=%" PRIu64 " detached=%zu", current_ui, n);
5894  } else {
5895    // come on pooky let's burn this mf down
5896    //
5897    // 1. Send "error_exit" UI-event (notification only).
5898    // 2. Perform server-side UI detach.
5899    // 3. Close server-side channel without self-exit.
5900    Error err = ERROR_INIT;
5901    ui_detach_channel(current_ui, &err);
5902    if (ERROR_SET(&err)) {
5903      emsg(err.msg);  // UI disappeared already?
5904      api_clear_error(&err);
5905      return;
5906    }
5907    ILOG("detach current_ui=%" PRIu64, current_ui);
5908  }
5909}
5910
5911/// ":connect"
5912///
5913/// Connects the current UI to a different server
5914///
5915/// ":connect <address>" detaches the current UI and connects to the given server.
5916/// ":connect! <address>" stops the current server if no other UIs are attached, then connects to the given server.
5917static void ex_connect(exarg_T *eap)
5918{
5919  bool stop_server = eap->forceit ? (ui_active() == 1) : false;
5920
5921  Error err = ERROR_INIT;
5922  remote_ui_connect(current_ui, eap->arg, &err);
5923
5924  if (ERROR_SET(&err)) {
5925    emsg(err.msg);
5926    api_clear_error(&err);
5927    return;
5928  }
5929
5930  ex_detach(NULL);
5931  if (stop_server) {
5932    exiting = true;
5933    getout(0);
5934  }
5935}
5936
5937/// ":mode":
5938/// If no argument given, get the screen size and redraw.
5939static void ex_mode(exarg_T *eap)
5940{
5941  if (*eap->arg == NUL) {
5942    must_redraw = UPD_CLEAR;
5943    ex_redraw(eap);
5944  } else {
5945    emsg(_(e_screenmode));
5946  }
5947}
5948
5949/// ":resize".
5950/// set, increment or decrement current window height
5951static void ex_resize(exarg_T *eap)
5952{
5953  win_T *wp = curwin;
5954
5955  if (eap->addr_count > 0) {
5956    int n = (int)eap->line2;
5957    for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next) {}
5958  }
5959
5960  int n = (int)atol(eap->arg);
5961  if (cmdmod.cmod_split & WSP_VERT) {
5962    if (*eap->arg == '-' || *eap->arg == '+') {
5963      n += wp->w_width;
5964    } else if (n == 0 && eap->arg[0] == NUL) {  // default is very wide
5965      n = Columns;
5966    }
5967    win_setwidth_win(n, wp, true);
5968  } else {
5969    if (*eap->arg == '-' || *eap->arg == '+') {
5970      n += wp->w_height;
5971    } else if (n == 0 && eap->arg[0] == NUL) {  // default is very high
5972      n = Rows - 1;
5973    }
5974    win_setheight_win(n, wp, true);
5975  }
5976}
5977
5978/// ":find [+command] <file>" command.
5979static void ex_find(exarg_T *eap)
5980{
5981  if (!check_can_set_curbuf_forceit(eap->forceit)) {
5982    return;
5983  }
5984
5985  char *fname = NULL;
5986  if (get_findfunc()->type != kCallbackNone) {
5987    fname = findfunc_find_file(eap->arg, strlen(eap->arg),
5988                               eap->addr_count > 0 ? eap->line2 : 1);
5989  } else {
5990    char *file_to_find = NULL;
5991    char *search_ctx = NULL;
5992    fname = find_file_in_path(eap->arg, strlen(eap->arg), FNAME_MESS, true,
5993                              curbuf->b_ffname, &file_to_find, &search_ctx);
5994    if (eap->addr_count > 0) {
5995      // Repeat finding the file "count" times.  This matters when it appears
5996      // several times in the path.
5997      linenr_T count = eap->line2;
5998      while (fname != NULL && --count > 0) {
5999        xfree(fname);
6000        fname = find_file_in_path(NULL, 0, FNAME_MESS, false,
6001                                  curbuf->b_ffname, &file_to_find, &search_ctx);
6002      }
6003    }
6004    xfree(file_to_find);
6005    vim_findfile_cleanup(search_ctx);
6006  }
6007
6008  if (fname == NULL) {
6009    return;
6010  }
6011
6012  eap->arg = fname;
6013  do_exedit(eap, NULL);
6014  xfree(fname);
6015}
6016
6017/// ":edit", ":badd", ":balt", ":visual".
6018static void ex_edit(exarg_T *eap)
6019{
6020  set_browse_edit_arg(eap);
6021  char *ffname = eap->cmdidx == CMD_enew ? NULL : eap->arg;
6022
6023  // Exclude commands which keep the window's current buffer
6024  if (eap->cmdidx != CMD_badd
6025      && eap->cmdidx != CMD_balt
6026      // All other commands must obey 'winfixbuf' / ! rules
6027      && (is_other_file(0, ffname) && !check_can_set_curbuf_forceit(eap->forceit))) {
6028    return;
6029  }
6030
6031  // prevent use of :edit on prompt-buffers
6032  if (bt_prompt(curbuf) && eap->cmdidx == CMD_edit && *eap->arg == NUL) {
6033    emsg("cannot :edit a prompt buffer");
6034    return;
6035  }
6036
6037  do_exedit(eap, NULL);
6038}
6039
6040/// ":edit <file>" command and alike.
6041///
6042/// @param old_curwin  curwin before doing a split or NULL
6043void do_exedit(exarg_T *eap, win_T *old_curwin)
6044{
6045  if ((eap->cmdidx == CMD_new
6046       || eap->cmdidx == CMD_tabnew
6047       || eap->cmdidx == CMD_tabedit
6048       || eap->cmdidx == CMD_vnew) && *eap->arg == NUL) {
6049    // ":new" or ":tabnew" without argument: edit a new empty buffer
6050    setpcmark();
6051    do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
6052            ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
6053            old_curwin == NULL ? curwin : NULL);
6054  } else if ((eap->cmdidx != CMD_split && eap->cmdidx != CMD_vsplit)
6055             || *eap->arg != NUL) {
6056    // Can't edit another file when "textlock" or "curbuf->b_ro_locked" is set.
6057    // Only ":edit" or ":script" can bring us here, others are stopped earlier.
6058    if (*eap->arg != NUL && text_or_buf_locked()) {
6059      return;
6060    }
6061    int n = readonlymode;
6062    if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview) {
6063      readonlymode = true;
6064    } else if (eap->cmdidx == CMD_enew) {
6065      readonlymode = false;  // 'readonly' doesn't make sense
6066                             // in an empty buffer
6067    }
6068    if (eap->cmdidx != CMD_balt && eap->cmdidx != CMD_badd) {
6069      setpcmark();
6070    }
6071    if (do_ecmd(0, eap->cmdidx == CMD_enew ? NULL : eap->arg,
6072                NULL, eap, eap->do_ecmd_lnum,
6073                (buf_hide(curbuf) ? ECMD_HIDE : 0)
6074                + (eap->forceit ? ECMD_FORCEIT : 0)
6075                // After a split we can use an existing buffer.
6076                + (old_curwin != NULL ? ECMD_OLDBUF : 0)
6077                + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0)
6078                + (eap->cmdidx == CMD_balt ? ECMD_ALTBUF : 0),
6079                old_curwin == NULL ? curwin : NULL) == FAIL) {
6080      // Editing the file failed.  If the window was split, close it.
6081      if (old_curwin != NULL) {
6082        bool need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1);
6083        if (!need_hide || buf_hide(curbuf)) {
6084          cleanup_T cs;
6085
6086          // Reset the error/interrupt/exception state here so that
6087          // aborting() returns false when closing a window.
6088          enter_cleanup(&cs);
6089          win_close(curwin, !need_hide && !buf_hide(curbuf), false);
6090
6091          // Restore the error/interrupt/exception state if not
6092          // discarded by a new aborting error, interrupt, or
6093          // uncaught exception.
6094          leave_cleanup(&cs);
6095        }
6096      }
6097    } else if (readonlymode && curbuf->b_nwindows == 1) {
6098      // When editing an already visited buffer, 'readonly' won't be set
6099      // but the previous value is kept.  With ":view" and ":sview" we
6100      // want the  file to be readonly, except when another window is
6101      // editing the same buffer.
6102      curbuf->b_p_ro = true;
6103    }
6104    readonlymode = n;
6105  } else {
6106    if (eap->do_ecmd_cmd != NULL) {
6107      do_cmdline_cmd(eap->do_ecmd_cmd);
6108    }
6109    int n = curwin->w_arg_idx_invalid;
6110    check_arg_idx(curwin);
6111    if (n != curwin->w_arg_idx_invalid) {
6112      maketitle();
6113    }
6114  }
6115
6116  // if ":split file" worked, set alternate file name in old window to new
6117  // file
6118  if (old_curwin != NULL
6119      && *eap->arg != NUL
6120      && curwin != old_curwin
6121      && win_valid(old_curwin)
6122      && old_curwin->w_buffer != curbuf
6123      && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
6124    old_curwin->w_alt_fnum = curbuf->b_fnum;
6125  }
6126}
6127
6128/// ":gui" and ":gvim" when there is no GUI.
6129static void ex_nogui(exarg_T *eap)
6130{
6131  eap->errmsg = _("E25: Nvim does not have a built-in GUI");
6132}
6133
6134static void ex_popup(exarg_T *eap)
6135{
6136  pum_make_popup(eap->arg, eap->forceit);
6137}
6138
6139static void ex_swapname(exarg_T *eap)
6140{
6141  if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) {
6142    msg(_("No swap file"), 0);
6143  } else {
6144    msg(curbuf->b_ml.ml_mfp->mf_fname, 0);
6145  }
6146}
6147
6148/// ":syncbind" forces all 'scrollbind' windows to have the same relative
6149/// offset.
6150/// (1998-11-02 16:21:01  R. Edward Ralston <eralston@computer.org>)
6151static void ex_syncbind(exarg_T *eap)
6152{
6153  linenr_T vtopline;  // Target topline (including fill)
6154
6155  linenr_T old_linenr = curwin->w_cursor.lnum;
6156
6157  setpcmark();
6158
6159  // determine max (virtual) topline
6160  if (curwin->w_p_scb) {
6161    vtopline = get_vtopline(curwin);
6162    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
6163      if (wp->w_p_scb && wp->w_buffer) {
6164        linenr_T y = plines_m_win_fill(wp, 1, wp->w_buffer->b_ml.ml_line_count)
6165                     - (int)get_scrolloff_value(curwin);
6166        vtopline = MIN(vtopline, y);
6167      }
6168    }
6169    vtopline = MAX(vtopline, 1);
6170  } else {
6171    vtopline = 1;
6172  }
6173
6174  // Set all scrollbind windows to the same topline.
6175  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
6176    if (wp->w_p_scb) {
6177      int y = vtopline - get_vtopline(wp);
6178      if (y > 0) {
6179        scrollup(wp, y, true);
6180      } else {
6181        scrolldown(wp, -y, true);
6182      }
6183      wp->w_scbind_pos = vtopline;
6184      redraw_later(wp, UPD_VALID);
6185      cursor_correct(wp);
6186      wp->w_redr_status = true;
6187    }
6188  }
6189
6190  if (curwin->w_p_scb) {
6191    did_syncbind = true;
6192    checkpcmark();
6193    if (old_linenr != curwin->w_cursor.lnum) {
6194      char ctrl_o[2];
6195
6196      ctrl_o[0] = Ctrl_O;
6197      ctrl_o[1] = 0;
6198      ins_typebuf(ctrl_o, REMAP_NONE, 0, true, false);
6199    }
6200  }
6201}
6202
6203static void ex_read(exarg_T *eap)
6204{
6205  if (eap->usefilter) {  // :r!cmd
6206    do_bang(1, eap, false, false, true);
6207    return;
6208  }
6209
6210  if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL) {
6211    return;
6212  }
6213
6214  int i;
6215  if (*eap->arg == NUL) {
6216    if (check_fname() == FAIL) {       // check for no file name
6217      return;
6218    }
6219    i = readfile(curbuf->b_ffname, curbuf->b_fname,
6220                 eap->line2, 0, (linenr_T)MAXLNUM, eap, 0, false);
6221  } else {
6222    if (vim_strchr(p_cpo, kCpoAltread) != NULL) {
6223      setaltfname(eap->arg, eap->arg, 1);
6224    }
6225    i = readfile(eap->arg, NULL,
6226                 eap->line2, 0, (linenr_T)MAXLNUM, eap, 0, false);
6227  }
6228  if (i != OK) {
6229    if (!aborting()) {
6230      semsg(_(e_notopen), eap->arg);
6231    }
6232  } else {
6233    redraw_curbuf_later(UPD_VALID);
6234  }
6235}
6236
6237static char *prev_dir = NULL;
6238
6239#ifdef EXITFREE
6240void free_cd_dir(void)
6241{
6242  XFREE_CLEAR(prev_dir);
6243  XFREE_CLEAR(globaldir);
6244}
6245
6246#endif
6247
6248/// Gets the previous-directory slot for the given chdir scope.
6249static char **get_prevdir(CdScope scope)
6250{
6251  switch (scope) {
6252  case kCdScopeTabpage:
6253    return &curtab->tp_prevdir;
6254  case kCdScopeBuffer:
6255    return &curbuf->b_prevdir;
6256  case kCdScopeWindow:
6257    return &curwin->w_prevdir;
6258  default:
6259    return &prev_dir;
6260  }
6261}
6262
6263/// Deal with the side effects of changing the current directory.
6264///
6265/// @param scope  Scope of the function call (global, tab, window or buffer).
6266static void post_chdir(CdScope scope, bool trigger_dirchanged)
6267{
6268  // Only :bcd overwrites the buffer-local CWD.
6269  if (scope == kCdScopeBuffer) {
6270    XFREE_CLEAR(curbuf->b_localdir);
6271  }
6272
6273  // Overwrite the window-local CWD for :cd, :tcd, :lcd.
6274  if (scope >= kCdScopeWindow) {
6275    XFREE_CLEAR(curwin->w_localdir);
6276  }
6277
6278  // Overwrite the tab-local CWD for :cd, :tcd.
6279  if (scope >= kCdScopeTabpage) {
6280    XFREE_CLEAR(curtab->tp_localdir);
6281  }
6282
6283  if (scope < kCdScopeGlobal) {
6284    char *pdir = *get_prevdir(scope);
6285    // If still in global directory, set CWD as the global directory.
6286    if (globaldir == NULL && pdir != NULL) {
6287      globaldir = xstrdup(pdir);
6288    }
6289  }
6290
6291  char cwd[MAXPATHL];
6292  if (os_dirname(cwd, MAXPATHL) != OK) {
6293    return;
6294  }
6295  switch (scope) {
6296  case kCdScopeGlobal:
6297    // We are now in the global directory, no need to remember its name.
6298    // Unless a buffer-local CWD is active, then it is in effect and must be remembered.
6299    XFREE_CLEAR(globaldir);
6300    if (curbuf->b_localdir != NULL) {
6301      globaldir = xstrdup(cwd);
6302    }
6303    break;
6304  case kCdScopeTabpage:
6305    curtab->tp_localdir = xstrdup(cwd);
6306    break;
6307  case kCdScopeBuffer:
6308    curbuf->b_localdir = xstrdup(cwd);
6309    break;
6310  case kCdScopeWindow:
6311    curwin->w_localdir = xstrdup(cwd);
6312    break;
6313  case kCdScopeInvalid:
6314    abort();
6315  }
6316
6317  last_chdir_reason = NULL;
6318  shorten_fnames(vim_strchr(p_cpo, kCpoNosymlinks) == NULL);
6319
6320  if (trigger_dirchanged) {
6321    do_autocmd_dirchanged(cwd, scope, kCdCauseManual, false);
6322  }
6323}
6324
6325/// Performs explicit (user) chdir (:cd/:tcd/:lcd/:bcd/chdir()/nvim_set_current_dir()).  Unlike
6326/// do_autochdir() and update_cwd(), this sets the `scope` dir and reports kCdCauseManual.
6327///
6328/// @param new_dir  Directory to change to.
6329/// @param scope    Set the directory on this scope.
6330/// @return true if the directory was successfully changed.
6331bool do_chdir(char *new_dir, CdScope scope)
6332{
6333  if (new_dir == NULL || allbuf_locked()) {
6334    return false;
6335  }
6336
6337  char *pdir = NULL;
6338  // ":cd -": Change to previous directory
6339  if (strcmp(new_dir, "-") == 0) {
6340    pdir = *get_prevdir(scope);
6341    if (pdir == NULL) {
6342      emsg(_("E186: No previous directory"));
6343      return false;
6344    }
6345    new_dir = pdir;
6346  }
6347
6348  if (os_dirname(NameBuff, MAXPATHL) == OK) {
6349    pdir = xstrdup(NameBuff);
6350  } else {
6351    pdir = NULL;
6352  }
6353
6354  // For UNIX ":cd" means: go to home directory.
6355  // On other systems too if 'cdhome' is set.
6356  if (*new_dir == NUL && p_cdh) {
6357    // Use NameBuff for home directory name.
6358    expand_env("$HOME", NameBuff, MAXPATHL);
6359    new_dir = NameBuff;
6360  }
6361
6362  new_dir = TO_SLASH_SAVE(new_dir);
6363
6364  // Buffer-local CWD is never "cleared" by :lcd/:tcd/:cd, so it stays in effect.
6365  const bool bcd_active = scope != kCdScopeBuffer && curbuf->b_localdir != NULL;
6366
6367  bool dir_differs = pdir == NULL || !path_equal(pdir, new_dir, kPathCmpLiteral);
6368  if (dir_differs) {
6369    if (!bcd_active) {
6370      do_autocmd_dirchanged(new_dir, scope, kCdCauseManual, true);
6371    }
6372    // Enter `new_dir` even if it will not apply (because of buf-local dir):
6373    // post_chdir() reads back its resolved name.
6374    if (vim_chdir(new_dir) != 0) {
6375      emsg(_(e_failed));
6376      xfree(new_dir);
6377      xfree(pdir);
6378      return false;
6379    }
6380  }
6381  xfree(new_dir);
6382
6383  char **pp = get_prevdir(scope);
6384  xfree(*pp);
6385  *pp = pdir;
6386
6387  post_chdir(scope, dir_differs && !bcd_active);
6388  if (bcd_active) {
6389    os_chdir(curbuf->b_localdir);
6390    shorten_fnames(true);
6391  }
6392  ctx_did_chdir();
6393
6394  return true;
6395}
6396
6397/// ":lcd!", ":tcd!", ":bcd!": Clears the scope-local directory. No-op if scope has no local dir.
6398static void chdir_clear(CdScope scope)
6399{
6400  char **localdir = &curtab->tp_localdir;
6401  if (scope == kCdScopeBuffer) {
6402    localdir = &curbuf->b_localdir;
6403  } else if (scope == kCdScopeWindow) {
6404    localdir = &curwin->w_localdir;
6405  }
6406  if (*localdir == NULL) {
6407    return;
6408  }
6409  XFREE_CLEAR(*localdir);
6410  update_cwd(kCdCauseManual);
6411  ctx_did_chdir();
6412}
6413
6414/// ":cd", ":tcd", ":lcd", ":bcd", ":chdir", ":tchdir", ":lchdir", and ":bchdir".
6415void ex_cd(exarg_T *eap)
6416{
6417  char *new_dir = eap->arg;
6418
6419  CdScope scope = kCdScopeGlobal;
6420  switch (eap->cmdidx) {
6421  case CMD_tcd:
6422  case CMD_tchdir:
6423    scope = kCdScopeTabpage;
6424    break;
6425  case CMD_bcd:
6426  case CMD_bchdir:
6427    scope = kCdScopeBuffer;
6428    break;
6429  case CMD_lcd:
6430  case CMD_lchdir:
6431    scope = kCdScopeWindow;
6432    break;
6433  default:
6434    break;
6435  }
6436
6437  // ":lcd!", ":tcd!", ":bcd!": unset that scope.
6438  if (eap->forceit && *new_dir == NUL && scope != kCdScopeGlobal) {
6439    chdir_clear(scope);
6440    if (KeyTyped || p_verbose >= 5) {
6441      ex_pwd(eap);
6442    }
6443    return;
6444  }
6445
6446  // for non-UNIX ":cd" means: print current directory unless 'cdhome' is set
6447  if (*new_dir == NUL && !p_cdh) {
6448    ex_pwd(NULL);
6449    return;
6450  }
6451
6452  if (do_chdir(new_dir, scope)) {
6453    // Echo the new current directory if the command was typed.
6454    if (KeyTyped || p_verbose >= 5) {
6455      ex_pwd(eap);
6456    }
6457  }
6458}
6459
6460/// ":pwd".
6461static void ex_pwd(exarg_T *eap)
6462{
6463  if (os_dirname(NameBuff, MAXPATHL) == OK) {
6464#ifdef BACKSLASH_IN_FILENAME
6465    slash_adjust(NameBuff);
6466#endif
6467    if (p_verbose > 0) {
6468      char *context = "global";
6469      if (last_chdir_reason != NULL) {
6470        context = last_chdir_reason;
6471      } else if (curbuf->b_localdir != NULL) {
6472        context = "buffer";
6473      } else if (curwin->w_localdir != NULL) {
6474        context = "window";
6475      } else if (curtab->tp_localdir != NULL) {
6476        context = "tabpage";
6477      }
6478      smsg(0, "[%s] %s", context, NameBuff);
6479    } else {
6480      msg(NameBuff, 0);
6481    }
6482  } else {
6483    emsg(_("E187: Unknown"));
6484  }
6485}
6486
6487/// ":=".
6488static void ex_equal(exarg_T *eap)
6489{
6490  if (*eap->arg != NUL && *eap->arg != '|') {
6491    // equivalent to :lua= expr
6492    ex_lua(eap);
6493  } else {
6494    eap->nextcmd = find_nextcmd(eap->arg);
6495    smsg(0, "%" PRId64, (int64_t)eap->line2);
6496  }
6497}
6498
6499static void ex_sleep(exarg_T *eap)
6500{
6501  if (cursor_valid(curwin)) {
6502    setcursor_mayforce(curwin, true);
6503  }
6504
6505  int64_t len = eap->line2;
6506  switch (*eap->arg) {
6507  case 'm':
6508    break;
6509  case NUL:
6510    len *= 1000; break;
6511  default:
6512    semsg(_(e_invarg2), eap->arg); return;
6513  }
6514
6515  // Hide the cursor if invoked with !
6516  do_sleep(len, eap->forceit);
6517}
6518
6519/// Sleep for "msec" milliseconds, but return early on CTRL-C.
6520///
6521/// @param hide_cursor  hide the cursor if true
6522void do_sleep(int64_t msec, bool hide_cursor)
6523{
6524  if (hide_cursor) {
6525    ui_busy_start();
6526  }
6527
6528  ui_flush();  // flush before waiting
6529  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, main_loop.events, msec, got_int);
6530
6531  // If CTRL-C was typed to interrupt the sleep, drop the CTRL-C from the
6532  // input buffer, otherwise a following call to input() fails.
6533  if (got_int) {
6534    vpeekc();
6535  }
6536
6537  if (hide_cursor) {
6538    ui_busy_stop();
6539  }
6540}
6541
6542/// ":winsize" command (obsolete).
6543static void ex_winsize(exarg_T *eap)
6544{
6545  char *arg = eap->arg;
6546
6547  if (!ascii_isdigit(*arg)) {
6548    semsg(_(e_invarg2), arg);
6549    return;
6550  }
6551  int w = getdigits_int(&arg, false, 10);
6552  arg = skipwhite(arg);
6553  char *p = arg;
6554  int h = getdigits_int(&arg, false, 10);
6555  if (*p != NUL && *arg == NUL) {
6556    screen_resize(w, h);
6557  } else {
6558    emsg(_("E465: :winsize requires two number arguments"));
6559  }
6560}
6561
6562static void ex_wincmd(exarg_T *eap)
6563{
6564  int xchar = NUL;
6565  char *p;
6566
6567  if (*eap->arg == 'g' || *eap->arg == Ctrl_G) {
6568    // CTRL-W g and CTRL-W CTRL-G  have an extra command character
6569    if (eap->arg[1] == NUL) {
6570      emsg(_(e_invarg));
6571      return;
6572    }
6573    xchar = (uint8_t)eap->arg[1];
6574    p = eap->arg + 2;
6575  } else {
6576    p = eap->arg + 1;
6577  }
6578
6579  eap->nextcmd = check_nextcmd(p);
6580  p = skipwhite(p);
6581  if (*p != NUL && *p != '"' && eap->nextcmd == NULL) {
6582    emsg(_(e_invarg));
6583  } else if (!eap->skip) {
6584    // Pass flags on for ":vertical wincmd ]".
6585    postponed_split_flags = cmdmod.cmod_split;
6586    postponed_split_tab = cmdmod.cmod_tab;
6587    do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0, xchar);
6588    postponed_split_flags = 0;
6589    postponed_split_tab = 0;
6590  }
6591}
6592
6593/// Handle command that work like operators: ":delete", ":yank", ":>" and ":<".
6594static void ex_operators(exarg_T *eap)
6595{
6596  oparg_T oa;
6597
6598  clear_oparg(&oa);
6599  oa.regname = eap->regname;
6600  oa.start.lnum = eap->line1;
6601  oa.end.lnum = eap->line2;
6602  oa.line_count = eap->line2 - eap->line1 + 1;
6603  oa.motion_type = kMTLineWise;
6604  virtual_op = kFalse;
6605  if (eap->cmdidx != CMD_yank) {  // position cursor for undo
6606    setpcmark();
6607    curwin->w_cursor.lnum = eap->line1;
6608    beginline(BL_SOL | BL_FIX);
6609  }
6610
6611  if (Visual.active) {
6612    end_visual_mode();
6613  }
6614
6615  switch (eap->cmdidx) {
6616  case CMD_delete:
6617    oa.op_type = OP_DELETE;
6618    op_delete(&oa);
6619    break;
6620
6621  case CMD_yank:
6622    oa.op_type = OP_YANK;
6623    op_yank(&oa, true);
6624    break;
6625
6626  default:          // CMD_rshift or CMD_lshift
6627    if (
6628        (eap->cmdidx == CMD_rshift) ^ curwin->w_p_rl) {
6629      oa.op_type = OP_RSHIFT;
6630    } else {
6631      oa.op_type = OP_LSHIFT;
6632    }
6633    op_shift(&oa, false, eap->amount);
6634    break;
6635  }
6636  virtual_op = kNone;
6637  ex_may_print(eap);
6638}
6639
6640/// ":put".
6641static void ex_put(exarg_T *eap)
6642{
6643  // ":0put" works like ":1put!".
6644  if (eap->line2 == 0) {
6645    eap->line2 = 1;
6646    eap->forceit = true;
6647  }
6648  curwin->w_cursor.lnum = eap->line2;
6649  check_cursor_col(curwin);
6650  do_put(eap->regname, NULL, eap->forceit ? BACKWARD : FORWARD, 1,
6651         PUT_LINE|PUT_CURSLINE);
6652}
6653
6654/// ":iput".
6655static void ex_iput(exarg_T *eap)
6656{
6657  // ":0iput" works like ":1iput!".
6658  if (eap->line2 == 0) {
6659    eap->line2 = 1;
6660    eap->forceit = true;
6661  }
6662  curwin->w_cursor.lnum = eap->line2;
6663  check_cursor_col(curwin);
6664  do_put(eap->regname, NULL, eap->forceit ? BACKWARD : FORWARD, 1L,
6665         PUT_LINE|PUT_CURSLINE|PUT_FIXINDENT);
6666}
6667
6668/// Handle ":copy" and ":move".
6669static void ex_copymove(exarg_T *eap)
6670{
6671  const char *errormsg = NULL;
6672  linenr_T n = get_address(eap, &eap->arg, eap->addr_type, false, false, false, 1, &errormsg);
6673  if (eap->arg == NULL) {  // error detected
6674    if (errormsg != NULL) {
6675      emsg(errormsg);
6676    }
6677    eap->nextcmd = NULL;
6678    return;
6679  }
6680  get_flags(eap);
6681
6682  // move or copy lines from 'eap->line1'-'eap->line2' to below line 'n'
6683  if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count) {
6684    emsg(_(e_invrange));
6685    return;
6686  }
6687
6688  if (eap->cmdidx == CMD_move) {
6689    if (do_move(eap->line1, eap->line2, n) == FAIL) {
6690      return;
6691    }
6692  } else {
6693    ex_copy(eap->line1, eap->line2, n);
6694  }
6695  u_clearline(curbuf);
6696  beginline(BL_SOL | BL_FIX);
6697  ex_may_print(eap);
6698}
6699
6700/// Print the current line if flags were given to the Ex command.
6701void ex_may_print(exarg_T *eap)
6702{
6703  if (eap->flags != 0) {
6704    print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR),
6705               (eap->flags & EXFLAG_LIST), true);
6706  }
6707}
6708
6709/// ":join".
6710static void ex_join(exarg_T *eap)
6711{
6712  curwin->w_cursor.lnum = eap->line1;
6713  if (eap->line1 == eap->line2) {
6714    if (eap->addr_count >= 2) {     // :2,2join does nothing
6715      return;
6716    }
6717    if (eap->line2 == curbuf->b_ml.ml_line_count) {
6718      beep_flush();
6719      return;
6720    }
6721    eap->line2++;
6722  }
6723  do_join((size_t)((ssize_t)eap->line2 - eap->line1 + 1), !eap->forceit, true, true, true);
6724  beginline(BL_WHITE | BL_FIX);
6725  ex_may_print(eap);
6726}
6727
6728/// ":[addr]@r": execute register
6729static void ex_at(exarg_T *eap)
6730{
6731  int prev_len = typebuf.tb_len;
6732
6733  curwin->w_cursor.lnum = eap->line2;
6734  check_cursor_col(curwin);
6735
6736  // Get the register name. No name means use the previous one.
6737  int c = (uint8_t)(*eap->arg);
6738  if (c == NUL) {
6739    c = '@';
6740  }
6741
6742  // Put the register in the typeahead buffer with the "silent" flag.
6743  if (do_execreg(c, true, vim_strchr(p_cpo, kCpoExecbuf) != NULL, true) == FAIL) {
6744    beep_flush();
6745    return;
6746  }
6747
6748  const bool save_efr = exec_from_reg;
6749
6750  exec_from_reg = true;
6751
6752  // Execute from the typeahead buffer.
6753  // Continue until the stuff buffer is empty and all added characters
6754  // have been consumed.
6755  while (!stuff_empty() || typebuf.tb_len > prev_len) {
6756    do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
6757  }
6758
6759  exec_from_reg = save_efr;
6760}
6761
6762/// ":!".
6763static void ex_bang(exarg_T *eap)
6764{
6765  do_bang(eap->addr_count, eap, eap->forceit, true, true);
6766}
6767
6768/// ":undo".
6769static void ex_undo(exarg_T *eap)
6770{
6771  if (eap->addr_count != 1) {
6772    if (eap->forceit) {
6773      u_undo_and_forget(1, true);   // :undo!
6774    } else {
6775      u_undo(1);                    // :undo
6776    }
6777    return;
6778  }
6779
6780  linenr_T step = eap->line2;
6781
6782  if (eap->forceit) {             // undo! 123
6783    // change number for "undo!" must be lesser than current change number
6784    if (step >= curbuf->b_u_seq_cur) {
6785      emsg(_(e_undobang_cannot_redo_or_move_branch));
6786      return;
6787    }
6788    // ensure that target change number is in same branch
6789    // while also counting the amount of undoes it'd take to reach target
6790    u_header_T *uhp;
6791    int count = 0;
6792
6793    for (uhp = curbuf->b_u_curhead ? curbuf->b_u_curhead : curbuf->b_u_newhead;
6794         uhp != NULL && uhp->uh_seq > step;
6795         uhp = uhp->uh_next.ptr, ++count) {}
6796    if (step != 0 && (uhp == NULL || uhp->uh_seq < step)) {
6797      emsg(_(e_undobang_cannot_redo_or_move_branch));
6798      return;
6799    }
6800    u_undo_and_forget(count, true);
6801  } else {                        // :undo 123
6802    undo_time(step, false, false, true);
6803  }
6804}
6805
6806static void ex_wundo(exarg_T *eap)
6807{
6808  uint8_t hash[UNDO_HASH_SIZE];
6809
6810  u_compute_hash(curbuf, hash);
6811  u_write_undo(eap->arg, eap->forceit, curbuf, hash);
6812}
6813
6814static void ex_rundo(exarg_T *eap)
6815{
6816  uint8_t hash[UNDO_HASH_SIZE];
6817
6818  u_compute_hash(curbuf, hash);
6819  u_read_undo(eap->arg, hash, NULL);
6820}
6821
6822/// ":redo".
6823static void ex_redo(exarg_T *eap)
6824{
6825  u_redo(1);
6826}
6827
6828/// ":earlier" and ":later".
6829static void ex_later(exarg_T *eap)
6830{
6831  int count = 0;
6832  bool sec = false;
6833  bool file = false;
6834  char *p = eap->arg;
6835
6836  if (*p == NUL) {
6837    count = 1;
6838  } else if (isdigit((uint8_t)(*p))) {
6839    count = getdigits_int(&p, false, 0);
6840    switch (*p) {
6841    case 's':
6842      p++; sec = true; break;
6843    case 'm':
6844      p++; sec = true; count *= 60; break;
6845    case 'h':
6846      p++; sec = true; count *= 60 * 60; break;
6847    case 'd':
6848      p++; sec = true; count *= 24 * 60 * 60; break;
6849    case 'f':
6850      p++; file = true; break;
6851    }
6852  }
6853
6854  if (*p != NUL) {
6855    semsg(_(e_invarg2), eap->arg);
6856  } else {
6857    undo_time(eap->cmdidx == CMD_earlier ? -count : count,
6858              sec, file, false);
6859  }
6860}
6861
6862/// ":redir": start/stop redirection.
6863static void ex_redir(exarg_T *eap)
6864{
6865  char *arg = eap->arg;
6866
6867  if (STRICMP(eap->arg, "END") == 0) {
6868    close_redir();
6869  } else {
6870    if (*arg == '>') {
6871      arg++;
6872      char *mode;
6873      if (*arg == '>') {
6874        arg++;
6875        mode = "a";
6876      } else {
6877        mode = "w";
6878      }
6879      arg = skipwhite(arg);
6880
6881      close_redir();
6882
6883      // Expand environment variables and "~/".
6884      char *fname = expand_env_save(arg);
6885      if (fname == NULL) {
6886        return;
6887      }
6888
6889      redir_fd = open_exfile(fname, eap->forceit, mode);
6890      xfree(fname);
6891    } else if (*arg == '@') {
6892      // redirect to a register a-z (resp. A-Z for appending)
6893      close_redir();
6894      arg++;
6895      if (valid_yank_reg(*arg, true) && *arg != '_') {
6896        redir_reg = (uint8_t)(*arg++);
6897        if (*arg == '>' && arg[1] == '>') {        // append
6898          arg += 2;
6899        } else {
6900          // Can use both "@a" and "@a>".
6901          if (*arg == '>') {
6902            arg++;
6903          }
6904          // Make register empty when not using @A-@Z and the
6905          // command is valid.
6906          if (*arg == NUL && !isupper(redir_reg)) {
6907            write_reg_contents(redir_reg, "", 0, false);
6908          }
6909        }
6910      }
6911      if (*arg != NUL) {
6912        redir_reg = 0;
6913        semsg(_(e_invarg2), eap->arg);
6914      }
6915    } else if (*arg == '=' && arg[1] == '>') {
6916      bool append;
6917
6918      // redirect to a variable
6919      close_redir();
6920      arg += 2;
6921
6922      if (*arg == '>') {
6923        arg++;
6924        append = true;
6925      } else {
6926        append = false;
6927      }
6928
6929      if (var_redir_start(skipwhite(arg), append) == OK) {
6930        redir_vname = true;
6931      }
6932    } else {  // TODO(vim): redirect to a buffer
6933      semsg(_(e_invarg2), eap->arg);
6934    }
6935  }
6936
6937  // Make sure redirection is not off.  Can happen for cmdline completion
6938  // that indirectly invokes a command to catch its output.
6939  if (redir_fd != NULL
6940      || redir_reg || redir_vname) {
6941    redir_off = false;
6942  }
6943}
6944
6945/// ":redraw": force redraw
6946static void ex_redraw(exarg_T *eap)
6947{
6948  if (cmdpreview) {
6949    return;  // Ignore :redraw during 'inccommand' preview. #9777
6950  }
6951  int r = RedrawingDisabled;
6952  int p = p_lz;
6953
6954  RedrawingDisabled = 0;
6955  p_lz = false;
6956  validate_cursor(curwin);
6957  update_topline(curwin);
6958  if (eap->forceit) {
6959    redraw_all_later(UPD_NOT_VALID);
6960    redraw_cmdline = true;
6961  } else if (Visual.active) {
6962    redraw_curbuf_later(UPD_INVERTED);
6963  }
6964  update_screen();
6965  if (need_maketitle) {
6966    maketitle();
6967  }
6968  RedrawingDisabled = r;
6969  p_lz = p;
6970
6971  // Reset msg_didout, so that a message that's there is overwritten.
6972  msg_didout = false;
6973  msg_col = 0;
6974
6975  // No need to wait after an intentional redraw.
6976  need_wait_return = false;
6977
6978  ui_flush();
6979}
6980
6981/// ":redrawstatus": force redraw of status line(s) and window bar(s)
6982static void ex_redrawstatus(exarg_T *eap)
6983{
6984  if (cmdpreview) {
6985    return;  // Ignore :redrawstatus during 'inccommand' preview. #9777
6986  }
6987  int r = RedrawingDisabled;
6988  int p = p_lz;
6989
6990  if (eap->forceit) {
6991    status_redraw_all();
6992  } else {
6993    status_redraw_curbuf();
6994  }
6995
6996  RedrawingDisabled = 0;
6997  p_lz = false;
6998  if (State & MODE_CMDLINE) {
6999    redraw_statuslines();
7000  } else {
7001    if (Visual.active) {
7002      redraw_curbuf_later(UPD_INVERTED);
7003    }
7004    update_screen();
7005  }
7006  RedrawingDisabled = r;
7007  p_lz = p;
7008  ui_flush();
7009}
7010
7011/// ":redrawtabline": force redraw of the tabline
7012static void ex_redrawtabline(exarg_T *eap FUNC_ATTR_UNUSED)
7013{
7014  const int r = RedrawingDisabled;
7015  const int p = p_lz;
7016
7017  RedrawingDisabled = 0;
7018  p_lz = false;
7019
7020  draw_tabline();
7021
7022  RedrawingDisabled = r;
7023  p_lz = p;
7024  ui_flush();
7025}
7026
7027static void close_redir(void)
7028{
7029  if (redir_fd != NULL) {
7030    fclose(redir_fd);
7031    redir_fd = NULL;
7032  }
7033  redir_reg = 0;
7034  if (redir_vname) {
7035    var_redir_stop();
7036    redir_vname = false;
7037  }
7038}
7039
7040/// Try creating a directory, give error message on failure
7041///
7042/// @param[in]  name  Directory to create.
7043/// @param[in]  prot  Directory permissions.
7044///
7045/// @return OK in case of success, FAIL otherwise.
7046int vim_mkdir_emsg(const char *const name, const int prot)
7047  FUNC_ATTR_NONNULL_ALL
7048{
7049  int ret;
7050  if ((ret = os_mkdir(name, prot)) != 0) {
7051    semsg(_(e_mkdir), name, os_strerror(ret));
7052    return FAIL;
7053  }
7054  return OK;
7055}
7056
7057/// Open a file for writing for an Ex command, with some checks.
7058///
7059/// @param mode  "w" for create new file or "a" for append
7060///
7061/// @return  file descriptor, or NULL on failure.
7062FILE *open_exfile(char *fname, int forceit, char *mode)
7063{
7064#ifdef UNIX
7065  // with Unix it is possible to open a directory
7066  if (os_isdir(fname)) {
7067    semsg(_(e_isadir2), fname);
7068    return NULL;
7069  }
7070#endif
7071  if (!forceit && *mode != 'a' && os_path_exists(fname)) {
7072    semsg(_("E189: \"%s\" exists (add ! to override)"), fname);
7073    return NULL;
7074  }
7075
7076  FILE *fd;
7077  if ((fd = os_fopen(fname, mode)) == NULL) {
7078    semsg(_("E190: Cannot open \"%s\" for writing"), fname);
7079  }
7080
7081  return fd;
7082}
7083
7084/// ":mark" and ":k".
7085static void ex_mark(exarg_T *eap)
7086{
7087  if (*eap->arg == NUL) {               // No argument?
7088    emsg(_(e_argreq));
7089    return;
7090  }
7091
7092  if (eap->arg[1] != NUL) {         // more than one character?
7093    semsg(_(e_trailing_arg), eap->arg);
7094    return;
7095  }
7096
7097  pos_T pos = curwin->w_cursor;             // save curwin->w_cursor
7098  curwin->w_cursor.lnum = eap->line2;
7099  beginline(BL_WHITE | BL_FIX);
7100  if (setmark(*eap->arg) == FAIL) {   // set mark
7101    emsg(_("E191: Argument must be a letter or forward/backward quote"));
7102  }
7103  curwin->w_cursor = pos;             // restore curwin->w_cursor
7104}
7105
7106/// Update w_topline, w_leftcol and the cursor position.
7107void update_topline_cursor(void)
7108{
7109  check_cursor(curwin);               // put cursor on valid line
7110  update_topline(curwin);
7111  if (!curwin->w_p_wrap) {
7112    validate_cursor(curwin);
7113  }
7114  update_curswant();
7115}
7116
7117/// Save the current State (editor-mode) and go to Normal mode.
7118void save_current_state(save_state_T *sst)
7119  FUNC_ATTR_NONNULL_ALL
7120{
7121  sst->save_msg_scroll = msg_scroll;
7122  sst->save_restart_edit = restart_edit;
7123  sst->save_msg_didout = msg_didout;
7124  sst->save_State = State;
7125  sst->save_finish_op = finish_op;
7126  sst->save_opcount = opcount;
7127  sst->save_reg_executing = reg_executing;
7128  sst->save_pending_end_reg_executing = pending_end_reg_executing;
7129
7130  msg_scroll = false;   // no msg scrolling in Normal mode
7131  restart_edit = 0;     // don't go to Insert mode
7132
7133  // Save the current typeahead.  This is required to allow using ":normal"
7134  // from an event handler and makes sure we don't hang when the argument
7135  // ends with half a command.
7136  save_typeahead(&sst->tabuf);
7137}
7138
7139void restore_current_state(save_state_T *sst)
7140  FUNC_ATTR_NONNULL_ALL
7141{
7142  // Restore the previous typeahead.
7143  restore_typeahead(&sst->tabuf);
7144
7145  msg_scroll = sst->save_msg_scroll;
7146  if (force_restart_edit) {
7147    force_restart_edit = false;
7148  } else {
7149    // Some function (terminal_enter()) was aware of ex_normal and decided to
7150    // override the value of restart_edit anyway.
7151    restart_edit = sst->save_restart_edit;
7152  }
7153  finish_op = sst->save_finish_op;
7154  opcount = sst->save_opcount;
7155  reg_executing = sst->save_reg_executing;
7156  pending_end_reg_executing = sst->save_pending_end_reg_executing;
7157
7158  // don't reset msg_didout now
7159  msg_didout |= sst->save_msg_didout;
7160
7161  // Restore the state (needed when called from a function executed for
7162  // 'indentexpr'). Update the mouse and cursor, they may have changed.
7163  State = sst->save_State;
7164  ui_cursor_shape();  // may show different cursor shape
7165}
7166
7167/// True while evaluating an `<expr>` mapping.
7168/// Buffer changes are not allowed, except for internal-only dummy buffers.
7169bool expr_map_locked(void)
7170{
7171  return expr_map_lock > 0 && !(curbuf->b_flags & BF_DUMMY);
7172}
7173
7174/// ":normal[!] {commands}": Execute normal mode commands.
7175static void ex_normal(exarg_T *eap)
7176{
7177  if (curbuf->terminal && State & MODE_TERMINAL) {
7178    emsg("Can't re-enter normal mode from terminal mode");
7179    return;
7180  }
7181  char *arg = NULL;
7182
7183  if (expr_map_locked()) {
7184    emsg(_(e_secure));
7185    return;
7186  }
7187
7188  if (ex_normal_busy >= p_mmd) {
7189    emsg(_("E192: Recursive use of :normal too deep"));
7190    return;
7191  }
7192
7193  // vgetc() expects K_SPECIAL to have been escaped.  Don't do
7194  // this for the K_SPECIAL leading byte, otherwise special keys will not
7195  // work.
7196  {
7197    int len = 0;
7198
7199    // Count the number of characters to be escaped.
7200    int l;
7201    for (char *p = eap->arg; *p != NUL; p++) {
7202      for (l = utfc_ptr2len(p) - 1; l > 0; l--) {
7203        if (*++p == (char)K_SPECIAL) {  // trailbyte K_SPECIAL
7204          len += 2;
7205        }
7206      }
7207    }
7208    if (len > 0) {
7209      arg = xmalloc(strlen(eap->arg) + (size_t)len + 1);
7210      len = 0;
7211      for (char *p = eap->arg; *p != NUL; p++) {
7212        arg[len++] = *p;
7213        for (l = utfc_ptr2len(p) - 1; l > 0; l--) {
7214          arg[len++] = *++p;
7215          if (*p == (char)K_SPECIAL) {
7216            arg[len++] = (char)KS_SPECIAL;
7217            arg[len++] = KE_FILLER;
7218          }
7219        }
7220        arg[len] = NUL;
7221      }
7222    }
7223  }
7224
7225  ex_normal_busy++;
7226  save_state_T save_state;
7227  save_current_state(&save_state);
7228  // Repeat the :normal command for each line in the range.  When no
7229  // range given, execute it just once, without positioning the cursor
7230  // first.
7231  do {
7232    if (eap->addr_count != 0) {
7233      curwin->w_cursor.lnum = eap->line1++;
7234      curwin->w_cursor.col = 0;
7235      check_cursor_moved(curwin);
7236    }
7237
7238    exec_normal_cmd((arg != NULL ? arg : eap->arg),
7239                    eap->forceit ? REMAP_NONE : REMAP_YES, false);
7240  } while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int);
7241
7242  // Might not return to the main loop when in an event handler.
7243  update_topline_cursor();
7244
7245  restore_current_state(&save_state);
7246
7247  ex_normal_busy--;
7248
7249  setmouse();
7250  ui_cursor_shape();  // may show different cursor shape
7251  xfree(arg);
7252}
7253
7254/// ":startinsert", ":startreplace" and ":startgreplace"
7255static void ex_startinsert(exarg_T *eap)
7256{
7257  if (!curbuf->b_p_ma && !curbuf->terminal) {
7258    emsg(_(e_modifiable));
7259    return;
7260  }
7261  if (eap->forceit) {
7262    // cursor line can be zero on startup
7263    if (!curwin->w_cursor.lnum) {
7264      curwin->w_cursor.lnum = 1;
7265    }
7266    set_cursor_for_append_to_line();
7267  }
7268
7269  // Ignore the command when already in Insert mode.  Inserting an
7270  // expression register that invokes a function can do this.
7271  if (State & MODE_INSERT) {
7272    return;
7273  }
7274
7275  if (eap->cmdidx == CMD_startinsert) {
7276    restart_edit = 'a';
7277  } else if (eap->cmdidx == CMD_startreplace) {
7278    restart_edit = 'R';
7279  } else {
7280    restart_edit = 'V';
7281  }
7282
7283  if (!eap->forceit) {
7284    if (eap->cmdidx == CMD_startinsert) {
7285      restart_edit = 'i';
7286    }
7287    curwin->w_curswant = 0;  // avoid MAXCOL
7288  }
7289
7290  if (Visual.active) {
7291    showmode();
7292  }
7293}
7294
7295/// ":stopinsert"
7296static void ex_stopinsert(exarg_T *eap)
7297{
7298  restart_edit = 0;
7299  Ins.stop_insert_mode = true;
7300  clearmode();
7301}
7302
7303/// Execute normal mode command "cmd".
7304/// "remap" can be REMAP_NONE or REMAP_YES.
7305void exec_normal_cmd(char *cmd, int remap, bool silent)
7306{
7307  // Stuff the argument into the typeahead buffer.
7308  ins_typebuf(cmd, remap, 0, true, silent);
7309  exec_normal(false, false);
7310}
7311
7312/// Execute normal_cmd() until there is no typeahead left.
7313///
7314/// @param was_typed whether or not something was typed
7315/// @param use_vpeekc  true to use vpeekc() to check for available chars
7316void exec_normal(bool was_typed, bool use_vpeekc)
7317{
7318  oparg_T oa;
7319  int c;
7320
7321  // When calling vpeekc() from feedkeys() it will return Ctrl_C when there
7322  // is nothing to get, so also check for Ctrl_C.
7323  clear_oparg(&oa);
7324  finish_op = false;
7325  while ((!stuff_empty()
7326          || ((was_typed || !typebuf_typed())
7327              && typebuf.tb_len > 0)
7328          || (use_vpeekc && (c = vpeekc()) != NUL && c != Ctrl_C))
7329         && !got_int) {
7330    update_topline_cursor();
7331    normal_cmd(&oa, true);      // execute a Normal mode cmd
7332  }
7333}
7334
7335static void ex_checkpath(exarg_T *eap)
7336{
7337  find_pattern_in_path(NULL, 0, 0, false, false, CHECK_PATH, 1,
7338                       eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW,
7339                       1, (linenr_T)MAXLNUM, eap->forceit, false);
7340}
7341
7342/// ":psearch"
7343static void ex_psearch(exarg_T *eap)
7344{
7345  g_do_tagpreview = (int)p_pvh;
7346  ex_findpat(eap);
7347  g_do_tagpreview = 0;
7348}
7349
7350static void ex_findpat(exarg_T *eap)
7351{
7352  bool whole = true;
7353  int action;
7354
7355  switch (cmdnames[eap->cmdidx].cmd_name[2]) {
7356  case 'e':             // ":psearch", ":isearch" and ":dsearch"
7357    if (cmdnames[eap->cmdidx].cmd_name[0] == 'p') {
7358      action = ACTION_GOTO;
7359    } else {
7360      action = ACTION_SHOW;
7361    }
7362    break;
7363  case 'i':             // ":ilist" and ":dlist"
7364    action = ACTION_SHOW_ALL;
7365    break;
7366  case 'u':             // ":ijump" and ":djump"
7367    action = ACTION_GOTO;
7368    break;
7369  default:              // ":isplit" and ":dsplit"
7370    action = ACTION_SPLIT;
7371    break;
7372  }
7373
7374  int n = 1;
7375  if (ascii_isdigit(*eap->arg)) {  // get count
7376    n = getdigits_int(&eap->arg, false, 0);
7377    eap->arg = skipwhite(eap->arg);
7378  }
7379  if (*eap->arg == '/') {   // Match regexp, not just whole words
7380    whole = false;
7381    eap->arg++;
7382    char *p = skip_regexp(eap->arg, '/', p_magic);
7383    if (*p) {
7384      *p++ = NUL;
7385      p = skipwhite(p);
7386
7387      // Check for trailing illegal characters.
7388      if (!ends_excmd(*p)) {
7389        eap->errmsg = ex_errmsg(e_trailing_arg, p);
7390      } else {
7391        eap->nextcmd = check_nextcmd(p);
7392      }
7393    }
7394  }
7395  if (!eap->skip) {
7396    find_pattern_in_path(eap->arg, 0, strlen(eap->arg), whole, !eap->forceit,
7397                         *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY, n, action,
7398                         eap->line1, eap->line2, eap->forceit, false);
7399  }
7400}
7401
7402/// ":ptag", ":ptselect", ":ptjump", ":ptnext", etc.
7403static void ex_ptag(exarg_T *eap)
7404{
7405  g_do_tagpreview = (int)p_pvh;    // will be reset to 0 in ex_tag_cmd()
7406  ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
7407}
7408
7409/// ":pedit"
7410static void ex_pedit(exarg_T *eap)
7411{
7412  win_T *curwin_save = curwin;
7413  prepare_preview_window();
7414
7415  // Edit the file.
7416  do_exedit(eap, NULL);
7417
7418  back_to_current_window(curwin_save);
7419}
7420
7421/// ":pbuffer"
7422static void ex_pbuffer(exarg_T *eap)
7423{
7424  win_T *curwin_save = curwin;
7425  prepare_preview_window();
7426
7427  // Go to the buffer.
7428  do_exbuffer(eap);
7429
7430  back_to_current_window(curwin_save);
7431}
7432
7433static void prepare_preview_window(void)
7434{
7435  // Open the preview window or popup and make it the current window.
7436  g_do_tagpreview = (int)p_pvh;
7437  prepare_tagpreview(true, *p_pvp != NUL);
7438}
7439
7440static void back_to_current_window(win_T *curwin_save)
7441{
7442  if (curwin != curwin_save && win_valid(curwin_save)) {
7443    // Return cursor to where we were
7444    validate_cursor(curwin);
7445    redraw_later(curwin, UPD_VALID);
7446    win_enter(curwin_save, true);
7447  }
7448  g_do_tagpreview = 0;
7449}
7450
7451/// ":stag", ":stselect" and ":stjump".
7452static void ex_stag(exarg_T *eap)
7453{
7454  postponed_split = -1;
7455  postponed_split_flags = cmdmod.cmod_split;
7456  postponed_split_tab = cmdmod.cmod_tab;
7457  ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1);
7458  postponed_split_flags = 0;
7459  postponed_split_tab = 0;
7460}
7461
7462/// ":tag", ":tselect", ":tjump", ":tnext", etc.
7463static void ex_tag(exarg_T *eap)
7464{
7465  ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name);
7466}
7467
7468static void ex_tag_cmd(exarg_T *eap, const char *name)
7469{
7470  int cmd;
7471
7472  switch (name[1]) {
7473  case 'j':
7474    cmd = DT_JUMP;              // ":tjump"
7475    break;
7476  case 's':
7477    cmd = DT_SELECT;            // ":tselect"
7478    break;
7479  case 'p':                             // ":tprevious"
7480  case 'N':
7481    cmd = DT_PREV;              // ":tNext"
7482    break;
7483  case 'n':
7484    cmd = DT_NEXT;              // ":tnext"
7485    break;
7486  case 'o':
7487    cmd = DT_POP;               // ":pop"
7488    break;
7489  case 'f':                             // ":tfirst"
7490  case 'r':
7491    cmd = DT_FIRST;             // ":trewind"
7492    break;
7493  case 'l':
7494    cmd = DT_LAST;              // ":tlast"
7495    break;
7496  default:                              // ":tag"
7497    cmd = DT_TAG;
7498    break;
7499  }
7500
7501  if (name[0] == 'l') {
7502    cmd = DT_LTAG;
7503  }
7504
7505  do_tag(eap, eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1, eap->forceit, true);
7506}
7507
7508enum {
7509  SPEC_PERC = 0,
7510  SPEC_HASH,
7511  SPEC_CWORD,
7512  SPEC_CCWORD,
7513  SPEC_CEXPR,
7514  SPEC_CFILE,
7515  SPEC_SFILE,
7516  SPEC_SLNUM,
7517  SPEC_STACK,
7518  SPEC_SCRIPT,
7519  SPEC_AFILE,
7520  SPEC_ABUF,
7521  SPEC_AMATCH,
7522  SPEC_SFLNUM,
7523  SPEC_SID,
7524  // SPEC_CLIENT,
7525};
7526
7527/// Check "str" for starting with a special cmdline variable.
7528/// If found return one of the SPEC_ values and set "*usedlen" to the length of
7529/// the variable.  Otherwise return -1 and "*usedlen" is unchanged.
7530ssize_t find_cmdline_var(const char *src, size_t *usedlen)
7531  FUNC_ATTR_NONNULL_ALL
7532{
7533  static char *(spec_str[]) = {
7534    [SPEC_PERC] = "%",
7535    [SPEC_HASH] = "#",
7536    [SPEC_CWORD] = "<cword>",           // cursor word
7537    [SPEC_CCWORD] = "<cWORD>",          // cursor WORD
7538    [SPEC_CEXPR] = "<cexpr>",           // expr under cursor
7539    [SPEC_CFILE] = "<cfile>",           // cursor path name
7540    [SPEC_SFILE] = "<sfile>",           // ":so" file name
7541    [SPEC_SLNUM] = "<slnum>",           // ":so" file line number
7542    [SPEC_STACK] = "<stack>",           // call stack
7543    [SPEC_SCRIPT] = "<script>",         // script file name
7544    [SPEC_AFILE] = "<afile>",           // autocommand file name
7545    [SPEC_ABUF] = "<abuf>",             // autocommand buffer number
7546    [SPEC_AMATCH] = "<amatch>",         // autocommand match name
7547    [SPEC_SFLNUM] = "<sflnum>",         // script file line number
7548    [SPEC_SID] = "<SID>",               // script ID: <SNR>123_
7549    // [SPEC_CLIENT] = "<client>",
7550  };
7551
7552  for (size_t i = 0; i < ARRAY_SIZE(spec_str); i++) {
7553    size_t len = strlen(spec_str[i]);
7554    if (strncmp(src, spec_str[i], len) == 0) {
7555      *usedlen = len;
7556      assert(i <= SSIZE_MAX);
7557      return (ssize_t)i;
7558    }
7559  }
7560  return -1;
7561}
7562
7563/// Evaluate cmdline variables.
7564///
7565/// change "%"       to curbuf->b_ffname
7566///        "#"       to curwin->w_alt_fnum
7567///        "<cword>" to word under the cursor
7568///        "<cWORD>" to WORD under the cursor
7569///        "<cexpr>" to C-expression under the cursor
7570///        "<cfile>" to path name under the cursor
7571///        "<sfile>" to sourced file name
7572///        "<stack>" to call stack
7573///        "<script>" to current script name
7574///        "<slnum>" to sourced file line number
7575///        "<afile>" to file name for autocommand
7576///        "<abuf>"  to buffer number for autocommand
7577///        "<amatch>" to matching name for autocommand
7578///
7579/// When an error is detected, "errormsg" is set to a non-NULL pointer (may be
7580/// "" for error without a message) and NULL is returned.
7581///
7582/// @param src             pointer into commandline
7583/// @param srcstart        beginning of valid memory for src
7584/// @param usedlen         characters after src that are used
7585/// @param lnump           line number for :e command, or NULL
7586/// @param errormsg        pointer to error message
7587/// @param escaped         return value has escaped white space (can be NULL)
7588/// @param empty_is_error  empty result is considered an error
7589///
7590/// @return          an allocated string if a valid match was found.
7591///                  Returns NULL if no match was found.  "usedlen" then still contains the
7592///                  number of characters to skip.
7593char *eval_vars(char *src, const char *srcstart, size_t *usedlen, linenr_T *lnump,
7594                const char **errormsg, int *escaped, bool empty_is_error)
7595{
7596  char *result = "";
7597  char *resultbuf = NULL;
7598  size_t resultlen;
7599  int valid = VALID_HEAD | VALID_PATH;  // Assume valid result.
7600  bool tilde_file = false;
7601  bool skip_mod = false;
7602  char strbuf[30];
7603  // we want 'shellslash' for path expansions like "%", "#", "<afile>", etc.
7604  bool use_shellslash = false;
7605
7606  *errormsg = NULL;
7607  if (escaped != NULL) {
7608    *escaped = false;
7609  }
7610
7611  // Check if there is something to do.
7612  ssize_t spec_idx = find_cmdline_var(src, usedlen);
7613  if (spec_idx < 0) {   // no match
7614    *usedlen = 1;
7615    return NULL;
7616  }
7617
7618  // Skip when preceded with a backslash "\%" and "\#".
7619  // Note: In "\\%" the % is also not recognized!
7620  if (src > srcstart && src[-1] == '\\') {
7621    *usedlen = 0;
7622    STRMOVE(src - 1, src);      // remove backslash
7623    return NULL;
7624  }
7625
7626  // word or WORD under cursor
7627  if (spec_idx == SPEC_CWORD
7628      || spec_idx == SPEC_CCWORD
7629      || spec_idx == SPEC_CEXPR) {
7630    resultlen = find_ident_under_cursor(&result,
7631                                        spec_idx == SPEC_CWORD
7632                                        ? (FIND_IDENT | FIND_STRING)
7633                                        : (spec_idx == SPEC_CEXPR
7634                                           ? (FIND_IDENT | FIND_STRING | FIND_EVAL)
7635                                           : FIND_STRING), NULL);
7636    if (resultlen == 0) {
7637      *errormsg = "";
7638      return NULL;
7639    }
7640    //
7641    // '#': Alternate file name
7642    // '%': Current file name
7643    //        File name under the cursor
7644    //        File name for autocommand
7645    //    and following modifiers
7646    //
7647  } else {
7648    switch (spec_idx) {
7649    case SPEC_PERC:             // '%': current file
7650      if (curbuf->b_fname == NULL) {
7651        result = "";
7652        valid = 0;                  // Must have ":p:h" to be valid
7653      } else {
7654        result = curbuf->b_fname;
7655        tilde_file = strcmp(result, "~") == 0;
7656      }
7657      use_shellslash = true;
7658      break;
7659
7660    case SPEC_HASH:             // '#' or "#99": alternate file
7661      if (src[1] == '#') {          // "##": the argument list
7662        result = arg_all();
7663        resultbuf = result;
7664        *usedlen = 2;
7665        if (escaped != NULL) {
7666          *escaped = true;
7667        }
7668        skip_mod = true;
7669        break;
7670      }
7671      use_shellslash = true;
7672      char *s = src + 1;
7673      if (*s == '<') {                  // "#<99" uses v:oldfiles.
7674        s++;
7675      }
7676      int i = getdigits_int(&s, false, 0);
7677      if (s == src + 2 && src[1] == '-') {
7678        // just a minus sign, don't skip over it
7679        s--;
7680      }
7681      *usedlen = (size_t)(s - src);           // length of what we expand
7682
7683      if (src[1] == '<' && i != 0) {
7684        if (*usedlen < 2) {
7685          // Should we give an error message for #<text?
7686          *usedlen = 1;
7687          return NULL;
7688        }
7689        result = (char *)tv_list_find_str(get_vim_var_list(VV_OLDFILES), i - 1);
7690        if (result == NULL) {
7691          *errormsg = "";
7692          return NULL;
7693        }
7694      } else {
7695        if (i == 0 && src[1] == '<' && *usedlen > 1) {
7696          *usedlen = 1;
7697        }
7698        buf_T *buf = buflist_findnr(i);
7699        if (buf == NULL) {
7700          *errormsg = _("E194: No alternate file name to substitute for '#'");
7701          return NULL;
7702        }
7703        if (lnump != NULL) {
7704          *lnump = ECMD_LAST;
7705        }
7706        if (buf->b_fname == NULL) {
7707          result = "";
7708          valid = 0;                        // Must have ":p:h" to be valid
7709        } else {
7710          result = buf->b_fname;
7711          tilde_file = strcmp(result, "~") == 0;
7712        }
7713      }
7714      break;
7715
7716    case SPEC_CFILE:            // file name under cursor
7717      result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1, NULL);
7718      if (result == NULL) {
7719        *errormsg = "";
7720        return NULL;
7721      }
7722      resultbuf = result;                   // remember allocated string
7723      break;
7724
7725    case SPEC_AFILE:  // file name for autocommand
7726      use_shellslash = !autocmd_fname_full;
7727      if (autocmd_fname != NULL && !autocmd_fname_full) {
7728        // Still need to turn the fname into a full path.  It was
7729        // postponed to avoid a delay when <afile> is not used.
7730        autocmd_fname_full = true;
7731        result = FullName_save(autocmd_fname, false);
7732        // Copy into `autocmd_fname`, don't reassign it. #8165
7733        xstrlcpy(autocmd_fname, result, MAXPATHL);
7734        xfree(result);
7735      }
7736      result = autocmd_fname;
7737      if (result == NULL) {
7738        *errormsg = _(e_no_autocommand_file_name_to_substitute_for_afile);
7739        return NULL;
7740      }
7741      result = path_try_shorten_fname(result);
7742      break;
7743
7744    case SPEC_ABUF:             // buffer number for autocommand
7745      if (autocmd_bufnr <= 0) {
7746        *errormsg = _(e_no_autocommand_buffer_number_to_substitute_for_abuf);
7747        return NULL;
7748      }
7749      snprintf(strbuf, sizeof(strbuf), "%d", autocmd_bufnr);
7750      result = strbuf;
7751      break;
7752
7753    case SPEC_AMATCH:           // match name for autocommand
7754      result = autocmd_match;
7755      if (result == NULL) {
7756        *errormsg = _(e_no_autocommand_match_name_to_substitute_for_amatch);
7757        return NULL;
7758      }
7759      break;
7760
7761    case SPEC_SFILE:            // file name for ":so" command
7762      use_shellslash = true;
7763      result = estack_sfile(ESTACK_SFILE);
7764      if (result == NULL) {
7765        *errormsg = _(e_no_source_file_name_to_substitute_for_sfile);
7766        return NULL;
7767      }
7768      resultbuf = result;  // remember allocated string
7769      break;
7770    case SPEC_STACK:            // call stack
7771      use_shellslash = true;
7772      result = estack_sfile(ESTACK_STACK);
7773      if (result == NULL) {
7774        *errormsg = _(e_no_call_stack_to_substitute_for_stack);
7775        return NULL;
7776      }
7777      resultbuf = result;  // remember allocated string
7778      break;
7779    case SPEC_SCRIPT:           // script file name
7780      use_shellslash = true;
7781      result = estack_sfile(ESTACK_SCRIPT);
7782      if (result == NULL) {
7783        *errormsg = _(e_no_script_file_name_to_substitute_for_script);
7784        return NULL;
7785      }
7786      resultbuf = result;  // remember allocated string
7787      break;
7788
7789    case SPEC_SLNUM:            // line in file for ":so" command
7790      if (SOURCING_NAME == NULL || SOURCING_LNUM == 0) {
7791        *errormsg = _(e_no_line_number_to_use_for_slnum);
7792        return NULL;
7793      }
7794      snprintf(strbuf, sizeof(strbuf), "%" PRIdLINENR, SOURCING_LNUM);
7795      result = strbuf;
7796      break;
7797
7798    case SPEC_SFLNUM:  // line in script file
7799      if (current_sctx.sc_lnum + SOURCING_LNUM == 0) {
7800        *errormsg = _(e_no_line_number_to_use_for_sflnum);
7801        return NULL;
7802      }
7803      snprintf(strbuf, sizeof(strbuf), "%" PRIdLINENR,
7804               current_sctx.sc_lnum + SOURCING_LNUM);
7805      result = strbuf;
7806      break;
7807
7808    case SPEC_SID:
7809      if (current_sctx.sc_sid <= 0) {
7810        *errormsg = _(e_usingsid);
7811        return NULL;
7812      }
7813      snprintf(strbuf, sizeof(strbuf), "<SNR>%" PRIdSCID "_", current_sctx.sc_sid);
7814      result = strbuf;
7815      break;
7816
7817    default:
7818      // should not happen
7819      *errormsg = "";
7820      break;
7821    }
7822
7823    // Length of new string.
7824    resultlen = strlen(result);
7825    // Remove the file name extension.
7826    if (src[*usedlen] == '<') {
7827      (*usedlen)++;
7828      char *s;
7829      if ((s = strrchr(result, '.')) != NULL
7830          && s >= path_tail(result)) {
7831        resultlen = (size_t)(s - result);
7832      }
7833    } else if (!skip_mod) {
7834      valid |= modify_fname(src, tilde_file, usedlen, &result,
7835                            &resultbuf, &resultlen, use_shellslash);
7836      if (result == NULL) {
7837        *errormsg = "";
7838        return NULL;
7839      }
7840    }
7841  }
7842
7843  if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH) {
7844    if (empty_is_error) {
7845      if (valid != VALID_HEAD + VALID_PATH) {
7846        // xgettext:no-c-format
7847        *errormsg = _("E499: Empty file name for '%' or '#', only works with \":p:h\"");
7848      } else {
7849        *errormsg = _("E500: Evaluates to an empty string");
7850      }
7851    }
7852    result = NULL;
7853  } else {
7854    result = xmemdupz(result, resultlen);
7855  }
7856  xfree(resultbuf);
7857  return result;
7858}
7859
7860/// Expand the <sfile> string in "arg".
7861///
7862/// @return  an allocated string, or NULL for any error.
7863char *expand_sfile(char *arg)
7864{
7865  char *result = xstrdup(arg);
7866
7867  for (char *p = result; *p;) {
7868    if (strncmp(p, "<sfile>", 7) != 0) {
7869      p++;
7870    } else {
7871      // replace "<sfile>" with the sourced file name, and do ":" stuff
7872      size_t srclen;
7873      const char *errormsg;
7874      char *repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL, true);
7875      if (errormsg != NULL) {
7876        if (*errormsg) {
7877          emsg(errormsg);
7878        }
7879        xfree(result);
7880        return NULL;
7881      }
7882      if (repl == NULL) {               // no match (cannot happen)
7883        p += srclen;
7884        continue;
7885      }
7886      size_t len = strlen(result) - srclen + strlen(repl) + 1;
7887      char *newres = xmalloc(len);
7888      memmove(newres, result, (size_t)(p - result));
7889      STRCPY(newres + (p - result), repl);
7890      len = strlen(newres);
7891      strcat(newres, p + srclen);
7892      xfree(repl);
7893      xfree(result);
7894      result = newres;
7895      p = newres + len;                 // continue after the match
7896    }
7897  }
7898
7899  return result;
7900}
7901
7902/// ":rshada" and ":wshada".
7903static void ex_shada(exarg_T *eap)
7904{
7905  char *save_shada = p_shada;
7906  if (*p_shada == NUL) {
7907    p_shada = "'100";
7908  }
7909  if (eap->cmdidx == CMD_rviminfo || eap->cmdidx == CMD_rshada) {
7910    shada_read_everything(eap->arg, eap->forceit, false);
7911  } else {
7912    shada_write_file(eap->arg, eap->forceit);
7913  }
7914  p_shada = save_shada;
7915}
7916
7917static TriState filetype_detect = kNone;
7918static TriState filetype_plugin = kNone;
7919static TriState filetype_indent = kNone;
7920
7921/// ":filetype [plugin] [indent] {on,off,detect}"
7922/// on: Load the filetype.vim file to install autocommands for file types.
7923/// off: Load the ftoff.vim file to remove all autocommands for file types.
7924/// plugin on: load filetype.vim and ftplugin.vim
7925/// plugin off: load ftplugof.vim
7926/// indent on: load filetype.vim and indent.vim
7927/// indent off: load indoff.vim
7928static void ex_filetype(exarg_T *eap)
7929{
7930  if (*eap->arg == NUL) {
7931    // Print current status.
7932    smsg(0, "filetype detection:%s  plugin:%s  indent:%s",
7933         filetype_detect == kTrue ? "ON" : "OFF",
7934         filetype_plugin == kTrue ? (filetype_detect == kTrue ? "ON" : "(on)") : "OFF",
7935         filetype_indent == kTrue ? (filetype_detect == kTrue ? "ON" : "(on)") : "OFF");
7936    return;
7937  }
7938
7939  char *arg = eap->arg;
7940  bool plugin = false;
7941  bool indent = false;
7942
7943  // Accept "plugin" and "indent" in any order.
7944  while (true) {
7945    if (strncmp(arg, "plugin", 6) == 0) {
7946      plugin = true;
7947      arg = skipwhite(arg + 6);
7948      continue;
7949    }
7950    if (strncmp(arg, "indent", 6) == 0) {
7951      indent = true;
7952      arg = skipwhite(arg + 6);
7953      continue;
7954    }
7955    break;
7956  }
7957  if (strcmp(arg, "on") == 0 || strcmp(arg, "detect") == 0) {
7958    if (*arg == 'o' || filetype_detect != kTrue) {
7959      source_runtime(FILETYPE_FILE, DIP_ALL);
7960      filetype_detect = kTrue;
7961      if (plugin) {
7962        source_runtime(FTPLUGIN_FILE, DIP_ALL);
7963        filetype_plugin = kTrue;
7964      }
7965      if (indent) {
7966        source_runtime(INDENT_FILE, DIP_ALL);
7967        filetype_indent = kTrue;
7968      }
7969    }
7970    if (*arg == 'd') {
7971      do_doautocmd("filetypedetect BufRead", true, NULL);
7972      do_modelines(0);
7973    }
7974  } else if (strcmp(arg, "off") == 0) {
7975    if (plugin || indent) {
7976      if (plugin) {
7977        source_runtime(FTPLUGOF_FILE, DIP_ALL);
7978        filetype_plugin = kFalse;
7979      }
7980      if (indent) {
7981        source_runtime(INDOFF_FILE, DIP_ALL);
7982        filetype_indent = kFalse;
7983      }
7984    } else {
7985      source_runtime(FTOFF_FILE, DIP_ALL);
7986      filetype_detect = kFalse;
7987    }
7988  } else {
7989    semsg(_(e_invarg2), arg);
7990  }
7991}
7992
7993/// Source ftplugin.vim and indent.vim to create the necessary FileType
7994/// autocommands. We do this separately from filetype.vim so that these
7995/// autocommands will always fire first (and thus can be overridden) while still
7996/// allowing general filetype detection to be disabled in the user's init file.
7997void filetype_plugin_enable(void)
7998{
7999  if (filetype_plugin == kNone) {
8000    source_runtime(FTPLUGIN_FILE, DIP_ALL);
8001    filetype_plugin = kTrue;
8002  }
8003  if (filetype_indent == kNone) {
8004    source_runtime(INDENT_FILE, DIP_ALL);
8005    filetype_indent = kTrue;
8006  }
8007}
8008
8009/// Enable filetype detection if the user did not explicitly disable it.
8010void filetype_maybe_enable(void)
8011{
8012  if (filetype_detect == kNone) {
8013    // Normally .vim files are sourced before .lua files when both are
8014    // supported, but we reverse the order here because we want the Lua
8015    // autocommand to be defined first so that it runs first
8016    source_runtime(FILETYPE_FILE, DIP_ALL);
8017    filetype_detect = kTrue;
8018  }
8019}
8020
8021/// ":setfiletype [FALLBACK] {name}"
8022static void ex_setfiletype(exarg_T *eap)
8023{
8024  if (curbuf->b_did_filetype) {
8025    return;
8026  }
8027
8028  char *arg = eap->arg;
8029  if (strncmp(arg, "FALLBACK ", 9) == 0) {
8030    arg += 9;
8031  }
8032
8033  set_option_value_give_err(kOptFiletype, CSTR_AS_OBJ(arg), OPT_LOCAL);
8034  if (arg != eap->arg) {
8035    curbuf->b_did_filetype = false;
8036  }
8037}
8038
8039static void ex_digraphs(exarg_T *eap)
8040{
8041  if (*eap->arg != NUL) {
8042    putdigraph(eap->arg);
8043  } else {
8044    listdigraphs(eap->forceit);
8045  }
8046}
8047
8048void set_no_hlsearch(bool flag)
8049{
8050  Search.no_hlsearch = flag;
8051  set_vim_var_nr(VV_HLSEARCH, !Search.no_hlsearch && p_hls);
8052}
8053
8054/// ":nohlsearch"
8055static void ex_nohlsearch(exarg_T *eap)
8056{
8057  set_no_hlsearch(true);
8058  redraw_all_later(UPD_SOME_VALID);
8059}
8060
8061static void ex_fold(exarg_T *eap)
8062{
8063  if (foldManualAllowed(true)) {
8064    pos_T start = { eap->line1, 1, 0 };
8065    pos_T end = { eap->line2, 1, 0 };
8066    foldCreate(curwin, start, end);
8067  }
8068}
8069
8070static void ex_foldopen(exarg_T *eap)
8071{
8072  pos_T start = { eap->line1, 1, 0 };
8073  pos_T end = { eap->line2, 1, 0 };
8074  opFoldRange(start, end, eap->cmdidx == CMD_foldopen, eap->forceit, false);
8075}
8076
8077static void ex_folddo(exarg_T *eap)
8078{
8079  // First set the marks for all lines closed/open.
8080  for (linenr_T lnum = eap->line1; lnum <= eap->line2; lnum++) {
8081    if (hasFolding(curwin, lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed)) {
8082      ml_setmarked(lnum);
8083    }
8084  }
8085
8086  global_exe(eap->arg);  // Execute the command on the marked lines.
8087  ml_clearmarked();      // clear rest of the marks
8088}
8089
8090/// @return  true if the supplied Ex cmdidx is for a location list command
8091///          instead of a quickfix command.
8092bool is_loclist_cmd(int cmdidx)
8093  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
8094{
8095  if (cmdidx < 0 || cmdidx >= CMD_SIZE) {
8096    return false;
8097  }
8098  return cmdnames[cmdidx].cmd_name[0] == 'l';
8099}
8100
8101/// ":checkhealth [plugins]"
8102static void ex_checkhealth(exarg_T *eap)
8103{
8104  // Suppress the Lua error (E5108) so the VIMRUNTIME diagnostic is the primary error.
8105  emsg_off++;
8106  bool ok = nlua_call_excmd("vim.health", "_check", eap, &cmdmod, NULL);
8107  emsg_off--;
8108  if (ok) {
8109    return;
8110  }
8111
8112  char *vimruntime_env = os_getenv_noalloc("VIMRUNTIME");
8113  if (!vimruntime_env) {
8114    emsg(_("E5009: $VIMRUNTIME is empty or unset"));
8115  } else {
8116    bool rtp_ok = NULL != strstr(p_rtp, vimruntime_env);
8117    if (rtp_ok) {
8118      semsg(_("E5009: Invalid $VIMRUNTIME: %s"), vimruntime_env);
8119    } else {
8120      emsg(_("E5009: Invalid 'runtimepath'"));
8121    }
8122  }
8123}
8124
8125static void ex_terminal(exarg_T *eap)
8126{
8127  const int scroll_save = msg_scroll;
8128  msg_scroll = false;
8129  autowrite_all();
8130  msg_scroll = scroll_save;
8131
8132  if (*eap->arg != NUL) {
8133    nlua_call_excmd("vim._core.ex_cmd", "ex_terminal", eap, &cmdmod, NULL);
8134  } else {
8135    // No cmd given, run 'shell'.
8136    if (*p_sh == NUL) {
8137      emsg(_(e_shellempty));
8138      return;
8139    }
8140    // Tokenize 'shell' via shell_build_argv (handles quoting) and pass as arg2.
8141    char **argv = shell_build_argv(NULL, NULL);
8142    typval_T shell_tv;
8143    tv_list_alloc_ret(&shell_tv, 0);
8144    for (char **p = argv; *p; p++) {
8145      tv_list_append_allocated_string(shell_tv.vval.v_list, *p);
8146    }
8147    xfree(argv);
8148    nlua_call_excmd("vim._core.ex_cmd", "ex_terminal", eap, &cmdmod, &shell_tv);
8149    tv_clear(&shell_tv);
8150  }
8151}
8152
8153/// ":log {name}"
8154static void ex_log(exarg_T *eap)
8155{
8156  nlua_call_excmd("vim._core.ex_cmd", "ex_log", eap, &cmdmod, NULL);
8157}
8158
8159/// ":lsp {subcmd} {clients}"
8160static void ex_lsp(exarg_T *eap)
8161{
8162  nlua_call_excmd("vim._core.ex_cmd", "ex_lsp", eap, &cmdmod, NULL);
8163}
8164
8165/// ":packdel {name}"
8166static void ex_packdel(exarg_T *eap)
8167{
8168  nlua_call_excmd("vim._core.ex_cmd", "ex_packdel", eap, &cmdmod, NULL);
8169}
8170
8171/// ":packupdate {name}"
8172static void ex_packupdate(exarg_T *eap)
8173{
8174  nlua_call_excmd("vim._core.ex_cmd", "ex_packupdate", eap, &cmdmod, NULL);
8175}
8176
8177/// ":uptime"
8178static void ex_uptime(exarg_T *eap)
8179{
8180  nlua_call_excmd("vim._core.ex_cmd", "ex_uptime", eap, &cmdmod, NULL);
8181}
8182
8183/// ":fclose"
8184static void ex_fclose(exarg_T *eap)
8185{
8186  win_float_remove(eap->forceit, eap->line1);
8187}
8188
8189void verify_command(char *cmd)
8190{
8191  if (strcmp("smile", cmd) != 0) {
8192    return;  // acceptable non-existing command
8193  }
8194  int a = HLF_E;
8195  msg(" #xxn`          #xnxx`        ,+x@##@Mz;`        .xxx"
8196      "xxxxxxnz+,      znnnnnnnnnnnnnnnn.", a);
8197  msg(" n###z          x####`      :x##########W+`      ,###"
8198      "##########M;    W################.", a);
8199  msg(" n####;         x####`    `z##############W:     ,###"
8200      "#############   W################.", a);
8201  msg(" n####W.        x####`   ,W#################+    ,###"
8202      "##############  W################.", a);
8203  msg(" n#####n        x####`   @###################    ,###"
8204      "##############i W################.", a);
8205  msg(" n######i       x####`  .#########@W@########*   ,###"
8206      "##############W`W################.", a);
8207  msg(" n######@.      x####`  x######W*.  `;n#######:  ,###"
8208      "#x,,,,:*M######iW###@:,,,,,,,,,,,`", a);
8209  msg(" n#######n      x####` *######+`       :M#####M  ,###"
8210      "#n      `x#####xW###@`", a);
8211  msg(" n########*     x####``@####@;          `x#####i ,###"
8212      "#n       ,#####@W###@`", a);
8213  msg(" n########@     x####`*#####i            `M####M ,###"
8214      "#n        x#########@`", a);
8215  msg(" n#########     x####`M####z              :#####:,###"
8216      "#n        z#########@`", a);
8217  msg(" n#########*    x####,#####.               n####+,###"
8218      "#n        n#########@`", a);
8219  msg(" n####@####@,   x####i####x                ;####x,###"
8220      "#n       `W#####@####+++++++++++i", a);
8221  msg(" n####*#####M`  x#########*                `####@,###"
8222      "#n       i#####MW###############W", a);
8223  msg(" n####.######+  x####z####;                 W####,###"
8224      "#n      i@######W###############W", a);
8225  msg(" n####.`W#####: x####n####:                 M####:###"
8226      "#@nnnnnW#######,W###############W", a);
8227  msg(" n####. :#####M`x####z####;                 W####,###"
8228      "##############z W###############W", a);
8229  msg(" n####.  #######x#########*                `####W,###"
8230      "#############W` W###############W", a);
8231  msg(" n####.  `M#####W####i####x                ;####x,###"
8232      "############W,  W####+**********i", a);
8233  msg(" n####.   ,##########,#####.               n####+,###"
8234      "###########n.   W###@`", a);
8235  msg(" n####.    ##########`M####z              :#####:,###"
8236      "########Wz:     W###@`", a);
8237  msg(" n####.    x#########`*#####i            `M####M ,###"
8238      "#x.....`        W###@`", a);
8239  msg(" n####.    ,@########``@####@;          `x#####i ,###"
8240      "#n              W###@`", a);
8241  msg(" n####.     *########` *#####@+`       ,M#####M  ,###"
8242      "#n              W###@`", a);
8243  msg(" n####.      x#######`  x######W*.  `;n######@:  ,###"
8244      "#n              W###@,,,,,,,,,,,,`", a);
8245  msg(" n####.      .@######`  .#########@W@########*   ,###"
8246      "#n              W################,", a);
8247  msg(" n####.       i######`   @###################    ,###"
8248      "#n              W################,", a);
8249  msg(" n####.        n#####`   ,W#################+    ,###"
8250      "#n              W################,", a);
8251  msg(" n####.        .@####`    .n##############W;     ,###"
8252      "#n              W################,", a);
8253  msg(" n####.         i####`      :x##########W+`      ,###"
8254      "#n              W################,", a);
8255  msg(" +nnnn`          +nnn`        ,+x@##@Mz;`        .nnn"
8256      "n+              zxxxxxxxxxxxxxxxx.", a);
8257  msg(" ", a);
8258  msg("                                                     "
8259      "                              ,+M@#Mi", a);
8260  msg("                                 "
8261      "                                                .z########", a);
8262  msg("                                 "
8263      "                                               i@#########i", a);
8264  msg("                                 "
8265      "                                             `############W`", a);
8266  msg("                                 "
8267      "                                            `n#############i", a);
8268  msg("                                 "
8269      "                                           `n##############n", a);
8270  msg("     ``                          "
8271      "                                           z###############@`", a);
8272  msg("    `W@z,                        "
8273      "                                          ##################,", a);
8274  msg("    *#####`                      "
8275      "                                         i############@x@###i", a);
8276  msg("    ######M.                     "
8277      "                                        :#############n`,W##+", a);
8278  msg("    +######@:                    "
8279      "                                       .W#########M@##+  *##z", a);
8280  msg("    :#######@:                   "
8281      "                                      `x########@#x###*  ,##n", a);
8282  msg("    `@#######@;                  "
8283      "                                      z#########M*@nW#i  .##x", a);
8284  msg("     z########@i                 "
8285      "                                     *###########WM#@#,  `##x", a);
8286  msg("     i##########+                "
8287      "                                    ;###########*n###@   `##x", a);
8288  msg("     `@#MM#######x,              "
8289      "                                   ,@#########zM,`z##M   `@#x", a);
8290  msg("      n##M#W#######n.            "
8291      "   `.:i*+#zzzz##+i:.`             ,W#########Wii,`n@#@` n@##n", a);
8292  msg("      ;###@#x#######n         `,i"
8293      "#nW@#####@@WWW@@####@Mzi.        ,W##########@z.. ;zM#+i####z", a);
8294  msg("       x####nz########    .;#x@##"
8295      "@Wn#*;,.`      ``,:*#x@##M+,    ;@########xz@WM+#` `n@#######", a);
8296  msg("       ,@####M########xi#@##@Mzi,"
8297      "`                     .+x###Mi:n##########Mz```.:i  *@######*", a);
8298  msg("        *#####W#########ix+:`    "
8299      "                         :n#############z:       `*.`M######i", a);
8300  msg("        i#W##nW@+@##@#M@;        "
8301      "                           ;W@@##########W,        i`x@#####,", a);
8302  msg("        `@@n@Wn#@iMW*#*:         "
8303      "                            `iz#z@######x.           M######`", a);
8304  msg("         z##zM###x`*, .`         "
8305      "                                 `iW#####W;:`        +#####M", a);
8306  msg("         ,###nn##n`              "
8307      "                                  ,#####x;`        ,;@######", a);
8308  msg("          x###xz#.               "
8309      "                                    in###+        `:######@.", a);
8310  msg("          ;####n+                "
8311      "                                    `Mnx##xi`   , zM#######", a);
8312  msg("          `W####+                "
8313      "i.                                   `.+x###@#. :n,z######:", a);
8314  msg("           z####@`              ;"
8315      "#:                                     .ii@###@;.*M*z####@`", a);
8316  msg("           i####M         `   `i@"
8317      "#,           ::                           +#n##@+@##W####n", a);
8318  msg("           :####x    ,i. ##xzM###"
8319      "@`     i.   .@@,                           .z####x#######*", a);
8320  msg("           ,###W;   i##Wz########"
8321      "#     :##   z##n                           ,@########x###:", a);
8322  msg("            n##n   `W###########M"
8323      "`;n,  i#x  ,###@i                           *W########W#@`", a);
8324  msg("           .@##+  `x###########@."
8325      " z#+ .M#W``x#####n`                         `;#######@z#x", a);
8326  msg("           n###z :W############@ "
8327      " z#*  @##xM#######@n;                        `########nW+", a);
8328  msg("          ;####nW##############W "
8329      ":@#* `@#############*                        :########z@i`", a);
8330  msg("          M##################### "
8331      "M##:  @#############@:                       *W########M#", a);
8332  msg("         ;#####################i."
8333      "##x`  W#############W,                       :n########zx", a);
8334  msg("         x####################@.`"
8335      "x;    @#############z.                       .@########W#", a);
8336  msg("        ,######################` "
8337      "      W###############x*,`                    W######zM#i", a);
8338  msg("        #######################: "
8339      "      z##################@x+*#zzi            `@#########.", a);
8340  msg("        W########W#z#M#########; "
8341      "      *##########################z            :@#######@`", a);
8342  msg("       `@#######x`;#z ,x#######; "
8343      "      z###########M###xnM@########*            :M######@", a);
8344  msg("       i########, x#@`  z######; "
8345      "      *##########i *#@`  `+########+`            n######.", a);
8346  msg("       n#######@` M##,  `W#####. "
8347      "      *#########z  ###;    z########M:           :W####n", a);
8348  msg("       M#######M  n##.   x####x  "
8349      "      `x########:  z##+    M#########@;           .n###+", a);
8350  msg("       W#######@` :#W   `@####:  "
8351      "       `@######W   i###   ;###########@.            n##n", a);
8352  msg("       W########z` ,,  .x####z   "
8353      "        @######@`  `W#;  `W############*            *###;", a);
8354  msg("      `@#########Mi,:*n@####W`   "
8355      "        W#######*   ..  `n#############i            i###x", a);
8356  msg("      .#####################z    "
8357      "       `@#######@*`    .x############n:`            ;####.", a);
8358  msg("      :####################x`,,` "
8359      "       `W#########@x#+#@#############i              ,####:", a);
8360  msg("      ;###################x#@###x"
8361      "i`      *############################:              `####i", a);
8362  msg("      i##################+#######"
8363      "#M,      x##########################@`               W###i", a);
8364  msg("      *################@; @######"
8365      "##@,     .W#########################@                x###:", a);
8366  msg("      .+M#############z.  M######"
8367      "###x      ,W########################@`               ####.", a);
8368  msg("      *M*;z@########x:    :W#####"
8369      "##i        .M########################i               i###:", a);
8370  msg("      *##@z;#@####x:        :z###"
8371      "@i          `########################x               .###;", a);
8372  msg("      *#####n;#@##            ;##"
8373      "*             ,x#####################@`               W##*", a);
8374  msg("      *#######n;*            :M##"
8375      "W*,             *W####################`               n##z", a);
8376  msg("      i########@.         ,*n####"
8377      "###M*`           `###################M                *##M", a);
8378  msg("      i########n        `z#####@@"
8379      "#####Wi            ,M################;                ,##@`", a);
8380  msg("      ;WMWW@###*       .x##@ni.``"
8381      ".:+zW##z`           `n##############z                  @##,", a);
8382  msg("      .*++*i;;;.      .M#@+`     "
8383      "     .##n            `x############x`                  n##i", a);
8384  msg("      :########*      x#W,       "
8385      "       *#+            *###########M`                   +##+", a);
8386  msg("      ,#########     :#@:        "
8387      "        ##:           #nzzzzzzzzzz.                    :##x", a);
8388  msg("      .#####Wz+`     ##+         "
8389      "        `MM`          .znnnnnnnnn.                     `@#@`", a);
8390  msg("      `@@ni;*nMz`    @W`         "
8391      "         :#+           .x#######n                       x##,", a);
8392  msg("       i;z@#####,   .#*          "
8393      "          z#:           ;;;*zW##;                       ###i", a);
8394  msg("       z########:   :#;          "
8395      "          `Wx          +###Wni;n.                       ;##z", a);
8396  msg("       n########W:  .#*          "
8397      "           ,#,        ;#######@+                        `@#M", a);
8398  msg("      .###########n;.MM          "
8399      "            n*        ;iM#######*                        x#@`", a);
8400  msg("      :#############@;;          "
8401      "            .n`      ,#W*iW#####W`                       +##,", a);
8402  msg("      ,##############.           "
8403      "             ix.    `x###M;#######                       ,##i", a);
8404  msg("      .#############@`           "
8405      "              x@n**#W######z;M###@.                       W##", a);
8406  msg("      .##############W:          "
8407      "              .x############@*;zW#;                       z#x", a);
8408  msg("      ,###############@;         "
8409      "               `##############@n*;.                       i#@", a);
8410  msg("      ,#################i        "
8411      "                 :n##############W`                       .##,", a);
8412  msg("      ,###################`      "
8413      "                   .+W##########W,                        `##i", a);
8414  msg("      :###################@zi,`  "
8415      "                      ;zM@@@WMn*`                          @#z", a);
8416  msg("      :#######################@x+"
8417      "*i;;:i#M,                 ``                               M#W", a);
8418  msg("      ;##########################"
8419      "######@x.                                                  n##,", a);
8420  msg("      i#####################@W@@@"
8421      "@Wxz*:`                                                    *##+", a);
8422  msg("      *######################+```"
8423      "                                                           :##M", a);
8424  msg("      ########################M; "
8425      "                                                           `@##,", a);
8426  msg("      z#########################x"
8427      ",                                                           z###", a);
8428  msg("      n##########################"
8429      "#n:                                                         ;##W`", a);
8430  msg("      x##########################"
8431      "###Mz#++##*                                                 `W##i", a);
8432  msg("      M##########################"
8433      "##########@`                                                 ###x", a);
8434  msg("      W##########################"
8435      "###########`                                                 .###,", a);
8436  msg("      @##########################"
8437      "##########M                                                   n##z", a);
8438  msg("      @##################z*i@WMMM"
8439      "x#x@#####,.                                                   :##@.", a);
8440  msg("     `#####################@xi`  "
8441      "   `::,*                                                       x##+", a);
8442  msg("     .#####################@#M.  "
8443      "                                                               ;##@`", a);
8444  msg("     ,#####################:.    "
8445      "                                                                M##i", a);
8446  msg("     ;###################ni`     "
8447      "                                                                i##M", a);
8448  msg("     *#################W#`       "
8449      "                                                                `W##,", a);
8450  msg("     z#################@Wx+.     "
8451      "                                                                 +###", a);
8452  msg("     x######################z.   "
8453      "                                                                 .@#@`", a);
8454  msg("    `@#######################@;  "
8455      "                                                                  z##;", a);
8456  msg("    :##########################: "
8457      "                                                                  :##z", a);
8458  msg("    +#########################W# "
8459      "                                                                   M#W", a);
8460  msg("    W################@n+*i;:,`                                "
8461      "                                      +##,", a);
8462  msg("   :##################WMxz+,                                  "
8463      "                                      ,##i", a);
8464  msg("   n#######################W..,                               "
8465      "                                       W##", a);
8466  msg("  +#########################WW@+. .:.                         "
8467      "                                       z#x", a);
8468  msg(" `@#############################@@###:                        "
8469      "                                       *#W", a);
8470  msg(" #################################Wz:                         "
8471      "                                       :#@", a);
8472  msg(",@###############################i                            "
8473      "                                       .##", a);
8474  msg("n@@@@@@@#########################+                            "
8475      "                                       `##", a);
8476  msg("`      `.:.`.,:iii;;;;;;;;iii;;;:`       `.``                 "
8477      "                                       `nW", a);
8478}
8479
8480/// Check if a command is a :map/:abbrev command.
8481bool is_map_cmd(cmdidx_T cmdidx)
8482{
8483  if (IS_USER_CMDIDX(cmdidx)) {
8484    return false;
8485  }
8486
8487  ex_func_T func = cmdnames[cmdidx].cmd_func;
8488  return func == ex_map           // :map, :nmap, :noremap, etc.
8489         || func == ex_unmap         // :unmap, :nunmap, etc.
8490         || func == ex_mapclear      // :mapclear, :nmapclear, etc.
8491         || func == ex_abbreviate    // :abbreviate, :iabbrev, etc.
8492         || func == ex_abclear;      // :abclear, :iabclear, etc.
8493}