robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
137.5 KiB4723 linesraw
1// ex_getln.c: Functions for entering and editing an Ex command line.
2
3#include <assert.h>
4#include <inttypes.h>
5#include <limits.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <time.h>
11
12#include "klib/kvec.h"
13#include "nvim/api/extmark.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/helpers.h"
16#include "nvim/api/vim.h"
17#include "nvim/ascii_defs.h"
18#include "nvim/autocmd.h"
19#include "nvim/autocmd_defs.h"
20#include "nvim/buffer.h"
21#include "nvim/buffer_defs.h"
22#include "nvim/charset.h"
23#include "nvim/clipboard.h"
24#include "nvim/cmdexpand.h"
25#include "nvim/cmdexpand_defs.h"
26#include "nvim/cmdhist.h"
27#include "nvim/context.h"
28#include "nvim/cursor.h"
29#include "nvim/digraph.h"
30#include "nvim/drawscreen.h"
31#include "nvim/errors.h"
32#include "nvim/eval.h"
33#include "nvim/eval/typval.h"
34#include "nvim/eval/vars.h"
35#include "nvim/event/defs.h"
36#include "nvim/event/loop.h"
37#include "nvim/event/multiqueue.h"
38#include "nvim/ex_cmds.h"
39#include "nvim/ex_cmds_defs.h"
40#include "nvim/ex_docmd.h"
41#include "nvim/ex_eval.h"
42#include "nvim/ex_getln.h"
43#include "nvim/extmark.h"
44#include "nvim/garray.h"
45#include "nvim/garray_defs.h"
46#include "nvim/gettext_defs.h"
47#include "nvim/globals.h"
48#include "nvim/highlight_defs.h"
49#include "nvim/highlight_group.h"
50#include "nvim/input.h"
51#include "nvim/input_cmdatom.h"
52#include "nvim/insert.h"
53#include "nvim/keycodes.h"
54#include "nvim/lua/executor.h"
55#include "nvim/macros_defs.h"
56#include "nvim/main.h"
57#include "nvim/map_defs.h"
58#include "nvim/mapping.h"
59#include "nvim/mark.h"
60#include "nvim/mark_defs.h"
61#include "nvim/mbyte.h"
62#include "nvim/memline.h"
63#include "nvim/memory.h"
64#include "nvim/memory_defs.h"
65#include "nvim/message.h"
66#include "nvim/mouse.h"
67#include "nvim/move.h"
68#include "nvim/normal.h"
69#include "nvim/ops.h"
70#include "nvim/option.h"
71#include "nvim/option_defs.h"
72#include "nvim/option_vars.h"
73#include "nvim/os/input.h"
74#include "nvim/os/os.h"
75#include "nvim/path.h"
76#include "nvim/popupmenu.h"
77#include "nvim/pos_defs.h"
78#include "nvim/profile.h"
79#include "nvim/regexp.h"
80#include "nvim/regexp_defs.h"
81#include "nvim/register.h"
82#include "nvim/search.h"
83#include "nvim/state.h"
84#include "nvim/state_defs.h"
85#include "nvim/strings.h"
86#include "nvim/types_defs.h"
87#include "nvim/ui.h"
88#include "nvim/ui_defs.h"
89#include "nvim/undo.h"
90#include "nvim/undo_defs.h"
91#include "nvim/usercmd.h"
92#include "nvim/vim_defs.h"
93#include "nvim/viml/parser/expressions.h"
94#include "nvim/viml/parser/parser.h"
95#include "nvim/viml/parser/parser_defs.h"
96#include "nvim/window.h"
97
98/// Last value of prompt_id, incremented when doing new prompt
99static unsigned last_prompt_id = 0;
100
101// Struct to store the state of 'incsearch' highlighting.
102typedef struct {
103  pos_T search_start;   // where 'incsearch' starts searching
104  pos_T save_cursor;
105  handle_T winid;       // window where this state is valid
106  viewstate_T init_viewstate;
107  viewstate_T old_viewstate;
108  pos_T match_start;
109  pos_T match_end;
110  bool did_incsearch;
111  bool incsearch_postponed;
112} incsearch_state_T;
113
114typedef struct {
115  VimState state;
116  int firstc;
117  int count;
118  int indent;
119  int c;
120  bool gotesc;                          // true when <ESC> just typed
121  bool do_abbr;                         // when true check for abbr.
122  char *lookfor;                        // string to match
123  int lookforlen;
124  int hiscnt;                           // current history line in use
125  int save_hiscnt;                      // history line before attempting
126                                        // to jump to next match
127  int histype;                          // history type to be used
128  incsearch_state_T is_state;
129  bool did_wild_list;                   // did wild_list() recently
130  int wim_index;                        // index in wim_flags[]
131  int save_msg_scroll;
132  int save_State;                       // remember State when called
133  int prev_cmdpos;
134  char *prev_cmdbuff;
135  char *save_p_icm;
136  bool skip_pum_redraw;
137  bool some_key_typed;                  // one of the keys was typed
138  // mouse drag and release events are ignored, unless they are
139  // preceded with a mouse down event
140  bool ignore_drag_release;
141  bool break_ctrl_c;
142  expand_T xpc;
143  OptInt *b_im_ptr;
144  buf_T *b_im_ptr_buf;  ///< buffer where b_im_ptr is valid
145  int cmdline_type;
146  bool event_cmdlineleavepre_triggered;
147  bool did_hist_navigate;
148} CommandLineState;
149
150typedef struct {
151  buf_T *buf;
152  int save_b_p_ma;
153  int save_b_changed;
154  pos_T save_b_op_start;
155  pos_T save_b_op_end;
156  UndoCheckpoint undo_checkpoint;
157} CpBufInfo;
158
159typedef struct {
160  win_T *win;
161  pos_T save_w_cursor;
162  viewstate_T save_viewstate;
163  int save_w_p_cul;
164  int save_w_p_cuc;
165} CpWinInfo;
166
167typedef struct {
168  kvec_t(CpWinInfo) win_info;
169  kvec_t(CpBufInfo) buf_info;
170  bool save_hls;
171  cmdmod_T save_cmdmod;
172  garray_T save_view;
173} CpInfo;
174
175/// Return value when handling keys in command-line mode.
176enum {
177  CMDLINE_NOT_CHANGED = 1,
178  CMDLINE_CHANGED     = 2,
179  GOTO_NORMAL_MODE    = 3,
180  PROCESS_NEXT_KEY    = 4,
181};
182
183/// The current cmdline_info.  It is initialized in getcmdline() and after that
184/// used by other functions.  When invoking getcmdline() recursively it needs
185/// to be saved with save_cmdline() and restored with restore_cmdline().
186static CmdlineInfo ccline;
187
188static int new_cmdpos;          // position set by set_cmdline_pos()
189
190/// currently displayed block of context
191static Array cmdline_block = ARRAY_DICT_INIT;
192
193/// Flag for command_line_handle_key to ignore <C-c>
194///
195/// Used if it was received while processing highlight function in order for
196/// user interrupting highlight function to not interrupt command-line.
197static bool getln_interrupted_highlight = false;
198
199static int cedit_key = -1;  ///< key value of 'cedit' option
200
201#include "ex_getln.c.generated.h"
202
203static handle_T cmdpreview_bufnr = 0;
204static int cmdpreview_ns = 0;
205
206static void trigger_cmd_autocmd(int typechar, event_T evt)
207{
208  char typestr[2] = { (char)typechar, NUL };
209  apply_autocmds(evt, typestr, typestr, false, curbuf);
210}
211
212static void init_incsearch_state(incsearch_state_T *s)
213{
214  s->winid = curwin->handle;
215  s->match_start = curwin->w_cursor;
216  s->did_incsearch = false;
217  s->incsearch_postponed = false;
218  clearpos(&s->match_end);
219  s->save_cursor = curwin->w_cursor;  // may be restored later
220  s->search_start = curwin->w_cursor;
221  save_viewstate(curwin, &s->init_viewstate);
222  save_viewstate(curwin, &s->old_viewstate);
223}
224
225static void set_search_match(pos_T *t)
226{
227  // First move cursor to end of match, then to the start.  This
228  // moves the whole match onto the screen when 'nowrap' is set.
229  t->lnum += Search.match_lines;
230  t->col = Search.match_endcol;
231  if (t->lnum > curbuf->b_ml.ml_line_count) {
232    t->lnum = curbuf->b_ml.ml_line_count;
233    coladvance(curwin, MAXCOL);
234  }
235}
236
237/// Parses the :[range]s/foo like commands and returns details needed for
238/// incsearch and wildmenu completion.
239/// Returns true if pattern is valid.
240/// Sets skiplen, patlen, Search.first_line, and Search.last_line and magic if overruled.
241bool parse_pattern_and_range(pos_T *incsearch_start, int *search_delim, int *skiplen, int *patlen,
242                             bool *is_magic)
243  FUNC_ATTR_NONNULL_ALL
244{
245  char *p;
246  bool delim_optional = false;
247  const char *dummy;
248  magic_T magic = 0;
249
250  *skiplen = 0;
251  *patlen = ccline.cmdlen;
252
253  // Default range
254  Search.first_line = 0;
255  Search.last_line = MAXLNUM;
256
257  exarg_T ea = {
258    .line1 = 1,
259    .line2 = 1,
260    .cmd = ccline.cmdbuff,
261    .addr_type = ADDR_LINES,
262  };
263
264  cmdmod_T dummy_cmdmod;
265  // Skip over command modifiers
266  parse_command_modifiers(&ea, &dummy, &dummy_cmdmod, true);
267
268  // Skip over the range to find the command.
269  char *cmd = skip_range(ea.cmd, NULL);
270  if (vim_strchr("sgvlu", (uint8_t)(*cmd)) == NULL) {
271    return false;
272  }
273
274  // Skip over command name to find pattern separator
275  for (p = cmd; ASCII_ISALPHA(*p); p++) {}
276  if (*skipwhite(p) == NUL) {
277    return false;
278  }
279
280  if (strncmp(cmd, "substitute", (size_t)(p - cmd)) == 0
281      || strncmp(cmd, "smagic", (size_t)(p - cmd)) == 0
282      || strncmp(cmd, "snomagic", (size_t)MAX(p - cmd, 3)) == 0
283      || strncmp(cmd, "vglobal", (size_t)(p - cmd)) == 0) {
284    if (*cmd == 's' && cmd[1] == 'm') {
285      *is_magic = true;
286    } else if (*cmd == 's' && cmd[1] == 'n') {
287      *is_magic = false;
288    }
289  } else if (strncmp(cmd, "sort", (size_t)MAX(p - cmd, 3)) == 0
290             || strncmp(cmd, "uniq", (size_t)MAX(p - cmd, 3)) == 0) {
291    // skip over ! and flags
292    if (*p == '!') {
293      p = skipwhite(p + 1);
294    }
295    while (ASCII_ISALPHA(*(p = skipwhite(p)))) {
296      p++;
297    }
298    if (*p == NUL) {
299      return false;
300    }
301  } else if (strncmp(cmd, "vimgrep", (size_t)MAX(p - cmd, 3)) == 0
302             || strncmp(cmd, "vimgrepadd", (size_t)MAX(p - cmd, 8)) == 0
303             || strncmp(cmd, "lvimgrep", (size_t)MAX(p - cmd, 2)) == 0
304             || strncmp(cmd, "lvimgrepadd", (size_t)MAX(p - cmd, 9)) == 0
305             || strncmp(cmd, "global", (size_t)(p - cmd)) == 0) {
306    // skip optional "!"
307    if (*p == '!') {
308      p++;
309      if (*skipwhite(p) == NUL) {
310        return false;
311      }
312    }
313    if (*cmd != 'g') {
314      delim_optional = true;
315    }
316  } else {
317    return false;
318  }
319
320  p = skipwhite(p);
321  int delim = (delim_optional && vim_isIDc((uint8_t)(*p))) ? ' ' : *p++;
322  *search_delim = delim;
323
324  char *end = skip_regexp_ex(p, delim, *is_magic, NULL, NULL, &magic);
325  bool use_last_pat = end == p && *end == delim;
326
327  if (end == p && !use_last_pat) {
328    return false;
329  }
330
331  // Skip if the pattern matches everything (e.g., for 'hlsearch')
332  if (!use_last_pat) {
333    char c = *end;
334    *end = NUL;
335    bool empty = empty_pattern_magic(p, (size_t)(end - p), magic);
336    *end = c;
337    if (empty) {
338      return false;
339    }
340  }
341
342  // Found a non-empty pattern or //
343  *skiplen = (int)(p - ccline.cmdbuff);
344  *patlen = (int)(end - p);
345
346  // Parse the address range
347  pos_T save_cursor = curwin->w_cursor;
348  curwin->w_cursor = *incsearch_start;
349
350  parse_cmd_address(&ea, &dummy, true);
351
352  if (ea.addr_count > 0) {
353    // Allow for reverse match.
354    Search.first_line = MIN(ea.line2, ea.line1);
355    Search.last_line = MAX(ea.line2, ea.line1);
356  } else if (cmd[0] == 's' && cmd[1] != 'o') {
357    // :s defaults to the current line
358    Search.first_line = Search.last_line = curwin->w_cursor.lnum;
359  }
360
361  curwin->w_cursor = save_cursor;
362  return true;
363}
364
365/// Return true when 'incsearch' highlighting is to be done.
366/// Sets Search.first_line and Search.last_line to the address range.
367/// May change the last search pattern.
368static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_state_T *is_state,
369                                      int *skiplen, int *patlen, bool *magic)
370{
371  bool retval = false;
372
373  *skiplen = 0;
374  *patlen = ccline.cmdlen;
375
376  if (!p_is || cmd_silent) {
377    return false;
378  }
379
380  // By default search all lines
381  Search.first_line = 0;
382  Search.last_line = MAXLNUM;
383
384  if (firstc == '/' || firstc == '?') {
385    *search_delim = firstc;
386    return true;
387  }
388
389  if (firstc != ':') {
390    return false;
391  }
392
393  emsg_off++;
394  retval = parse_pattern_and_range(&is_state->search_start, search_delim,
395                                   skiplen, patlen, magic);
396  emsg_off--;
397
398  return retval;
399}
400
401// May do 'incsearch' highlighting if desired.
402static void may_do_incsearch_highlighting(int firstc, int count, incsearch_state_T *s)
403{
404  int skiplen, patlen;
405  int search_delim;
406  bool magic = p_magic;
407
408  // Parsing range may already set the last search pattern.
409  // NOTE: must call restore_last_search_pattern() before returning!
410  save_last_search_pattern();
411
412  if (!do_incsearch_highlighting(firstc, &search_delim, s, &skiplen, &patlen, &magic)) {
413    restore_last_search_pattern();
414    finish_incsearch_highlighting(false, s, true);
415    return;
416  }
417
418  // if there is a character waiting, search and redraw later
419  if (char_avail()) {
420    restore_last_search_pattern();
421    s->incsearch_postponed = true;
422    return;
423  }
424  s->incsearch_postponed = false;
425
426  // Use the previous pattern for ":s//".
427  char next_char = ccline.cmdbuff[skiplen + patlen];
428  bool use_last_pat = patlen == 0 && skiplen > 0
429                      && ccline.cmdbuff[skiplen - 1] == next_char;
430
431  if (patlen != 0 || use_last_pat) {
432    ui_busy_start();
433    ui_flush();
434  }
435
436  if (Search.first_line == 0) {
437    // start at the original cursor position
438    curwin->w_cursor = s->search_start;
439  } else if (Search.first_line > curbuf->b_ml.ml_line_count) {
440    // start after the last line
441    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
442    curwin->w_cursor.col = MAXCOL;
443  } else {
444    // start at the first line in the range
445    curwin->w_cursor.lnum = Search.first_line;
446    curwin->w_cursor.col = 0;
447  }
448
449  int found = 0;  // do_search() result
450
451  if (patlen != 0 || use_last_pat) {
452    int search_flags = SEARCH_OPT + SEARCH_NOOF + SEARCH_PEEK;
453    if (!p_hls) {
454      search_flags += SEARCH_KEEP;
455    }
456    if (Search.first_line != 0) {
457      search_flags += SEARCH_START;
458    }
459    // Set the time limit to half a second.
460    proftime_T tm = profile_setlimit(500);
461    searchit_arg_T sia = { .sa_tm = &tm };
462    ccline.cmdbuff[skiplen + patlen] = NUL;
463    emsg_off++;            // So it doesn't beep if bad expr
464    found = do_search(NULL, firstc == ':' ? '/' : firstc, search_delim,
465                      ccline.cmdbuff + skiplen, (size_t)patlen, count,
466                      search_flags, magic, &sia);
467    emsg_off--;
468    ccline.cmdbuff[skiplen + patlen] = next_char;
469    if (curwin->w_cursor.lnum < Search.first_line
470        || curwin->w_cursor.lnum > Search.last_line) {
471      // match outside of address range
472      found = 0;
473      curwin->w_cursor = s->search_start;
474    }
475
476    // if interrupted while searching, behave like it failed
477    if (got_int) {
478      vpeekc();               // remove <C-C> from input stream
479      got_int = false;              // don't abandon the command line
480      found = 0;
481    } else if (char_avail()) {
482      // cancelled searching because a char was typed
483      s->incsearch_postponed = true;
484    }
485    ui_busy_stop();
486  } else {
487    set_no_hlsearch(true);  // turn off previous highlight
488    redraw_all_later(UPD_SOME_VALID);
489  }
490
491  Search.hl_match = found != 0;  // add or remove search match position
492
493  // first restore the old curwin values, so the screen is
494  // positioned in the same way as the actual search command
495  restore_viewstate(curwin, &s->old_viewstate);
496  changed_cline_bef_curs(curwin);
497  update_topline(curwin);
498
499  pos_T end_pos = curwin->w_cursor;
500  if (found != 0) {
501    s->match_start = curwin->w_cursor;
502    set_search_match(&curwin->w_cursor);
503    validate_cursor(curwin);
504    s->match_end = curwin->w_cursor;
505    curwin->w_cursor = end_pos;
506    end_pos = s->match_end;
507  }
508
509  // Disable 'hlsearch' highlighting if the pattern matches
510  // everything. Avoids a flash when typing "foo\|".
511  if (!use_last_pat) {
512    next_char = ccline.cmdbuff[skiplen + patlen];
513    ccline.cmdbuff[skiplen + patlen] = NUL;
514    if (empty_pattern(ccline.cmdbuff + skiplen, (size_t)patlen, search_delim)
515        && !Search.no_hlsearch) {
516      redraw_all_later(UPD_SOME_VALID);
517      set_no_hlsearch(true);
518    }
519    ccline.cmdbuff[skiplen + patlen] = next_char;
520  }
521
522  validate_cursor(curwin);
523
524  // May redraw the status line to show the cursor position.
525  if (p_ru && (curwin->w_status_height > 0 || global_stl_height() > 0)) {
526    curwin->w_redr_status = true;
527  }
528
529  redraw_later(curwin, UPD_SOME_VALID);
530  update_screen();
531  Search.hl_match = false;
532  restore_last_search_pattern();
533
534  // Leave it at the end to make CTRL-R CTRL-W work.  But not when beyond the
535  // end of the pattern, e.g. for ":s/pat/".
536  if (ccline.cmdbuff[skiplen + patlen] != NUL) {
537    curwin->w_cursor = s->search_start;
538  } else if (found != 0) {
539    curwin->w_cursor = end_pos;
540    curwin->w_valid_cursor = end_pos;  // mark as valid for cmdline_show redraw
541  }
542
543  msg_starthere();
544  redrawcmdline();
545  s->did_incsearch = true;
546  // Fire WinScrolled/WinResized last, after all state is finalized: the
547  // autocmd may mutate curwin or ccline via arbitrary user code.
548  may_trigger_win_scrolled_resized();
549}
550
551// When CTRL-L typed: add character from the match to the pattern.
552// May set "*c" to the added character.
553// Return OK when calling command_line_not_changed.
554static int may_add_char_to_search(int firstc, int *c, incsearch_state_T *s)
555  FUNC_ATTR_NONNULL_ALL
556{
557  int skiplen, patlen;
558  int search_delim;
559  bool magic = p_magic;
560
561  // Parsing range may already set the last search pattern.
562  // NOTE: must call restore_last_search_pattern() before returning!
563  save_last_search_pattern();
564
565  // Add a character from under the cursor for 'incsearch'
566  if (!do_incsearch_highlighting(firstc, &search_delim, s, &skiplen,
567                                 &patlen, &magic)) {
568    restore_last_search_pattern();
569    return FAIL;
570  }
571  restore_last_search_pattern();
572
573  if (s->did_incsearch) {
574    curwin->w_cursor = s->match_end;
575    *c = gchar_cursor();
576    if (*c != NUL) {
577      // If 'ignorecase' and 'smartcase' are set and the
578      // command line has no uppercase characters, convert
579      // the character to lowercase
580      if (p_ic && p_scs
581          && !pat_has_uppercase(ccline.cmdbuff + skiplen)) {
582        *c = mb_tolower(*c);
583      }
584      if (*c == search_delim
585          || vim_strchr((p_magic ? "\\~^$.*[" : "\\^$"), *c) != NULL) {
586        // put a backslash before special characters
587        stuffcharReadbuff(*c);
588        *c = '\\';
589      }
590      // add any composing characters
591      if (utf_char2len(*c) != utfc_ptr2len(get_cursor_pos_ptr())) {
592        const int save_c = *c;
593        while (utf_char2len(*c) != utfc_ptr2len(get_cursor_pos_ptr())) {
594          curwin->w_cursor.col += utf_char2len(*c);
595          *c = gchar_cursor();
596          stuffcharReadbuff(*c);
597        }
598        *c = save_c;
599      }
600      return FAIL;
601    }
602  }
603  return OK;
604}
605
606static void finish_incsearch_highlighting(bool gotesc, incsearch_state_T *s,
607                                          bool call_update_screen)
608{
609  if (!s->did_incsearch) {
610    return;
611  }
612
613  s->did_incsearch = false;
614  if (gotesc) {
615    curwin->w_cursor = s->save_cursor;
616  } else {
617    if (!equalpos(s->save_cursor, s->search_start)) {
618      // put the '" mark at the original position
619      curwin->w_cursor = s->save_cursor;
620      setpcmark();
621    }
622    curwin->w_cursor = s->search_start;
623  }
624  restore_viewstate(curwin, &s->old_viewstate);
625  Search.hl_match = false;
626
627  // by default search all lines
628  Search.first_line = 0;
629  Search.last_line = MAXLNUM;
630
631  validate_cursor(curwin);          // needed for TAB
632  status_redraw_all();
633  redraw_all_later(UPD_SOME_VALID);
634  if (call_update_screen) {
635    update_screen();
636    may_trigger_win_scrolled_resized();
637  }
638}
639
640/// Initialize the current command-line info.
641static void init_ccline(int firstc, int indent)
642{
643  ccline.overstrike = false;                // always start in insert mode
644
645  assert(indent >= 0);
646
647  // set some variables for redrawcmd()
648  ccline.cmdfirstc = (firstc == '@' ? 0 : firstc);
649  ccline.cmdindent = (firstc > 0 ? indent : 0);
650
651  // alloc initial ccline.cmdbuff
652  alloc_cmdbuff(indent + 50);
653  ccline.cmdlen = ccline.cmdpos = 0;
654  ccline.cmdbuff[0] = NUL;
655
656  ccline.last_colors = (ColoredCmdline){ .cmdbuff = NULL,
657                                         .colors = KV_INITIAL_VALUE };
658  sb_text_start_cmdline();
659
660  // autoindent for :insert and :append
661  if (firstc <= 0) {
662    memset(ccline.cmdbuff, ' ', (size_t)indent);
663    ccline.cmdbuff[indent] = NUL;
664    ccline.cmdpos = indent;
665    ccline.cmdspos = indent;
666    ccline.cmdlen = indent;
667  }
668}
669
670static void ui_ext_cmdline_hide(bool abort)
671{
672  if (ui_has(kUICmdline)) {
673    cmdline_was_last_drawn = false;
674    ccline.redraw_state = kCmdRedrawNone;
675    ui_call_cmdline_hide(ccline.level, abort);
676  }
677}
678
679/// Internal entry point for cmdline mode.
680///
681/// @param count  only used for incremental search
682/// @param indent  indent for inside conditionals
683/// @param clear_ccline  clear ccline first
684static uint8_t *command_line_enter(int firstc, int count, int indent, bool clear_ccline)
685{
686  // can be invoked recursively, identify each level
687  static int cmdline_level = 0;
688  cmdline_level++;
689
690  bool save_cmdpreview = cmdpreview;
691  cmdpreview = false;
692  CommandLineState state = {
693    .firstc = firstc,
694    .count = count,
695    .indent = indent,
696    .save_msg_scroll = msg_scroll,
697    .save_State = State,
698    .prev_cmdpos = -1,
699    .ignore_drag_release = true,
700  };
701  CommandLineState *s = &state;
702  s->save_p_icm = xstrdup(p_icm);
703  init_incsearch_state(&s->is_state);
704  CmdlineInfo save_ccline;
705  bool did_save_ccline = false;
706
707  if (ccline.cmdbuff != NULL) {
708    // Currently ccline can never be in use if clear_ccline is false.
709    // Some changes will be needed if this is no longer the case.
710    assert(clear_ccline);
711    // Being called recursively.  Since ccline is global, we need to save
712    // the current buffer and restore it when returning.
713    save_cmdline(&save_ccline);
714    did_save_ccline = true;
715  } else if (clear_ccline) {
716    CLEAR_FIELD(ccline);
717  }
718
719  if (s->firstc == -1) {
720    s->firstc = NUL;
721    s->break_ctrl_c = true;
722  }
723
724  init_ccline(s->firstc, s->indent);
725  assert(ccline.cmdbuff != NULL);
726  ccline.prompt_id = last_prompt_id++;
727  ccline.level = cmdline_level;
728
729  if (cmdline_level == 50) {
730    // Somehow got into a loop recursively calling getcmdline(), bail out.
731    emsg(_(e_command_too_recursive));
732    goto theend;
733  }
734
735  ExpandInit(&s->xpc);
736  ccline.xpc = &s->xpc;
737  clear_cmdline_orig();
738
739  cmdmsg_rl = (curwin->w_p_rl && *curwin->w_p_rlc == 's'
740               && (s->firstc == '/' || s->firstc == '?'));
741
742  msg_grid_validate();
743
744  redir_off = true;             // don't redirect the typed command
745  if (!cmd_silent) {
746    gotocmdline(true);
747    redrawcmdprompt();          // draw prompt or indent
748    ccline.cmdspos = cmd_startcol();
749  }
750  s->xpc.xp_context = EXPAND_NOTHING;
751  s->xpc.xp_backslash = XP_BS_NONE;
752#ifndef BACKSLASH_IN_FILENAME
753  s->xpc.xp_shell = false;
754#endif
755
756  if (ccline.input_fn) {
757    s->xpc.xp_context = ccline.xp_context;
758    s->xpc.xp_pattern = ccline.cmdbuff;
759    s->xpc.xp_arg = ccline.xp_arg;
760  }
761
762  // Avoid scrolling when called by a recursive do_cmdline(), e.g. when
763  // doing ":@0" when register 0 doesn't contain a CR.
764  msg_scroll = false;
765
766  State = MODE_CMDLINE;
767
768  if (s->firstc == '/' || s->firstc == '?' || s->firstc == '@') {
769    // Use ":lmap" mappings for search pattern and input().
770    if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT) {
771      s->b_im_ptr = &curbuf->b_p_iminsert;
772    } else {
773      s->b_im_ptr = &curbuf->b_p_imsearch;
774    }
775    s->b_im_ptr_buf = curbuf;
776    if (*s->b_im_ptr == B_IMODE_LMAP) {
777      State |= MODE_LANGMAP;
778    }
779  }
780
781  setmouse();
782
783  s->cmdline_type = firstc > 0 ? firstc : '-';
784  Error err = ERROR_INIT;
785  char firstcbuf[2];
786  firstcbuf[0] = (char)s->cmdline_type;
787  firstcbuf[1] = 0;
788
789  if (has_event(EVENT_CMDLINEENTER)) {
790    save_v_event_T save_v_event;
791    dict_T *dict = get_v_event(&save_v_event);
792
793    // set v:event to a dictionary with information about the commandline
794    tv_dict_add_str(dict, S_LEN("cmdtype"), firstcbuf);
795    tv_dict_add_nr(dict, S_LEN("cmdlevel"), ccline.level);
796    tv_dict_set_keys_readonly(dict);
797    TRY_WRAP(&err, {
798      apply_autocmds(EVENT_CMDLINEENTER, firstcbuf, firstcbuf, false, curbuf);
799      restore_v_event(dict, &save_v_event);
800    });
801
802    if (ERROR_SET(&err)) {
803      if (!ui_has(kUIMessages)) {
804        msg_putchar('\n');
805      }
806      msg_scroll = true;
807      msg_puts_hl(err.msg, HLF_E, true);
808      api_clear_error(&err);
809      redrawcmd();
810    }
811    err = ERROR_INIT;
812  }
813  may_trigger_modechanged();
814
815  init_history();
816  s->hiscnt = get_hislen();  // set hiscnt to impossible history value
817  s->histype = hist_char2type(s->firstc);
818  do_digraph(-1);                       // init digraph typeahead
819
820  // If something above caused an error, reset the flags, we do want to type
821  // and execute commands. Display may be messed up a bit.
822  if (did_emsg) {
823    redrawcmd();
824  }
825
826  // Redraw the statusline in case it uses the current mode using the mode()
827  // function.
828  if (!cmd_silent) {
829    bool found_one = false;
830
831    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
832      if (*p_stl != NUL || *wp->w_p_stl != NUL || *p_wbr != NUL || *wp->w_p_wbr != NUL) {
833        wp->w_redr_status = true;
834        found_one = true;
835      }
836    }
837
838    if (*p_tal != NUL) {
839      redraw_tabline = true;
840      found_one = true;
841    }
842
843    if (redraw_custom_title_later()) {
844      found_one = true;
845    }
846
847    if (found_one) {
848      redraw_statuslines();
849    }
850  }
851
852  did_emsg = false;
853  got_int = false;
854  s->state.check = command_line_check;
855  s->state.execute = command_line_execute;
856
857  state_enter(&s->state);
858
859  // Trigger CmdlineLeavePre autocommands if not already triggered.
860  if (!s->event_cmdlineleavepre_triggered) {
861    set_vim_var_char(s->c);  // Set v:char
862    trigger_cmd_autocmd(s->cmdline_type, EVENT_CMDLINELEAVEPRE);
863  }
864
865  if (has_event(EVENT_CMDLINELEAVE)) {
866    save_v_event_T save_v_event;
867    dict_T *dict = get_v_event(&save_v_event);
868
869    tv_dict_add_str(dict, S_LEN("cmdtype"), firstcbuf);
870    tv_dict_add_nr(dict, S_LEN("cmdlevel"), ccline.level);
871    tv_dict_set_keys_readonly(dict);
872    // not readonly:
873    tv_dict_add_bool(dict, S_LEN("abort"),
874                     s->gotesc ? kBoolVarTrue : kBoolVarFalse);
875    set_vim_var_char(s->c);  // Set v:char
876    TRY_WRAP(&err, {
877      apply_autocmds(EVENT_CMDLINELEAVE, firstcbuf, firstcbuf, false, curbuf);
878      // error printed below, to avoid redraw issues
879    });
880    if (tv_dict_get_number(dict, "abort") != 0) {
881      s->gotesc = true;
882    }
883    restore_v_event(dict, &save_v_event);
884  }
885
886  cmdmsg_rl = false;
887
888  // We could have reached here without having a chance to clean up wild menu
889  // if certain special keys like <Esc> or <C-\> were used as wildchar. Make
890  // sure to still clean up to avoid memory corruption.
891  if (cmdline_pum_active()) {
892    cmdline_pum_remove(false);
893  } else {
894    // A previous cmdline_pum_remove() may have deferred redraw.
895    pum_check_clear();
896  }
897  wildmenu_cleanup(&ccline);
898  s->did_wild_list = false;
899  s->wim_index = 0;
900
901  ExpandCleanup(&s->xpc);
902  ccline.xpc = NULL;
903  clear_cmdline_orig();
904
905  finish_incsearch_highlighting(s->gotesc, &s->is_state, false);
906
907  if (ccline.cmdbuff != NULL) {
908    // Put line in history buffer (":" and "=" only when it was typed).
909    if (s->histype != HIST_INVALID
910        && ccline.cmdlen
911        && s->firstc != NUL
912        && (s->some_key_typed || s->histype == HIST_SEARCH)) {
913      add_to_history(s->histype, ccline.cmdbuff, (size_t)ccline.cmdlen, true,
914                     s->histype == HIST_SEARCH ? s->firstc : NUL);
915      if (s->firstc == ':') {
916        xfree(new_last_cmdline);
917        new_last_cmdline = xstrnsave(ccline.cmdbuff, (size_t)ccline.cmdlen);
918      }
919    }
920
921    if (!s->gotesc && ccline.level == 1) {
922      // An accepted toplevel cmdline is the executing command's payload (":cnext<CR>", "/pat<CR>").
923      atom_cmdline_set(s->firstc, ccline.cmdbuff, (size_t)ccline.cmdlen);
924    }
925
926    if (s->gotesc) {
927      abandon_cmdline();
928    }
929  }
930
931  // If the screen was shifted up, redraw the whole screen (later).
932  // If the line is too long, clear it, so ruler and shown command do
933  // not get printed in the middle of it.
934  msg_check();
935  if (p_ch == 0 && !ui_has(kUIMessages)) {
936    set_must_redraw(UPD_VALID);
937  }
938  msg_scroll = s->save_msg_scroll;
939  redir_off = false;
940
941  if (ERROR_SET(&err)) {
942    if (!ui_has(kUIMessages)) {
943      msg_putchar('\n');
944    }
945    emsg(err.msg);
946    did_emsg = false;
947    api_clear_error(&err);
948  }
949
950  // When the command line was typed, no need for a wait-return prompt.
951  if (s->some_key_typed && !ERROR_SET(&err)) {
952    need_wait_return = false;
953  }
954
955  set_option_direct(kOptInccommand, CSTR_AS_OBJ(s->save_p_icm), 0, SID_NONE);
956  State = s->save_State;
957  if (cmdpreview != save_cmdpreview) {
958    cmdpreview = save_cmdpreview;  // restore preview state
959    redraw_all_later(UPD_SOME_VALID);
960  }
961  may_trigger_modechanged();
962  setmouse();
963  sb_text_end_cmdline();
964
965theend:
966  xfree(s->save_p_icm);
967  xfree(ccline.last_colors.cmdbuff);
968  kv_destroy(ccline.last_colors.colors);
969
970  char *p = ccline.cmdbuff;
971
972  if (ui_has(kUICmdline)) {
973    ui_ext_cmdline_hide(s->gotesc);
974  }
975  if (!cmd_silent) {
976    redraw_custom_title_later();
977    status_redraw_all();  // redraw to show mode change
978  }
979
980  cmdline_level--;
981
982  if (did_save_ccline) {
983    restore_cmdline(&save_ccline);
984  } else {
985    ccline.cmdbuff = NULL;
986  }
987
988  xfree(s->prev_cmdbuff);
989  return (uint8_t *)p;
990}
991
992static int command_line_check(VimState *state)
993{
994  CommandLineState *s = (CommandLineState *)state;
995
996  s->prev_cmdpos = ccline.cmdpos;
997  XFREE_CLEAR(s->prev_cmdbuff);
998
999  redir_off = true;        // Don't redirect the typed command.
1000  // Repeated, because a ":redir" inside
1001  // completion may switch it on.
1002  quit_more = false;       // reset after CTRL-D which had a more-prompt
1003
1004  did_emsg = false;        // There can't really be a reason why an error
1005                           // that occurs while typing a command should
1006                           // cause the command not to be executed.
1007
1008  if (ex_normal_busy == 0 && stuff_empty() && typebuf.tb_len == 0) {
1009    // There is no pending input from sources other than user input, so
1010    // Vim is going to wait for the user to type a key.  Consider the
1011    // command line typed even if next key will trigger a mapping.
1012    s->some_key_typed = true;
1013  }
1014
1015  // Trigger SafeState if nothing is pending.
1016  may_trigger_safestate(s->xpc.xp_numfiles <= 0);
1017
1018  if (ccline.cmdbuff != NULL) {
1019    s->prev_cmdbuff = xstrdup(ccline.cmdbuff);
1020  }
1021
1022  // Defer screen update to avoid pum flicker during wildtrigger()
1023  if (s->c == K_WILD && s->firstc != '@') {
1024    s->skip_pum_redraw = true;
1025  }
1026
1027  cursorcmd();             // set the cursor on the right spot
1028  ui_cursor_shape();
1029  return 1;
1030}
1031
1032/// Handle CTRL-\ pressed in Command-line mode:
1033/// - CTRL-\ CTRL-N or CTRL-\ CTRL-G goes to Normal mode.
1034/// - CTRL-\ e prompts for an expression.
1035static int command_line_handle_ctrl_bsl(CommandLineState *s)
1036{
1037  no_mapping++;
1038  allow_keys++;
1039  s->c = plain_vgetc();
1040  no_mapping--;
1041  allow_keys--;
1042
1043  // CTRL-\ e doesn't work when obtaining an expression, unless it
1044  // is in a mapping.
1045  if (s->c != Ctrl_N
1046      && s->c != Ctrl_G
1047      && (s->c != 'e'
1048          || (ccline.cmdfirstc == '=' && KeyTyped)
1049          || cmdline_star > 0)) {
1050    vungetc(s->c);
1051    return PROCESS_NEXT_KEY;
1052  }
1053
1054  if (s->c == 'e') {
1055    // Replace the command line with the result of an expression.
1056    // This will call getcmdline() recursively in get_expr_register().
1057    if (ccline.cmdpos == ccline.cmdlen) {
1058      new_cmdpos = 99999;           // keep it at the end
1059    } else {
1060      new_cmdpos = ccline.cmdpos;
1061    }
1062
1063    s->c = get_expr_register();
1064    if (s->c == '=') {
1065      // Evaluate the expression.  Set "textlock" to avoid nasty things
1066      // like going to another buffer.
1067      textlock++;
1068      char *p = get_expr_line();
1069      textlock--;
1070
1071      if (p != NULL) {
1072        int len = (int)strlen(p);
1073        realloc_cmdbuff(len + 1);
1074        ccline.cmdlen = len;
1075        STRCPY(ccline.cmdbuff, p);
1076        xfree(p);
1077
1078        // Restore the cursor or use the position set with
1079        // set_cmdline_pos().
1080        ccline.cmdpos = MIN(ccline.cmdlen, new_cmdpos);
1081
1082        KeyTyped = false;                 // Don't do p_wc completion.
1083        redrawcmd();
1084        return CMDLINE_CHANGED;
1085      }
1086    }
1087    beep_flush();
1088    got_int = false;                // don't abandon the command line
1089    did_emsg = false;
1090    emsg_on_display = false;
1091    redrawcmd();
1092    return CMDLINE_NOT_CHANGED;
1093  }
1094
1095  s->gotesc = true;  // will free ccline.cmdbuff after putting it in history
1096  return GOTO_NORMAL_MODE;
1097}
1098
1099/// Completion for 'wildchar' or 'wildcharm' key.
1100/// - hitting <ESC> twice means: abandon command line.
1101/// - wildcard expansion is only done when the 'wildchar' key is really
1102///   typed, not when it comes from a macro
1103/// @return  CMDLINE_CHANGED if command line is changed or CMDLINE_NOT_CHANGED.
1104static int command_line_wildchar_complete(CommandLineState *s)
1105{
1106  int res;
1107  int options = WILD_NO_BEEP;
1108  bool escape = s->firstc != '@';
1109  bool redraw_if_menu_empty = s->c == K_WILD;
1110  bool wim_noselect = p_wmnu && (wim_flags[0] & kOptWimFlagNoselect) != 0;
1111  bool wim_noinsert = p_wmnu && (wim_flags[0] & kOptWimFlagNoinsert) != 0;
1112
1113  if (wim_flags[s->wim_index] & kOptWimFlagLastused) {
1114    options |= WILD_BUFLASTUSED;
1115  }
1116  if (s->xpc.xp_numfiles > 0) {       // typed p_wc at least twice
1117    // If "list" is present, list matches unless already listed
1118    if (s->xpc.xp_numfiles > 1
1119        && !s->did_wild_list
1120        && (wim_flags[s->wim_index] & kOptWimFlagList)) {
1121      showmatches(&s->xpc, false, true, p_wmnu ? wim_flags[s->wim_index] : 0);
1122      redrawcmd();
1123      s->did_wild_list = true;
1124    }
1125    if (wim_flags[s->wim_index] & kOptWimFlagLongest) {
1126      res = nextwild(&s->xpc, WILD_LONGEST, options, escape);
1127    } else if (wim_flags[s->wim_index] & kOptWimFlagFull) {
1128      res = nextwild(&s->xpc, WILD_NEXT, options, escape);
1129    } else {
1130      res = OK;                 // don't insert 'wildchar' now
1131    }
1132  } else {                    // typed p_wc first time
1133    bool wim_longest = (wim_flags[0] & kOptWimFlagLongest);
1134    bool wim_list = (wim_flags[0] & kOptWimFlagList);
1135    bool wim_full = (wim_flags[0] & kOptWimFlagFull);
1136
1137    s->wim_index = 0;
1138    if (s->c == p_wc || s->c == p_wcm || s->c == K_WILD || s->c == Ctrl_Z) {
1139      options |= WILD_MAY_EXPAND_PATTERN;
1140      if (s->c == K_WILD) {
1141        options |= WILD_FUNC_TRIGGER;
1142      }
1143      s->xpc.xp_pre_incsearch_pos = s->is_state.search_start;
1144    }
1145    int cmdpos_before = ccline.cmdpos;
1146
1147    // if 'wildmode' first contains "longest", get longest
1148    // common part
1149    if (wim_longest) {
1150      res = nextwild(&s->xpc, WILD_LONGEST, options, escape);
1151    } else {
1152      if (wim_noselect || (wim_list && !wim_full)) {
1153        options |= WILD_NOSELECT;
1154      }
1155      if (wim_noinsert) {
1156        options |= WILD_NOINSERT;
1157      }
1158      res = nextwild(&s->xpc, WILD_EXPAND_KEEP, options, escape);
1159    }
1160
1161    // Remove popup menu if no completion items are available
1162    if (redraw_if_menu_empty && s->xpc.xp_numfiles <= 0) {
1163      pum_check_clear();
1164    }
1165
1166    // if interrupted while completing, behave like it failed
1167    if (got_int) {
1168      vpeekc();               // remove <C-C> from input stream
1169      got_int = false;              // don't abandon the command line
1170      ExpandOne(&s->xpc, NULL, NULL, 0, WILD_FREE);
1171      s->xpc.xp_context = EXPAND_NOTHING;
1172      return CMDLINE_CHANGED;
1173    }
1174
1175    // Display matches
1176    if (res == OK && s->xpc.xp_numfiles > ((wim_noselect || wim_noinsert) ? 0 : 1)) {
1177      if (wim_longest) {
1178        bool found_longest_prefix = (ccline.cmdpos != cmdpos_before);
1179        bool show_menu = p_wmnu && wim_full;
1180        if (wim_list || show_menu) {
1181          showmatches(&s->xpc, show_menu, wim_list, kOptWimFlagNoselect);
1182        } else if (!found_longest_prefix) {
1183          bool wim_list_next = (wim_flags[1] & kOptWimFlagList);
1184          bool wim_full_next = (wim_flags[1] & kOptWimFlagFull);
1185          bool wim_noselect_next = (wim_flags[1] & kOptWimFlagNoselect);
1186          bool wim_noinsert_next = (wim_flags[1] & kOptWimFlagNoinsert);
1187          if (wim_list_next
1188              || (p_wmnu && (wim_full_next || wim_noselect_next || wim_noinsert_next))) {
1189            if (wim_full_next && !wim_noselect_next && !wim_noinsert_next) {
1190              nextwild(&s->xpc, WILD_NEXT, options, escape);
1191            } else {
1192              showmatches(&s->xpc, p_wmnu && (wim_noselect_next || wim_noinsert_next),
1193                          wim_list_next, p_wmnu ? wim_flags[1] : 0);
1194            }
1195            if (wim_list_next) {
1196              s->did_wild_list = true;
1197            }
1198          }
1199        }
1200      } else {
1201        bool show_menu = p_wmnu && (wim_full || wim_noselect || wim_noinsert);
1202        if (wim_list || show_menu) {
1203          showmatches(&s->xpc, show_menu, wim_list, p_wmnu ? wim_flags[0] : 0);
1204        } else {
1205          vim_beep(kOptBoFlagWildmode);
1206        }
1207      }
1208
1209      redrawcmd();
1210      if (wim_list) {
1211        s->did_wild_list = true;
1212      }
1213    } else if (s->xpc.xp_numfiles == -1) {
1214      s->xpc.xp_context = EXPAND_NOTHING;
1215    }
1216  }
1217
1218  if (s->wim_index < 3) {
1219    s->wim_index++;
1220  }
1221
1222  if (s->c == ESC) {
1223    s->gotesc = true;
1224  }
1225
1226  return (res == OK) ? CMDLINE_CHANGED : CMDLINE_NOT_CHANGED;
1227}
1228
1229static void command_line_end_wildmenu(CommandLineState *s, bool key_is_wc, int c)
1230{
1231  if (cmdline_pum_active()) {
1232    if (c != -1) {
1233      s->skip_pum_redraw = (s->skip_pum_redraw && !key_is_wc
1234                            && !ascii_iswhite(c)
1235                            && (vim_isprintc(c)
1236                                || c == K_BS || c == Ctrl_H || c == K_DEL
1237                                || c == K_KDEL || c == Ctrl_W || c == Ctrl_U));
1238    }
1239    cmdline_pum_remove(c != -1 && s->skip_pum_redraw);
1240  }
1241  if (s->xpc.xp_numfiles != -1) {
1242    ExpandOne(&s->xpc, NULL, NULL, 0, WILD_FREE);
1243  }
1244  s->did_wild_list = false;
1245  if (!p_wmnu || (c != K_UP && c != K_DOWN)) {
1246    s->xpc.xp_context = EXPAND_NOTHING;
1247  }
1248  s->wim_index = 0;
1249  wildmenu_cleanup(&ccline);
1250}
1251
1252static int command_line_execute(VimState *state, int key)
1253{
1254  if (key == K_IGNORE || key == K_NOP) {
1255    return -1;  // get another key
1256  }
1257
1258  disptick_T display_tick_saved = curwin->w_display_tick;
1259  CommandLineState *s = (CommandLineState *)state;
1260  s->c = key;
1261
1262  // If the cmdline was replaced externally (e.g. by setcmdline()
1263  // during an <expr> mapping), clean up the wildmenu completion
1264  // state to avoid using stale completion data.
1265  if (ccline.cmdbuff_replaced && s->xpc.xp_numfiles > 0) {
1266    command_line_end_wildmenu(s, false, -1);
1267  }
1268  ccline.cmdbuff_replaced = false;
1269
1270  // Skip wildmenu during history navigation via Up/Down keys
1271  if (s->c == K_WILD && s->did_hist_navigate) {
1272    s->did_hist_navigate = false;
1273    return 1;
1274  }
1275
1276  if (s->c == K_EVENT || s->c == K_COMMAND || s->c == K_LUA) {
1277    if (s->c == K_EVENT) {
1278      state_handle_k_event();
1279    } else if (s->c == K_COMMAND) {
1280      do_cmdline(NULL, getcmdkeycmd, NULL, DOCMD_NOWAIT);
1281    } else {
1282      map_execute_lua(false, false);
1283    }
1284    // If the window changed incremental search state is not valid.
1285    if (s->is_state.winid != curwin->handle) {
1286      init_incsearch_state(&s->is_state);
1287    }
1288    // Re-apply 'incsearch' highlighting in case it was cleared.
1289    if (curwin->w_display_tick > display_tick_saved && s->is_state.did_incsearch) {
1290      may_do_incsearch_highlighting(s->firstc, s->count, &s->is_state);
1291    }
1292    // If f_setcmdline() changed the cmdline treat it as such.
1293    if (ccline.cmdbuff_replaced) {
1294      command_line_changed(s);
1295    }
1296
1297    // nvim_select_popupmenu_item() can be called from the handling of
1298    // K_EVENT, K_COMMAND, or K_LUA.
1299    if (pum_want.active) {
1300      if (cmdline_pum_active()) {
1301        nextwild(&s->xpc, WILD_PUM_WANT, 0, s->firstc != '@');
1302        if (pum_want.finish) {
1303          nextwild(&s->xpc, WILD_APPLY, WILD_NO_BEEP, s->firstc != '@');
1304          command_line_end_wildmenu(s, false, s->c);
1305        }
1306      }
1307      pum_want.active = false;
1308    }
1309
1310    if (!cmdline_was_last_drawn) {
1311      redrawcmdline();
1312    }
1313    return 1;
1314  }
1315
1316  if (KeyTyped) {
1317    s->some_key_typed = true;
1318
1319    if (cmdmsg_rl && !KeyStuffed) {
1320      // Invert horizontal movements and operations.  Only when
1321      // typed by the user directly, not when the result of a
1322      // mapping.
1323      switch (s->c) {
1324      case K_RIGHT:
1325        s->c = K_LEFT; break;
1326      case K_S_RIGHT:
1327        s->c = K_S_LEFT; break;
1328      case K_C_RIGHT:
1329        s->c = K_C_LEFT; break;
1330      case K_LEFT:
1331        s->c = K_RIGHT; break;
1332      case K_S_LEFT:
1333        s->c = K_S_RIGHT; break;
1334      case K_C_LEFT:
1335        s->c = K_C_RIGHT; break;
1336      }
1337    }
1338  }
1339
1340  // Ignore got_int when CTRL-C was typed here.
1341  // Don't ignore it in :global, we really need to break then, e.g., for
1342  // ":g/pat/normal /pat" (without the <CR>).
1343  // Don't ignore it for the input() function.
1344  if ((s->c == Ctrl_C)
1345      && s->firstc != '@'
1346      && !s->break_ctrl_c
1347      && !global_busy) {
1348    got_int = false;
1349  }
1350
1351  // free old command line when finished moving around in the history
1352  // list
1353  if (s->lookfor != NULL
1354      && s->c != K_S_DOWN && s->c != K_S_UP
1355      && s->c != K_DOWN && s->c != K_UP
1356      && s->c != K_PAGEDOWN && s->c != K_PAGEUP
1357      && s->c != K_KPAGEDOWN && s->c != K_KPAGEUP
1358      && s->c != K_LEFT && s->c != K_RIGHT
1359      && (s->xpc.xp_numfiles > 0 || (s->c != Ctrl_P && s->c != Ctrl_N))) {
1360    XFREE_CLEAR(s->lookfor);
1361    s->lookforlen = 0;
1362  }
1363
1364  // When there are matching completions to select <S-Tab> works like
1365  // CTRL-P (unless 'wc' is <S-Tab>).
1366  if (s->c != p_wc && s->c == K_S_TAB && s->xpc.xp_numfiles > 0) {
1367    s->c = Ctrl_P;
1368  }
1369
1370  if (p_wmnu) {
1371    s->c = wildmenu_translate_key(&ccline, s->c, &s->xpc, s->did_wild_list);
1372  }
1373
1374  int wild_type = 0;
1375  const bool key_is_wc = (s->c == p_wc && KeyTyped) || s->c == p_wcm;
1376  if ((cmdline_pum_active() || wild_menu_showing || s->did_wild_list)
1377      && !key_is_wc && s->xpc.xp_numfiles > 0) {
1378    // Ctrl-Y: Accept the current selection and close the popup menu.
1379    // Ctrl-E: cancel the cmdline popup menu and return the original text.
1380    if (s->c == Ctrl_E || s->c == Ctrl_Y) {
1381      wild_type = (s->c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;
1382      nextwild(&s->xpc, wild_type, WILD_NO_BEEP, s->firstc != '@');
1383    }
1384  }
1385
1386  // Trigger CmdlineLeavePre autocommand
1387  if ((KeyTyped && (s->c == '\n' || s->c == '\r' || s->c == K_KENTER || s->c == ESC))
1388      || s->c == Ctrl_C) {
1389    set_vim_var_char(s->c);  // Set v:char
1390    trigger_cmd_autocmd(s->cmdline_type, EVENT_CMDLINELEAVEPRE);
1391    s->event_cmdlineleavepre_triggered = true;
1392    if ((s->c == ESC || s->c == Ctrl_C) && (wim_flags[0] & kOptWimFlagList)) {
1393      set_no_hlsearch(true);
1394    }
1395  }
1396
1397  // The wildmenu is cleared if the pressed key is not used for
1398  // navigating the wild menu (i.e. the key is not 'wildchar' or
1399  // 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).
1400  // If the popup menu is displayed, then PageDown and PageUp keys are
1401  // also used to navigate the menu.
1402  bool end_wildmenu = (!key_is_wc && s->c != Ctrl_Z
1403                       && s->c != Ctrl_N && s->c != Ctrl_P && s->c != Ctrl_A
1404                       && s->c != Ctrl_L);
1405  end_wildmenu = end_wildmenu && (!cmdline_pum_active()
1406                                  || (s->c != K_PAGEDOWN && s->c != K_PAGEUP
1407                                      && s->c != K_KPAGEDOWN && s->c != K_KPAGEUP
1408                                      && s->c != K_MOUSEDOWN && s->c != K_MOUSEUP
1409                                      && s->c != K_MOUSELEFT && s->c != K_MOUSERIGHT));
1410
1411  // free expanded names when finished walking through matches
1412  if (end_wildmenu) {
1413    command_line_end_wildmenu(s, key_is_wc, s->c);
1414  }
1415
1416  if (p_wmnu) {
1417    s->c = wildmenu_process_key(&ccline, s->c, &s->xpc);
1418  }
1419
1420  // CTRL-\ CTRL-N or CTRL-\ CTRL-G goes to Normal mode,
1421  // CTRL-\ e prompts for an expression.
1422  if (s->c == Ctrl_BSL) {
1423    switch (command_line_handle_ctrl_bsl(s)) {
1424    case CMDLINE_CHANGED:
1425      return command_line_changed(s);
1426    case CMDLINE_NOT_CHANGED:
1427      return command_line_not_changed(s);
1428    case GOTO_NORMAL_MODE:
1429      return 0;                   // back to cmd mode
1430    default:
1431      s->c = Ctrl_BSL;            // backslash key not processed by
1432                                  // command_line_handle_ctrl_bsl()
1433    }
1434  }
1435
1436  if (s->c == cedit_key) {
1437    // c_CTRL-F: Open cmdwin. Return Ctrl_C so the current cmdline cancels; when the user
1438    // confirms/cancels cmdwin, it will reopen cmdline with the command pre-filled.
1439    if (ex_normal_busy == 0 && got_int == false) {
1440      s->c = open_cmdwin();
1441      s->some_key_typed = true;  // Treat c_CTRL-F as "typed" to skip the wait-return prompt.
1442    }
1443  } else {
1444    s->c = do_digraph(s->c);
1445  }
1446
1447  if (s->c == '\n'
1448      || s->c == '\r'
1449      || s->c == K_KENTER
1450      || (s->c == ESC
1451          && (!KeyTyped || vim_strchr(p_cpo, kCpoEsc) != NULL))) {
1452    s->gotesc = false;         // Might have typed ESC previously, don't
1453                               // truncate the cmdline now.
1454    if (ccheck_abbr(s->c + ABBR_OFF)) {
1455      return command_line_changed(s);
1456    }
1457
1458    if (!cmd_silent) {
1459      if (!ui_has(kUICmdline)) {
1460        msg_cursor_goto(msg_row, 0);
1461      }
1462      ui_flush();
1463    }
1464    return 0;
1465  }
1466
1467  // Completion for 'wildchar', 'wildcharm', and wildtrigger()
1468  if ((s->c == p_wc && !s->gotesc && KeyTyped) || s->c == p_wcm || s->c == K_WILD
1469      || s->c == Ctrl_Z) {
1470    if (s->c == K_WILD) {
1471      emsg_silent++;  // Silence the bell
1472    }
1473    int res = command_line_wildchar_complete(s);
1474    if (s->c == K_WILD) {
1475      emsg_silent--;
1476    }
1477    if (res == CMDLINE_CHANGED) {
1478      return command_line_changed(s);
1479    }
1480    if (s->c == K_WILD) {
1481      return command_line_not_changed(s);
1482    }
1483  }
1484
1485  s->gotesc = false;
1486
1487  // <S-Tab> goes to last match, in a clumsy way
1488  if (s->c == K_S_TAB && KeyTyped) {
1489    if (nextwild(&s->xpc, WILD_EXPAND_KEEP, 0, s->firstc != '@') == OK) {
1490      if (s->xpc.xp_numfiles > 1
1491          && ((!s->did_wild_list && (wim_flags[s->wim_index] & kOptWimFlagList)) || p_wmnu)) {
1492        // Trigger the popup menu when wildoptions=pum
1493        bool list = wim_flags[s->wim_index] & kOptWimFlagList;
1494        showmatches(&s->xpc, p_wmnu && !list, list, p_wmnu ? wim_flags[0] : 0);
1495      }
1496      nextwild(&s->xpc, WILD_PREV, 0, s->firstc != '@');
1497      nextwild(&s->xpc, WILD_PREV, 0, s->firstc != '@');
1498      return command_line_changed(s);
1499    }
1500  }
1501
1502  if (s->c == NUL || s->c == K_ZERO) {
1503    // NUL is stored as NL
1504    s->c = NL;
1505  }
1506
1507  s->do_abbr = true;             // default: check for abbreviation
1508
1509  // If already used to cancel/accept wildmenu, don't process the key further.
1510  if (wild_type == WILD_CANCEL || wild_type == WILD_APPLY) {
1511    // Apply search highlighting
1512    if (s->is_state.winid != curwin->handle) {
1513      init_incsearch_state(&s->is_state);
1514    }
1515    if (KeyTyped || vpeekc() == NUL) {
1516      may_do_incsearch_highlighting(s->firstc, s->count, &s->is_state);
1517    }
1518    return command_line_not_changed(s);
1519  }
1520
1521  return command_line_handle_key(s);
1522}
1523
1524// May adjust 'incsearch' highlighting for typing CTRL-G and CTRL-T, go to next
1525// or previous match.
1526// Returns FAIL when calling command_line_not_changed.
1527static int may_do_command_line_next_incsearch(int firstc, int count, incsearch_state_T *s,
1528                                              bool next_match)
1529  FUNC_ATTR_NONNULL_ALL
1530{
1531  int skiplen, patlen, search_delim;
1532  bool magic = p_magic;
1533
1534  // Parsing range may already set the last search pattern.
1535  // NOTE: must call restore_last_search_pattern() before returning!
1536  save_last_search_pattern();
1537
1538  if (!do_incsearch_highlighting(firstc, &search_delim, s, &skiplen,
1539                                 &patlen, &magic)) {
1540    restore_last_search_pattern();
1541    return OK;
1542  }
1543  if (patlen == 0 && ccline.cmdbuff[skiplen] == NUL) {
1544    restore_last_search_pattern();
1545    return FAIL;
1546  }
1547
1548  ui_busy_start();
1549  ui_flush();
1550
1551  pos_T t;
1552  char *pat = ccline.cmdbuff + skiplen;
1553  char *dircp = NULL;
1554  char *searchstr = pat;
1555  char *strcopy = NULL;
1556  size_t searchstrlen = (size_t)patlen;
1557  SearchOffset offset;
1558  int search_flags = SEARCH_NOOF;
1559  size_t patlen_s = (size_t)(ccline.cmdlen - skiplen);
1560
1561  // do not search for the search end delimiter,
1562  // unless it is part of the pattern
1563  parse_search_pattern_offset(&pat, &patlen_s, search_delim, SEARCH_OPT, &strcopy, &searchstr,
1564                              &searchstrlen, &dircp, &offset);
1565
1566  if (next_match) {
1567    t = s->match_end;
1568    if (lt(s->match_start, s->match_end)) {
1569      // start searching at the end of the match
1570      // not at the beginning of the next column
1571      decl(&t);
1572    }
1573    search_flags += SEARCH_COL;
1574  } else {
1575    t = s->match_start;
1576  }
1577  if (!p_hls) {
1578    search_flags += SEARCH_KEEP;
1579  }
1580  emsg_off++;
1581  int found = searchit(curwin, curbuf, &t, NULL,
1582                       next_match ? FORWARD : BACKWARD,
1583                       searchstr, searchstrlen, count, search_flags,
1584                       RE_SEARCH, magic, NULL);
1585  emsg_off--;
1586  if (dircp != NULL) {
1587    *dircp = (char)search_delim;
1588  }
1589  ui_busy_stop();
1590  if (found) {
1591    pos_T match_start = s->match_start;
1592    pos_T match_end = s->match_end;
1593    int64_t off = offset.off;
1594
1595    s->search_start = match_start;
1596    if (!offset.line && (offset.end || off != 0)) {
1597      if (offset.end) {
1598        s->search_start = match_end;
1599        decl(&s->search_start);
1600      }
1601      while (off > 0) {
1602        if (incl(&s->search_start) == -1) {
1603          break;
1604        }
1605        off--;
1606      }
1607      while (off < 0) {
1608        if (decl(&s->search_start) == -1) {
1609          break;
1610        }
1611        off++;
1612      }
1613    }
1614    s->match_end = t;
1615    s->match_start = t;
1616    if (!next_match && firstc != '?') {
1617      // move just before the current match, so that
1618      // when nv_search finishes the cursor will be
1619      // put back on the match
1620      s->search_start = t;
1621      decl(&s->search_start);
1622    } else if (next_match && firstc == '?') {
1623      // move just after the current match, so that
1624      // when nv_search finishes the cursor will be
1625      // put back on the match
1626      s->search_start = t;
1627      incl(&s->search_start);
1628    }
1629    if (lt(t, s->search_start) && next_match) {
1630      // wrap around
1631      s->search_start = t;
1632      if (firstc == '?') {
1633        incl(&s->search_start);
1634      } else {
1635        decl(&s->search_start);
1636      }
1637    }
1638
1639    set_search_match(&s->match_end);
1640    curwin->w_cursor = s->match_start;
1641    changed_cline_bef_curs(curwin);
1642    update_topline(curwin);
1643    validate_cursor(curwin);
1644    Search.hl_match = true;
1645    save_viewstate(curwin, &s->old_viewstate);
1646    redraw_later(curwin, UPD_NOT_VALID);
1647    update_screen();
1648    Search.hl_match = false;
1649    redrawcmdline();
1650    curwin->w_cursor = s->match_end;
1651  } else {
1652    vim_beep(kOptBoFlagError);
1653  }
1654  xfree(strcopy);
1655  restore_last_search_pattern();
1656  return FAIL;
1657}
1658
1659/// Handle backspace, delete and CTRL-W keys in the command-line mode.
1660static int command_line_erase_chars(CommandLineState *s)
1661{
1662  if (s->c == K_KDEL) {
1663    s->c = K_DEL;
1664  }
1665
1666  // Delete current character is the same as backspace on next
1667  // character, except at end of line
1668  if (s->c == K_DEL && ccline.cmdpos != ccline.cmdlen) {
1669    ccline.cmdpos++;
1670  }
1671  if (s->c == K_DEL) {
1672    ccline.cmdpos += mb_off_next(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos);
1673  }
1674
1675  if (ccline.cmdpos > 0) {
1676    int j = ccline.cmdpos;
1677    char *p = mb_prevptr(ccline.cmdbuff, ccline.cmdbuff + j);
1678
1679    if (s->c == Ctrl_W) {
1680      while (p > ccline.cmdbuff && ascii_isspace(*p)) {
1681        p = mb_prevptr(ccline.cmdbuff, p);
1682      }
1683
1684      int i = mb_get_class(p);
1685      while (p > ccline.cmdbuff && mb_get_class(p) == i) {
1686        p = mb_prevptr(ccline.cmdbuff, p);
1687      }
1688
1689      if (mb_get_class(p) != i) {
1690        p += utfc_ptr2len(p);
1691      }
1692    }
1693
1694    ccline.cmdpos = (int)(p - ccline.cmdbuff);
1695    ccline.cmdlen -= j - ccline.cmdpos;
1696    int i = ccline.cmdpos;
1697
1698    while (i < ccline.cmdlen) {
1699      ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
1700    }
1701
1702    // Truncate at the end, required for multi-byte chars.
1703    ccline.cmdbuff[ccline.cmdlen] = NUL;
1704    if (ccline.cmdlen == 0) {
1705      s->is_state.search_start = s->is_state.save_cursor;
1706      // save view settings, so that the screen won't be restored at the
1707      // wrong position
1708      s->is_state.old_viewstate = s->is_state.init_viewstate;
1709    }
1710    redrawcmd();
1711  } else if (ccline.cmdlen == 0 && s->c != Ctrl_W
1712             && ccline.cmdprompt == NULL && s->indent == 0) {
1713    // In debug mode it doesn't make sense to return.
1714    if (ccline.cmdfirstc == '>') {
1715      return CMDLINE_NOT_CHANGED;
1716    }
1717
1718    dealloc_cmdbuff();  // no commandline to return
1719
1720    if (!cmd_silent && !ui_has(kUICmdline)) {
1721      msg_col = 0;
1722      msg_putchar(' ');                             // delete ':'
1723    }
1724    s->is_state.search_start = s->is_state.save_cursor;
1725    redraw_cmdline = true;
1726    return GOTO_NORMAL_MODE;
1727  }
1728  return CMDLINE_CHANGED;
1729}
1730
1731/// Handle the CTRL-^ key in the command-line mode and toggle the use of the
1732/// language :lmap mappings and/or Input Method.
1733static void command_line_toggle_langmap(CommandLineState *s)
1734{
1735  OptInt *b_im_ptr = buf_valid(s->b_im_ptr_buf) ? s->b_im_ptr : NULL;
1736  if (map_to_exists_mode("", MODE_LANGMAP, false)) {
1737    // ":lmap" mappings exists, toggle use of mappings.
1738    State ^= MODE_LANGMAP;
1739    if (b_im_ptr != NULL) {
1740      if (State & MODE_LANGMAP) {
1741        *b_im_ptr = B_IMODE_LMAP;
1742      } else {
1743        *b_im_ptr = B_IMODE_NONE;
1744      }
1745    }
1746  }
1747
1748  if (b_im_ptr != NULL) {
1749    if (b_im_ptr == &curbuf->b_p_iminsert) {
1750      set_iminsert_global(curbuf);
1751    } else {
1752      set_imsearch_global(curbuf);
1753    }
1754  }
1755  ui_cursor_shape();                // may show different cursor shape
1756  // Show/unshow value of 'keymap' in status lines later.
1757  status_redraw_curbuf();
1758}
1759
1760/// Handle the CTRL-R key in the command-line mode and insert the contents of a
1761/// numbered or named register.
1762static int command_line_insert_reg(CommandLineState *s)
1763{
1764  const int save_new_cmdpos = new_cmdpos;
1765
1766  putcmdline('"', true);
1767  no_mapping++;
1768  allow_keys++;
1769  int i = s->c = plain_vgetc();      // CTRL-R <char>
1770  if (i == Ctrl_O) {
1771    i = Ctrl_R;                      // CTRL-R CTRL-O == CTRL-R CTRL-R
1772  }
1773
1774  if (i == Ctrl_R) {
1775    s->c = plain_vgetc();              // CTRL-R CTRL-R <char>
1776  }
1777  no_mapping--;
1778  allow_keys--;
1779  // Insert the result of an expression.
1780  new_cmdpos = -1;
1781  if (s->c == '=') {
1782    if (ccline.cmdfirstc == '='   // can't do this recursively
1783        || cmdline_star > 0) {    // or when typing a password
1784      beep_flush();
1785      s->c = ESC;
1786    } else {
1787      s->c = get_expr_register();
1788    }
1789  }
1790
1791  bool literally = false;
1792  if (s->c != ESC) {               // use ESC to cancel inserting register
1793    literally = i == Ctrl_R || is_literal_register(s->c);
1794    cmdline_paste(s->c, literally, false);
1795
1796    // When there was a serious error abort getting the
1797    // command line.
1798    if (aborting()) {
1799      s->gotesc = true;              // will free ccline.cmdbuff after
1800                                     // putting it in history
1801      return GOTO_NORMAL_MODE;
1802    }
1803    KeyTyped = false;                // Don't do p_wc completion.
1804    if (new_cmdpos >= 0) {
1805      // set_cmdline_pos() was used
1806      ccline.cmdpos = MIN(ccline.cmdlen, new_cmdpos);
1807    }
1808  }
1809  new_cmdpos = save_new_cmdpos;
1810
1811  // remove the double quote
1812  ccline.special_char = NUL;
1813  redrawcmd();
1814
1815  // With "literally": the command line has already changed.
1816  // Else: the text has been stuffed, but the command line didn't change yet.
1817  return literally ? CMDLINE_CHANGED : CMDLINE_NOT_CHANGED;
1818}
1819
1820/// Handle the Left and Right mouse clicks in the command-line mode.
1821static void command_line_left_right_mouse(CommandLineState *s)
1822{
1823  if (s->c == K_LEFTRELEASE || s->c == K_RIGHTRELEASE) {
1824    s->ignore_drag_release = true;
1825  } else {
1826    s->ignore_drag_release = false;
1827  }
1828
1829  ccline.cmdspos = cmd_startcol();
1830  for (ccline.cmdpos = 0; ccline.cmdpos < ccline.cmdlen;
1831       ccline.cmdpos++) {
1832    int cells = cmdline_charsize(ccline.cmdpos);
1833    if (mouse_row <= cmdline_row + ccline.cmdspos / Columns
1834        && mouse_col < ccline.cmdspos % Columns + cells) {
1835      break;
1836    }
1837
1838    // Count ">" for double-wide char that doesn't fit.
1839    correct_screencol(ccline.cmdpos, cells, &ccline.cmdspos);
1840    ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1;
1841    ccline.cmdspos += cells;
1842  }
1843}
1844
1845static void command_line_next_histidx(CommandLineState *s, bool next_match)
1846{
1847  while (true) {
1848    // one step backwards
1849    if (!next_match) {
1850      if (s->hiscnt == get_hislen()) {
1851        // first time
1852        s->hiscnt = *get_hisidx(s->histype);
1853      } else if (s->hiscnt == 0 && *get_hisidx(s->histype) != get_hislen() - 1) {
1854        s->hiscnt = get_hislen() - 1;
1855      } else if (s->hiscnt != *get_hisidx(s->histype) + 1) {
1856        s->hiscnt--;
1857      } else {
1858        // at top of list
1859        s->hiscnt = s->save_hiscnt;
1860        break;
1861      }
1862    } else {          // one step forwards
1863      // on last entry, clear the line
1864      if (s->hiscnt == *get_hisidx(s->histype)) {
1865        s->hiscnt = get_hislen();
1866        break;
1867      }
1868
1869      // not on a history line, nothing to do
1870      if (s->hiscnt == get_hislen()) {
1871        break;
1872      }
1873
1874      if (s->hiscnt == get_hislen() - 1) {
1875        // wrap around
1876        s->hiscnt = 0;
1877      } else {
1878        s->hiscnt++;
1879      }
1880    }
1881
1882    if (s->hiscnt < 0 || get_histentry(s->histype)[s->hiscnt].hisstr == NULL) {
1883      s->hiscnt = s->save_hiscnt;
1884      break;
1885    }
1886
1887    if ((s->c != K_UP && s->c != K_DOWN)
1888        || s->hiscnt == s->save_hiscnt
1889        || strncmp(get_histentry(s->histype)[s->hiscnt].hisstr,
1890                   s->lookfor, (size_t)s->lookforlen) == 0) {
1891      break;
1892    }
1893  }
1894}
1895
1896/// Handle the Up, Down, Page Up, Page down, CTRL-N and CTRL-P key in the
1897/// command-line mode.
1898static int command_line_browse_history(CommandLineState *s)
1899{
1900  if (s->histype == HIST_INVALID || get_hislen() == 0 || s->firstc == NUL) {
1901    // no history
1902    return CMDLINE_NOT_CHANGED;
1903  }
1904
1905  s->save_hiscnt = s->hiscnt;
1906
1907  // save current command string so it can be restored later
1908  if (s->lookfor == NULL) {
1909    s->lookfor = xstrnsave(ccline.cmdbuff, (size_t)ccline.cmdlen);
1910    s->lookfor[ccline.cmdpos] = NUL;
1911    s->lookforlen = ccline.cmdpos;
1912  }
1913
1914  bool next_match = (s->c == K_DOWN || s->c == K_S_DOWN || s->c == Ctrl_N
1915                     || s->c == K_PAGEDOWN || s->c == K_KPAGEDOWN);
1916  command_line_next_histidx(s, next_match);
1917
1918  if (s->hiscnt != s->save_hiscnt) {  // jumped to other entry
1919    char *p;
1920    int plen;
1921    int old_firstc;
1922
1923    dealloc_cmdbuff();
1924
1925    s->xpc.xp_context = EXPAND_NOTHING;
1926    if (s->hiscnt == get_hislen()) {
1927      p = s->lookfor;                  // back to the old one
1928      plen = s->lookforlen;
1929    } else {
1930      p = get_histentry(s->histype)[s->hiscnt].hisstr;
1931      plen = (int)get_histentry(s->histype)[s->hiscnt].hisstrlen;
1932    }
1933
1934    if (s->histype == HIST_SEARCH
1935        && p != s->lookfor
1936        && (old_firstc = (uint8_t)p[plen + 1]) != s->firstc) {
1937      int len = 0;
1938      // Correct for the separator character used when
1939      // adding the history entry vs the one used now.
1940      // First loop: count length.
1941      // Second loop: copy the characters.
1942      for (int i = 0; i <= 1; i++) {
1943        len = 0;
1944        for (int j = 0; p[j] != NUL; j++) {
1945          // Replace old sep with new sep, unless it is
1946          // escaped.
1947          if (p[j] == old_firstc
1948              && (j == 0 || p[j - 1] != '\\')) {
1949            if (i > 0) {
1950              ccline.cmdbuff[len] = (char)s->firstc;
1951            }
1952          } else {
1953            // Escape new sep, unless it is already
1954            // escaped.
1955            if (p[j] == s->firstc
1956                && (j == 0 || p[j - 1] != '\\')) {
1957              if (i > 0) {
1958                ccline.cmdbuff[len] = '\\';
1959              }
1960              len++;
1961            }
1962
1963            if (i > 0) {
1964              ccline.cmdbuff[len] = p[j];
1965            }
1966          }
1967          len++;
1968        }
1969
1970        if (i == 0) {
1971          alloc_cmdbuff(len);
1972        }
1973      }
1974      ccline.cmdbuff[len] = NUL;
1975      ccline.cmdpos = ccline.cmdlen = len;
1976    } else {
1977      alloc_cmdbuff(plen);
1978      STRCPY(ccline.cmdbuff, p);
1979      ccline.cmdpos = ccline.cmdlen = plen;
1980    }
1981
1982    redrawcmd();
1983    return CMDLINE_CHANGED;
1984  }
1985  beep_flush();
1986  return CMDLINE_NOT_CHANGED;
1987}
1988
1989static int command_line_handle_key(CommandLineState *s)
1990{
1991  // For one key prompt, avoid putting ESC and Ctrl_C onto cmdline.
1992  // For all other keys, just put onto cmdline and exit.
1993  if (ccline.one_key && s->c != ESC && s->c != Ctrl_C) {
1994    goto end;
1995  }
1996
1997  // Big switch for a typed command line character.
1998  switch (s->c) {
1999  case K_BS:
2000  case Ctrl_H:
2001  case K_DEL:
2002  case K_KDEL:
2003  case Ctrl_W:
2004    switch (command_line_erase_chars(s)) {
2005    case CMDLINE_NOT_CHANGED:
2006      return command_line_not_changed(s);
2007    case GOTO_NORMAL_MODE:
2008      return 0;  // back to cmd mode
2009    default:
2010      return command_line_changed(s);
2011    }
2012
2013  case K_INS:
2014  case K_KINS:
2015    ccline.overstrike = !ccline.overstrike;
2016    ui_cursor_shape();                // may show different cursor shape
2017    may_trigger_modechanged();
2018    status_redraw_curbuf();
2019    redraw_statuslines();
2020    return command_line_not_changed(s);
2021
2022  case Ctrl_HAT:
2023    command_line_toggle_langmap(s);
2024    return command_line_not_changed(s);
2025
2026  case Ctrl_U: {
2027    // delete all characters left of the cursor
2028    int j = ccline.cmdpos;
2029    ccline.cmdlen -= j;
2030    int i = ccline.cmdpos = 0;
2031    while (i < ccline.cmdlen) {
2032      ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
2033    }
2034
2035    // Truncate at the end, required for multi-byte chars.
2036    ccline.cmdbuff[ccline.cmdlen] = NUL;
2037    if (ccline.cmdlen == 0) {
2038      s->is_state.search_start = s->is_state.save_cursor;
2039    }
2040    redrawcmd();
2041    return command_line_changed(s);
2042  }
2043
2044  case ESC:           // get here if p_wc != ESC or when ESC typed twice
2045  case Ctrl_C:
2046    // When the highlight callback is active <C-c> should interrupt only it.
2047    if (getln_interrupted_highlight && s->c == Ctrl_C) {
2048      getln_interrupted_highlight = false;
2049      return command_line_not_changed(s);
2050    }
2051
2052    s->gotesc = true;                 // will free ccline.cmdbuff after
2053                                      // putting it in history
2054    return 0;                         // back to cmd mode
2055
2056  case Ctrl_R:                        // insert register
2057    switch (command_line_insert_reg(s)) {
2058    case GOTO_NORMAL_MODE:
2059      return 0;  // back to cmd mode
2060    case CMDLINE_CHANGED:
2061      return command_line_changed(s);
2062    default:
2063      return command_line_not_changed(s);
2064    }
2065
2066  case Ctrl_D:
2067    if (showmatches(&s->xpc, false, true, p_wmnu ? wim_flags[0] : 0)
2068        == EXPAND_NOTHING) {
2069      break;                  // Use ^D as normal char instead
2070    }
2071
2072    redrawcmd();
2073    return 1;                 // don't do incremental search now
2074
2075  case K_RIGHT:
2076  case K_S_RIGHT:
2077  case K_C_RIGHT:
2078    do {
2079      if (ccline.cmdpos >= ccline.cmdlen) {
2080        break;
2081      }
2082
2083      int cells = cmdline_charsize(ccline.cmdpos);
2084      if (KeyTyped && ccline.cmdspos + cells >= Columns * Rows) {
2085        break;
2086      }
2087
2088      ccline.cmdspos += cells;
2089      ccline.cmdpos += utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos);
2090    } while ((s->c == K_S_RIGHT || s->c == K_C_RIGHT
2091              || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
2092             && ccline.cmdbuff[ccline.cmdpos] != ' ');
2093    ccline.cmdspos = cmd_screencol(ccline.cmdpos);
2094    return command_line_not_changed(s);
2095
2096  case K_LEFT:
2097  case K_S_LEFT:
2098  case K_C_LEFT:
2099    if (ccline.cmdpos == 0) {
2100      return command_line_not_changed(s);
2101    }
2102    do {
2103      ccline.cmdpos--;
2104      // Move to first byte of possibly multibyte char.
2105      ccline.cmdpos -= utf_head_off(ccline.cmdbuff,
2106                                    ccline.cmdbuff + ccline.cmdpos);
2107      ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
2108    } while (ccline.cmdpos > 0
2109             && (s->c == K_S_LEFT || s->c == K_C_LEFT
2110                 || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
2111             && ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
2112
2113    ccline.cmdspos = cmd_screencol(ccline.cmdpos);
2114    if (ccline.special_char != NUL) {
2115      putcmdline(ccline.special_char, ccline.special_shift);
2116    }
2117
2118    return command_line_not_changed(s);
2119
2120  case K_IGNORE:
2121    // Ignore mouse event or open_cmdwin() result.
2122    return command_line_not_changed(s);
2123
2124  case K_MIDDLEDRAG:
2125  case K_MIDDLERELEASE:
2126    return command_line_not_changed(s);                 // Ignore mouse
2127
2128  case K_MIDDLEMOUSE:
2129    cmdline_paste(eval_has_provider("clipboard", false) ? '*' : 0, true, true);
2130    redrawcmd();
2131    return command_line_changed(s);
2132
2133  case K_LEFTDRAG:
2134  case K_LEFTRELEASE:
2135  case K_RIGHTDRAG:
2136  case K_RIGHTRELEASE:
2137    // Ignore drag and release events when the button-down wasn't
2138    // seen before.
2139    if (s->ignore_drag_release) {
2140      return command_line_not_changed(s);
2141    }
2142    FALLTHROUGH;
2143  case K_LEFTMOUSE:
2144    // Return on left click above number prompt
2145    if (ccline.mouse_used && mouse_row < cmdline_row) {
2146      *ccline.mouse_used = true;
2147      return 0;
2148    }
2149    FALLTHROUGH;
2150  case K_RIGHTMOUSE:
2151    command_line_left_right_mouse(s);
2152    return command_line_not_changed(s);
2153
2154  // Mouse scroll wheel: scroll the completion info popup when the mouse
2155  // is on top of it, otherwise ignored here.
2156  case K_MOUSEDOWN:
2157  case K_MOUSEUP:
2158  case K_MOUSELEFT:
2159  case K_MOUSERIGHT:
2160    if (cmdline_pum_active()) {
2161      cmdline_mousescroll(s->c == K_MOUSEDOWN
2162                          ? MSCR_DOWN
2163                          : (s->c == K_MOUSEUP
2164                             ? MSCR_UP
2165                             : s->c == K_MOUSELEFT ? MSCR_LEFT : MSCR_RIGHT));
2166    }
2167    return command_line_not_changed(s);
2168
2169  // Alternate buttons ignored here
2170  case K_X1MOUSE:
2171  case K_X1DRAG:
2172  case K_X1RELEASE:
2173  case K_X2MOUSE:
2174  case K_X2DRAG:
2175  case K_X2RELEASE:
2176  case K_MOUSEMOVE:
2177    return command_line_not_changed(s);
2178
2179  case K_SELECT:          // end of Select mode mapping - ignore
2180    return command_line_not_changed(s);
2181
2182  case Ctrl_B:            // begin of command line
2183  case K_HOME:
2184  case K_KHOME:
2185  case K_S_HOME:
2186  case K_C_HOME:
2187    ccline.cmdpos = 0;
2188    ccline.cmdspos = cmd_startcol();
2189    return command_line_not_changed(s);
2190
2191  case Ctrl_E:            // end of command line
2192  case K_END:
2193  case K_KEND:
2194  case K_S_END:
2195  case K_C_END:
2196    ccline.cmdpos = ccline.cmdlen;
2197    ccline.cmdspos = cmd_screencol(ccline.cmdpos);
2198    return command_line_not_changed(s);
2199
2200  case Ctrl_A:            // all matches
2201    if (cmdline_pum_active()) {
2202      // As Ctrl-A completes all the matches, close the popup
2203      // menu (if present)
2204      cmdline_pum_cleanup(&ccline);
2205    }
2206
2207    if (nextwild(&s->xpc, WILD_ALL, 0, s->firstc != '@') == FAIL) {
2208      break;
2209    }
2210    s->xpc.xp_context = EXPAND_NOTHING;
2211    s->did_wild_list = false;
2212    return command_line_changed(s);
2213
2214  case Ctrl_L:
2215    if (may_add_char_to_search(s->firstc, &s->c, &s->is_state) == OK) {
2216      return command_line_not_changed(s);
2217    }
2218
2219    // completion: longest common part
2220    if (nextwild(&s->xpc, WILD_LONGEST, 0, s->firstc != '@') == FAIL) {
2221      break;
2222    }
2223    return command_line_changed(s);
2224
2225  case Ctrl_N:            // next match
2226  case Ctrl_P:            // previous match
2227    if (s->xpc.xp_numfiles > 0) {
2228      const int wild_type = (s->c == Ctrl_P) ? WILD_PREV : WILD_NEXT;
2229      if (nextwild(&s->xpc, wild_type, 0, s->firstc != '@') == FAIL) {
2230        break;
2231      }
2232      return command_line_changed(s);
2233    }
2234    FALLTHROUGH;
2235
2236  case K_UP:
2237  case K_DOWN:
2238  case K_S_UP:
2239  case K_S_DOWN:
2240  case K_PAGEUP:
2241  case K_KPAGEUP:
2242  case K_PAGEDOWN:
2243  case K_KPAGEDOWN:
2244    if (cmdline_pum_active()
2245        && (s->c == K_PAGEUP || s->c == K_PAGEDOWN
2246            || s->c == K_KPAGEUP || s->c == K_KPAGEDOWN)) {
2247      // If the popup menu is displayed, then PageUp and PageDown
2248      // are used to scroll the menu.
2249      const int wild_type =
2250        (s->c == K_PAGEDOWN || s->c == K_KPAGEDOWN) ? WILD_PAGEDOWN : WILD_PAGEUP;
2251      if (nextwild(&s->xpc, wild_type, 0, s->firstc != '@') == FAIL) {
2252        break;
2253      }
2254      return command_line_changed(s);
2255    } else {
2256      switch (command_line_browse_history(s)) {
2257      case CMDLINE_CHANGED:
2258        s->did_hist_navigate = true;
2259        return command_line_changed(s);
2260      case GOTO_NORMAL_MODE:
2261        return 0;
2262      default:
2263        return command_line_not_changed(s);
2264      }
2265    }
2266
2267  case Ctrl_G:  // next match
2268  case Ctrl_T:  // previous match
2269    if (may_do_command_line_next_incsearch(s->firstc, s->count, &s->is_state,
2270                                           s->c == Ctrl_G) == FAIL) {
2271      return command_line_not_changed(s);
2272    }
2273    break;
2274
2275  case Ctrl_V:
2276  case Ctrl_Q:
2277    s->ignore_drag_release = true;
2278    putcmdline('^', true);
2279
2280    // Get next (two) characters.
2281    // Do not include modifiers into the key for CTRL-SHIFT-V.
2282    s->c = get_literal(mod_mask & MOD_MASK_SHIFT);
2283
2284    s->do_abbr = false;                   // don't do abbreviation now
2285    ccline.special_char = NUL;
2286    // may need to remove ^ when composing char was typed
2287    if (utf_iscomposing_first(s->c) && !cmd_silent) {
2288      if (ui_has(kUICmdline)) {
2289        // TODO(bfredl): why not make unputcmdline also work with true?
2290        unputcmdline();
2291      } else {
2292        draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
2293        msg_putchar(' ');
2294        cursorcmd();
2295      }
2296    }
2297    break;
2298
2299  case Ctrl_K:
2300    s->ignore_drag_release = true;
2301    putcmdline('?', true);
2302    s->c = get_digraph(true);
2303    ccline.special_char = NUL;
2304
2305    if (s->c != NUL) {
2306      break;
2307    }
2308
2309    redrawcmd();
2310    return command_line_not_changed(s);
2311
2312  case Ctrl__:            // CTRL-_: switch language mode
2313    if (!p_ari) {
2314      break;
2315    }
2316    return command_line_not_changed(s);
2317
2318  case 'q':
2319    // Number prompts use the mouse and return on 'q' press
2320    if (ccline.mouse_used) {
2321      *ccline.cmdbuff = NUL;
2322      return 0;
2323    }
2324    FALLTHROUGH;
2325
2326  default:
2327    // Normal character with no special meaning.  Just set mod_mask
2328    // to 0x0 so that typing Shift-Space in the GUI doesn't enter
2329    // the string <S-Space>.  This should only happen after ^V.
2330    if (!IS_SPECIAL(s->c)) {
2331      mod_mask = 0x0;
2332    }
2333    break;
2334  }
2335
2336  // End of switch on command line character.
2337  // We come here if we have a normal character.
2338  if (s->do_abbr && (IS_SPECIAL(s->c) || !vim_iswordc(s->c))
2339      // Add ABBR_OFF for characters above 0x100, this is
2340      // what check_abbr() expects.
2341      && (ccheck_abbr((s->c >= 0x100) ? (s->c + ABBR_OFF) : s->c)
2342          || s->c == Ctrl_RSB)) {
2343    return command_line_changed(s);
2344  }
2345
2346end:
2347  // put the character in the command line
2348  if (IS_SPECIAL(s->c) || mod_mask != 0) {
2349    put_on_cmdline(get_special_key_name(s->c, mod_mask), -1, true);
2350  } else {
2351    int j = utf_char2bytes(s->c, IObuff);
2352    IObuff[j] = NUL;                // exclude composing chars
2353    put_on_cmdline(IObuff, j, true);
2354  }
2355  return ccline.one_key ? 0 : command_line_changed(s);
2356}
2357
2358/// Trigger CursorMovedC autocommands.
2359static void may_trigger_cursormovedc(CommandLineState *s)
2360{
2361  if (ccline.cmdpos != s->prev_cmdpos) {
2362    trigger_cmd_autocmd(s->cmdline_type, EVENT_CURSORMOVEDC);
2363    ccline.redraw_state = MAX(ccline.redraw_state, kCmdRedrawPos);
2364  }
2365}
2366
2367static int command_line_not_changed(CommandLineState *s)
2368{
2369  may_trigger_cursormovedc(s);
2370  s->prev_cmdpos = ccline.cmdpos;
2371  // Incremental searches for "/" and "?":
2372  // Enter command_line_not_changed() when a character has been read but the
2373  // command line did not change. Then we only search and redraw if something
2374  // changed in the past.
2375  // Enter command_line_changed() when the command line did change.
2376  if (!s->is_state.incsearch_postponed) {
2377    return 1;
2378  }
2379  return command_line_changed(s);
2380}
2381
2382/// Guess that the pattern matches everything.  Only finds specific cases, such
2383/// as a trailing \|, which can happen while typing a pattern.
2384static bool empty_pattern(char *p, size_t len, int delim)
2385{
2386  magic_T magic_val = MAGIC_ON;
2387
2388  if (len > 0) {
2389    skip_regexp_ex(p, delim, p_magic, NULL, NULL, &magic_val);
2390  } else {
2391    return true;
2392  }
2393
2394  return empty_pattern_magic(p, len, magic_val);
2395}
2396
2397static bool empty_pattern_magic(char *p, size_t len, magic_T magic_val)
2398{
2399  // remove trailing \v and the like
2400  while (len >= 2 && p[len - 2] == '\\'
2401         && vim_strchr("mMvVcCZ", (uint8_t)p[len - 1]) != NULL) {
2402    len -= 2;
2403  }
2404
2405  // true, if the pattern is empty, or the pattern ends with \| and magic is
2406  // set (or it ends with '|' and very magic is set)
2407  return len == 0 || (len > 1 && p[len - 1] == '|'
2408                      && ((p[len - 2] == '\\' && magic_val == MAGIC_ON)
2409                          || (p[len - 2] != '\\' && magic_val == MAGIC_ALL)));
2410}
2411
2412handle_T cmdpreview_get_bufnr(void)
2413{
2414  return cmdpreview_bufnr;
2415}
2416
2417int cmdpreview_get_ns(void)
2418{
2419  return cmdpreview_ns;
2420}
2421
2422/// Sets up command preview buffer.
2423///
2424/// @return Pointer to command preview buffer if succeeded, NULL if failed.
2425static buf_T *cmdpreview_open_buf(void)
2426{
2427  buf_T *cmdpreview_buf = cmdpreview_bufnr ? buflist_findnr(cmdpreview_bufnr) : NULL;
2428
2429  // If preview buffer doesn't exist, open one.
2430  if (cmdpreview_buf == NULL) {
2431    Error err = ERROR_INIT;
2432    handle_T bufnr = nvim_create_buf(false, true, &err);
2433
2434    if (ERROR_SET(&err)) {
2435      return NULL;
2436    }
2437
2438    cmdpreview_buf = buflist_findnr(bufnr);
2439  }
2440
2441  // Preview buffer cannot preview itself!
2442  if (cmdpreview_buf == curbuf) {
2443    return NULL;
2444  }
2445
2446  // Rename preview buffer.
2447  CtxSwitch aco = { 0 };
2448  ctx_switch(&aco, NULL, NULL, cmdpreview_buf, kCtxKeepDirs);
2449  int retv = rename_buffer("[Preview]");
2450  ctx_restore(&aco);
2451
2452  if (retv == FAIL) {
2453    return NULL;
2454  }
2455
2456  // Temporarily switch to preview buffer to set it up for previewing.
2457  ctx_switch(&aco, NULL, NULL, cmdpreview_buf, kCtxKeepDirs);
2458  buf_clear();
2459  curbuf->b_p_ma = true;
2460  curbuf->b_p_ul = -1;
2461  curbuf->b_p_tw = 0;  // Reset 'textwidth' (was set by ftplugin)
2462  ctx_restore(&aco);
2463  cmdpreview_bufnr = cmdpreview_buf->handle;
2464
2465  return cmdpreview_buf;
2466}
2467
2468/// Open command preview window if it's not already open.
2469/// Returns to original window after opening command preview window.
2470///
2471/// @param cmdpreview_buf Pointer to command preview buffer
2472///
2473/// @return Pointer to command preview window if succeeded, NULL if failed.
2474static win_T *cmdpreview_open_win(buf_T *cmdpreview_buf)
2475  FUNC_ATTR_NONNULL_ALL
2476{
2477  win_T *save_curwin = curwin;
2478
2479  // Open preview window.
2480  if (win_split((int)p_cwh, WSP_BOT) == FAIL) {
2481    return NULL;
2482  }
2483
2484  win_T *preview_win = curwin;
2485  Error err = ERROR_INIT;
2486  int result = OK;
2487
2488  // Switch to preview buffer
2489  TRY_WRAP(&err, {
2490    result = do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, cmdpreview_buf->handle, 0);
2491  });
2492  if (ERROR_SET(&err) || result == FAIL) {
2493    api_clear_error(&err);
2494    return NULL;
2495  }
2496
2497  curwin->w_p_cul = false;
2498  curwin->w_p_cuc = false;
2499  curwin->w_p_spell = false;
2500  curwin->w_p_fen = false;
2501
2502  win_enter(save_curwin, false);
2503  return preview_win;
2504}
2505
2506/// Closes any open command preview windows.
2507static void cmdpreview_close_win(void)
2508{
2509  buf_T *buf = cmdpreview_bufnr ? buflist_findnr(cmdpreview_bufnr) : NULL;
2510  if (buf != NULL) {
2511    close_windows(buf, false);
2512  }
2513}
2514
2515/// Save current state and prepare windows and buffers for command preview.
2516static void cmdpreview_prepare(CpInfo *cpinfo)
2517  FUNC_ATTR_NONNULL_ALL
2518{
2519  Set(ptr_t) saved_bufs = SET_INIT;
2520
2521  kv_init(cpinfo->buf_info);
2522  kv_init(cpinfo->win_info);
2523
2524  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
2525    buf_T *buf = win->w_buffer;
2526
2527    // Don't save state of command preview buffer or preview window.
2528    if (buf->handle == cmdpreview_bufnr) {
2529      continue;
2530    }
2531
2532    if (!set_has(ptr_t, &saved_bufs, buf)) {
2533      CpBufInfo cp_bufinfo;
2534      cp_bufinfo.buf = buf;
2535      cp_bufinfo.save_b_p_ma = buf->b_p_ma;
2536      cp_bufinfo.save_b_changed = buf->b_changed;
2537      cp_bufinfo.save_b_op_start = buf->b_op_start;
2538      cp_bufinfo.save_b_op_end = buf->b_op_end;
2539      u_checkpoint(&cp_bufinfo.undo_checkpoint, buf);
2540      kv_push(cpinfo->buf_info, cp_bufinfo);
2541      set_put(ptr_t, &saved_bufs, buf);
2542    }
2543
2544    CpWinInfo cp_wininfo;
2545    cp_wininfo.win = win;
2546
2547    // Save window cursor position and viewstate
2548    cp_wininfo.save_w_cursor = win->w_cursor;
2549    save_viewstate(win, &cp_wininfo.save_viewstate);
2550
2551    // Save 'cursorline' and 'cursorcolumn'
2552    cp_wininfo.save_w_p_cul = win->w_p_cul;
2553    cp_wininfo.save_w_p_cuc = win->w_p_cuc;
2554
2555    kv_push(cpinfo->win_info, cp_wininfo);
2556
2557    win->w_p_cul = false;       // Disable 'cursorline' so it doesn't mess up the highlights
2558    win->w_p_cuc = false;       // Disable 'cursorcolumn' so it doesn't mess up the highlights
2559  }
2560
2561  set_destroy(ptr_t, &saved_bufs);
2562
2563  cpinfo->save_hls = p_hls;
2564  cpinfo->save_cmdmod = cmdmod;
2565  win_size_save(&cpinfo->save_view);
2566  save_search_patterns();
2567
2568  p_hls = false;                 // Don't show search highlighting during live substitution
2569  cmdmod.cmod_split = 0;         // Disable :leftabove/botright modifiers
2570  cmdmod.cmod_tab = 0;           // Disable :tab modifier
2571  cmdmod.cmod_flags |= CMOD_NOSWAPFILE;  // Disable swap for preview buffer
2572
2573  u_sync(true);
2574}
2575
2576/// Restore the state of buffers and windows for command preview.
2577static void cmdpreview_restore_state(CpInfo *cpinfo)
2578  FUNC_ATTR_NONNULL_ALL
2579{
2580  for (size_t i = 0; i < cpinfo->buf_info.size; i++) {
2581    CpBufInfo cp_bufinfo = cpinfo->buf_info.items[i];
2582    buf_T *buf = cp_bufinfo.buf;
2583
2584    buf->b_changed = cp_bufinfo.save_b_changed;
2585
2586    // Clear preview highlights.
2587    extmark_clear(buf, (uint32_t)cmdpreview_ns, 0, 0, MAXLNUM, MAXCOL);
2588
2589    u_rollback(&cp_bufinfo.undo_checkpoint, buf);
2590
2591    buf->b_op_start = cp_bufinfo.save_b_op_start;
2592    buf->b_op_end = cp_bufinfo.save_b_op_end;
2593
2594    buf->b_p_ma = cp_bufinfo.save_b_p_ma;        // Restore 'modifiable'
2595  }
2596
2597  for (size_t i = 0; i < cpinfo->win_info.size; i++) {
2598    CpWinInfo cp_wininfo = cpinfo->win_info.items[i];
2599    win_T *win = cp_wininfo.win;
2600
2601    // Restore window cursor position and viewstate
2602    win->w_cursor = cp_wininfo.save_w_cursor;
2603    restore_viewstate(win, &cp_wininfo.save_viewstate);
2604
2605    // Restore 'cursorline' and 'cursorcolumn'
2606    win->w_p_cul = cp_wininfo.save_w_p_cul;
2607    win->w_p_cuc = cp_wininfo.save_w_p_cuc;
2608
2609    update_topline(win);
2610  }
2611
2612  cmdmod = cpinfo->save_cmdmod;                // Restore cmdmod
2613  p_hls = cpinfo->save_hls;                    // Restore 'hlsearch'
2614  restore_search_patterns();           // Restore search patterns
2615  win_size_restore(&cpinfo->save_view);        // Restore window sizes
2616
2617  ga_clear(&cpinfo->save_view);
2618  kv_destroy(cpinfo->win_info);
2619  kv_destroy(cpinfo->buf_info);
2620}
2621
2622/// Show 'inccommand' preview if command is previewable. It works like this:
2623///    1. Store current undo information so we can revert to current state later.
2624///    2. Execute the preview callback with the parsed command, preview buffer number and preview
2625///       namespace number as arguments. The preview callback sets the highlight and does the
2626///       changes required for the preview if needed.
2627///    3. Preview callback returns 0, 1 or 2. 0 means no preview is shown. 1 means preview is shown
2628///       but preview window doesn't need to be opened. 2 means preview is shown and preview window
2629///       needs to be opened if inccommand=split.
2630///    4. Use the return value of the preview callback to determine whether to
2631///       open the preview window or not and open preview window if needed.
2632///    5. If the return value of the preview callback is not 0, update the screen while the effects
2633///       of the preview are still in place.
2634///    6. Revert all changes made by the preview callback.
2635///
2636/// @return whether preview is shown or not.
2637static bool cmdpreview_may_show(CommandLineState *s)
2638{
2639  // Parse the command line and return if it fails.
2640  exarg_T ea;
2641  cmdmod_T cmod;
2642  // Copy the command line so we can modify it.
2643  int cmdpreview_type = 0;
2644  char *cmdline = xstrdup(ccline.cmdbuff);
2645  const char *errormsg = NULL;
2646  emsg_off++;  // Block errors when parsing the command line, and don't update v:errmsg
2647  if (!parse_cmdline(&cmdline, &ea, &cmod, &errormsg, false)) {
2648    emsg_off--;
2649    goto end;
2650  }
2651  emsg_off--;
2652
2653  // Check if command is previewable, if not, don't attempt to show preview
2654  if (!(ea.argt & EX_PREVIEW)) {
2655    undo_cmdmod(&cmod);
2656    goto end;
2657  }
2658
2659  // Cursor may be at the end of the message grid rather than at cmdspos.
2660  // Place it there in case preview callback flushes it. #30696
2661  cursorcmd();
2662  // Flush now: external cmdline may itself wish to update the screen which is
2663  // currently disallowed during cmdpreview (no longer needed in case that changes).
2664  cmdline_ui_flush();
2665
2666  // Swap invalid command range if needed
2667  if ((ea.argt & EX_RANGE) && ea.line1 > ea.line2) {
2668    linenr_T lnum = ea.line1;
2669    ea.line1 = ea.line2;
2670    ea.line2 = lnum;
2671  }
2672
2673  CpInfo cpinfo;
2674  bool icm_split = *p_icm == 's';  // inccommand=split
2675  buf_T *cmdpreview_buf = NULL;
2676  win_T *cmdpreview_win = NULL;
2677
2678  emsg_silent++;                 // Block error reporting as the command may be incomplete,
2679                                 // but still update v:errmsg
2680  msg_silent++;                  // Block messages, namely ones that prompt
2681  block_autocmds();              // Block events
2682
2683  // Save current state and prepare for command preview.
2684  cmdpreview_prepare(&cpinfo);
2685
2686  // Open preview buffer if inccommand=split.
2687  if (icm_split && (cmdpreview_buf = cmdpreview_open_buf()) == NULL) {
2688    // Failed to create preview buffer, so disable preview.
2689    set_option_direct(kOptInccommand, STATIC_CSTR_AS_OBJ("nosplit"), 0, SID_NONE);
2690    icm_split = false;
2691  }
2692  // Setup preview namespace if it's not already set.
2693  if (!cmdpreview_ns) {
2694    cmdpreview_ns = (int)nvim_create_namespace((String)STRING_INIT);
2695  }
2696
2697  // Set cmdpreview state.
2698  cmdpreview = true;
2699
2700  // Execute the preview callback and use its return value to determine whether to show preview or
2701  // open the preview window. The preview callback also handles doing the changes and highlights for
2702  // the preview.
2703  Error err = ERROR_INIT;
2704  TRY_WRAP(&err, {
2705    cmdpreview_type = execute_cmd(&ea, &cmod, true);
2706  });
2707  if (ERROR_SET(&err)) {
2708    api_clear_error(&err);
2709    cmdpreview_type = 0;
2710  }
2711
2712  // If inccommand=split and preview callback returns 2, open preview window.
2713  if (icm_split && cmdpreview_type == 2
2714      && (cmdpreview_win = cmdpreview_open_win(cmdpreview_buf)) == NULL) {
2715    // If there's not enough room to open the preview window, just preview without the window.
2716    cmdpreview_type = 1;
2717  }
2718
2719  // If preview callback return value is nonzero, update screen now.
2720  if (cmdpreview_type != 0) {
2721    int save_rd = RedrawingDisabled;
2722    RedrawingDisabled = 0;
2723    update_screen();
2724    RedrawingDisabled = save_rd;
2725  }
2726
2727  // Close preview window if it's open.
2728  if (icm_split && cmdpreview_type == 2 && cmdpreview_win != NULL) {
2729    cmdpreview_close_win();
2730  }
2731
2732  // Restore state.
2733  cmdpreview_restore_state(&cpinfo);
2734
2735  unblock_autocmds();                  // Unblock events
2736  msg_silent--;                        // Unblock messages
2737  emsg_silent--;                       // Unblock error reporting
2738  redrawcmdline();
2739end:
2740  xfree(cmdline);
2741  return cmdpreview_type != 0;
2742}
2743
2744/// Trigger CmdlineChanged autocommands.
2745static void do_autocmd_cmdlinechanged(int firstc)
2746{
2747  if (has_event(EVENT_CMDLINECHANGED)) {
2748    Error err = ERROR_INIT;
2749    save_v_event_T save_v_event;
2750    dict_T *dict = get_v_event(&save_v_event);
2751
2752    char firstcbuf[2];
2753    firstcbuf[0] = (char)firstc;
2754    firstcbuf[1] = 0;
2755
2756    // set v:event to a dictionary with information about the commandline
2757    tv_dict_add_str(dict, S_LEN("cmdtype"), firstcbuf);
2758    tv_dict_add_nr(dict, S_LEN("cmdlevel"), ccline.level);
2759    tv_dict_set_keys_readonly(dict);
2760    TRY_WRAP(&err, {
2761      apply_autocmds(EVENT_CMDLINECHANGED, firstcbuf, firstcbuf, false, curbuf);
2762      restore_v_event(dict, &save_v_event);
2763    });
2764    if (ERROR_SET(&err)) {
2765      if (!ui_has(kUIMessages)) {
2766        msg_putchar('\n');
2767      }
2768      msg_scroll = true;
2769      msg_puts_hl(err.msg, HLF_E, true);
2770      api_clear_error(&err);
2771      redrawcmd();
2772    }
2773  }
2774}
2775
2776static int command_line_changed(CommandLineState *s)
2777{
2778  const bool prev_cmdpreview = cmdpreview;
2779  if (s->firstc == ':'
2780      && current_sctx.sc_sid == 0    // only if interactive
2781      && *p_icm != NUL       // 'inccommand' is set
2782      && cmdline_star == 0   // not typing a password
2783      && !vpeekc_any()
2784      && cmdpreview_may_show(s)) {
2785    // 'inccommand' preview has been shown.
2786  } else {
2787    cmdpreview = false;
2788    if (prev_cmdpreview) {
2789      // TODO(bfredl): add an immediate redraw flag for cmdline mode which will trigger
2790      // at next wait-for-input
2791      update_screen();  // Clear 'inccommand' preview.
2792    }
2793    if (s->xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL)) {
2794      may_do_incsearch_highlighting(s->firstc, s->count, &s->is_state);
2795    }
2796  }
2797
2798  if (!ccline.cmdbuff_replaced
2799      && (ccline.cmdpos != s->prev_cmdpos
2800          || (s->prev_cmdbuff != NULL && strcmp(s->prev_cmdbuff, ccline.cmdbuff) != 0))) {
2801    // Trigger CmdlineChanged autocommands.
2802    do_autocmd_cmdlinechanged(s->firstc > 0 ? s->firstc : '-');
2803  }
2804
2805  may_trigger_cursormovedc(s);
2806
2807  if (p_arshape && !p_tbidi) {
2808    // Always redraw the whole command line to fix shaping and
2809    // right-left typing.  Not efficient, but it works.
2810    // Do it only when there are no characters left to read
2811    // to avoid useless intermediate redraws.
2812    // if cmdline is external the ui handles shaping, no redraw needed.
2813    if (!ui_has(kUICmdline) && vpeekc() == NUL) {
2814      redrawcmd();
2815    }
2816  }
2817
2818  return 1;
2819}
2820
2821/// Abandon the command line.
2822static void abandon_cmdline(void)
2823{
2824  dealloc_cmdbuff();
2825  if (msg_scrolled == 0) {
2826    compute_cmdrow();
2827  }
2828  // Avoid overwriting key prompt
2829  if (!ccline.one_key) {
2830    msg("", 0);
2831    redraw_cmdline = true;
2832  }
2833}
2834
2835/// getcmdline() - accept a command line starting with firstc.
2836///
2837/// firstc == ':'            get ":" command line.
2838/// firstc == '/' or '?'     get search pattern
2839/// firstc == '='            get expression
2840/// firstc == '@'            get text for input() function
2841/// firstc == '>'            get text for debug mode
2842/// firstc == NUL            get text for :insert command
2843/// firstc == -1             like NUL, and break on CTRL-C
2844///
2845/// The line is collected in ccline.cmdbuff, which is reallocated to fit the
2846/// command line.
2847///
2848/// Careful: getcmdline() can be called recursively!
2849///
2850/// Return pointer to allocated string if there is a commandline, NULL
2851/// otherwise.
2852///
2853/// @param count  only used for incremental search
2854/// @param indent  indent for inside conditionals
2855char *getcmdline(int firstc, int count, int indent, bool do_concat FUNC_ATTR_UNUSED)
2856{
2857  return (char *)command_line_enter(firstc, count, indent, true);
2858}
2859
2860/// Get a command line with a prompt
2861///
2862/// This is prepared to be called recursively from getcmdline() (e.g. by
2863/// f_input() when evaluating an expression from `<C-r>=`).
2864///
2865/// @param[in]  firstc  Prompt type: e.g. '@' for input(), '>' for debug.
2866/// @param[in]  prompt  Prompt string: what is displayed before the user text.
2867/// @param[in]  hl_id  Prompt highlight id.
2868/// @param[in]  xp_context  Type of expansion.
2869/// @param[in]  xp_arg  User-defined expansion argument.
2870/// @param[in]  highlight_callback  Callback used for highlighting user input.
2871/// @param[in]  one_key  Return after one key press for button prompt.
2872/// @param[in]  mouse_used  Set to true when returning after right mouse click.
2873///
2874/// @return [allocated] Command line or NULL.
2875char *getcmdline_prompt(const int firstc, const char *const prompt, const int hl_id,
2876                        const int xp_context, const char *const xp_arg,
2877                        const Callback highlight_callback, bool one_key, bool *mouse_used)
2878  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
2879{
2880  const int msg_col_save = msg_col;
2881
2882  CmdlineInfo save_ccline;
2883  bool did_save_ccline = false;
2884  if (ccline.cmdbuff != NULL) {
2885    // Save the values of the current cmdline and restore them below.
2886    save_cmdline(&save_ccline);
2887    did_save_ccline = true;
2888  } else {
2889    CLEAR_FIELD(ccline);
2890  }
2891  ccline.prompt_id = last_prompt_id++;
2892  ccline.cmdprompt = (char *)prompt;
2893  ccline.hl_id = hl_id;
2894  ccline.xp_context = xp_context;
2895  ccline.xp_arg = (char *)xp_arg;
2896  ccline.input_fn = (firstc == '@');
2897  ccline.highlight_callback = highlight_callback;
2898  ccline.one_key = one_key;
2899  ccline.mouse_used = mouse_used;
2900
2901  const bool cmd_silent_saved = cmd_silent;
2902  int msg_silent_saved = msg_silent;
2903  msg_silent = 0;
2904  cmd_silent = false;  // Want to see the prompt.
2905
2906  char *const ret = (char *)command_line_enter(firstc, 1, 0, false);
2907  ccline.redraw_state = kCmdRedrawNone;
2908
2909  if (did_save_ccline) {
2910    restore_cmdline(&save_ccline);
2911  }
2912  msg_silent = msg_silent_saved;
2913  cmd_silent = cmd_silent_saved;
2914  // Restore msg_col, the prompt from input() may have changed it.
2915  // But only if called recursively and the commandline is therefore being
2916  // restored to an old one; if not, the input() prompt stays on the screen,
2917  // so we need its modified msg_col left intact.
2918  if (ccline.cmdbuff != NULL) {
2919    msg_col = msg_col_save;
2920  }
2921
2922  return ret;
2923}
2924
2925/// Read the 'wildmode' option, fill wim_flags[].
2926int check_opt_wim(void)
2927{
2928  uint8_t new_wim_flags[4];
2929  int i;
2930  int idx = 0;
2931
2932  for (i = 0; i < 4; i++) {
2933    new_wim_flags[i] = 0;
2934  }
2935
2936  for (char *p = p_wim; *p; p++) {
2937    // Note: Keep this in sync with opt_wim_values.
2938    for (i = 0; ASCII_ISALPHA(p[i]); i++) {}
2939    if (p[i] != NUL && p[i] != ',' && p[i] != ':') {
2940      return FAIL;
2941    }
2942    if (i == 7 && strncmp(p, "longest", 7) == 0) {
2943      new_wim_flags[idx] |= kOptWimFlagLongest;
2944    } else if (i == 4 && strncmp(p, "full", 4) == 0) {
2945      new_wim_flags[idx] |= kOptWimFlagFull;
2946    } else if (i == 4 && strncmp(p, "list", 4) == 0) {
2947      new_wim_flags[idx] |= kOptWimFlagList;
2948    } else if (i == 8 && strncmp(p, "lastused", 8) == 0) {
2949      new_wim_flags[idx] |= kOptWimFlagLastused;
2950    } else if (i == 8 && strncmp(p, "noselect", 8) == 0) {
2951      new_wim_flags[idx] |= kOptWimFlagNoselect;
2952    } else if (i == 8 && strncmp(p, "noinsert", 8) == 0) {
2953      new_wim_flags[idx] |= kOptWimFlagNoinsert;
2954    } else {
2955      return FAIL;
2956    }
2957    p += i;
2958    if (*p == NUL) {
2959      break;
2960    }
2961    if (*p == ',') {
2962      if (idx == 3) {
2963        return FAIL;
2964      }
2965      idx++;
2966    }
2967  }
2968
2969  // fill remaining entries with last flag
2970  while (idx < 3) {
2971    new_wim_flags[idx + 1] = new_wim_flags[idx];
2972    idx++;
2973  }
2974
2975  // only when there are no errors, wim_flags[] is changed
2976  for (i = 0; i < 4; i++) {
2977    wim_flags[i] = new_wim_flags[i];
2978  }
2979  return OK;
2980}
2981
2982/// Return true when the text must not be changed and we can't switch to
2983/// another window or buffer.  True when editing the command line etc.
2984bool text_locked(void)
2985{
2986  if (expr_map_locked()) {
2987    return true;
2988  }
2989  return textlock != 0;
2990}
2991
2992// Give an error message for a command that isn't allowed while the cmdline
2993// window is open or editing the cmdline in another way.
2994void text_locked_msg(void)
2995{
2996  emsg(_(get_text_locked_msg()));
2997}
2998
2999const char *get_text_locked_msg(void)
3000{
3001  return e_textlock;
3002}
3003
3004/// Check for text, window or buffer locked.
3005/// Give an error message and return true if something is locked.
3006bool text_or_buf_locked(void)
3007{
3008  if (text_locked()) {
3009    text_locked_msg();
3010    return true;
3011  }
3012  return curbuf_locked();
3013}
3014
3015/// Check if "curbuf->b_ro_locked" or "allbuf_lock" is set and
3016/// return true when it is and give an error message.
3017bool curbuf_locked(void)
3018{
3019  if (curbuf->b_ro_locked > 0) {
3020    emsg(_(e_cannot_edit_other_buf));
3021    return true;
3022  }
3023  return allbuf_locked();
3024}
3025
3026// Check if "allbuf_lock" is set and return true when it is and give an error
3027// message.
3028bool allbuf_locked(void)
3029{
3030  if (allbuf_lock > 0) {
3031    emsg(_("E811: Not allowed to change buffer information now"));
3032    return true;
3033  }
3034  return false;
3035}
3036
3037static int cmdline_charsize(int idx)
3038{
3039  if (cmdline_star > 0) {           // showing '*', always 1 position
3040    return 1;
3041  }
3042  return ptr2cells(ccline.cmdbuff + idx);
3043}
3044
3045/// Compute the offset of the cursor on the command line for the prompt and
3046/// indent.
3047static int cmd_startcol(void)
3048{
3049  return ccline.cmdindent + ((ccline.cmdfirstc != NUL) ? 1 : 0);
3050}
3051
3052/// Compute the column position for a byte position on the command line.
3053int cmd_screencol(int bytepos)
3054{
3055  int m;  // maximum column
3056  int col = cmd_startcol();
3057  if (KeyTyped) {
3058    m = cmdline_win ? cmdline_win->w_view_width * cmdline_win->w_view_height : Columns * Rows;
3059    if (m < 0) {        // overflow, Columns or Rows at weird value
3060      m = MAXCOL;
3061    }
3062  } else {
3063    m = MAXCOL;
3064  }
3065
3066  for (int i = 0; i < ccline.cmdlen && i < bytepos;
3067       i += utfc_ptr2len(ccline.cmdbuff + i)) {
3068    int c = cmdline_charsize(i);
3069    // Count ">" for double-wide multi-byte char that doesn't fit.
3070    correct_screencol(i, c, &col);
3071
3072    // If the cmdline doesn't fit, show cursor on last visible char.
3073    // Don't move the cursor itself, so we can still append.
3074    if ((col += c) >= m) {
3075      col -= c;
3076      break;
3077    }
3078  }
3079  return col;
3080}
3081
3082/// Check if the character at "idx", which is "cells" wide, is a multi-byte
3083/// character that doesn't fit, so that a ">" must be displayed.
3084static void correct_screencol(int idx, int cells, int *col)
3085{
3086  if (utfc_ptr2len(ccline.cmdbuff + idx) > 1
3087      && utf_ptr2cells(ccline.cmdbuff + idx) > 1
3088      && (*col) % Columns + cells > Columns) {
3089    (*col)++;
3090  }
3091}
3092
3093/// Get an Ex command line for the ":" command.
3094///
3095/// @param c  normally ':', NUL for ":append"
3096/// @param indent  indent for inside conditionals
3097char *getexline(int c, void *cookie, int indent, bool do_concat)
3098{
3099  // When executing a register, remove ':' that's in front of each line.
3100  if (exec_from_reg && vpeekc() == ':') {
3101    vgetc();
3102  }
3103
3104  return getcmdline(c, 1, indent, do_concat);
3105}
3106
3107bool cmdline_overstrike(void)
3108  FUNC_ATTR_PURE
3109{
3110  return ccline.overstrike;
3111}
3112
3113/// Return true if the cursor is at the end of the cmdline.
3114bool cmdline_at_end(void)
3115  FUNC_ATTR_PURE
3116{
3117  return (ccline.cmdpos >= ccline.cmdlen);
3118}
3119
3120/// Deallocate a command line buffer, updating the buffer size and length.
3121static void dealloc_cmdbuff(void)
3122{
3123  XFREE_CLEAR(ccline.cmdbuff);
3124  ccline.cmdlen = ccline.cmdbufflen = 0;
3125}
3126
3127/// Allocate a new command line buffer.
3128/// Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
3129static void alloc_cmdbuff(int len)
3130{
3131  // give some extra space to avoid having to allocate all the time
3132  if (len < 80) {
3133    len = 100;
3134  } else {
3135    len += 20;
3136  }
3137
3138  ccline.cmdbuff = xmalloc((size_t)len);
3139  ccline.cmdbufflen = len;
3140}
3141
3142/// Re-allocate the command line to length len + something extra.
3143void realloc_cmdbuff(int len)
3144{
3145  if (len < ccline.cmdbufflen) {
3146    return;  // no need to resize
3147  }
3148
3149  char *p = ccline.cmdbuff;
3150
3151  alloc_cmdbuff(len);                   // will get some more
3152  // There isn't always a NUL after the command, but it may need to be
3153  // there, thus copy up to the NUL and add a NUL.
3154  memmove(ccline.cmdbuff, p, (size_t)ccline.cmdlen);
3155  ccline.cmdbuff[ccline.cmdlen] = NUL;
3156
3157  if (ccline.xpc != NULL
3158      && ccline.xpc->xp_pattern != NULL
3159      && ccline.xpc->xp_context != EXPAND_NOTHING
3160      && ccline.xpc->xp_context != EXPAND_UNSUCCESSFUL) {
3161    int i = (int)(ccline.xpc->xp_pattern - p);
3162
3163    // If xp_pattern points inside the old cmdbuff it needs to be adjusted
3164    // to point into the newly allocated memory.
3165    if (i >= 0 && i <= ccline.cmdlen) {
3166      ccline.xpc->xp_pattern = ccline.cmdbuff + i;
3167    }
3168  }
3169
3170  xfree(p);
3171}
3172
3173enum { MAX_CB_ERRORS = 1, };
3174
3175/// Color expression cmdline using built-in expressions parser
3176///
3177/// @param[in]  colored_ccline  Command-line to color.
3178/// @param[out]  ret_ccline_colors  What should be colored.
3179///
3180/// Always colors the whole cmdline.
3181static void color_expr_cmdline(const CmdlineInfo *const colored_ccline,
3182                               ColoredCmdline *const ret_ccline_colors)
3183  FUNC_ATTR_NONNULL_ALL
3184{
3185  ParserLine parser_lines[] = {
3186    {
3187      .data = colored_ccline->cmdbuff,
3188      .size = strlen(colored_ccline->cmdbuff),
3189      .allocated = false,
3190    },
3191    { NULL, 0, false },
3192  };
3193  ParserLine *plines_p = parser_lines;
3194  ParserHighlight colors;
3195  kvi_init(colors);
3196  ParserState pstate;
3197  viml_parser_init(&pstate, parser_simple_get_line, &plines_p, &colors);
3198  ExprAST east = viml_pexpr_parse(&pstate, kExprFlagsDisallowEOC);
3199  viml_pexpr_free_ast(east);
3200  viml_parser_destroy(&pstate);
3201  kv_resize(ret_ccline_colors->colors, kv_size(colors));
3202  size_t prev_end = 0;
3203  for (size_t i = 0; i < kv_size(colors); i++) {
3204    const ParserHighlightChunk chunk = kv_A(colors, i);
3205    assert(chunk.start.col < INT_MAX);
3206    assert(chunk.end_col < INT_MAX);
3207    if (chunk.start.col != prev_end) {
3208      kv_push(ret_ccline_colors->colors, ((CmdlineColorChunk) {
3209        .start = (int)prev_end,
3210        .end = (int)chunk.start.col,
3211        .hl_id = 0,
3212      }));
3213    }
3214    kv_push(ret_ccline_colors->colors, ((CmdlineColorChunk) {
3215      .start = (int)chunk.start.col,
3216      .end = (int)chunk.end_col,
3217      .hl_id = syn_name2id(chunk.group),
3218    }));
3219    prev_end = chunk.end_col;
3220  }
3221  if (prev_end < (size_t)colored_ccline->cmdlen) {
3222    kv_push(ret_ccline_colors->colors, ((CmdlineColorChunk) {
3223      .start = (int)prev_end,
3224      .end = colored_ccline->cmdlen,
3225      .hl_id = 0,
3226    }));
3227  }
3228  kvi_destroy(colors);
3229}
3230
3231/// Color command-line
3232///
3233/// Should use built-in command parser or user-specified one. Currently only the
3234/// latter is supported.
3235///
3236/// @param[in,out]  colored_ccline  Command-line to color. Also holds a cache:
3237///                                 if ->prompt_id and ->cmdbuff values happen
3238///                                 to be equal to those from colored_cmdline it
3239///                                 will just do nothing, assuming that ->colors
3240///                                 already contains needed data.
3241///
3242/// Always colors the whole cmdline.
3243///
3244/// @return true if draw_cmdline may proceed, false if it does not need anything
3245///         to do.
3246static bool color_cmdline(CmdlineInfo *colored_ccline)
3247  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
3248{
3249  bool printed_errmsg = false;
3250
3251#define PRINT_ERRMSG(...) \
3252  do { \
3253    msg_scroll = true; \
3254    msg_putchar('\n'); \
3255    smsg(HLF_E, __VA_ARGS__); \
3256    printed_errmsg = true; \
3257  } while (0)
3258  bool ret = true;
3259
3260  ColoredCmdline *ccline_colors = &colored_ccline->last_colors;
3261
3262  // Check whether result of the previous call is still valid.
3263  if (ccline_colors->prompt_id == colored_ccline->prompt_id
3264      && ccline_colors->cmdbuff != NULL
3265      && strcmp(ccline_colors->cmdbuff, colored_ccline->cmdbuff) == 0) {
3266    return ret;
3267  }
3268
3269  kv_size(ccline_colors->colors) = 0;
3270
3271  if (colored_ccline->cmdbuff == NULL || *colored_ccline->cmdbuff == NUL) {
3272    // Nothing to do, exiting.
3273    XFREE_CLEAR(ccline_colors->cmdbuff);
3274    return ret;
3275  }
3276
3277  bool arg_allocated = false;
3278  typval_T arg = {
3279    .v_type = VAR_STRING,
3280    .vval.v_string = colored_ccline->cmdbuff,
3281  };
3282  typval_T tv = { .v_type = VAR_UNKNOWN };
3283
3284  static unsigned prev_prompt_id = UINT_MAX;
3285  static int prev_prompt_errors = 0;
3286  Callback color_cb = CALLBACK_NONE;
3287  bool can_free_cb = false;
3288  Error err = ERROR_INIT;
3289  const char *err_errmsg = e_intern2;
3290  bool dgc_ret = true;
3291
3292  if (colored_ccline->prompt_id != prev_prompt_id) {
3293    prev_prompt_errors = 0;
3294    prev_prompt_id = colored_ccline->prompt_id;
3295  } else if (prev_prompt_errors >= MAX_CB_ERRORS) {
3296    goto color_cmdline_end;
3297  }
3298  if (colored_ccline->highlight_callback.type != kCallbackNone) {
3299    // Currently this should only happen while processing input() prompts.
3300    assert(colored_ccline->input_fn);
3301    color_cb = colored_ccline->highlight_callback;
3302  } else if (colored_ccline->cmdfirstc == ':') {
3303    TRY_WRAP(&err, {
3304      err_errmsg = N_("E5408: Unable to get g:Nvim_color_cmdline callback: %s");
3305      dgc_ret = tv_dict_get_callback(get_globvar_dict(), S_LEN("Nvim_color_cmdline"),
3306                                     &color_cb);
3307    });
3308    can_free_cb = true;
3309  } else if (colored_ccline->cmdfirstc == '=') {
3310    color_expr_cmdline(colored_ccline, ccline_colors);
3311  }
3312  if (ERROR_SET(&err) || !dgc_ret) {
3313    goto color_cmdline_error;
3314  }
3315
3316  if (color_cb.type == kCallbackNone) {
3317    goto color_cmdline_end;
3318  }
3319  if (colored_ccline->cmdbuff[colored_ccline->cmdlen] != NUL) {
3320    arg_allocated = true;
3321    arg.vval.v_string = xmemdupz(colored_ccline->cmdbuff, (size_t)colored_ccline->cmdlen);
3322  }
3323  // msg_start() called by e.g. :echo may shift command-line to the first column
3324  // even though msg_silent is here. Two ways to workaround this problem without
3325  // altering message.c: use full_screen or save and restore msg_col.
3326  //
3327  // Saving and restoring full_screen does not work well with :redraw!. Saving
3328  // and restoring msg_col is neither ideal, but while with full_screen it
3329  // appears shifted one character to the right and cursor position is no longer
3330  // correct, with msg_col it just misses leading `:`. Since `redraw!` in
3331  // callback lags this is least of the user problems.
3332  //
3333  // Also using TRY_WRAP because error messages may overwrite typed
3334  // command-line which is not expected.
3335  getln_interrupted_highlight = false;
3336  bool cbcall_ret = true;
3337  TRY_WRAP(&err, {
3338    err_errmsg = N_("E5407: Callback has thrown an exception: %s");
3339    const int saved_msg_col = msg_col;
3340    msg_silent++;
3341    cbcall_ret = callback_call(&color_cb, 1, &arg, &tv);
3342    msg_silent--;
3343    msg_col = saved_msg_col;
3344    if (got_int) {
3345      getln_interrupted_highlight = true;
3346    }
3347  });
3348  if (ERROR_SET(&err) || !cbcall_ret) {
3349    goto color_cmdline_error;
3350  }
3351  if (tv.v_type != VAR_LIST) {
3352    PRINT_ERRMSG("%s", _("E5400: Callback should return list"));
3353    goto color_cmdline_error;
3354  }
3355  if (tv.vval.v_list == NULL) {
3356    goto color_cmdline_end;
3357  }
3358  varnumber_T prev_end = 0;
3359  int i = 0;
3360  TV_LIST_ITER_CONST(tv.vval.v_list, li, {
3361    if (TV_LIST_ITEM_TV(li)->v_type != VAR_LIST) {
3362      PRINT_ERRMSG(_("E5401: List item %i is not a List"), i);
3363      goto color_cmdline_error;
3364    }
3365    const list_T *const l = TV_LIST_ITEM_TV(li)->vval.v_list;
3366    if (tv_list_len(l) != 3) {
3367      PRINT_ERRMSG(_("E5402: List item %i has incorrect length: %d /= 3"),
3368                   i, tv_list_len(l));
3369      goto color_cmdline_error;
3370    }
3371    bool error = false;
3372    const varnumber_T start = (
3373                               tv_get_number_chk(TV_LIST_ITEM_TV(tv_list_first(l)), &error));
3374    if (error) {
3375      goto color_cmdline_error;
3376    } else if (!(prev_end <= start && start < colored_ccline->cmdlen)) {
3377      PRINT_ERRMSG(_("E5403: Chunk %i start %" PRIdVARNUMBER " not in range "
3378                     "[%" PRIdVARNUMBER ", %i)"),
3379                   i, start, prev_end, colored_ccline->cmdlen);
3380      goto color_cmdline_error;
3381    } else if (utf8len_tab_zero[(uint8_t)colored_ccline->cmdbuff[start]] == 0) {
3382      PRINT_ERRMSG(_("E5405: Chunk %i start %" PRIdVARNUMBER " splits "
3383                     "multibyte character"), i, start);
3384      goto color_cmdline_error;
3385    }
3386    if (start != prev_end) {
3387      kv_push(ccline_colors->colors, ((CmdlineColorChunk) {
3388        .start = (int)prev_end,
3389        .end = (int)start,
3390        .hl_id = 0,
3391      }));
3392    }
3393    const varnumber_T end =
3394      tv_get_number_chk(TV_LIST_ITEM_TV(TV_LIST_ITEM_NEXT(l, tv_list_first(l))), &error);
3395    if (error) {
3396      goto color_cmdline_error;
3397    } else if (!(start < end && end <= colored_ccline->cmdlen)) {
3398      PRINT_ERRMSG(_("E5404: Chunk %i end %" PRIdVARNUMBER " not in range "
3399                     "(%" PRIdVARNUMBER ", %i]"),
3400                   i, end, start, colored_ccline->cmdlen);
3401      goto color_cmdline_error;
3402    } else if (end < colored_ccline->cmdlen
3403               && (utf8len_tab_zero[(uint8_t)colored_ccline->cmdbuff[end]]
3404                   == 0)) {
3405      PRINT_ERRMSG(_("E5406: Chunk %i end %" PRIdVARNUMBER " splits multibyte "
3406                     "character"), i, end);
3407      goto color_cmdline_error;
3408    }
3409    prev_end = end;
3410    const char *const group = tv_get_string_chk(TV_LIST_ITEM_TV(tv_list_last(l)));
3411    if (group == NULL) {
3412      goto color_cmdline_error;
3413    }
3414    kv_push(ccline_colors->colors, ((CmdlineColorChunk) {
3415      .start = (int)start,
3416      .end = (int)end,
3417      .hl_id = syn_name2id(group),
3418    }));
3419    i++;
3420  });
3421  if (prev_end < colored_ccline->cmdlen) {
3422    kv_push(ccline_colors->colors, ((CmdlineColorChunk) {
3423      .start = (int)prev_end,
3424      .end = colored_ccline->cmdlen,
3425      .hl_id = 0,
3426    }));
3427  }
3428  prev_prompt_errors = 0;
3429color_cmdline_end:
3430  assert(!ERROR_SET(&err));
3431  if (can_free_cb) {
3432    callback_free(&color_cb);
3433  }
3434  xfree(ccline_colors->cmdbuff);
3435  // Note: errors “output” is cached just as well as regular results.
3436  ccline_colors->prompt_id = colored_ccline->prompt_id;
3437  if (arg_allocated) {
3438    ccline_colors->cmdbuff = arg.vval.v_string;
3439  } else {
3440    ccline_colors->cmdbuff = xmemdupz(colored_ccline->cmdbuff, (size_t)colored_ccline->cmdlen);
3441  }
3442  tv_clear(&tv);
3443  return ret;
3444color_cmdline_error:
3445  if (ERROR_SET(&err)) {
3446    PRINT_ERRMSG(_(err_errmsg), err.msg);
3447    api_clear_error(&err);
3448  }
3449  assert(printed_errmsg);
3450  (void)printed_errmsg;
3451
3452  prev_prompt_errors++;
3453  kv_size(ccline_colors->colors) = 0;
3454  redrawcmdline();
3455  ret = false;
3456  goto color_cmdline_end;
3457#undef PRINT_ERRMSG
3458}
3459
3460// Draw part of the cmdline at the current cursor position.  But draw stars
3461// when cmdline_star is true.
3462static void draw_cmdline(int start, int len)
3463{
3464  if (ccline.cmdbuff == NULL || !color_cmdline(&ccline)) {
3465    return;
3466  }
3467
3468  if (ui_has(kUICmdline)) {
3469    ccline.special_char = NUL;
3470    ccline.redraw_state = kCmdRedrawAll;
3471    return;
3472  }
3473
3474  if (cmdline_star > 0) {
3475    for (int i = 0; i < len; i++) {
3476      msg_putchar('*');
3477      i += utfc_ptr2len(ccline.cmdbuff + start + i) - 1;
3478    }
3479  } else {
3480    if (kv_size(ccline.last_colors.colors)) {
3481      for (size_t i = 0; i < kv_size(ccline.last_colors.colors); i++) {
3482        CmdlineColorChunk chunk = kv_A(ccline.last_colors.colors, i);
3483        if (chunk.end <= start) {
3484          continue;
3485        }
3486        const int chunk_start = MAX(chunk.start, start);
3487        msg_outtrans_len(ccline.cmdbuff + chunk_start, chunk.end - chunk_start, chunk.hl_id, false);
3488      }
3489    } else {
3490      msg_outtrans_len(ccline.cmdbuff + start, len, 0, false);
3491    }
3492  }
3493}
3494
3495static void ui_ext_cmdline_show(CmdlineInfo *line)
3496{
3497  Arena arena = ARENA_EMPTY;
3498  Array content;
3499  if (cmdline_star) {
3500    content = arena_array(&arena, 1);
3501    size_t len = 0;
3502    for (char *p = ccline.cmdbuff; *p; MB_PTR_ADV(p)) {
3503      len++;
3504    }
3505    char *buf = arena_alloc(&arena, len, false);
3506    memset(buf, '*', len);
3507    Array item = arena_array(&arena, 3);
3508    ADD_C(item, INTEGER_OBJ(0));
3509    ADD_C(item, STRING_OBJ(cbuf_as_string(buf, len)));
3510    ADD_C(item, INTEGER_OBJ(0));
3511    ADD_C(content, ARRAY_OBJ(item));
3512  } else if (kv_size(line->last_colors.colors)) {
3513    content = arena_array(&arena, kv_size(line->last_colors.colors));
3514    for (size_t i = 0; i < kv_size(line->last_colors.colors); i++) {
3515      CmdlineColorChunk chunk = kv_A(line->last_colors.colors, i);
3516      Array item = arena_array(&arena, 3);
3517      ADD_C(item, INTEGER_OBJ(chunk.hl_id == 0 ? 0 : syn_id2attr(chunk.hl_id)));
3518
3519      assert(chunk.end >= chunk.start);
3520      ADD_C(item, STRING_OBJ(cbuf_as_string(line->cmdbuff + chunk.start,
3521                                            (size_t)(chunk.end - chunk.start))));
3522      ADD_C(item, INTEGER_OBJ(chunk.hl_id));
3523      ADD_C(content, ARRAY_OBJ(item));
3524    }
3525  } else {
3526    Array item = arena_array(&arena, 3);
3527    ADD_C(item, INTEGER_OBJ(0));
3528    ADD_C(item, CSTR_AS_OBJ(line->cmdbuff));
3529    ADD_C(item, INTEGER_OBJ(0));
3530    content = arena_array(&arena, 1);
3531    ADD_C(content, ARRAY_OBJ(item));
3532  }
3533  char charbuf[2] = { (char)line->cmdfirstc, 0 };
3534  ui_call_cmdline_show(content, line->cmdpos,
3535                       cstr_as_string(charbuf),
3536                       cstr_as_string(line->cmdprompt),
3537                       line->cmdindent, line->level, line->cmdprompt ? line->hl_id : -1);
3538  if (line->special_char) {
3539    charbuf[0] = line->special_char;
3540    ui_call_cmdline_special_char(cstr_as_string(charbuf),
3541                                 line->special_shift,
3542                                 line->level);
3543  }
3544  arena_mem_free(arena_finish(&arena));
3545}
3546
3547void ui_ext_cmdline_block_append(size_t indent, const char *line)
3548{
3549  char *buf = xmallocz(indent + strlen(line));
3550  memset(buf, ' ', indent);
3551  memcpy(buf + indent, line, strlen(line));
3552
3553  Array item = ARRAY_DICT_INIT;
3554  ADD(item, INTEGER_OBJ(0));
3555  ADD(item, CSTR_AS_OBJ(buf));
3556  ADD(item, INTEGER_OBJ(0));
3557  Array content = ARRAY_DICT_INIT;
3558  ADD(content, ARRAY_OBJ(item));
3559  ADD(cmdline_block, ARRAY_OBJ(content));
3560  if (cmdline_block.size > 1) {
3561    ui_call_cmdline_block_append(content);
3562  } else {
3563    ui_call_cmdline_block_show(cmdline_block);
3564  }
3565}
3566
3567void ui_ext_cmdline_block_leave(void)
3568{
3569  api_free_array(cmdline_block);
3570  cmdline_block = (Array)ARRAY_DICT_INIT;
3571  ui_call_cmdline_block_hide();
3572}
3573
3574/// Extra redrawing needed for redraw! and on ui_attach.
3575void cmdline_screen_cleared(void)
3576{
3577  if (!ui_has(kUICmdline)) {
3578    return;
3579  }
3580
3581  if (cmdline_block.size) {
3582    ui_call_cmdline_block_show(cmdline_block);
3583  }
3584
3585  int prev_level = ccline.level - 1;
3586  CmdlineInfo *line = ccline.prev_ccline;
3587  while (prev_level > 0 && line) {
3588    if (line->level == prev_level) {
3589      // Always redraw (cmdwin is not special since #40312).
3590      line->redraw_state = kCmdRedrawAll;
3591      prev_level--;
3592    }
3593    line = line->prev_ccline;
3594  }
3595  redrawcmd();
3596}
3597
3598/// called by ui_flush, do what redraws necessary to keep cmdline updated.
3599void cmdline_ui_flush(void)
3600{
3601  if (!ui_has(kUICmdline)) {
3602    return;
3603  }
3604  int level = ccline.level;
3605  CmdlineInfo *line = &ccline;
3606  while (level > 0 && line) {
3607    if (line->level == level) {
3608      CmdRedraw redraw_state = line->redraw_state;
3609      line->redraw_state = kCmdRedrawNone;
3610      if (redraw_state == kCmdRedrawAll) {
3611        cmdline_was_last_drawn = true;
3612        ui_ext_cmdline_show(line);
3613      } else if (redraw_state == kCmdRedrawPos && cmdline_was_last_drawn) {
3614        ui_call_cmdline_pos(line->cmdpos, line->level);
3615      }
3616      level--;
3617    }
3618    line = line->prev_ccline;
3619  }
3620}
3621
3622// Put a character on the command line.  Shifts the following text to the
3623// right when "shift" is true.  Used for CTRL-V, CTRL-K, etc.
3624// "c" must be printable (fit in one display cell)!
3625void putcmdline(char c, bool shift)
3626{
3627  if (cmd_silent) {
3628    return;
3629  }
3630  if (!ui_has(kUICmdline)) {
3631    msg_no_more = true;
3632    msg_putchar(c);
3633    if (shift) {
3634      draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
3635    }
3636    msg_no_more = false;
3637  } else if (ccline.redraw_state != kCmdRedrawAll) {
3638    char charbuf[2] = { c, 0 };
3639    ui_call_cmdline_special_char(cstr_as_string(charbuf), shift,
3640                                 ccline.level);
3641  }
3642  cursorcmd();
3643  ccline.special_char = c;
3644  ccline.special_shift = shift;
3645  ui_cursor_shape();
3646}
3647
3648/// Undo a putcmdline(c, false).
3649void unputcmdline(void)
3650{
3651  if (cmd_silent) {
3652    return;
3653  }
3654  msg_no_more = true;
3655  if (ccline.cmdlen == ccline.cmdpos && !ui_has(kUICmdline)) {
3656    msg_putchar(' ');
3657  } else {
3658    draw_cmdline(ccline.cmdpos, utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos));
3659  }
3660  msg_no_more = false;
3661  cursorcmd();
3662  ccline.special_char = NUL;
3663  ui_cursor_shape();
3664}
3665
3666// Put the given string, of the given length, onto the command line.
3667// If len is -1, then strlen() is used to calculate the length.
3668// If 'redraw' is true then the new part of the command line, and the remaining
3669// part will be redrawn, otherwise it will not.  If this function is called
3670// twice in a row, then 'redraw' should be false and redrawcmd() should be
3671// called afterwards.
3672void put_on_cmdline(const char *str, int len, bool redraw)
3673{
3674  if (len < 0) {
3675    len = (int)strlen(str);
3676  }
3677
3678  realloc_cmdbuff(ccline.cmdlen + len + 1);
3679
3680  if (!ccline.overstrike) {
3681    memmove(ccline.cmdbuff + ccline.cmdpos + len,
3682            ccline.cmdbuff + ccline.cmdpos,
3683            (size_t)(ccline.cmdlen - ccline.cmdpos));
3684    ccline.cmdlen += len;
3685  } else {
3686    // Count nr of characters in the new string.
3687    int m = 0;
3688    int i;
3689    for (i = 0; i < len; i += utfc_ptr2len(str + i)) {
3690      m++;
3691    }
3692    // Count nr of bytes in cmdline that are overwritten by these
3693    // characters.
3694    for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0;
3695         i += utfc_ptr2len(ccline.cmdbuff + i)) {
3696      m--;
3697    }
3698    if (i < ccline.cmdlen) {
3699      memmove(ccline.cmdbuff + ccline.cmdpos + len,
3700              ccline.cmdbuff + i, (size_t)(ccline.cmdlen - i));
3701      ccline.cmdlen += ccline.cmdpos + len - i;
3702    } else {
3703      ccline.cmdlen = ccline.cmdpos + len;
3704    }
3705  }
3706  memmove(ccline.cmdbuff + ccline.cmdpos, str, (size_t)len);
3707  ccline.cmdbuff[ccline.cmdlen] = NUL;
3708
3709  // When the inserted text starts with a composing character,
3710  // backup to the character before it.
3711  if (ccline.cmdpos > 0 && (uint8_t)ccline.cmdbuff[ccline.cmdpos] >= 0x80) {
3712    int i = utf_head_off(ccline.cmdbuff, ccline.cmdbuff + ccline.cmdpos);
3713    if (i != 0) {
3714      ccline.cmdpos -= i;
3715      len += i;
3716      ccline.cmdspos = cmd_screencol(ccline.cmdpos);
3717    }
3718  }
3719
3720  if (redraw && !cmd_silent) {
3721    msg_no_more = true;
3722    int i = cmdline_row;
3723    cursorcmd();
3724    draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
3725    // Avoid clearing the rest of the line too often.
3726    if (cmdline_row != i || ccline.overstrike) {
3727      msg_clr_eos();
3728    }
3729    msg_no_more = false;
3730  }
3731  int m;
3732  if (KeyTyped) {
3733    m = Columns * Rows;
3734    if (m < 0) {            // overflow, Columns or Rows at weird value
3735      m = MAXCOL;
3736    }
3737  } else {
3738    m = MAXCOL;
3739  }
3740  for (int i = 0; i < len; i++) {
3741    int c = cmdline_charsize(ccline.cmdpos);
3742    // count ">" for a double-wide char that doesn't fit.
3743    correct_screencol(ccline.cmdpos, c, &ccline.cmdspos);
3744    // Stop cursor at the end of the screen, but do increment the
3745    // insert position, so that entering a very long command
3746    // works, even though you can't see it.
3747    if (ccline.cmdspos + c < m) {
3748      ccline.cmdspos += c;
3749    }
3750    c = utfc_ptr2len(ccline.cmdbuff + ccline.cmdpos) - 1;
3751    c = MIN(c, len - i - 1);
3752    ccline.cmdpos += c;
3753    i += c;
3754    ccline.cmdpos++;
3755  }
3756
3757  if (redraw) {
3758    msg_check();
3759  }
3760}
3761
3762/// Save ccline, because obtaining the "=" register may execute "normal :cmd"
3763/// and overwrite it.
3764static void save_cmdline(CmdlineInfo *ccp)
3765{
3766  *ccp = ccline;
3767  CLEAR_FIELD(ccline);
3768  ccline.prev_ccline = ccp;
3769  ccline.cmdbuff = NULL;  // signal that ccline is not in use
3770}
3771
3772/// Restore ccline after it has been saved with save_cmdline().
3773static void restore_cmdline(CmdlineInfo *ccp)
3774  FUNC_ATTR_NONNULL_ALL
3775{
3776  ccline = *ccp;
3777}
3778
3779/// Paste a yank register into the command line.
3780/// Used by CTRL-R command in command-line mode.
3781/// insert_reg() can't be used here, because special characters from the
3782/// register contents will be interpreted as commands.
3783///
3784/// @param regname   Register name.
3785/// @param literally Insert text literally instead of "as typed".
3786/// @param remcr     When true, remove trailing CR.
3787///
3788/// @returns FAIL for failure, OK otherwise
3789static bool cmdline_paste(int regname, bool literally, bool remcr)
3790{
3791  char *arg;
3792  bool allocated;
3793
3794  // check for valid regname; also accept special characters for CTRL-R in
3795  // the command line
3796  if (regname != Ctrl_F && regname != Ctrl_P && regname != Ctrl_W
3797      && regname != Ctrl_A && regname != Ctrl_L
3798      && !valid_yank_reg(regname, false)) {
3799    return FAIL;
3800  }
3801
3802  // A register containing CTRL-R can cause an endless loop.  Allow using
3803  // CTRL-C to break the loop.
3804  line_breakcheck();
3805  if (got_int) {
3806    return FAIL;
3807  }
3808
3809  // Need to  set "textlock" to avoid nasty things like going to another
3810  // buffer when evaluating an expression.
3811  textlock++;
3812  const bool i = get_spec_reg(regname, &arg, &allocated, true);
3813  textlock--;
3814
3815  if (i) {
3816    // Got the value of a special register in "arg".
3817    if (arg == NULL) {
3818      return FAIL;
3819    }
3820
3821    // When 'incsearch' is set and CTRL-R CTRL-W used: skip the duplicate
3822    // part of the word.
3823    char *p = arg;
3824    if (p_is && regname == Ctrl_W) {
3825      char *w;
3826      int len;
3827
3828      // Locate start of last word in the cmd buffer.
3829      for (w = ccline.cmdbuff + ccline.cmdpos; w > ccline.cmdbuff;) {
3830        len = utf_head_off(ccline.cmdbuff, w - 1) + 1;
3831        if (!vim_iswordc(utf_ptr2char(w - len))) {
3832          break;
3833        }
3834        w -= len;
3835      }
3836      len = (int)((ccline.cmdbuff + ccline.cmdpos) - w);
3837      if (p_ic ? STRNICMP(w, arg, (size_t)len) == 0 : strncmp(w, arg, (size_t)len) == 0) {
3838        p += len;
3839      }
3840    }
3841
3842    cmdline_paste_str(p, literally);
3843    if (allocated) {
3844      xfree(arg);
3845    }
3846    return OK;
3847  }
3848
3849  return cmdline_paste_reg(regname, literally, remcr);
3850}
3851
3852// Put a string on the command line.
3853// When "literally" is true, insert literally.
3854// When "literally" is false, insert as typed, but don't leave the command
3855// line.
3856void cmdline_paste_str(const char *s, bool literally)
3857{
3858  if (literally) {
3859    put_on_cmdline(s, -1, true);
3860  } else {
3861    while (*s != NUL) {
3862      int cv = (uint8_t)(*s);
3863      if (cv == Ctrl_V && s[1]) {
3864        s++;
3865      }
3866      int c = mb_cptr2char_adv(&s);
3867      if (cv == Ctrl_V || c == ESC || c == Ctrl_C
3868          || c == CAR || c == NL || c == Ctrl_L
3869          || (c == Ctrl_BSL && *s == Ctrl_N)) {
3870        stuffcharReadbuff(Ctrl_V);
3871      }
3872      stuffcharReadbuff(c);
3873    }
3874  }
3875}
3876
3877// This function is called when the screen size changes and with incremental
3878// search and in other situations where the command line may have been
3879// overwritten.
3880void redrawcmdline(void)
3881{
3882  if (cmd_silent) {
3883    return;
3884  }
3885  need_wait_return = false;
3886  compute_cmdrow();
3887  redrawcmd();
3888  cursorcmd();
3889  ui_cursor_shape();
3890}
3891
3892static void redrawcmdprompt(void)
3893{
3894  if (cmd_silent) {
3895    return;
3896  }
3897  if (ui_has(kUICmdline)) {
3898    ccline.redraw_state = kCmdRedrawAll;
3899    return;
3900  }
3901  if (ccline.cmdfirstc != NUL) {
3902    msg_putchar(ccline.cmdfirstc);
3903  }
3904  if (ccline.cmdprompt != NULL) {
3905    msg_puts_hl(ccline.cmdprompt, ccline.hl_id, false);
3906    ccline.cmdindent = msg_col + (msg_row - cmdline_row) * Columns;
3907    // do the reverse of cmd_startcol()
3908    if (ccline.cmdfirstc != NUL) {
3909      ccline.cmdindent--;
3910    }
3911  } else {
3912    for (int i = ccline.cmdindent; i > 0; i--) {
3913      msg_putchar(' ');
3914    }
3915  }
3916}
3917
3918// Redraw what is currently on the command line.
3919void redrawcmd(void)
3920{
3921  if (cmd_silent) {
3922    return;
3923  }
3924
3925  if (ui_has(kUICmdline)) {
3926    draw_cmdline(0, ccline.cmdlen);
3927    return;
3928  }
3929
3930  // when 'incsearch' is set there may be no command line while redrawing
3931  if (ccline.cmdbuff == NULL) {
3932    msg_cursor_goto(cmdline_row, 0);
3933    msg_clr_eos();
3934    return;
3935  }
3936
3937  redrawing_cmdline = true;
3938
3939  sb_text_restart_cmdline();
3940  msg_start();
3941  // Reset lines_left so a wrapped cmdline isn't truncated by msg_no_more.
3942  msg_starthere();
3943  redrawcmdprompt();
3944
3945  // Don't use more prompt, truncate the cmdline if it doesn't fit.
3946  msg_no_more = true;
3947  draw_cmdline(0, ccline.cmdlen);
3948  msg_clr_eos();
3949  msg_no_more = false;
3950
3951  ccline.cmdspos = cmd_screencol(ccline.cmdpos);
3952
3953  if (ccline.special_char != NUL) {
3954    putcmdline(ccline.special_char, ccline.special_shift);
3955  }
3956
3957  // An emsg() before may have set msg_scroll. This is used in normal mode,
3958  // in cmdline mode we can reset them now.
3959  msg_scroll = false;           // next message overwrites cmdline
3960
3961  // Typing ':' at the more prompt may set skip_redraw.  We don't want this
3962  // in cmdline mode.
3963  skip_redraw = false;
3964  cmdline_was_last_drawn = true;
3965  redrawing_cmdline = false;
3966}
3967
3968void compute_cmdrow(void)
3969{
3970  if (msg_scrolled != 0) {
3971    cmdline_row = Rows - 1;
3972  } else {
3973    win_T *wp = lastwin_nofloating(NULL);
3974    cmdline_row = wp->w_winrow + wp->w_height
3975                  + wp->w_hsep_height + wp->w_status_height + global_stl_height();
3976  }
3977  if (cmdline_row == Rows && p_ch > 0) {
3978    cmdline_row--;
3979  }
3980  lines_left = cmdline_row;
3981}
3982
3983void cursorcmd(void)
3984{
3985  if (cmd_silent || ui_has(kUICmdline)) {
3986    return;
3987  }
3988
3989  msg_row = cmdline_row + (ccline.cmdspos / Columns);
3990  msg_col = ccline.cmdspos % Columns;
3991  msg_row = MIN(msg_row, Rows - 1);
3992
3993  msg_cursor_goto(msg_row, msg_col);
3994}
3995
3996void gotocmdline(bool clr)
3997{
3998  if (ui_has(kUICmdline)) {
3999    return;
4000  }
4001  msg_start();
4002  msg_col = 0;  // always start in column 0
4003  if (clr) {  // clear the bottom line(s)
4004    msg_clr_eos();  // will reset clear_cmdline
4005  }
4006  msg_cursor_goto(cmdline_row, 0);
4007}
4008
4009// Check the word in front of the cursor for an abbreviation.
4010// Called when the non-id character "c" has been entered.
4011// When an abbreviation is recognized it is removed from the text with
4012// backspaces and the replacement string is inserted, followed by "c".
4013static int ccheck_abbr(int c)
4014{
4015  int spos = 0;
4016
4017  if (p_paste || no_abbr) {         // no abbreviations or in paste mode
4018    return false;
4019  }
4020
4021  // Do not consider '<,'> be part of the mapping, skip leading whitespace.
4022  // Actually accepts any mark.
4023  while (spos < ccline.cmdlen && ascii_iswhite(ccline.cmdbuff[spos])) {
4024    spos++;
4025  }
4026  if (ccline.cmdlen - spos > 5
4027      && ccline.cmdbuff[spos] == '\''
4028      && ccline.cmdbuff[spos + 2] == ','
4029      && ccline.cmdbuff[spos + 3] == '\'') {
4030    spos += 5;
4031  } else {
4032    // check abbreviation from the beginning of the commandline
4033    spos = 0;
4034  }
4035
4036  return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, spos);
4037}
4038
4039/// Escape special characters in "fname", depending on "what":
4040///
4041/// @param[in]  fname  File name to escape.
4042/// @param[in]  what   What to escape for:
4043/// - VSE_NONE: for when used as a file name argument after a Vim command.
4044/// - VSE_SHELL: for a shell command.
4045/// - VSE_BUFFER: for the ":buffer" command.
4046///
4047/// @return [allocated] escaped file name.
4048char *vim_strsave_fnameescape(const char *const fname, const int what)
4049  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
4050{
4051#ifdef BACKSLASH_IN_FILENAME
4052# define PATH_ESC_CHARS " \t\n*?[{`%#'\"|!<"
4053// '%' and '#' are not escaped for ":buffer": it has no EX_XFILE, so they are
4054// not expanded, and escaping them as "\%"/"\#" breaks buffer name matching
4055// when '%'/'#' is in 'isfname' (backslash treated as a path separator).
4056# define BUFFER_ESC_CHARS (" \t\n*?[`'\"|!<")
4057  char buf[sizeof(PATH_ESC_CHARS)];
4058  int j = 0;
4059
4060  // Don't escape '[', '{' and '!' if they are in 'isfname' and for the
4061  // ":buffer" command.
4062  for (const char *p = what == VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS;
4063       *p != NUL; p++) {
4064    if ((*p != '[' && *p != '{' && *p != '!') || !vim_isfilec((uint8_t)(*p))) {
4065      buf[j++] = *p;
4066    }
4067  }
4068  buf[j] = NUL;
4069  char *p = vim_strsave_escaped(fname, buf);
4070#else
4071# define PATH_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<"
4072# define SHELL_ESC_CHARS " \t\n*?[{`$\\%#'\"|!<>();&"
4073# define BUFFER_ESC_CHARS " \t\n*?[`$\\%#'\"|!<"
4074  char *p = vim_strsave_escaped(fname,
4075                                what == VSE_SHELL ? SHELL_ESC_CHARS : what ==
4076                                VSE_BUFFER ? BUFFER_ESC_CHARS : PATH_ESC_CHARS);
4077  if (what == VSE_SHELL && csh_like_shell()) {
4078    // For csh and similar shells need to put two backslashes before '!'.
4079    // One is taken by Vim, one by the shell.
4080    char *s = vim_strsave_escaped(p, "!");
4081    xfree(p);
4082    p = s;
4083  }
4084#endif
4085
4086  // '>' and '+' are special at the start of some commands, e.g. ":edit" and
4087  // ":write".  "cd -" has a special meaning.
4088  if (*p == '>' || *p == '+' || (*p == '-' && p[1] == NUL)) {
4089    escape_fname(&p);
4090  }
4091
4092  return p;
4093}
4094
4095/// Put a backslash before the file name in "pp", which is in allocated memory.
4096void escape_fname(char **pp)
4097{
4098  char *p = xmalloc(strlen(*pp) + 2);
4099  p[0] = '\\';
4100  STRCPY(p + 1, *pp);
4101  xfree(*pp);
4102  *pp = p;
4103}
4104
4105/// For each file name in files[num_files]:
4106/// If 'orig_pat' starts with "~/", replace the home directory with "~".
4107void tilde_replace(char *orig_pat, int num_files, char **files)
4108{
4109  if (orig_pat[0] == '~' && vim_ispathsep(orig_pat[1])) {
4110    for (int i = 0; i < num_files; i++) {
4111      char *p = home_replace_save(NULL, files[i]);
4112      xfree(files[i]);
4113      files[i] = p;
4114    }
4115  }
4116}
4117
4118/// Get a pointer to the current command line info.
4119CmdlineInfo *get_cmdline_info(void)
4120{
4121  return &ccline;
4122}
4123
4124unsigned get_cmdline_last_prompt_id(void)
4125{
4126  return last_prompt_id;
4127}
4128
4129/// Get pointer to the command line info to use. save_cmdline() may clear
4130/// ccline and put the previous value in ccline.prev_ccline.
4131static CmdlineInfo *get_ccline_ptr(void)
4132{
4133  if ((State & MODE_CMDLINE) == 0) {
4134    return NULL;
4135  } else if (ccline.cmdbuff != NULL) {
4136    return &ccline;
4137  } else if (ccline.prev_ccline && ccline.prev_ccline->cmdbuff != NULL) {
4138    return ccline.prev_ccline;
4139  } else {
4140    return NULL;
4141  }
4142}
4143
4144/// Get the current command-line type.
4145/// Returns ':' or '/' or '?' or '@' or '>' or '-'
4146/// Only works when the command line is being edited.
4147/// Returns NUL when something is wrong.
4148static int get_cmdline_type(void)
4149{
4150  CmdlineInfo *p = get_ccline_ptr();
4151
4152  if (p == NULL) {
4153    return NUL;
4154  }
4155  if (p->cmdfirstc == NUL) {
4156    return (p->input_fn) ? '@' : '-';
4157  }
4158  return p->cmdfirstc;
4159}
4160
4161/// Get the current command line in allocated memory.
4162/// Only works when the command line is being edited.
4163///
4164/// @return  NULL when something is wrong.
4165static char *get_cmdline_str(void)
4166{
4167  if (cmdline_star > 0) {
4168    return NULL;
4169  }
4170  CmdlineInfo *p = get_ccline_ptr();
4171
4172  if (p == NULL) {
4173    return NULL;
4174  }
4175  return xstrnsave(p->cmdbuff, (size_t)p->cmdlen);
4176}
4177
4178/// Get the current command-line completion pattern.
4179static char *get_cmdline_completion_pattern(void)
4180{
4181  if (cmdline_star > 0) {
4182    return NULL;
4183  }
4184
4185  CmdlineInfo *p = get_ccline_ptr();
4186  if (p == NULL || p->xpc == NULL) {
4187    return NULL;
4188  }
4189
4190  int xp_context = p->xpc->xp_context;
4191  if (xp_context == EXPAND_NOTHING) {
4192    set_expand_context(p->xpc);
4193    xp_context = p->xpc->xp_context;
4194    p->xpc->xp_context = EXPAND_NOTHING;
4195  }
4196  if (xp_context == EXPAND_UNSUCCESSFUL) {
4197    return NULL;
4198  }
4199
4200  char *compl_pat = p->xpc->xp_pattern;
4201  if (compl_pat == NULL) {
4202    return NULL;
4203  }
4204
4205  return xstrdup(compl_pat);
4206}
4207
4208/// Get the command-line completion type.
4209static char *get_cmdline_completion(void)
4210{
4211  if (cmdline_star > 0) {
4212    return NULL;
4213  }
4214
4215  CmdlineInfo *p = get_ccline_ptr();
4216  if (p == NULL || p->xpc == NULL) {
4217    return NULL;
4218  }
4219
4220  int xp_context = p->xpc->xp_context;
4221  if (xp_context == EXPAND_NOTHING) {
4222    set_expand_context(p->xpc);
4223    xp_context = p->xpc->xp_context;
4224    p->xpc->xp_context = EXPAND_NOTHING;
4225  }
4226  if (xp_context == EXPAND_UNSUCCESSFUL) {
4227    return NULL;
4228  }
4229
4230  return cmdcomplete_type_to_str(xp_context, p->xpc->xp_arg);
4231}
4232
4233/// "getcmdcomplpat()" function
4234void f_getcmdcomplpat(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4235{
4236  rettv->v_type = VAR_STRING;
4237  rettv->vval.v_string = get_cmdline_completion_pattern();
4238}
4239
4240/// "getcmdcompltype()" function
4241void f_getcmdcompltype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4242{
4243  rettv->v_type = VAR_STRING;
4244  rettv->vval.v_string = get_cmdline_completion();
4245}
4246
4247/// "getcmdline()" function
4248void f_getcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4249{
4250  rettv->v_type = VAR_STRING;
4251  rettv->vval.v_string = get_cmdline_str();
4252}
4253
4254/// "getcmdpos()" function
4255void f_getcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4256{
4257  CmdlineInfo *p = get_ccline_ptr();
4258  rettv->vval.v_number = p != NULL ? p->cmdpos + 1 : 0;
4259}
4260
4261/// "getcmdprompt()" function
4262void f_getcmdprompt(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4263{
4264  CmdlineInfo *p = get_ccline_ptr();
4265  rettv->v_type = VAR_STRING;
4266  rettv->vval.v_string = p != NULL && p->cmdprompt != NULL
4267                         ? xstrdup(p->cmdprompt) : NULL;
4268}
4269
4270/// "getcmdscreenpos()" function
4271void f_getcmdscreenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4272{
4273  CmdlineInfo *p = get_ccline_ptr();
4274  rettv->vval.v_number = p != NULL ? p->cmdspos + 1 : 0;
4275}
4276
4277/// "getcmdtype()" function
4278void f_getcmdtype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4279{
4280  rettv->v_type = VAR_STRING;
4281  rettv->vval.v_string = xmallocz(1);
4282  rettv->vval.v_string[0] = (char)get_cmdline_type();
4283}
4284
4285/// Set the command line str to "str".
4286/// @return  1 when failed, 0 when OK.
4287static int set_cmdline_str(const char *str, int pos)
4288{
4289  CmdlineInfo *p = get_ccline_ptr();
4290
4291  if (p == NULL) {
4292    return 1;
4293  }
4294
4295  int len = (int)strlen(str);
4296  realloc_cmdbuff(len + 1);
4297  p->cmdlen = len;
4298  STRCPY(p->cmdbuff, str);
4299
4300  p->cmdpos = pos < 0 || pos > p->cmdlen ? p->cmdlen : pos;
4301  new_cmdpos = p->cmdpos;
4302  p->cmdbuff_replaced = true;
4303
4304  redrawcmd();
4305
4306  // Trigger CmdlineChanged autocommands.
4307  do_autocmd_cmdlinechanged(get_cmdline_type());
4308
4309  return 0;
4310}
4311
4312/// Set the command line byte position to "pos".  Zero is the first position.
4313/// Only works when the command line is being edited.
4314/// @return  1 when failed, 0 when OK.
4315static int set_cmdline_pos(int pos)
4316{
4317  CmdlineInfo *p = get_ccline_ptr();
4318
4319  if (p == NULL) {
4320    return 1;
4321  }
4322
4323  // The position is not set directly but after CTRL-\ e or CTRL-R = has
4324  // changed the command line.
4325  new_cmdpos = MAX(0, pos);
4326
4327  return 0;
4328}
4329
4330/// "setcmdline()" function
4331void f_setcmdline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4332{
4333  if (tv_check_for_string_arg(argvars, 0) == FAIL
4334      || tv_check_for_opt_number_arg(argvars, 1) == FAIL) {
4335    return;
4336  }
4337
4338  int pos = -1;
4339  if (argvars[1].v_type != VAR_UNKNOWN) {
4340    bool error = false;
4341
4342    pos = (int)tv_get_number_chk(&argvars[1], &error) - 1;
4343    if (error) {
4344      return;
4345    }
4346    if (pos < 0) {
4347      emsg(_(e_positive));
4348      return;
4349    }
4350  }
4351
4352  // Use tv_get_string() to handle a NULL string like an empty string.
4353  rettv->vval.v_number = set_cmdline_str(tv_get_string(&argvars[0]), pos);
4354}
4355
4356/// "setcmdpos()" function
4357void f_setcmdpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4358{
4359  const int pos = (int)tv_get_number(&argvars[0]) - 1;
4360
4361  if (pos >= 0) {
4362    rettv->vval.v_number = set_cmdline_pos(pos);
4363  }
4364}
4365
4366/// Return the first character of the current command line.
4367int get_cmdline_firstc(void)
4368{
4369  return ccline.cmdfirstc;
4370}
4371
4372/// Get indices that specify a range within a list (not a range of text lines
4373/// in a buffer!) from a string.  Used for ":history" and ":clist".
4374///
4375/// @param str string to parse range from
4376/// @param num1 from
4377/// @param num2 to
4378///
4379/// @return OK if parsed successfully, otherwise FAIL.
4380int get_list_range(char **str, int *num1, int *num2)
4381{
4382  int len;
4383  bool first = false;
4384  varnumber_T num;
4385
4386  *str = skipwhite((*str));
4387  if (**str == '-' || ascii_isdigit(**str)) {  // parse "from" part of range
4388    vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false, NULL);
4389    *str += len;
4390    // overflow
4391    if (num > INT_MAX) {
4392      return FAIL;
4393    }
4394
4395    *num1 = (int)num;
4396    first = true;
4397  }
4398  *str = skipwhite((*str));
4399  if (**str == ',') {                   // parse "to" part of range
4400    *str = skipwhite((*str) + 1);
4401    vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, false, NULL);
4402    if (len > 0) {
4403      *str = skipwhite((*str) + len);
4404      // overflow
4405      if (num > INT_MAX) {
4406        return FAIL;
4407      }
4408
4409      *num2 = (int)num;
4410    } else if (!first) {                  // no number given at all
4411      return FAIL;
4412    }
4413  } else if (first) {                     // only one number given
4414    *num2 = *num1;
4415  }
4416  return OK;
4417}
4418
4419void cmdline_init(void)
4420{
4421  CLEAR_FIELD(ccline);
4422}
4423
4424/// Check value of 'cedit' and set cedit_key.
4425/// Returns NULL if value is OK, error message otherwise.
4426const char *did_set_cedit(optset_T *args)
4427{
4428  if (*p_cedit == NUL) {
4429    cedit_key = -1;
4430  } else {
4431    int n = string_to_key(p_cedit);
4432    if (n == 0 || vim_isprintc(n)) {
4433      return e_invarg;
4434    }
4435    cedit_key = n;
4436  }
4437  return NULL;
4438}
4439
4440typedef struct {
4441  int firstc;     ///< ':'/'/'/'?'.
4442  char *content;  ///< Initial cmdline (owned).
4443  int pos;        ///< Cursor column.
4444} CmdwinOpenArgs;
4445
4446/// Synchronously calls `vim._core.cmdwin.<action>(...)`.
4447static void cmdwin_invoke(const char *action, int firstc, char *content, int pos)
4448{
4449  char fc[2] = { (char)firstc, 0 };
4450  typval_T tv_args[] = {
4451    { .v_type = VAR_STRING, .vval.v_string = fc },
4452    { .v_type = VAR_STRING, .vval.v_string = content ? content : "" },
4453    { .v_type = VAR_NUMBER, .vval.v_number = pos + 1 },
4454    { .v_type = VAR_UNKNOWN },
4455  };
4456  nlua_call_typval("vim._core.cmdwin", action, firstc ? tv_args : tv_args + 3, NULL);
4457  xfree(content);
4458}
4459
4460/// Calls `vim._core.cmdwin.<action>()`, synchronously.
4461void cmdwin_do_action(const char *action)
4462{
4463  cmdwin_invoke(action, 0, NULL, 0);
4464}
4465
4466/// Deferred event: opens cmdwin after the cmdline-reader unwinds. Can't run synchronously (cmdline
4467/// is still being read), nor via vim.schedule (could fire _during typeahead_; revisit after #40380).
4468static void open_cmdwin_event(void **argv)
4469{
4470  CmdwinOpenArgs *a = argv[0];
4471  cmdwin_invoke("open", a->firstc, a->content, a->pos);  // frees a->content
4472  xfree(a);
4473}
4474
4475/// Schedules cmdwin to open after the current cmdline-reader returns. Returns Ctrl_C so the cmdline
4476/// input loop unwinds, then `vim._core.cmdwin` does its work after typeahead. #40312
4477static int open_cmdwin(void)
4478{
4479  // Disallow during textlock or when typing a password.
4480  if (text_locked() || cmdline_star > 0) {
4481    beep_flush();
4482    return K_IGNORE;
4483  }
4484  // Already open (also guarded in `vim._core.cmdwin`, but check here to avoid scheduling).
4485  if (cmdwin_buf != NULL) {
4486    beep_flush();
4487    return K_IGNORE;
4488  }
4489  // Disallow for expr-register and input()/inputlist(): no reentrant return path. #40407
4490  int ft = get_cmdline_type();
4491  if (ft != ':' && ft != '/' && ft != '?') {
4492    beep_flush();
4493    return K_IGNORE;
4494  }
4495
4496  CmdwinOpenArgs *a = xmalloc(sizeof(*a));
4497  a->firstc = ft;
4498  a->pos = ccline.cmdpos;
4499
4500  // Capture the cmdline; will append to end of cmdwin.
4501  a->content = ccline.cmdbuff ? xstrnsave(ccline.cmdbuff, (size_t)ccline.cmdlen) : NULL;
4502  // Clear cmdline so that unwinding it (via Ctrl_C below) does not add it to history.
4503  ccline.cmdlen = 0;
4504  ccline.cmdpos = 0;
4505
4506  // Intentionally not using vim.scheduled, see note on `open_cmdwin_event`.
4507  loop_schedule_deferred(&main_loop, event_create(open_cmdwin_event, a));
4508  return Ctrl_C;
4509}
4510
4511/// @return true if curbuf is the cmdwin and we're not editing the command line.
4512bool is_in_cmdwin(void)
4513  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4514{
4515  return bt_cmdwin(curbuf) && get_cmdline_type() == NUL;
4516}
4517
4518/// Get script string
4519///
4520/// Used for commands which accept either `:command script` or
4521///
4522///     :command << endmarker
4523///       script
4524///     endmarker
4525///
4526/// @param  eap  Command being run.
4527/// @param[out]  lenp  Location where length of resulting string is saved. Will
4528///                    be set to zero when skipping.
4529///
4530/// @return [allocated] NULL or script. Does not show any error messages.
4531///                     NULL is returned when skipping and on error.
4532char *script_get(exarg_T *const eap, size_t *const lenp)
4533  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
4534{
4535  char *cmd = eap->arg;
4536
4537  if (cmd[0] != '<' || cmd[1] != '<' || eap->ea_getline == NULL) {
4538    *lenp = strlen(eap->arg);
4539    return eap->skip ? NULL : xmemdupz(eap->arg, *lenp);
4540  }
4541  cmd += 2;
4542
4543  garray_T ga = { .ga_data = NULL, .ga_len = 0 };
4544
4545  list_T *const l = heredoc_get(eap, cmd, true);
4546  if (l == NULL) {
4547    return NULL;
4548  }
4549
4550  if (!eap->skip) {
4551    ga_init(&ga, 1, 0x400);
4552  }
4553
4554  TV_LIST_ITER_CONST(l, li, {
4555    if (!eap->skip) {
4556      ga_concat(&ga, tv_get_string(TV_LIST_ITEM_TV(li)));
4557      ga_append(&ga, '\n');
4558    }
4559  });
4560  *lenp = (size_t)ga.ga_len;  // Set length without trailing NUL.
4561  if (!eap->skip) {
4562    ga_append(&ga, NUL);
4563  }
4564
4565  tv_list_free(l);
4566  return (char *)ga.ga_data;
4567}
4568
4569/// This function is used by f_input() and f_inputdialog() functions. The third
4570/// argument to f_input() specifies the type of completion to use at the
4571/// prompt. The third argument to f_inputdialog() specifies the value to return
4572/// when the user cancels the prompt.
4573void get_user_input(const typval_T *const argvars, typval_T *const rettv, const bool inputdialog,
4574                    const bool secret)
4575  FUNC_ATTR_NONNULL_ALL
4576{
4577  rettv->v_type = VAR_STRING;
4578  rettv->vval.v_string = NULL;
4579
4580  if (cmdpreview) {
4581    return;
4582  }
4583
4584  const char *prompt;
4585  const char *defstr = "";
4586  typval_T *cancelreturn = NULL;
4587  typval_T cancelreturn_strarg2 = TV_INITIAL_VALUE;
4588  const char *xp_name = NULL;
4589  Callback input_callback = CALLBACK_INIT;
4590  char prompt_buf[NUMBUFLEN];
4591  char defstr_buf[NUMBUFLEN];
4592  char cancelreturn_buf[NUMBUFLEN];
4593  char xp_name_buf[NUMBUFLEN];
4594  char def[1] = { 0 };
4595  if (argvars[0].v_type == VAR_DICT) {
4596    if (argvars[1].v_type != VAR_UNKNOWN) {
4597      emsg(_("E5050: {opts} must be the only argument"));
4598      return;
4599    }
4600    dict_T *const dict = argvars[0].vval.v_dict;
4601    prompt = tv_dict_get_string_buf_chk(dict, S_LEN("prompt"), prompt_buf, "");
4602    if (prompt == NULL) {
4603      return;
4604    }
4605    defstr = tv_dict_get_string_buf_chk(dict, S_LEN("default"), defstr_buf, "");
4606    if (defstr == NULL) {
4607      return;
4608    }
4609    dictitem_T *cancelreturn_di = tv_dict_find(dict, S_LEN("cancelreturn"));
4610    if (cancelreturn_di != NULL) {
4611      cancelreturn = &cancelreturn_di->di_tv;
4612    }
4613    xp_name = tv_dict_get_string_buf_chk(dict, S_LEN("completion"),
4614                                         xp_name_buf, def);
4615    if (xp_name == NULL) {  // error
4616      return;
4617    }
4618    if (xp_name == def) {  // default to NULL
4619      xp_name = NULL;
4620    }
4621    if (!tv_dict_get_callback(dict, S_LEN("highlight"), &input_callback)) {
4622      return;
4623    }
4624  } else {
4625    prompt = tv_get_string_buf_chk(&argvars[0], prompt_buf);
4626    if (prompt == NULL) {
4627      return;
4628    }
4629    if (argvars[1].v_type != VAR_UNKNOWN) {
4630      defstr = tv_get_string_buf_chk(&argvars[1], defstr_buf);
4631      if (defstr == NULL) {
4632        return;
4633      }
4634      if (argvars[2].v_type != VAR_UNKNOWN) {
4635        const char *const strarg2 = tv_get_string_buf_chk(&argvars[2], cancelreturn_buf);
4636        if (strarg2 == NULL) {
4637          return;
4638        }
4639        if (inputdialog) {
4640          cancelreturn_strarg2.v_type = VAR_STRING;
4641          cancelreturn_strarg2.vval.v_string = (char *)strarg2;
4642          cancelreturn = &cancelreturn_strarg2;
4643        } else {
4644          xp_name = strarg2;
4645        }
4646      }
4647    }
4648  }
4649
4650  int xp_type = EXPAND_NOTHING;
4651  char *xp_arg = NULL;
4652  if (xp_name != NULL) {
4653    // input() with a third argument: completion
4654    const int xp_namelen = (int)strlen(xp_name);
4655
4656    uint32_t argt = 0;
4657    if (parse_compl_arg(xp_name, xp_namelen, &xp_type,
4658                        &argt, &xp_arg) == FAIL) {
4659      return;
4660    }
4661  }
4662
4663  // Only the part of the message after the last NL is considered as
4664  // prompt for the command line, unlsess cmdline is externalized
4665  const char *p = prompt;
4666  if (!ui_has(kUICmdline)) {
4667    const char *lastnl = strrchr(prompt, '\n');
4668    if (lastnl != NULL) {
4669      p = lastnl + 1;
4670      msg_start();
4671      msg_clr_eos();
4672      msg_puts_len(prompt, p - prompt, get_echo_hl_id(), false);
4673      msg_didout = false;
4674      msg_starthere();
4675    }
4676  }
4677  cmdline_row = msg_row;
4678
4679  stuffReadbuffSpecial(defstr);
4680
4681  const int save_ex_normal_busy = ex_normal_busy;
4682  ex_normal_busy = 0;
4683  atom_payload_start();
4684  rettv->vval.v_string = getcmdline_prompt(secret ? NUL : '@', p, get_echo_hl_id(),
4685                                           xp_type, xp_arg, input_callback, false, NULL);
4686  atom_payload_end();
4687  ex_normal_busy = save_ex_normal_busy;
4688  callback_free(&input_callback);
4689
4690  if (rettv->vval.v_string == NULL && cancelreturn != NULL) {
4691    tv_copy(cancelreturn, rettv);
4692  }
4693
4694  xfree(xp_arg);
4695
4696  // Since the user typed this, no need to wait for return.
4697  need_wait_return = false;
4698  msg_didout = false;
4699}
4700
4701/// "wildtrigger()" function
4702void f_wildtrigger(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4703{
4704  if (!(State & MODE_CMDLINE) || char_avail()
4705      || wild_menu_showing
4706      || cmdline_pum_active()) {
4707    return;
4708  }
4709
4710  int cmd_type = get_cmdline_type();
4711
4712  if (cmd_type == ':' || cmd_type == '/' || cmd_type == '?') {
4713    // Add K_WILD as a single special key
4714    uint8_t key_string[4];
4715    key_string[0] = K_SPECIAL;
4716    key_string[1] = KS_EXTRA;
4717    key_string[2] = KE_WILD;
4718    key_string[3] = NUL;
4719
4720    // Insert it into the typeahead buffer
4721    ins_typebuf((char *)key_string, REMAP_NONE, 0, true, false);
4722  }
4723}