robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
111.0 KiB3614 linesraw
1// input.c: The input engine "bytes layer" (input_cmdatom.c is the "policy layer").
2//
3// - Get a character from the user, a script file, or the keybufs described below.
4// - Apply mappings and abbreviations to typed keys (the :map tables live in mapping.c; the
5//   matching loop is handle_mapping()).
6// - Assemble K_SPECIAL/multibyte byte sequences into keys (vgetc()).
7// - Record macros (recordbuff); capture the redo state (redobuff: "." capture and replay).
8//
9// Concepts:
10// - "Stuffing" = when some internal logic pushes keys to execute next. This is how a cmd
11//   "translates" into another cmd: "x" stuffs "dl", "." stuffs the redo buf.
12//   - XXX NOTE: stuffed keys must have a consumer in the current codepath (not "later on the main
13//     loop"). There are 3 different rituals, depending on the consumer:
14//     1. basic translation: stuff, then exec_stuffed(); runs as CmdFrames of the stuffing command.
15//     2. input staged for a nested reader (getcmdline(), edit()): stuff only.
16//     3. main-loop wakeup (K_NOP): stuffed so it precedes input (unlike an event).
17// - TYPEAHEAD vs READ-AHEAD:
18//   - typeahead = external input that arrived faster than can be executed (user typed fast).
19//   - readahead = Nvim's own self-input.
20//     - vgetorpeek() drains it BEFORE typeahead.
21//     - Its keys are never mapped (mappings apply only to the
22//       typebuf; abbreviations are disabled too), though they count as typed for most purposes
23//       (KeyStuffed).
24//
25// These buffers are used:
26//
27//   input ──► [ typebuf │ readbuf2 (redo) │ readbuf1 (stuff) ] ──► vgetc() ──► exec
28//               ▲ mappings expand at typebuf front
29//
30// - typeahead (`typebuf`).
31// - readahead/stuff buffers (`readbuf1`, `readbuf2`).
32//   - Two stuff buffers, because stuffing nests: a cmd executed FROM redo keys (readbuf2) may
33//     itself stuff a translation (readbuf1), which must be consumed before the remaining redo.
34// - `redobuff` (RedoState): the current + previous change.
35// - `recordbuff`: accumulates the keys of a recording ("q").
36//
37// Buffer bytes use "typeahead encoding":
38// - K_SPECIAL introduces a special key (two more bytes follow).
39//   A literal K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
40// - These translations are also done on multi-byte characters!
41// - Escaping K_SPECIAL is done by inchar().
42// - Un-escaping is done by vgetc().
43
44#include <assert.h>
45#include <limits.h>
46#include <stdbool.h>
47#include <stddef.h>
48#include <stdint.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52
53#include "klib/kvec.h"
54#include "nvim/api/private/defs.h"
55#include "nvim/api/private/helpers.h"
56#include "nvim/api/vim.h"
57#include "nvim/ascii_defs.h"
58#include "nvim/buffer_defs.h"
59#include "nvim/charset.h"
60#include "nvim/cursor.h"
61#include "nvim/drawscreen.h"
62#include "nvim/errors.h"
63#include "nvim/eval.h"
64#include "nvim/eval/typval.h"
65#include "nvim/eval/typval_defs.h"
66#include "nvim/eval/vars.h"
67#include "nvim/event/loop.h"
68#include "nvim/event/multiqueue.h"
69#include "nvim/ex_cmds.h"
70#include "nvim/ex_docmd.h"
71#include "nvim/ex_getln.h"
72#include "nvim/ex_getln_defs.h"
73#include "nvim/garray.h"
74#include "nvim/garray_defs.h"
75#include "nvim/gettext_defs.h"
76#include "nvim/globals.h"
77#include "nvim/input.h"
78#include "nvim/input_cmdatom.h"
79#include "nvim/insert.h"
80#include "nvim/insexpand.h"
81#include "nvim/keycodes.h"
82#include "nvim/lua/executor.h"
83#include "nvim/macros_defs.h"
84#include "nvim/main.h"
85#include "nvim/mapping.h"
86#include "nvim/mapping_defs.h"
87#include "nvim/mbyte.h"
88#include "nvim/mbyte_defs.h"
89#include "nvim/mcursor.h"
90#include "nvim/memline.h"
91#include "nvim/memory.h"
92#include "nvim/memory_defs.h"
93#include "nvim/message.h"
94#include "nvim/mouse.h"
95#include "nvim/move.h"
96#include "nvim/normal.h"
97#include "nvim/normal_defs.h"
98#include "nvim/ops.h"
99#include "nvim/option_vars.h"
100#include "nvim/os/fileio.h"
101#include "nvim/os/fileio_defs.h"
102#include "nvim/os/input.h"
103#include "nvim/os/os.h"
104#include "nvim/os/os_defs.h"
105#include "nvim/plines.h"
106#include "nvim/pos_defs.h"
107#include "nvim/register.h"
108#include "nvim/state.h"
109#include "nvim/state_defs.h"
110#include "nvim/strings.h"
111#include "nvim/types_defs.h"
112#include "nvim/ui.h"
113#include "nvim/undo.h"
114#include "nvim/vim_defs.h"
115
116/// State for adding bytes to a recording or 'showcmd'.
117typedef struct {
118  uint8_t buf[MB_MAXBYTES * 3 + 4];
119  int prev_c;
120  size_t buflen;
121  unsigned pending_special;
122  unsigned pending_mbyte;
123} gotchars_state_T;
124
125/// Index in scriptin
126static int curscript = -1;
127/// Streams to read script from
128static FileDescriptor scriptin[NSCRIPT] = { 0 };
129
130/// The current + previous change. redo_append_xx() captures in `redobuff.cur`; "." replays it.
131static RedoState redobuff;
132/// Macro recording.
133static StringBuilder recordbuff = KV_INITIAL_VALUE;
134/// First readahead buffer ("stuffbuf"): command translations ("x" => "dl"). Drains before readbuf2.
135static StuffBuf readbuf1;
136/// Second readahead buffer ("stuffbuf"): "." replay (start_redo()).
137static StuffBuf readbuf2;
138static UngotKey ungot = { .c = -1 };
139
140/// Buffer used to store typed characters for vim.on_key().
141static kvec_withinit_t(char, MAXMAPLEN + 1) on_key_buf = KVI_INITIAL_VALUE(on_key_buf);
142
143/// Number of following bytes that should not be stored for vim.on_key().
144static size_t on_key_ignore_len = 0;
145/// Nesting depth of getchar()/getcharstr(). Will skip vim.on_key() callbacks. #40010
146static int getchar_depth = 0;
147
148static int typeahead_char = 0;  ///< typeahead char that's not flushed
149
150/// When block_redo is true the redo buffer will not be changed.
151/// Used by edit() to repeat insertions.
152static bool block_redo = false;
153
154static int KeyNoremap = 0;  ///< remapping flags
155
156/// Variables used by vgetorpeek() and flush_buffers()
157///
158/// typebuf.tb_buf[] contains all characters that are not consumed yet.
159/// typebuf.tb_buf[typebuf.tb_off] is the first valid character.
160/// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
161/// typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
162/// The head of the buffer may contain the result of mappings, abbreviations
163/// and @a commands.  The length of this part is typebuf.tb_maplen.
164/// typebuf.tb_silent is the part where <silent> applies.
165/// After the head are characters that come from the terminal.
166/// typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
167/// should not be considered for abbreviations.
168/// Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
169/// in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
170/// contains RM_NONE for the characters that are not to be remapped.
171/// typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
172enum {
173  RM_YES    = 0,  ///< tb_noremap: remap
174  RM_NONE   = 1,  ///< tb_noremap: don't remap
175  RM_SCRIPT = 2,  ///< tb_noremap: remap local script mappings
176  RM_ABBR   = 4,  ///< tb_noremap: don't remap, do abbrev.
177};
178
179// typebuf.tb_buf has three parts: room in front (for result of mappings), the
180// middle for typeahead and room for new characters (which needs to be 3 *
181// MAXMAPLEN for the Amiga).
182#define TYPELEN_INIT    (5 * (MAXMAPLEN + 3))
183static uint8_t typebuf_init[TYPELEN_INIT];     ///< initial typebuf.tb_buf
184static uint8_t noremapbuf_init[TYPELEN_INIT];  ///< initial typebuf.tb_noremap
185
186static size_t last_recorded_len = 0;  ///< number of last recorded chars
187
188enum {
189  KEYLEN_PART_KEY = -1,  ///< keylen value for incomplete key-code
190  KEYLEN_PART_MAP = -2,  ///< keylen value for incomplete mapping
191};
192
193#include "input.c.generated.h"
194
195static const char e_recursive_mapping[] = N_("E223: Recursive mapping");
196static const char e_cmd_mapping_must_end_with_cr[]
197  = N_("E1255: <Cmd> mapping must end with <CR>");
198static const char e_cmd_mapping_must_end_with_cr_before_second_cmd[]
199  = N_("E1136: <Cmd> mapping must end with <CR> before second <Cmd>");
200static const char e_lua_mapping_gone[] = N_("E5117: Lua mapping no longer exists");
201
202/// Frees the buffer's memory; it becomes empty.
203static void free_buff(StuffBuf *buf)
204  FUNC_ATTR_NONNULL_ALL
205{
206  kv_destroy(buf->keys);
207  *buf = (StuffBuf){ 0 };
208}
209
210/// Gets the contents of the record buffer as a string (typeahead encoding) and clears the buffer.
211char *get_recorded(void)
212{
213  size_t len = recordbuff.size;
214  kv_push(recordbuff, NUL);
215  char *p = recordbuff.items;  // ownership moves to the caller
216  recordbuff = (StringBuilder)KV_INITIAL_VALUE;
217
218  // Remove the characters that were added the last time, these must be the
219  // (possibly mapped) characters that stopped the recording.
220  if (len >= last_recorded_len) {
221    len -= last_recorded_len;
222    p[len] = NUL;
223  }
224
225  // When stopping recording from Insert mode with CTRL-O q, also remove the
226  // CTRL-O.
227  if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O) {
228    p[len - 1] = NUL;
229  }
230
231  return p;
232}
233
234/// Composes a `["x][count]` prefix from `spec` and appends it to `buf`.
235/// This is "Step 1" of redo-composition ("Step 2" is either `redobuff.cur.body` or `redo_chars`).
236///
237/// @param replay  Composing an actual replay (start_redo()): a `"=` register spec appends <CR>,
238///                re-evaluating the last expression.
239static void redo_prefix(const CmdSpec *spec, StringBuilder *buf, bool replay)
240  FUNC_ATTR_NONNULL_ARG(1)
241{
242  if (spec->regname != 0) {
243    sb_add_char(buf, '"');
244    sb_add_char(buf, spec->regname);
245    if (replay && spec->regname == '=') {
246      sb_add_char(buf, CAR);
247    }
248  }
249  if (spec->count != 0) {
250    kv_printf(*buf, "%d", (int)spec->count);
251  }
252}
253
254/// Composes a command keysequence from `spec` and appends it to `buf`.
255/// This is "Step 2" of redo-composition ("Step 1" is `redo_prefix`).
256///
257/// @param arg_meta  Skip the `arg` byte (see prep_redo()).
258static void redo_chars(const CmdSpec *spec, StringBuilder *buf, bool arg_meta)
259  FUNC_ATTR_NONNULL_ALL
260{
261  if (spec->op != NUL) {
262    sb_add_char(buf, spec->op);
263  }
264  if (spec->op_extra != NUL) {
265    sb_add_char(buf, spec->op_extra);
266  }
267  if (spec->motion_force != NUL) {
268    sb_add_char(buf, spec->motion_force);
269  }
270  if (spec->cmd != NUL) {
271    sb_add_char(buf, spec->cmd);
272  }
273  if (spec->cmd2 != NUL) {
274    sb_add_char(buf, spec->cmd2);
275  }
276  if (spec->cmdarg != NUL && !arg_meta) {
277    sb_add_char(buf, spec->cmdarg);
278  }
279}
280
281/// Takes `buf`'s bytes as an allocated, NUL-terminated String, and clears `buf`.
282///
283/// @return  String; .data=NULL if `buf` is empty.
284static String sb_take_string(StringBuilder *buf)
285  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
286{
287  if (buf->size == 0) {
288    kv_destroy(*buf);
289    return (String)STRING_INIT;
290  }
291  size_t len = buf->size;
292  assert(buf->items != NULL);  // Coverity false-positive (already checked `size` above).
293  kv_push(*buf, NUL);
294  char *items = buf->items;  // ownership moves to the caller
295  *buf = (StringBuilder)KV_INITIAL_VALUE;
296  return cbuf_as_string(items, len);
297}
298
299/// Gets `spec` (or current pending change, if `spec` is NULL), composed into a "redo" keyseq
300/// `["x][count][body]`, where `[body]` is `spec.body`, or composed from the spec if body is empty.
301///
302/// @return Allocated key sequence; .data == NULL if the result is empty.
303String redo_keys(const CmdSpec *spec)
304  FUNC_ATTR_WARN_UNUSED_RESULT
305{
306  spec = spec ? spec : &redobuff.cur;
307
308  StringBuilder buf = KV_INITIAL_VALUE;
309  redo_prefix(spec, &buf, false);
310  if (spec->body.size > 0) {
311    kv_splice(buf, spec->body);
312  } else {
313    redo_chars(spec, &buf, false);
314  }
315  return sb_take_string(&buf);
316}
317
318/// Gets the pending change's CmdSpec (without `body`).
319CmdSpec redo_spec(void)
320{
321  CmdSpec spec = redobuff.cur;
322  spec.body = (StringBuilder)KV_INITIAL_VALUE;
323  return spec;
324}
325
326/// Inserts string `s` at `buf.insert`: the end, or ahead of not-yet-read keys (see start_stuff()).
327///
328/// `s` must be in typeahead encoding, and must not point into `buf->keys`.
329///
330/// @param slen  String length, or -1 for a NUL-terminated string.
331static void add_buff(StuffBuf *const buf, const char *const s, ptrdiff_t slen)
332{
333  if (slen < 0) {
334    slen = (ptrdiff_t)strlen(s);
335  }
336  if (slen == 0) {                              // don't add empty strings
337    return;
338  }
339
340  kv_ensure_space(buf->keys, (size_t)slen);
341  char *at = buf->keys.items + buf->insert;
342  memmove(at + slen, at, buf->keys.size - buf->insert);
343  memcpy(at, s, (size_t)slen);
344  buf->keys.size += (size_t)slen;
345  buf->insert += (size_t)slen;
346}
347
348/// Append number "n" to buffer "buf".
349static void add_num_buff(StuffBuf *buf, int n)
350  FUNC_ATTR_NONNULL_ALL
351{
352  char number[32];
353  int numberlen = snprintf(number, sizeof(number), "%d", n);
354  add_buff(buf, number, numberlen);
355}
356
357/// Encodes byte or special key `c` into `temp`: the K_SPECIAL three-byte sequence for special
358/// keys, NUL and K_SPECIAL itself; the byte otherwise.
359///
360/// @return  Encoded length.
361static ptrdiff_t key_byte_encode(int c, char temp[4])
362  FUNC_ATTR_NONNULL_ALL
363{
364  if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL) {
365    // Translate special key code into three byte sequence.
366    temp[0] = (char)K_SPECIAL;
367    temp[1] = (char)K_SECOND(c);
368    temp[2] = (char)K_THIRD(c);
369    temp[3] = NUL;
370    return 3;
371  }
372  temp[0] = (char)c;
373  temp[1] = NUL;
374  return 1;
375}
376
377/// Encodes char `c` into `buf` (at least `MB_MAXBYTES * 3 + 1` bytes): a special key as its
378/// K_SPECIAL sequence, a multibyte char byte-wise with K_SPECIAL escaping.
379///
380/// @return  Encoded length.
381static size_t key_char_encode(int c, char *buf)
382  FUNC_ATTR_NONNULL_ALL
383{
384  uint8_t bytes[MB_MAXBYTES + 1];
385  int len = IS_SPECIAL(c) ? 1 : utf_char2bytes(c, (char *)bytes);
386  size_t off = 0;
387  for (int i = 0; i < len; i++) {
388    off += (size_t)key_byte_encode(IS_SPECIAL(c) ? c : bytes[i], buf + off);
389  }
390  return off;
391}
392
393/// Append character `c` to `buf`, translated to typeahead encoding.
394static void add_char_buff(StuffBuf *buf, int c)
395  FUNC_ATTR_NONNULL_ALL
396{
397  char temp[MB_MAXBYTES * 3 + 1];
398  add_buff(buf, temp, (ptrdiff_t)key_char_encode(c, temp));
399}
400
401/// Appends byte or special key `c` to `sb`.
402static void sb_add_byte(StringBuilder *sb, int c)
403  FUNC_ATTR_NONNULL_ALL
404{
405  char temp[4];
406  size_t templen = (size_t)key_byte_encode(c, temp);
407  kv_concat_len(*sb, temp, templen);
408}
409
410/// Dual of add_char_buff(), for a StringBuilder.
411void sb_add_char(StringBuilder *sb, int c)
412  FUNC_ATTR_NONNULL_ALL
413{
414  char temp[MB_MAXBYTES * 3 + 1];
415  size_t len = key_char_encode(c, temp);
416  kv_concat_len(*sb, temp, len);
417}
418
419/// Gets one byte (typeahead encoding, no translation) from the read buffers.  Uses `readbuf1` one
420/// first, or `readbuf2` if that one is empty.
421///
422/// @param advance Go to the next char.
423static int read_readbuffers(bool advance)
424{
425  int c = read_readbuf(&readbuf1, advance);
426  if (c == NUL) {
427    c = read_readbuf(&readbuf2, advance);
428  }
429  return c;
430}
431
432static int read_readbuf(StuffBuf *buf, bool advance)
433  FUNC_ATTR_NONNULL_ALL
434{
435  if (buf->read == buf->keys.size) {  // buffer is empty
436    return NUL;
437  }
438
439  uint8_t c = (uint8_t)buf->keys.items[buf->read];
440
441  if (advance) {
442    buf->read++;
443    if (buf->read == buf->keys.size) {  // drained: reset positions, keep capacity for reuse
444      buf->keys.size = 0;
445      buf->read = 0;
446      buf->insert = 0;
447    } else {
448      buf->insert = MAX(buf->insert, buf->read);
449    }
450  }
451  return c;
452}
453
454/// Makes the next stuffed text be read before the existing readahead.
455static void start_stuff(void)
456{
457  readbuf1.insert = readbuf1.read;
458  readbuf2.insert = readbuf2.read;
459}
460
461/// @return  true if the readahead ("stuff") buffer is empty.
462bool stuff_empty(void)
463  FUNC_ATTR_PURE
464{
465  return readbuf1.keys.size == 0 && readbuf2.keys.size == 0;
466}
467
468/// @return  true if readbuf1 is empty.  There may still be redo characters in
469///          readbuf2.
470bool readbuf1_empty(void)
471  FUNC_ATTR_PURE
472{
473  return readbuf1.keys.size == 0;
474}
475
476/// Set a typeahead character that won't be flushed.
477void typeahead_noflush(int c)
478{
479  typeahead_char = c;
480}
481
482/// Remove the contents of the stuff buffer and the mapped characters in the typeahead buffer (used
483/// in case of an error).
484///
485/// @param flush_typeahead Flush all typeahead characters (used when interrupted by CTRL-C).
486void flush_buffers(flush_buffers_T flush_typeahead)
487{
488  init_typebuf();
489
490  if (typebuf.tb_maplen > 0) {
491    // Discarding a mapping's unconsumed keys: the mapping will never
492    // complete, discard its subatoms.
493    atom_composite_abort();
494  }
495
496  if (readbuf2.keys.size > 0 && Visual.active) {
497    // This flush discards the dot-repeat keys, including the operator that would end the selection.
498    // End Visual mode at cmd end, not here (else its autocmds would run inside emsg/vgetorpeek).
499    Visual.need_end = true;
500  }
501  free_buff(&readbuf1);
502  free_buff(&readbuf2);
503
504  if (flush_typeahead == FLUSH_MINIMAL) {
505    // remove mapped characters at the start only,
506    // but only when enough space left in typebuf
507    if (typebuf.tb_off + typebuf.tb_maplen >= typebuf.tb_buflen) {
508      typebuf.tb_off = MAXMAPLEN;
509      typebuf.tb_len = 0;
510    } else {
511      typebuf.tb_off += typebuf.tb_maplen;
512      typebuf.tb_len -= typebuf.tb_maplen;
513    }
514    if (typebuf.tb_len == 0) {
515      typebuf_was_filled = false;
516    }
517  } else {
518    // remove typeahead
519    if (flush_typeahead == FLUSH_INPUT) {
520      // We have to get all characters, because we may delete the first
521      // part of an escape sequence.  In an xterm we get one char at a
522      // time and we have to get them all.
523      while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10) != 0) {}
524    }
525    typebuf.tb_off = MAXMAPLEN;
526    typebuf.tb_len = 0;
527    // Reset the flag that text received from a client or from feedkeys()
528    // was inserted in the typeahead buffer.
529    typebuf_was_filled = false;
530  }
531  typebuf.tb_maplen = 0;
532  typebuf.tb_silent = 0;
533  cmd_silent = false;
534  typebuf.tb_no_abbr_cnt = 0;
535  if (++typebuf.tb_change_cnt == 0) {
536    typebuf.tb_change_cnt = 1;
537  }
538}
539
540/// flush map and typeahead buffers and give a warning for an error
541void beep_flush(void)
542{
543  // Don't flush during mc-replay. A failed motion ("vt;" where there is no ";") should not eat
544  // the keys typed after it ("c"). This matches Helix multiselection: each action during a Visual
545  // selection proceeds or fails, without canceling the next action.
546  if (emsg_silent == 0 && !mc_replaying()) {
547    flush_buffers(FLUSH_MINIMAL);
548  }
549  vim_beep(kOptBoFlagError);
550}
551
552/// Starts capturing a new change: stores `spec`, caller appends the body (redo_append_x). The
553/// outgoing change moves to `redobuff.old`, which may be repeated by "CTRL-O ." in Insert mode,
554/// or restored by redo_cancel() if this change aborts.
555///
556/// @param spec  Structured command fields; zeroed if the caller only appends keys.
557void redo_new(CmdSpec spec)
558{
559  assert(spec.body.size == 0);
560  if (block_redo) {
561    return;
562  }
563
564  kv_destroy(redobuff.old.body);
565  redobuff.old = redobuff.cur;
566  redobuff.cur = spec;
567}
568
569#ifdef EXITFREE
570/// Frees both redo buffers.
571void redo_free_all(void)
572{
573  kv_destroy(redobuff.cur.body);
574  kv_destroy(redobuff.old.body);
575  redobuff = (RedoState){ 0 };
576}
577#endif
578
579/// Prepare for redo of any command: stores `spec` and appends its command chars.
580///
581/// @param as_atom   The redo also defines the command's atom (`CmdFrame.redo_frame`). False for
582///                  "prep-exempt" special cases (insert-session entry/restart, "z=").
583/// @param arg_meta  Skip the `arg` byte: an interactively-typed operand may need CTRL-V quoting
584///                  or its composing-char string form, which the caller appends itself.
585void prep_redo(bool as_atom, bool arg_meta, CmdSpec spec)
586{
587  if (as_atom) {
588    atom_redo_prepped();
589  }
590  redo_new(spec);
591  if (block_redo) {
592    return;
593  }
594  redo_chars(&spec, &redobuff.cur.body, arg_meta);
595}
596
597/// Prepare for redo of a Visual-mode command: the body opens with `keys` (the captured selection),
598/// so "." re-executes the selection at cursor; the `["x][count]` prefix and command chars of
599/// `spec` compose into the body after them (zeroed in the stored spec, so replay doesn't also
600/// prefix them).
601void prep_redo_visual(const char *keys, size_t len, CmdSpec spec)
602{
603  CmdSpec stored = spec;
604  stored.regname = 0;
605  stored.count = 0;
606  atom_redo_prepped();
607  redo_new(stored);
608  if (block_redo) {
609    return;
610  }
611  kv_concat_len(redobuff.cur.body, keys, len);
612  redo_prefix(&spec, &redobuff.cur.body, false);
613  redo_chars(&spec, &redobuff.cur.body, false);
614}
615
616/// Discard the contents of the redo buffer and restore the previous redo
617/// buffer.
618void redo_cancel(void)
619{
620  if (block_redo) {
621    return;
622  }
623
624  atom_redo_cancel();
625  kv_destroy(redobuff.cur.body);
626  redobuff.cur = redobuff.old;
627  redobuff.old = (CmdSpec){ 0 };
628  free_buff(&readbuf1);
629  free_buff(&readbuf2);
630}
631
632/// Saves the redo state to "save_redo" and detaches it.
633/// Used before executing autocommands and user functions.
634void save_redobuff(RedoState *save_redo)
635  FUNC_ATTR_NONNULL_ALL
636{
637  *save_redo = redobuff;
638  redobuff.cur.body = (StringBuilder)KV_INITIAL_VALUE;
639  redobuff.old = (CmdSpec){ 0 };
640
641  // Make a copy (the fields stayed, copy the body), so that ":normal ." in a
642  // function works.
643  kv_splice(redobuff.cur.body, save_redo->cur.body);
644}
645
646/// Restores the redo state from "save_redo".
647/// Used after executing autocommands and user functions.
648void restore_redobuff(RedoState *save_redo)
649  FUNC_ATTR_NONNULL_ALL
650{
651  kv_destroy(redobuff.cur.body);
652  kv_destroy(redobuff.old.body);
653  redobuff = *save_redo;
654}
655
656/// Append `len` bytes of `s` (-1: up to the NUL) to the redo buffer.
657/// `s` must be in typeahead encoding.
658void redo_append_str(const char *s, ptrdiff_t len)
659{
660  if (!block_redo) {
661    size_t slen = len < 0 ? strlen(s) : (size_t)len;
662    kv_concat_len(redobuff.cur.body, s, slen);
663  }
664}
665
666/// Appends `str` to `buf` literally, escaping special characters with CTRL-V.
667/// K_SPECIAL is escaped as well.
668///
669/// @param str  String to append.
670/// @param len  Length of `str` or -1 for up to the NUL.
671void sb_add_lit(StringBuilder *buf, const char *str, int len)
672{
673  const char *s = str;
674  while (len < 0 ? *s != NUL : s - str < len) {
675    // Put a string of normal characters in the buffer (that's faster).
676    const char *start = s;
677    while (*s >= ' ' && *s < DEL && (len < 0 || s - str < len)) {
678      s++;
679    }
680
681    // Don't put '0' or '^' as last character, just in case a CTRL-D is
682    // typed next.
683    if (*s == NUL && (s[-1] == '0' || s[-1] == '^')) {
684      s--;
685    }
686    if (s > start) {
687      kv_concat_len(*buf, start, (size_t)(s - start));
688    }
689
690    if (*s == NUL || (len >= 0 && s - str >= len)) {
691      break;
692    }
693
694    // Handle a special or multibyte character.
695    // Composing chars separately are handled separately.
696    const int c = mb_cptr2char_adv(&s);
697    if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^'))) {
698      sb_add_char(buf, Ctrl_V);
699    }
700
701    // CTRL-V '0' must be inserted as CTRL-V 048.
702    if (*s == NUL && c == '0') {
703      kv_concat_len(*buf, "048", 3);
704    } else {
705      sb_add_char(buf, c);
706    }
707  }
708}
709
710/// Append to redo literally; no-op if `block_redo` is set; Insert dot-repeat consumes
711/// the redo buffer and must not append to it while doing so.
712void redo_append_lit(const char *str, int len)
713{
714  if (block_redo) {
715    return;
716  }
717  sb_add_lit(&redobuff.cur.body, str, len);
718}
719
720/// Appends `s` to `buf`, leaving 3-byte special key codes unmodified and escaping other K_SPECIAL
721/// bytes. Unlike sb_add_lit(), no CTRL-V: for text read raw (<Cmd>), not typed into a cmdline.
722void sb_add_spec(StringBuilder *buf, const char *s)
723{
724  while (*s != NUL) {
725    if ((uint8_t)(*s) == K_SPECIAL && s[1] != NUL && s[2] != NUL) {
726      // Insert special key literally.
727      kv_concat_len(*buf, s, 3);
728      s += 3;
729    } else {
730      sb_add_char(buf, mb_cptr2char_adv(&s));
731    }
732  }
733}
734
735/// Append "s" to the redo buffer.
736void redo_append_spec(const char *s)
737{
738  if (block_redo) {
739    return;
740  }
741  sb_add_spec(&redobuff.cur.body, s);
742}
743
744/// Appends character `c` to the redo buffer, translated to typeahead encoding.
745void redo_append_char(int c)
746{
747  if (!block_redo) {
748    sb_add_char(&redobuff.cur.body, c);
749  }
750}
751
752/// Appends string `s` (must be typeahead encoding) to the stuff buffer.
753void stuffReadbuff(const char *s)
754  FUNC_ATTR_NONNULL_ALL
755{
756  add_buff(&readbuf1, s, -1);
757}
758
759/// Appends string `s` (must be typeahead encoding) to the redo stuff buffer.
760void stuffRedoReadbuff(const char *s)
761  FUNC_ATTR_NONNULL_ALL
762{
763  add_buff(&readbuf2, s, -1);
764}
765
766void stuffReadbuffLen(const char *s, ptrdiff_t len)
767{
768  if (add_last_insert == 1) {  // Only add if this is the first call, for
769                               // recursive calls, ignore.
770    ga_concat_len(&last_insert_ga, s, (size_t)len);
771  }
772  add_buff(&readbuf1, s, len);
773}
774
775/// Stuff "s" into the stuff buffer, leaving special key codes unmodified and
776/// escaping other K_SPECIAL bytes.
777/// Change CR, LF and ESC into a space.
778void stuffReadbuffSpecial(const char *s)
779  FUNC_ATTR_NONNULL_ALL
780{
781  while (*s != NUL) {
782    if ((uint8_t)(*s) == K_SPECIAL && s[1] != NUL && s[2] != NUL) {
783      // Insert special key literally.
784      stuffReadbuffLen(s, 3);
785      s += 3;
786    } else {
787      int c = mb_cptr2char_adv(&s);
788      if (c == CAR || c == NL || c == ESC) {
789        c = ' ';
790      }
791      stuffcharReadbuff(c);
792    }
793  }
794}
795
796/// Appends character `c` to the stuff buffer, translated to typeahead encoding.
797void stuffcharReadbuff(int c)
798{
799  add_char_buff(&readbuf1, c);
800}
801
802// Append a number to the stuff buffer.
803void stuffnumReadbuff(int n)
804{
805  add_num_buff(&readbuf1, n);
806}
807
808/// Stuff a string into the typeahead buffer, such that edit() will insert it
809/// literally ("literally" true) or interpret is as typed characters.
810void stuffescaped(const char *arg, bool literally)
811  FUNC_ATTR_NONNULL_ALL
812{
813  while (*arg != NUL) {
814    // Stuff a sequence of normal ASCII characters, that's fast.  Also
815    // stuff K_SPECIAL to get the effect of a special key when "literally"
816    // is true.
817    const char *const start = arg;
818    while ((*arg >= ' ' && *arg < DEL) || ((uint8_t)(*arg) == K_SPECIAL
819                                           && !literally)) {
820      arg++;
821    }
822    if (arg > start) {
823      stuffReadbuffLen(start, arg - start);
824    }
825
826    // stuff a single special character
827    if (*arg != NUL) {
828      const int c = mb_cptr2char_adv(&arg);
829      if (literally && ((c < ' ' && c != TAB) || c == DEL)) {
830        stuffcharReadbuff(Ctrl_V);
831      }
832      stuffcharReadbuff(c);
833    }
834  }
835}
836
837/// Dot-repeat "." command: repeats the last change by composing the redo into readbuf2. "3."
838/// replaces count; a numbered-register redo increments regname ('"1p' then "." pastes '"2'), so "."
839/// steps through the delete history. A Visual-mode change re-executes its captured selection keys
840/// (embedded in the body, see prep_redo()).
841///
842/// @param old_redo  repeat the last-but-one change (i_CTRL-O ".": the insert
843///                  session's own prep moved the last change to redobuff.old)
844/// @return  FAIL for failure, OK otherwise
845int start_redo(int count, bool old_redo)
846{
847  CmdSpec *rd = old_redo ? &redobuff.old : &redobuff.cur;
848  if (rd->body.size == 0 && rd->regname == 0 && rd->count == 0) {
849    return FAIL;  // nothing to redo
850  }
851
852  // Tweak the captured spec for replay:
853  CmdSpec spec = *rd;
854  spec.body = (StringBuilder)KV_INITIAL_VALUE;
855  if (spec.regname >= '1' && spec.regname < '9') {
856    spec.regname++;  // numbered register: "." steps through the delete history
857  }
858  if (count != 0) {
859    spec.count = count;  // the new count replaces the captured one
860  }
861  StringBuilder prefix = KV_INITIAL_VALUE;
862  redo_prefix(&spec, &prefix, true);
863  // coverity[var_deref_model] `items` is NULL only when size=0, which add_buff() ignores.
864  add_buff(&readbuf2, prefix.items, (ptrdiff_t)prefix.size);
865  kv_destroy(prefix);
866  if (spec.regname == '=') {
867    cmd_silent = true;
868  }
869
870  add_buff(&readbuf2, rd->body.items, (ptrdiff_t)rd->body.size);
871  return OK;
872}
873
874/// Repeats the last insert (R, o, O, a, A, i or I command) by stuffing the redo body's inserted
875/// text into readbuf2 (counted inserts: "3iZ<Esc>").
876///
877/// @return  FAIL for failure, OK otherwise
878int start_redo_ins(void)
879{
880  if (redobuff.cur.body.size == 0) {
881    return FAIL;
882  }
883  start_stuff();
884
885  // Skip to the insert command; the rest of the keys is the inserted text.
886  const char *p = redobuff.cur.body.items;
887  const char *const end = p + redobuff.cur.body.size;
888  while (p < end) {
889    if ((uint8_t)(*p) == K_SPECIAL && end - p >= 3) {
890      p += 3;  // a special key is never the insert command
891      continue;
892    }
893    if (vim_strchr("AaIiRrOo", (uint8_t)(*p)) != NULL) {
894      if (*p == 'O' || *p == 'o') {
895        add_buff(&readbuf2, NL_STR, -1);
896      }
897      p++;
898      break;
899    }
900    p++;
901  }
902
903  // copy the typed text from the redo buffer into the stuff buffer
904  add_buff(&readbuf2, p, end - p);
905  block_redo = true;
906  return OK;
907}
908
909void stop_redo_ins(void)
910{
911  block_redo = false;
912}
913
914/// Initialize typebuf.tb_buf to point to typebuf_init.
915/// alloc() cannot be used here: In out-of-memory situations it would
916/// be impossible to type anything.
917static void init_typebuf(void)
918{
919  if (typebuf.tb_buf != NULL) {
920    return;
921  }
922
923  typebuf.tb_buf = typebuf_init;
924  typebuf.tb_noremap = noremapbuf_init;
925  typebuf.tb_buflen = TYPELEN_INIT;
926  typebuf.tb_len = 0;
927  typebuf.tb_off = MAXMAPLEN + 4;
928  typebuf.tb_change_cnt = 1;
929}
930
931/// @return true when keys cannot be remapped.
932bool noremap_keys(void)
933  FUNC_ATTR_PURE
934{
935  return KeyNoremap & (RM_NONE|RM_SCRIPT);
936}
937
938/// Insert a string in position "offset" in the typeahead buffer.
939///
940/// If "noremap" is REMAP_YES, new string can be mapped again.
941/// If "noremap" is REMAP_NONE, new string cannot be mapped again.
942/// If "noremap" is REMAP_SKIP, first char of new string cannot be mapped again,
943/// but abbreviations are allowed.
944/// If "noremap" is REMAP_SCRIPT, new string cannot be mapped again, except for
945///                               script-local mappings.
946/// If "noremap" is > 0, that many characters of the new string cannot be mapped.
947///
948/// If "nottyped" is true, the string does not return KeyTyped (don't use when
949/// "offset" is non-zero!).
950///
951/// If "silent" is true, cmd_silent is set when the characters are obtained.
952///
953/// @return  FAIL for failure, OK otherwise
954int ins_typebuf(char *str, int noremap, int offset, bool nottyped, bool silent)
955  FUNC_ATTR_NONNULL_ALL
956{
957  int val;
958  int nrm;
959
960  init_typebuf();
961  if (++typebuf.tb_change_cnt == 0) {
962    typebuf.tb_change_cnt = 1;
963  }
964  state_no_longer_safe("ins_typebuf()");
965
966  int addlen = (int)strlen(str);
967
968  if (offset == 0 && addlen <= typebuf.tb_off) {
969    // Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
970    typebuf.tb_off -= addlen;
971    memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
972  } else if (typebuf.tb_len == 0
973             && typebuf.tb_buflen >= addlen + 3 * (MAXMAPLEN + 4)) {
974    // Buffer is empty and string fits in the existing buffer.
975    // Leave some space before and after, if possible.
976    typebuf.tb_off = (typebuf.tb_buflen - addlen - 3 * (MAXMAPLEN + 4)) / 2;
977    memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
978  } else {
979    // Need to allocate a new buffer.
980    // In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4)
981    // characters.  We add some extra room to avoid having to allocate too
982    // often.
983    int newoff = MAXMAPLEN + 4;
984    int extra = addlen + newoff + 4 * (MAXMAPLEN + 4);
985    if (typebuf.tb_len > INT_MAX - extra) {
986      // string is getting too long for 32 bit int
987      emsg(_(e_command_too_complex));  // also calls flush_buffers
988      setcursor();
989      return FAIL;
990    }
991    int newlen = typebuf.tb_len + extra;
992    uint8_t *s1 = xmalloc((size_t)newlen);
993    uint8_t *s2 = xmalloc((size_t)newlen);
994    typebuf.tb_buflen = newlen;
995
996    // copy the old chars, before the insertion point
997    memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
998    // copy the new chars
999    memmove(s1 + newoff + offset, str, (size_t)addlen);
1000    // copy the old chars, after the insertion point, including the NUL at
1001    // the end
1002    int bytes = typebuf.tb_len - offset + 1;
1003    assert(bytes > 0);
1004    memmove(s1 + newoff + offset + addlen,
1005            typebuf.tb_buf + typebuf.tb_off + offset, (size_t)bytes);
1006    if (typebuf.tb_buf != typebuf_init) {
1007      xfree(typebuf.tb_buf);
1008    }
1009    typebuf.tb_buf = s1;
1010
1011    memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
1012            (size_t)offset);
1013    memmove(s2 + newoff + offset + addlen,
1014            typebuf.tb_noremap + typebuf.tb_off + offset,
1015            (size_t)(typebuf.tb_len - offset));
1016    if (typebuf.tb_noremap != noremapbuf_init) {
1017      xfree(typebuf.tb_noremap);
1018    }
1019    typebuf.tb_noremap = s2;
1020
1021    typebuf.tb_off = newoff;
1022  }
1023  typebuf.tb_len += addlen;
1024
1025  // If noremap == REMAP_SCRIPT: do remap script-local mappings.
1026  if (noremap == REMAP_SCRIPT) {
1027    val = RM_SCRIPT;
1028  } else if (noremap == REMAP_SKIP) {
1029    val = RM_ABBR;
1030  } else {
1031    val = RM_NONE;
1032  }
1033
1034  // Adjust typebuf.tb_noremap[] for the new characters:
1035  // If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
1036  //                    (sometimes) not remappable
1037  // If noremap == REMAP_YES: all the new characters are mappable
1038  // If noremap  > 0: "noremap" characters are not remappable, the rest
1039  //                    mappable
1040  if (noremap == REMAP_SKIP) {
1041    nrm = 1;
1042  } else if (noremap < 0) {
1043    nrm = addlen;
1044  } else {
1045    nrm = noremap;
1046  }
1047  for (int i = 0; i < addlen; i++) {
1048    typebuf.tb_noremap[typebuf.tb_off + i + offset] =
1049      (uint8_t)((--nrm >= 0) ? val : RM_YES);
1050  }
1051
1052  // tb_maplen and tb_silent only remember the length of mapped and/or
1053  // silent mappings at the start of the buffer, assuming that a mapped
1054  // sequence doesn't result in typed characters.
1055  if (nottyped || typebuf.tb_maplen > offset) {
1056    typebuf.tb_maplen += addlen;
1057  }
1058  if (silent || typebuf.tb_silent > offset) {
1059    typebuf.tb_silent += addlen;
1060    cmd_silent = true;
1061  }
1062  if (typebuf.tb_no_abbr_cnt && offset == 0) {  // and not used for abbrev.s
1063    typebuf.tb_no_abbr_cnt += addlen;
1064  }
1065
1066  return OK;
1067}
1068
1069/// Re-queues key `c`: puts a key obtained by vgetc() back into typeahead, to be reprocessed: mapped
1070/// (cf. vungetc(), which bypasses mapping), recorded and reported. Calls ungetchars() to drop the
1071/// effects of consuming it the first time.
1072///
1073/// Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to the char.
1074///
1075/// @param recorded  Pass false if the caller suppressed recording on the initial read.
1076/// @param extra_consumed  Extra consumed bytes to un-record beyond the key itself (vgetc()'s
1077///                        ALT-rewrite consumed a `K_SPECIAL KS_MODIFIER` prefix too).
1078void requeue_key(int c, int modifiers, int extra_consumed, bool recorded)
1079{
1080  char buf[MB_MAXBYTES * 3 + 4];
1081  unsigned len = special_to_buf(c, modifiers, true, buf);
1082  assert(len < sizeof(buf));
1083  buf[len] = NUL;
1084  ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
1085  ungetchars((int)len + extra_consumed, recorded);
1086}
1087
1088/// Return true if the typeahead buffer was changed (while waiting for a
1089/// character to arrive).  Happens when a message was received from a client or
1090/// from feedkeys().
1091/// But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
1092/// changed it was reallocated and the old pointer can no longer be used.
1093/// Or "typebuf.tb_off" may have been changed and we would overwrite characters
1094/// that was just added.
1095///
1096/// @param tb_change_cnt  old value of typebuf.tb_change_cnt
1097bool typebuf_changed(int tb_change_cnt)
1098  FUNC_ATTR_PURE
1099{
1100  return tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
1101                                || typebuf_was_filled);
1102}
1103
1104/// Return true if there are no characters in the typeahead buffer that have
1105/// not been typed (result from a mapping or come from ":normal").
1106int typebuf_typed(void)
1107  FUNC_ATTR_PURE
1108{
1109  return typebuf.tb_maplen == 0;
1110}
1111
1112/// Get the number of characters that are mapped (or not typed).
1113int typebuf_maplen(void)
1114  FUNC_ATTR_PURE
1115{
1116  return typebuf.tb_maplen;
1117}
1118
1119/// Remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
1120void del_typebuf(int len, int offset)
1121{
1122  if (len == 0) {
1123    return;             // nothing to do
1124  }
1125
1126  typebuf.tb_len -= len;
1127
1128  // Easy case: Just increase typebuf.tb_off.
1129  if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
1130      >= 3 * MAXMAPLEN + 3) {
1131    typebuf.tb_off += len;
1132  } else {
1133    // Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
1134    int i = typebuf.tb_off + offset;
1135    // Leave some extra room at the end to avoid reallocation.
1136    if (typebuf.tb_off > MAXMAPLEN) {
1137      memmove(typebuf.tb_buf + MAXMAPLEN,
1138              typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
1139      memmove(typebuf.tb_noremap + MAXMAPLEN,
1140              typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
1141      typebuf.tb_off = MAXMAPLEN;
1142    }
1143    // adjust typebuf.tb_buf (include the NUL at the end)
1144    int bytes = typebuf.tb_len - offset + 1;
1145    assert(bytes > 0);
1146    memmove(typebuf.tb_buf + typebuf.tb_off + offset,
1147            typebuf.tb_buf + i + len, (size_t)bytes);
1148    // adjust typebuf.tb_noremap[]
1149    memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
1150            typebuf.tb_noremap + i + len,
1151            (size_t)(typebuf.tb_len - offset));
1152  }
1153
1154  if (typebuf.tb_maplen > offset) {             // adjust tb_maplen
1155    if (typebuf.tb_maplen < offset + len) {
1156      typebuf.tb_maplen = offset;
1157    } else {
1158      typebuf.tb_maplen -= len;
1159    }
1160  }
1161  if (typebuf.tb_silent > offset) {             // adjust tb_silent
1162    if (typebuf.tb_silent < offset + len) {
1163      typebuf.tb_silent = offset;
1164    } else {
1165      typebuf.tb_silent -= len;
1166    }
1167  }
1168  if (typebuf.tb_no_abbr_cnt > offset) {        // adjust tb_no_abbr_cnt
1169    if (typebuf.tb_no_abbr_cnt < offset + len) {
1170      typebuf.tb_no_abbr_cnt = offset;
1171    } else {
1172      typebuf.tb_no_abbr_cnt -= len;
1173    }
1174  }
1175
1176  // Reset the flag that text received from a client or from feedkeys()
1177  // was inserted in the typeahead buffer.
1178  typebuf_was_filled = false;
1179  if (++typebuf.tb_change_cnt == 0) {
1180    typebuf.tb_change_cnt = 1;
1181  }
1182}
1183
1184/// Append a single byte to a recording or 'showcmd'.
1185/// Return true if a full key has been received, false otherwise.
1186static bool gotchars_add_byte(gotchars_state_T *state, uint8_t byte)
1187  FUNC_ATTR_NONNULL_ALL
1188{
1189  int c = state->buf[state->buflen++] = byte;
1190  bool retval = false;
1191  const bool in_special = state->pending_special > 0;
1192  const bool in_mbyte = state->pending_mbyte > 0;
1193
1194  if (in_special) {
1195    state->pending_special--;
1196  } else if (c == K_SPECIAL) {
1197    // When receiving a special key sequence, store it until we have all
1198    // the bytes and we can decide what to do with it.
1199    state->pending_special = 2;
1200  }
1201
1202  if (state->pending_special > 0) {
1203    goto ret_false;
1204  }
1205
1206  if (in_mbyte) {
1207    state->pending_mbyte--;
1208  } else {
1209    if (in_special) {
1210      if (state->prev_c == KS_MODIFIER) {
1211        // When receiving a modifier, wait for the modified key.
1212        goto ret_false;
1213      }
1214      c = TO_SPECIAL(state->prev_c, c);
1215      // Drop K_COMPLETE_DELAY, it's not useful in a recording.
1216      if (c == K_COMPLETE_DELAY) {
1217        state->buflen = 0;
1218      }
1219    }
1220    // When receiving a multibyte character, store it until we have all the bytes, so that
1221    // whole keys reach the recording and ungetchars() removes whole keys.
1222    state->pending_mbyte = MB_BYTE2LEN_CHECK(c) - 1;
1223  }
1224
1225  if (state->pending_mbyte > 0) {
1226    goto ret_false;
1227  }
1228
1229  retval = true;
1230ret_false:
1231  state->prev_c = c;
1232  return retval;
1233}
1234
1235/// Write typed characters to script file.
1236/// If recording is on put the character in the record buffer.
1237static void gotchars(const uint8_t *chars, size_t len)
1238  FUNC_ATTR_NONNULL_ALL
1239{
1240  const uint8_t *s = chars;
1241  size_t todo = len;
1242  static gotchars_state_T state;
1243
1244  while (todo-- > 0) {
1245    if (!gotchars_add_byte(&state, *s++)) {
1246      continue;
1247    }
1248
1249    // Handle one byte at a time; no translation to be done.
1250    for (size_t i = 0; i < state.buflen; i++) {
1251      updatescript(state.buf[i]);
1252    }
1253
1254    if (state.buflen > on_key_ignore_len) {
1255      kvi_concat_len(on_key_buf, (char *)state.buf + on_key_ignore_len,
1256                     state.buflen - on_key_ignore_len);
1257      on_key_ignore_len = 0;
1258    } else {
1259      on_key_ignore_len -= state.buflen;
1260    }
1261
1262    if (reg_recording != 0) {
1263      kv_concat_len(recordbuff, (char *)state.buf, state.buflen);
1264      // remember how many chars were last recorded
1265      last_recorded_len += state.buflen;
1266    }
1267
1268    // Typed keys consumed during 'operatorfunc' are the op's interactive payload.
1269    atom_typed_add(state.buf, state.buflen);
1270
1271    state.buflen = 0;
1272  }
1273
1274  may_sync_undo();
1275
1276  // output "debug mode" message next time in debug mode
1277  debug_did_msg = false;
1278
1279  // Since characters have been typed, consider the following to be in
1280  // another mapping.  Search string will be kept in history.
1281  maptick++;
1282}
1283
1284/// Record an <Ignore> key.
1285void gotchars_ignore(void)
1286{
1287  uint8_t nop_buf[3] = { K_SPECIAL, KS_EXTRA, KE_IGNORE };
1288  on_key_ignore_len += 3;
1289  gotchars(nop_buf, 3);
1290}
1291
1292/// Undo the last gotchars() for `len` bytes: a key that was read is being re-queued into typeahead,
1293/// so it will be read (+ gotchars()) again. Un-reports the bytes, and (if `recorded`) removes them
1294/// from the recording.
1295///
1296/// @param recorded  Pass false if recording was suppressed on the first read: the trailing
1297///        `recordbuff` bytes are unrelated and deleting them would corrupt it.
1298static void ungetchars(int len, bool recorded)
1299{
1300  if (!KeyTyped) {
1301    return;  // gotchars() only sees typed keys; nothing to undo.
1302  }
1303  if (recorded && reg_recording != 0 && recordbuff.size >= (size_t)len) {
1304    recordbuff.size -= (size_t)len;
1305    last_recorded_len -= (size_t)len;
1306  }
1307  atom_typed_del((size_t)len);
1308  size_t trim = MIN((size_t)len, on_key_buf.size);
1309  on_key_buf.size -= trim;
1310  on_key_ignore_len += (size_t)len - trim;
1311}
1312
1313/// Sync undo.  Called when typed characters are obtained from the typeahead
1314/// buffer, or when a menu is used.
1315/// Do not sync:
1316/// - In Insert mode, unless cursor key has been used.
1317/// - While reading a script file.
1318/// - When no_u_sync is non-zero.
1319void may_sync_undo(void)
1320{
1321  if ((!(State & (MODE_INSERT | MODE_CMDLINE)) || Ins.moved != kInsNone)
1322      && curscript < 0) {
1323    u_sync(false);
1324  }
1325}
1326
1327/// Make "typebuf" empty and allocate new buffers.
1328static void alloc_typebuf(void)
1329{
1330  typebuf.tb_buf = xmalloc(TYPELEN_INIT);
1331  typebuf.tb_noremap = xmalloc(TYPELEN_INIT);
1332  typebuf.tb_buflen = TYPELEN_INIT;
1333  typebuf.tb_off = MAXMAPLEN + 4;     // can insert without realloc
1334  typebuf.tb_len = 0;
1335  typebuf.tb_maplen = 0;
1336  typebuf.tb_silent = 0;
1337  typebuf.tb_no_abbr_cnt = 0;
1338  if (++typebuf.tb_change_cnt == 0) {
1339    typebuf.tb_change_cnt = 1;
1340  }
1341  typebuf_was_filled = false;
1342}
1343
1344/// Free the buffers of "typebuf".
1345static void free_typebuf(void)
1346{
1347  if (typebuf.tb_buf == typebuf_init) {
1348    internal_error("Free typebuf 1");
1349  } else {
1350    XFREE_CLEAR(typebuf.tb_buf);
1351  }
1352  if (typebuf.tb_noremap == noremapbuf_init) {
1353    internal_error("Free typebuf 2");
1354  } else {
1355    XFREE_CLEAR(typebuf.tb_noremap);
1356  }
1357}
1358
1359/// When doing ":so! file", the current typeahead needs to be saved, and
1360/// restored when "file" has been read completely.
1361static typebuf_T saved_typebuf[NSCRIPT];
1362
1363static void save_typebuf(void)
1364{
1365  assert(curscript >= 0);
1366  init_typebuf();
1367  saved_typebuf[curscript] = typebuf;
1368  alloc_typebuf();
1369}
1370
1371static bool can_get_ungot(void)
1372  FUNC_ATTR_PURE
1373{
1374  // If the ungotten character was not stuffed and characters have been added to
1375  // the stuff buffer, need to first get the stuffed characters instead.
1376  return ungot.c != -1 && (ungot.stuffed || stuff_empty());
1377}
1378
1379/// Save all three kinds of typeahead, so that the user must type at a prompt.
1380void save_typeahead(tasave_T *tp)
1381  FUNC_ATTR_NONNULL_ALL
1382{
1383  tp->save_typebuf = typebuf;
1384  alloc_typebuf();
1385  tp->ungot = ungot;
1386  ungot.c = -1;
1387
1388  tp->save_readbuf1 = readbuf1;
1389  readbuf1 = (StuffBuf){ 0 };
1390  tp->save_readbuf2 = readbuf2;
1391  readbuf2 = (StuffBuf){ 0 };
1392}
1393
1394/// Restore the typeahead to what it was before calling save_typeahead().
1395/// The allocated memory is freed, can only be called once!
1396void restore_typeahead(tasave_T *tp)
1397  FUNC_ATTR_NONNULL_ALL
1398{
1399  free_typebuf();
1400  typebuf = tp->save_typebuf;
1401  ungot = tp->ungot;
1402
1403  free_buff(&readbuf1);
1404  readbuf1 = tp->save_readbuf1;
1405  free_buff(&readbuf2);
1406  readbuf2 = tp->save_readbuf2;
1407}
1408
1409/// Open a new script file for the ":source!" command.
1410///
1411/// @param directly  when true execute directly
1412void openscript(char *name, bool directly)
1413{
1414  if (curscript + 1 == NSCRIPT) {
1415    emsg(_(e_nesting));
1416    return;
1417  }
1418
1419  // Disallow sourcing a file in the sandbox, the commands would be executed
1420  // later, possibly outside of the sandbox.
1421  if (check_secure()) {
1422    return;
1423  }
1424
1425  if (ignore_script) {
1426    // Not reading from script, also don't open one.  Warning message?
1427    return;
1428  }
1429
1430  curscript++;
1431  // use NameBuff for expanded name
1432  expand_env(name, NameBuff, MAXPATHL);
1433  int error = file_open(&scriptin[curscript], NameBuff, kFileReadOnly, 0);
1434  if (error) {
1435    semsg(_(e_notopen_2), name, os_strerror(error));
1436    curscript--;
1437    return;
1438  }
1439  save_typebuf();
1440
1441  // Execute the commands from the file right now when using ":source!"
1442  // after ":global" or ":argdo" or in a loop.  Also when another command
1443  // follows.  This means the display won't be updated.  Don't do this
1444  // always, "make test" would fail.
1445  if (directly) {
1446    oparg_T oa;
1447    int save_State = State;
1448    int save_restart_edit = restart_edit;
1449    int save_finish_op = finish_op;
1450    int save_msg_scroll = msg_scroll;
1451
1452    State = MODE_NORMAL;
1453    msg_scroll = false;         // no msg scrolling in Normal mode
1454    restart_edit = 0;           // don't go to Insert mode
1455    clear_oparg(&oa);
1456    finish_op = false;
1457
1458    int oldcurscript = curscript;
1459    do {
1460      update_topline_cursor();          // update cursor position and topline
1461      normal_cmd(&oa, false);           // execute one command
1462      vpeekc();                   // check for end of file
1463    } while (curscript >= oldcurscript);
1464
1465    State = save_State;
1466    msg_scroll = save_msg_scroll;
1467    restart_edit = save_restart_edit;
1468    finish_op = save_finish_op;
1469  }
1470}
1471
1472/// Close the currently active input script.
1473static void closescript(void)
1474{
1475  assert(curscript >= 0);
1476  free_typebuf();
1477  typebuf = saved_typebuf[curscript];
1478
1479  file_close(&scriptin[curscript], false);
1480  curscript--;
1481}
1482
1483#ifdef EXITFREE
1484void close_all_scripts(void)
1485{
1486  while (curscript >= 0) {
1487    closescript();
1488  }
1489}
1490
1491#endif
1492
1493bool open_scriptin(char *scriptin_name)
1494  FUNC_ATTR_NONNULL_ALL
1495{
1496  assert(curscript == -1);
1497  curscript++;
1498
1499  int error;
1500  if (strequal(scriptin_name, "-")) {
1501    error = file_open_stdin(&scriptin[0]);
1502  } else {
1503    error = file_open(&scriptin[0], scriptin_name,
1504                      kFileReadOnly|kFileNonBlocking, 0);
1505  }
1506  if (error) {
1507    fprintf(stderr, _("Cannot open for reading: \"%s\": %s\n"),
1508            scriptin_name, os_strerror(error));
1509    curscript--;
1510    return false;
1511  }
1512  save_typebuf();
1513
1514  return true;
1515}
1516
1517/// Return true when reading keys from a script file.
1518int using_script(void)
1519  FUNC_ATTR_PURE
1520{
1521  return curscript >= 0;
1522}
1523
1524/// This function is called just before doing a blocking wait.  Thus after
1525/// waiting 'updatetime' for a character to arrive.
1526void before_blocking(void)
1527{
1528  updatescript(0);
1529  if (may_garbage_collect) {
1530    garbage_collect(false);
1531  }
1532}
1533
1534/// updatescript() is called when a character can be written to the script
1535/// file or when we have waited some time for a character (c == 0).
1536///
1537/// All the changed memfiles are synced if c == 0 or when the number of typed
1538/// characters reaches 'updatecount' and 'updatecount' is non-zero.
1539static void updatescript(int c)
1540{
1541  static int count = 0;
1542
1543  if (c && scriptout) {
1544    putc(c, scriptout);
1545  }
1546  bool idle = (c == 0);
1547  if (idle || (p_uc > 0 && ++count >= p_uc)) {
1548    ml_sync_all(idle, true,
1549                (!!p_fs || idle));  // Always fsync at idle (CursorHold).
1550    count = 0;
1551  }
1552}
1553
1554/// Merge "modifiers" into "c_arg".
1555int merge_modifiers(int c_arg, int *modifiers)
1556  FUNC_ATTR_NONNULL_ALL
1557{
1558  int c = c_arg;
1559
1560  if (*modifiers & MOD_MASK_CTRL) {
1561    if (c >= '@' && c <= 0x7f) {
1562      c &= 0x1f;
1563      if (c == NUL) {
1564        c = K_ZERO;
1565      }
1566    } else if (c == '6') {
1567      // CTRL-6 is equivalent to CTRL-^
1568      c = 0x1e;
1569    }
1570    if (c != c_arg) {
1571      *modifiers &= ~MOD_MASK_CTRL;
1572    }
1573  }
1574  return c;
1575}
1576
1577/// Append a single byte to 'showcmd' for a partially matched mapping.
1578/// Call add_to_showcmd() if a full key has been received.
1579static void add_byte_to_showcmd(uint8_t byte)
1580{
1581  static gotchars_state_T state;
1582
1583  if (!p_sc || msg_silent != 0) {
1584    return;
1585  }
1586
1587  if (!gotchars_add_byte(&state, byte)) {
1588    return;
1589  }
1590
1591  state.buf[state.buflen] = NUL;
1592  state.buflen = 0;
1593
1594  int modifiers = 0;
1595  int c = NUL;
1596
1597  const uint8_t *ptr = state.buf;
1598  if (ptr[0] == K_SPECIAL && ptr[1] == KS_MODIFIER && ptr[2] != NUL) {
1599    modifiers = ptr[2];
1600    ptr += 3;
1601  }
1602
1603  if (*ptr != NUL) {
1604    const char *mb_ptr = mb_unescape((const char **)&ptr);
1605    c = mb_ptr != NULL ? utf_ptr2char(mb_ptr) : *ptr++;
1606    if (c <= 0x7f) {
1607      // Merge modifiers into the key to make the result more readable.
1608      int modifiers_after = modifiers;
1609      int mod_c = merge_modifiers(c, &modifiers_after);
1610      if (modifiers_after == 0) {
1611        modifiers = 0;
1612        c = mod_c;
1613      }
1614    }
1615  }
1616
1617  // TODO(zeertzjq): is there a more readable and yet compact representation of
1618  // modifiers and special keys?
1619  if (modifiers != 0) {
1620    add_to_showcmd(K_SPECIAL);
1621    add_to_showcmd(KS_MODIFIER);
1622    add_to_showcmd(modifiers);
1623  }
1624  if (c != NUL) {
1625    add_to_showcmd(c);
1626  }
1627  while (*ptr != NUL) {
1628    add_to_showcmd(*ptr++);
1629  }
1630}
1631
1632/// Get the next input character.
1633/// Can return a special key or a multi-byte character.
1634/// Can return NUL when called recursively, use safe_vgetc() if that's not
1635/// wanted.
1636/// This translates escaped K_SPECIAL bytes to a K_SPECIAL byte.
1637/// Collects the bytes of a multibyte character into the whole character.
1638/// Returns the modifiers in the global "mod_mask".
1639int vgetc(void)
1640{
1641  int c;
1642  uint8_t buf[MB_MAXBYTES + 1];
1643
1644  // Do garbage collection when garbagecollect() was called previously and
1645  // we are now at the toplevel.
1646  if (may_garbage_collect && want_garbage_collect) {
1647    garbage_collect(false);
1648  }
1649
1650  // If a character was put back with vungetc, it was already processed.
1651  // Return it directly.
1652  if (can_get_ungot()) {
1653    c = ungot.c;
1654    ungot.c = -1;
1655    mod_mask = ungot.mod_mask;
1656    mouse_grid = ungot.mouse_grid;
1657    mouse_row = ungot.mouse_row;
1658    mouse_col = ungot.mouse_col;
1659  } else {
1660    // number of characters recorded from the last vgetc() call
1661    static size_t last_vgetc_recorded_len = 0;
1662
1663    mod_mask = 0;
1664    vgetc_mod_mask = 0;
1665    vgetc_char = 0;
1666
1667    // last_recorded_len can be larger than last_vgetc_recorded_len
1668    // if peeking records more
1669    last_recorded_len -= last_vgetc_recorded_len;
1670
1671    while (true) {              // this is done twice if there are modifiers
1672      bool did_inc = false;
1673      if (mod_mask) {           // no mapping after modifier has been read
1674        no_mapping++;
1675        allow_keys++;
1676        did_inc = true;         // mod_mask may change value
1677      }
1678      c = vgetorpeek(true);
1679      if (did_inc) {
1680        no_mapping--;
1681        allow_keys--;
1682      }
1683
1684      // Get two extra bytes for special keys
1685      if (c == K_SPECIAL) {
1686        int save_allow_keys = allow_keys;
1687        no_mapping++;
1688        allow_keys = 0;                 // make sure BS is not found
1689        int c2 = vgetorpeek(true);          // no mapping for these chars
1690        c = vgetorpeek(true);
1691        no_mapping--;
1692        allow_keys = save_allow_keys;
1693        if (c2 == KS_MODIFIER) {
1694          mod_mask = c;
1695          continue;
1696        }
1697        c = TO_SPECIAL(c2, c);
1698      }
1699
1700      // For a multi-byte character get all the bytes and return the
1701      // converted character.
1702      // Note: This will loop until enough bytes are received!
1703      int n;
1704      if ((n = MB_BYTE2LEN_CHECK(c)) > 1) {
1705        no_mapping++;
1706        buf[0] = (uint8_t)c;
1707        for (int i = 1; i < n; i++) {
1708          buf[i] = (uint8_t)vgetorpeek(true);
1709          if (buf[i] == K_SPECIAL) {
1710            // Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence,
1711            // which represents a K_SPECIAL (0x80).
1712            vgetorpeek(true);  // skip KS_SPECIAL
1713            vgetorpeek(true);  // skip KE_FILLER
1714          }
1715        }
1716        no_mapping--;
1717        c = utf_ptr2char((char *)buf);
1718      }
1719
1720      // If mappings are enabled (i.e., not i_CTRL-V) and the user directly typed
1721      // something with MOD_MASK_ALT (<M-/<A- modifier) that was not mapped, interpret
1722      // <M-x> as <Esc>x rather than as an unbound <M-x> keypress. #8213
1723      // In Terminal mode, however, this is not desirable. #16202 #16220
1724      // Also do not do this for mouse keys, as terminals encode mouse events as
1725      // CSI sequences, and MOD_MASK_ALT has a meaning even for unmapped mouse keys.
1726      if (!no_mapping && KeyTyped && mod_mask == MOD_MASK_ALT
1727          && !(State & MODE_TERMINAL) && !is_mouse_key(c)) {
1728        mod_mask = 0;
1729        // Un-record/un-report the consumed <M-x> (its K_SPECIAL KS_MODIFIER MOD_MASK_ALT prefix
1730        // took 3 more bytes); the rewritten <Esc>x is consumed (recorded, reported) in its place.
1731        requeue_key(c, 0, 3, true);
1732        ins_typebuf(ESC_STR, KeyNoremap, 0, !KeyTyped, cmd_silent);
1733        continue;
1734      }
1735
1736      if (vgetc_char == 0) {
1737        vgetc_mod_mask = mod_mask;
1738        vgetc_char = c;
1739      }
1740
1741      // A keypad or special function key was not mapped, use it like
1742      // its ASCII equivalent.
1743      switch (c) {
1744      case K_KPLUS:
1745        c = '+'; break;
1746      case K_KMINUS:
1747        c = '-'; break;
1748      case K_KDIVIDE:
1749        c = '/'; break;
1750      case K_KMULTIPLY:
1751        c = '*'; break;
1752      case K_KENTER:
1753        c = CAR; break;
1754      case K_KPOINT:
1755        c = '.'; break;
1756      case K_KCOMMA:
1757        c = ','; break;
1758      case K_KEQUAL:
1759        c = '='; break;
1760      case K_K0:
1761        c = '0'; break;
1762      case K_K1:
1763        c = '1'; break;
1764      case K_K2:
1765        c = '2'; break;
1766      case K_K3:
1767        c = '3'; break;
1768      case K_K4:
1769        c = '4'; break;
1770      case K_K5:
1771        c = '5'; break;
1772      case K_K6:
1773        c = '6'; break;
1774      case K_K7:
1775        c = '7'; break;
1776      case K_K8:
1777        c = '8'; break;
1778      case K_K9:
1779        c = '9'; break;
1780
1781      case K_XHOME:
1782      case K_ZHOME:
1783        if (mod_mask == MOD_MASK_SHIFT) {
1784          c = K_S_HOME;
1785          mod_mask = 0;
1786        } else if (mod_mask == MOD_MASK_CTRL) {
1787          c = K_C_HOME;
1788          mod_mask = 0;
1789        } else {
1790          c = K_HOME;
1791        }
1792        break;
1793      case K_XEND:
1794      case K_ZEND:
1795        if (mod_mask == MOD_MASK_SHIFT) {
1796          c = K_S_END;
1797          mod_mask = 0;
1798        } else if (mod_mask == MOD_MASK_CTRL) {
1799          c = K_C_END;
1800          mod_mask = 0;
1801        } else {
1802          c = K_END;
1803        }
1804        break;
1805
1806      case K_KUP:
1807      case K_XUP:
1808        c = K_UP; break;
1809      case K_KDOWN:
1810      case K_XDOWN:
1811        c = K_DOWN; break;
1812      case K_KLEFT:
1813      case K_XLEFT:
1814        c = K_LEFT; break;
1815      case K_KRIGHT:
1816      case K_XRIGHT:
1817        c = K_RIGHT; break;
1818      }
1819
1820      break;
1821    }
1822
1823    last_vgetc_recorded_len = last_recorded_len;
1824  }
1825
1826  // In the main loop "may_garbage_collect" can be set to do garbage
1827  // collection in the first next vgetc().  It's disabled after that to
1828  // avoid internally used Lists and Dicts to be freed.
1829  may_garbage_collect = false;
1830
1831  // Execute Lua on_key callbacks.
1832  kvi_push(on_key_buf, NUL);
1833  if (getchar_depth == 0 && nlua_exec_on_key(c, on_key_buf.items)) {
1834    // Keys following K_COMMAND/K_LUA/K_PASTE_START aren't normally received by
1835    // vim.on_key() callbacks, so discard them along with the current key.
1836    if (c == K_COMMAND) {
1837      xfree(getcmdkeycmd(NUL, NULL, 0, false));
1838    } else if (c == K_LUA) {
1839      map_execute_lua(false, true);
1840    } else if (c == K_PASTE_START) {
1841      paste_repeat(0);
1842    }
1843    // Discard the current key.
1844    c = K_IGNORE;
1845  }
1846  kvi_destroy(on_key_buf);
1847  kvi_init(on_key_buf);
1848
1849  // Need to process the character before we know it's safe to do something
1850  // else.
1851  if (c != K_IGNORE) {
1852    state_no_longer_safe("key typed");
1853  }
1854
1855  return c;
1856}
1857
1858/// Like vgetc(), but never return a NUL when called recursively, get a key
1859/// directly from the user (ignoring typeahead).
1860int safe_vgetc(void)
1861{
1862  int c = vgetc();
1863  if (c == NUL) {
1864    c = get_keystroke(NULL);
1865  }
1866  return c;
1867}
1868
1869/// Like safe_vgetc(), but loop to handle K_IGNORE.
1870/// Also ignore scrollbar events.
1871int plain_vgetc(void)
1872{
1873  int c;
1874
1875  do {
1876    c = safe_vgetc();
1877  } while (c == K_IGNORE
1878           || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR
1879           || c == K_MOUSEMOVE);
1880  return c;
1881}
1882
1883/// Check if a character is available, such that vgetc() will not block.
1884/// If the next character is a special character or multi-byte, the returned
1885/// character is not valid!.
1886/// Returns NUL if no character is available.
1887int vpeekc(void)
1888{
1889  if (can_get_ungot()) {
1890    return ungot.c;
1891  }
1892  return vgetorpeek(false);
1893}
1894
1895/// Check if any character is available, also half an escape sequence.
1896/// Trick: when no typeahead found, but there is something in the typeahead
1897/// buffer, it must be an ESC that is recognized as the start of a key code.
1898int vpeekc_any(void)
1899{
1900  int c = vpeekc();
1901  if (c == NUL && typebuf.tb_len > 0) {
1902    c = ESC;
1903  }
1904  return c;
1905}
1906
1907/// Call vpeekc() without causing anything to be mapped.
1908/// @return  true if a character is available, false otherwise.
1909bool char_avail(void)
1910{
1911  if (test_disable_char_avail) {
1912    return false;
1913  }
1914  no_mapping++;
1915  int retval = vpeekc();
1916  no_mapping--;
1917  return retval != NUL;
1918}
1919
1920static int no_reduce_keys = 0;  ///< Do not apply modifiers to the key.
1921
1922/// "getchar()" and "getcharstr()" functions
1923static void getchar_common(typval_T *argvars, typval_T *rettv, bool allow_number)
1924  FUNC_ATTR_NONNULL_ALL
1925{
1926  varnumber_T n = 0;
1927  const int called_emsg_start = called_emsg;
1928  bool error = false;
1929  bool simplify = true;
1930  char cursor_flag = NUL;
1931
1932  if (argvars[0].v_type != VAR_UNKNOWN
1933      && tv_check_for_opt_dict_arg(argvars, 1) == FAIL) {
1934    return;
1935  }
1936
1937  if (argvars[0].v_type != VAR_UNKNOWN && argvars[1].v_type == VAR_DICT) {
1938    dict_T *d = argvars[1].vval.v_dict;
1939
1940    if (allow_number) {
1941      allow_number = tv_dict_get_bool(d, "number", true);
1942    } else if (tv_dict_has_key(d, "number")) {
1943      semsg(_(e_invarg2), "number");
1944    }
1945
1946    simplify = tv_dict_get_bool(d, "simplify", true);
1947
1948    const char *cursor_str = tv_dict_get_string(d, "cursor", false);
1949    if (cursor_str != NULL) {
1950      if (strcmp(cursor_str, "hide") != 0
1951          && strcmp(cursor_str, "keep") != 0
1952          && strcmp(cursor_str, "msg") != 0) {
1953        semsg(_(e_invargNval), "cursor", cursor_str);
1954      } else {
1955        cursor_flag = cursor_str[0];
1956      }
1957    }
1958  }
1959
1960  if (called_emsg != called_emsg_start) {
1961    return;
1962  }
1963
1964  if (cursor_flag == 'h') {
1965    ui_busy_start();
1966  }
1967
1968  no_mapping++;
1969  allow_keys++;
1970  getchar_depth++;
1971  if (!simplify) {
1972    no_reduce_keys++;
1973  }
1974  atom_payload_start();
1975  while (true) {
1976    if (cursor_flag == 'm' || (cursor_flag == NUL && msg_col > 0)) {
1977      ui_cursor_goto(msg_row, msg_col);
1978    }
1979
1980    if (argvars[0].v_type == VAR_UNKNOWN
1981        || (argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number == -1)) {
1982      // getchar(): blocking wait.
1983      // TODO(bfredl): deduplicate shared logic with state_enter ?
1984      if (!char_avail()) {
1985        // Flush screen updates before blocking.
1986        ui_flush();
1987        input_get(NULL, 0, -1, typebuf.tb_change_cnt, main_loop.events);
1988        if (!input_available() && !multiqueue_empty(main_loop.events)) {
1989          state_handle_k_event();
1990          continue;
1991        }
1992      }
1993      n = safe_vgetc();
1994    } else if (tv_get_bool_chk(&argvars[0], &error)) {
1995      // getchar(1): only check if char avail
1996      n = vpeekc_any();
1997    } else if (error || vpeekc_any() == NUL) {
1998      // illegal argument or getchar(0) and no char avail: return zero
1999      n = 0;
2000    } else {
2001      // getchar(0) and char avail() != NUL: get a character.
2002      // Note that vpeekc_any() returns K_SPECIAL for K_IGNORE.
2003      n = safe_vgetc();
2004    }
2005
2006    if (n == K_IGNORE
2007        || n == K_MOUSEMOVE
2008        || n == K_VER_SCROLLBAR
2009        || n == K_HOR_SCROLLBAR) {
2010      continue;
2011    }
2012    break;
2013  }
2014  atom_payload_end();
2015  no_mapping--;
2016  allow_keys--;
2017  getchar_depth--;
2018  if (!simplify) {
2019    no_reduce_keys--;
2020  }
2021
2022  if (cursor_flag == 'h') {
2023    ui_busy_stop();
2024  }
2025
2026  set_vim_var_nr(VV_MOUSE_WIN, 0);
2027  set_vim_var_nr(VV_MOUSE_WINID, 0);
2028  set_vim_var_nr(VV_MOUSE_LNUM, 0);
2029  set_vim_var_nr(VV_MOUSE_COL, 0);
2030
2031  if (n != 0 && (!allow_number || IS_SPECIAL(n) || mod_mask != 0)) {
2032    char temp[10];                // modifier: 3, mbyte-char: 6, NUL: 1
2033    int i = 0;
2034
2035    // Turn a special key into three bytes, plus modifier.
2036    if (mod_mask != 0) {
2037      temp[i++] = (char)K_SPECIAL;
2038      temp[i++] = (char)KS_MODIFIER;
2039      temp[i++] = (char)mod_mask;
2040    }
2041    if (IS_SPECIAL(n)) {
2042      temp[i++] = (char)K_SPECIAL;
2043      temp[i++] = (char)K_SECOND(n);
2044      temp[i++] = (char)K_THIRD(n);
2045    } else {
2046      i += utf_char2bytes((int)n, temp + i);
2047    }
2048    assert(i < 10);
2049    temp[i] = NUL;
2050    rettv->v_type = VAR_STRING;
2051    rettv->vval.v_string = xmemdupz(temp, (size_t)i);
2052
2053    if (is_mouse_key((int)n)) {
2054      int row = mouse_row;
2055      int col = mouse_col;
2056      int grid = mouse_grid;
2057      linenr_T lnum;
2058      win_T *wp;
2059
2060      if (row >= 0 && col >= 0) {
2061        int winnr = 1;
2062        // Find the window at the mouse coordinates and compute the
2063        // text position.
2064        win_T *const win = mouse_find_win_inner(&grid, &row, &col);
2065        if (win == NULL) {
2066          return;
2067        }
2068        mouse_comp_pos(win, &row, &col, &lnum);
2069        for (wp = firstwin; wp != win; wp = wp->w_next) {
2070          winnr++;
2071        }
2072        set_vim_var_nr(VV_MOUSE_WIN, winnr);
2073        set_vim_var_nr(VV_MOUSE_WINID, wp->handle);
2074        set_vim_var_nr(VV_MOUSE_LNUM, lnum);
2075        set_vim_var_nr(VV_MOUSE_COL, col + 1);
2076      }
2077    }
2078  } else if (!allow_number) {
2079    rettv->v_type = VAR_STRING;
2080  } else {
2081    rettv->vval.v_number = n;
2082  }
2083}
2084
2085/// "getchar()" function
2086void f_getchar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2087{
2088  getchar_common(argvars, rettv, true);
2089}
2090
2091/// "getcharstr()" function
2092void f_getcharstr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2093{
2094  getchar_common(argvars, rettv, false);
2095}
2096
2097/// "getcharmod()" function
2098void f_getcharmod(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2099{
2100  rettv->vval.v_number = mod_mask;
2101}
2102
2103typedef enum {
2104  map_result_fail,    // failed (recursion limit, OOM), break loop
2105  map_result_get,     // get a character from typeahead
2106  map_result_retry,   // try to map again
2107  map_result_nomatch,  // no matching mapping, get char
2108} map_result_T;
2109
2110/// Put "string[new_slen]" in typebuf.
2111/// Remove "slen" bytes.
2112/// @return  FAIL for error, OK otherwise.
2113static int put_string_in_typebuf(int offset, int slen, uint8_t *string, int new_slen)
2114  FUNC_ATTR_NONNULL_ALL
2115{
2116  int extra = new_slen - slen;
2117  string[new_slen] = NUL;
2118  if (extra < 0) {
2119    // remove matched chars, taking care of noremap
2120    del_typebuf(-extra, offset);
2121  } else if (extra > 0) {
2122    // insert the extra space we need
2123    if (ins_typebuf((char *)string + slen, REMAP_YES, offset, false, false) == FAIL) {
2124      return FAIL;
2125    }
2126  }
2127  // Careful: del_typebuf() and ins_typebuf() may have reallocated
2128  // typebuf.tb_buf[]!
2129  memmove(typebuf.tb_buf + typebuf.tb_off + offset, string, (size_t)new_slen);
2130  return OK;
2131}
2132
2133/// Check if the bytes at the start of the typeahead buffer are a character used
2134/// in Insert mode completion.  This includes the form with a CTRL modifier.
2135/// During completion started by complete() keys are mapped as usual.
2136static bool at_ins_compl_key(void)
2137{
2138  uint8_t *p = typebuf.tb_buf + typebuf.tb_off;
2139  int c = *p;
2140
2141  if (typebuf.tb_len > 3 && c == K_SPECIAL && p[1] == KS_MODIFIER && (p[2] & MOD_MASK_CTRL)) {
2142    c = p[3] & 0x1f;
2143  }
2144  return !ctrl_x_mode_eval()
2145         && ((ctrl_x_mode_not_default() && vim_is_ctrl_x_key(c))
2146             || (compl_status_local() && (c == Ctrl_N || c == Ctrl_P)));
2147}
2148
2149/// Check if typebuf.tb_buf[] contains a modifier plus key that can be changed
2150/// into just a key, apply that.
2151/// Check from typebuf.tb_buf[typebuf.tb_off] to typebuf.tb_buf[typebuf.tb_off + "max_offset"].
2152/// @return  the length of the replaced bytes, 0 if nothing changed, -1 for error.
2153static int check_simplify_modifier(int max_offset)
2154{
2155  // We want full modifiers in Terminal mode so that the key can be correctly
2156  // encoded
2157  if ((State & MODE_TERMINAL) || no_reduce_keys > 0) {
2158    return 0;
2159  }
2160
2161  for (int offset = 0; offset < max_offset; offset++) {
2162    if (offset + 3 >= typebuf.tb_len) {
2163      break;
2164    }
2165    uint8_t *tp = typebuf.tb_buf + typebuf.tb_off + offset;
2166    if (tp[0] == K_SPECIAL && tp[1] == KS_MODIFIER) {
2167      // A modifier was not used for a mapping, apply it to ASCII
2168      // keys.  Shift would already have been applied.
2169      int modifier = tp[2];
2170      int c = tp[3];
2171      int new_c = merge_modifiers(c, &modifier);
2172
2173      if (new_c != c) {
2174        if (offset == 0) {
2175          // At the start: remember the character and mod_mask before
2176          // merging, in some cases, e.g. at the hit-return prompt,
2177          // they are put back in the typeahead buffer.
2178          vgetc_char = c;
2179          vgetc_mod_mask = tp[2];
2180        }
2181        uint8_t new_string[MB_MAXBYTES];
2182        int len;
2183        if (IS_SPECIAL(new_c)) {
2184          new_string[0] = K_SPECIAL;
2185          new_string[1] = (uint8_t)K_SECOND(new_c);
2186          new_string[2] = (uint8_t)K_THIRD(new_c);
2187          len = 3;
2188        } else {
2189          len = utf_char2bytes(new_c, (char *)new_string);
2190        }
2191        if (modifier == 0) {
2192          if (put_string_in_typebuf(offset, 4, new_string, len) == FAIL) {
2193            return -1;
2194          }
2195        } else {
2196          tp[2] = (uint8_t)modifier;
2197          if (put_string_in_typebuf(offset + 3, 1, new_string, len) == FAIL) {
2198            return -1;
2199          }
2200        }
2201        return len;
2202      }
2203    }
2204  }
2205  return 0;
2206}
2207
2208/// Returns the next character from a NUL-terminated UTF-8-encoded escaped-K_SPECIAL string.
2209///
2210/// Combining characters are treated as separate code points.
2211///
2212/// @param[inout] itp   Pointer to the input string pointer. The string pointer will be advanced to
2213///                     the next character.
2214/// @param        nomap If non-zero, then multi-byte characters are not decoded and the function
2215///                     always returns the next byte from the string.
2216/// @return             Unicode code point or 0, if at the end.
2217///                     - Returns 0 when NUL is in the middle of a multi-byte sequence. This allows
2218///                       calling code to request more data.
2219///                     - If decoding of a multi-byte character fails, returns the first byte of
2220///                       the encoded character.
2221static int char_iter(const uint8_t **itp, int nomap)
2222  FUNC_ATTR_NONNULL_ALL
2223{
2224  const uint8_t *it = *itp;
2225  int c = *it;
2226  if (c == NUL) {
2227    return 0;
2228  }
2229
2230  if (nomap == 0) {
2231    int mblen = MB_BYTE2LEN(c);
2232    if (mblen > 1) {
2233      uint8_t buf[MB_MAXBYTES + 1];
2234      buf[0] = (uint8_t)c;
2235      int i = 1;
2236
2237      do {
2238        buf[i] = *++it;
2239        if (buf[i] == K_SPECIAL) {
2240          // Follows vgetc()'s logic: Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence, which
2241          // represents a K_SPECIAL (0x80). Skip KS_SPECIAL and KE_FILLER.
2242          if (*++it == NUL || *++it == NUL) {
2243            break;
2244          }
2245        }
2246      } while (buf[i] != NUL && ++i < mblen);
2247
2248      if (i != mblen) {
2249        *itp = it;
2250        return 0;
2251      }
2252
2253      c = utf_ptr2char((const char *)buf);
2254      if (c == buf[0]) {
2255        // Invalid UTF-8 sequence
2256        it = *itp;
2257      }
2258    }
2259  }
2260
2261  *itp = ++it;
2262  return c;
2263}
2264
2265/// Handle mappings in the typeahead buffer.
2266/// - When something was mapped, return map_result_retry for recursive mappings.
2267/// - When nothing mapped and typeahead has a character: return map_result_get.
2268/// - When there is no match yet, return map_result_nomatch, need to get more
2269///   typeahead.
2270/// - On failure (out of memory) return map_result_fail.
2271static int handle_mapping(int *keylenp, const bool *timedout, int *mapdepth, bool advance)
2272  FUNC_ATTR_NONNULL_ARG(1)
2273{
2274  mapblock_T *mp = NULL;
2275  mapblock_T *mp2;
2276  mapblock_T *mp_match;
2277  int mp_match_len = 0;
2278  int tb_match_len = 0;
2279  int max_mlen = 0;
2280  int keylen = *keylenp;
2281  int local_State = get_real_state();
2282  bool is_plug_map = false;
2283
2284  // If typeahead starts with <Plug> then remap, even for a "noremap" mapping.
2285  if (typebuf.tb_len >= 3
2286      && typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
2287      && typebuf.tb_buf[typebuf.tb_off + 1] == KS_EXTRA
2288      && typebuf.tb_buf[typebuf.tb_off + 2] == KE_PLUG) {
2289    is_plug_map = true;
2290  }
2291
2292  // Check for a mappable key sequence.
2293  // Walk through one maphash[] list until we find an entry that matches.
2294  //
2295  // Don't look for mappings if:
2296  // - no_mapping set: mapping disabled (e.g. for CTRL-V)
2297  // - maphash_valid not set: no mappings present.
2298  // - typebuf.tb_buf[typebuf.tb_off] should not be remapped
2299  // - in insert or cmdline mode and 'paste' option set
2300  // - waiting for "hit return to continue" and CR or SPACE typed
2301  // - waiting for a char with --more--
2302  // - in Ctrl-X mode, and we get a valid char for that mode
2303  // - in Ctrl-X mode (not started by complete()), and we get a valid char for that mode
2304  int tb_b1 = typebuf.tb_buf[typebuf.tb_off];
2305  if (no_mapping == 0
2306      && (no_zero_mapping == 0 || tb_b1 != '0')
2307      && (typebuf.tb_maplen == 0 || is_plug_map
2308          || (!(typebuf.tb_noremap[typebuf.tb_off] & (RM_NONE|RM_ABBR))))
2309      && !(p_paste && (State & (MODE_INSERT | MODE_CMDLINE)))
2310      && !(State == MODE_HITRETURN && (tb_b1 == CAR || tb_b1 == ' '))
2311      && State != MODE_ASKMORE
2312      && !at_ins_compl_key()) {
2313    int nolmaplen;
2314    int tb_c1 = tb_b1;
2315    const uint8_t *tb_iter = typebuf.tb_buf + typebuf.tb_off;
2316
2317    if (tb_b1 == K_SPECIAL) {
2318      nolmaplen = 2;
2319      tb_iter += 1;
2320    } else {
2321      tb_c1 = char_iter(&tb_iter, 0);
2322      if (tb_c1 == 0) {
2323        if (*timedout) {
2324          *keylenp = 0;
2325          return map_result_get;
2326        }
2327        *keylenp = KEYLEN_PART_KEY;
2328        return map_result_nomatch;
2329      }
2330
2331      int orig_tb_c1 = tb_c1;
2332      LANGMAP_ADJUST(tb_c1, ((State & (MODE_CMDLINE | MODE_INSERT)) == 0
2333                             && get_real_state() != MODE_SELECT));
2334      if (orig_tb_c1 != tb_c1) {
2335        // Mapped by 'langmap', update the first byte
2336        char cbuf[6];
2337        utf_char2bytes(tb_c1, cbuf);
2338        tb_b1 = (uint8_t)cbuf[0];
2339      }
2340      nolmaplen = 0;
2341    }
2342    // First try buffer-local mappings.
2343    mp = get_buf_maphash_list(local_State, tb_b1);
2344    mp2 = get_maphash_list(local_State, tb_b1);
2345    if (mp == NULL) {
2346      // There are no buffer-local mappings.
2347      mp = mp2;
2348      mp2 = NULL;
2349    }
2350    // Loop until a partly matching mapping is found or all (local)
2351    // mappings have been checked.
2352    // The longest full match is remembered in "mp_match".
2353    // A full match is only accepted if there is no partly match, so "aa"
2354    // and "aaa" can both be mapped.
2355    mp_match = NULL;
2356    mp_match_len = 0;
2357    tb_match_len = 0;
2358    for (; mp != NULL; mp->m_next == NULL ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next)) {
2359      // Only consider an entry if the first character matches and it is
2360      // for the current state.
2361      // Skip ":lmap" mappings if keys were mapped.
2362      const uint8_t *key_iter = (const uint8_t *)mp->m_keys;
2363
2364      if (char_iter(&key_iter, 0) == tb_c1 && (mp->m_mode & local_State)
2365          && ((mp->m_mode & MODE_LANGMAP) == 0 || typebuf.tb_maplen == 0)) {
2366        int nomap = nolmaplen;
2367        int modifiers = 0;
2368        int c2;
2369        const uint8_t *tmp_tb_iter = tb_iter;
2370        // Match length in key buffer
2371        int mlen = (int)(key_iter - (const uint8_t *)mp->m_keys);
2372        // Match length in typeahead buffer
2373        int tb_mlen = (int)(tmp_tb_iter - typebuf.tb_buf) - typebuf.tb_off;
2374
2375        // find the match length of this mapping
2376        while ((c2 = char_iter(&tmp_tb_iter, nomap)) != 0) {
2377          int tb_nomap = nomap;
2378          if (nomap > 0) {
2379            if (nomap == 2 && c2 == KS_MODIFIER) {
2380              modifiers = 1;
2381            } else if (nomap == 1 && modifiers == 1) {
2382              modifiers = c2;
2383            }
2384            nomap--;
2385          } else {
2386            if (c2 == K_SPECIAL) {
2387              nomap = 2;
2388            } else if (merge_modifiers(c2, &modifiers) == c2) {
2389              // Only apply 'langmap' if merging modifiers into
2390              // the key will not result in another character,
2391              // so that 'langmap' behaves consistently in
2392              // different terminals and GUIs.
2393              LANGMAP_ADJUST(c2, true);
2394            }
2395            modifiers = 0;
2396          }
2397
2398          int key_char = char_iter(&key_iter, tb_nomap);
2399          if (key_char != c2) {
2400            break;
2401          }
2402
2403          mlen = (int)(key_iter - (const uint8_t *)mp->m_keys);
2404          tb_mlen = (int)(tmp_tb_iter - typebuf.tb_buf) - typebuf.tb_off;
2405        }
2406
2407        // Check an entry whether it matches.
2408        // - Full match: mlen == keylen
2409        // - Partly match: mlen == typebuf.tb_len
2410        keylen = mp->m_keylen;
2411        if (mlen == keylen || (mlen == typebuf.tb_len && typebuf.tb_len < keylen)) {
2412          int n;
2413
2414          // If only script-local mappings are allowed, check if the
2415          // mapping starts with K_SNR.
2416          uint8_t *s = typebuf.tb_noremap + typebuf.tb_off;
2417          if (*s == RM_SCRIPT
2418              && ((uint8_t)mp->m_keys[0] != K_SPECIAL
2419                  || (uint8_t)mp->m_keys[1] != KS_EXTRA
2420                  || mp->m_keys[2] != KE_SNR)) {
2421            continue;
2422          }
2423
2424          // If one of the typed keys cannot be remapped, skip the entry.
2425          for (n = mlen; --n >= 0;) {
2426            if (*s++ & (RM_NONE|RM_ABBR)) {
2427              break;
2428            }
2429          }
2430          if (!is_plug_map && n >= 0) {
2431            continue;
2432          }
2433
2434          if (keylen > typebuf.tb_len) {
2435            if (!*timedout && !(mp_match != NULL && mp_match->m_nowait)) {
2436              // break at a partly match
2437              keylen = KEYLEN_PART_MAP;
2438              break;
2439            }
2440          } else if (keylen > mp_match_len
2441                     || (keylen == mp_match_len
2442                         && mp_match != NULL
2443                         && (mp_match->m_mode & MODE_LANGMAP) == 0
2444                         && (mp->m_mode & MODE_LANGMAP) != 0)) {
2445            // found a longer match
2446            mp_match = mp;
2447            mp_match_len = keylen;
2448            tb_match_len = tb_mlen;
2449          }
2450        } else {
2451          // No match; may have to check for termcode at next character.
2452          max_mlen = MAX(max_mlen, mlen);
2453        }
2454      }
2455    }
2456
2457    // If no partly match found, use the longest full match.
2458    if (keylen != KEYLEN_PART_MAP && mp_match != NULL) {
2459      mp = mp_match;
2460      keylen = tb_match_len;
2461    }
2462  }
2463
2464  if ((mp == NULL || max_mlen > mp_match_len) && keylen != KEYLEN_PART_MAP) {
2465    // When no matching mapping found or found a non-matching mapping that
2466    // matches at least what the matching mapping matched:
2467    // Try to include the modifier into the key when mapping is allowed.
2468    if (no_mapping == 0 || allow_keys != 0) {
2469      if (tb_b1 == K_SPECIAL
2470          && (typebuf.tb_len < 2
2471              || (typebuf.tb_buf[typebuf.tb_off + 1] == KS_MODIFIER && typebuf.tb_len < 4))) {
2472        // Incomplete modifier sequence: cannot decide whether to simplify yet.
2473        keylen = KEYLEN_PART_KEY;
2474      } else {
2475        // Try to include the modifier into the key.
2476        keylen = check_simplify_modifier(max_mlen + 1);
2477        if (keylen < 0) {
2478          // ins_typebuf() failed
2479          return map_result_fail;
2480        }
2481      }
2482    } else {
2483      keylen = 0;
2484    }
2485    if (keylen == 0) {  // no simplification has been done
2486      // If there was no mapping at all use the character from the
2487      // typeahead buffer right here.
2488      if (mp == NULL) {
2489        *keylenp = keylen;
2490        return map_result_get;  // get character from typeahead
2491      }
2492    }
2493
2494    if (keylen > 0) {  // keys have been simplified
2495      *keylenp = keylen;
2496      return map_result_retry;  // try mapping again
2497    }
2498
2499    if (keylen < 0) {
2500      // Incomplete key sequence: get some more characters.
2501      assert(keylen == KEYLEN_PART_KEY);
2502    } else {
2503      assert(mp != NULL);
2504      // When a matching mapping was found use that one.
2505      keylen = tb_match_len;
2506    }
2507  }
2508
2509  // complete match
2510  if (keylen >= 0 && keylen <= typebuf.tb_len) {
2511    int i;
2512    char *map_str = NULL;
2513
2514    // Write chars to script file(s).
2515    // Note: :lmap mappings are written *after* being applied. #5658
2516    if (keylen > typebuf.tb_maplen && (mp->m_mode & MODE_LANGMAP) == 0) {
2517      gotchars(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_maplen,
2518               (size_t)(keylen - typebuf.tb_maplen));
2519      // A typed key sequence resolved this mapping (not a nested expansion:
2520      // those keys come from another mapping): open its composite.
2521      atom_map_start(mp->m_keys, (size_t)mp->m_keylen, !advance);
2522    }
2523
2524    cmd_silent = (typebuf.tb_silent > 0);
2525    del_typebuf(keylen, 0);  // remove the mapped keys
2526
2527    // Put the replacement string in front of mapstr.
2528    // The depth check catches ":map x y" and ":map y x".
2529    if (++*mapdepth >= p_mmd) {
2530      emsg(_(e_recursive_mapping));
2531      if (State & MODE_CMDLINE) {
2532        redrawcmdline();
2533      } else {
2534        setcursor();
2535      }
2536      flush_buffers(FLUSH_MINIMAL);
2537      *mapdepth = 0;  // for next one
2538      *keylenp = keylen;
2539      return map_result_fail;
2540    }
2541
2542    // In Select mode and a Visual mode mapping is used: Switch to Visual
2543    // mode temporarily.  Append K_SELECT to switch back to Select mode.
2544    if (Visual.active && Visual.select && (mp->m_mode & MODE_VISUAL)) {
2545      Visual.select = false;
2546      ins_typebuf(K_SELECT_STRING, REMAP_NONE, 0, true, false);
2547    }
2548
2549    // Copy the values from *mp that are used, because evaluating the
2550    // expression may invoke a function that redefines the mapping, thereby
2551    // making *mp invalid.
2552    const bool save_m_expr = mp->m_expr;
2553    const int save_m_noremap = mp->m_noremap;
2554    const bool save_m_silent = mp->m_silent;
2555    char *save_m_keys = NULL;  // only saved when needed
2556    char *save_alt_m_keys = NULL;  // only saved when needed
2557    const int save_alt_m_keylen = mp->m_alt != NULL ? mp->m_alt->m_keylen : 0;
2558
2559    // Handle ":map <expr>": evaluate the {rhs} as an
2560    // expression.  Also save and restore the command line
2561    // for "normal :".
2562    if (mp->m_expr) {
2563      const int save_vgetc_busy = vgetc_busy;
2564      const bool save_may_garbage_collect = may_garbage_collect;
2565      const int prev_did_emsg = did_emsg;
2566
2567      vgetc_busy = 0;
2568      may_garbage_collect = false;
2569
2570      save_m_keys = xmemdupz(mp->m_keys, (size_t)mp->m_keylen);
2571      save_alt_m_keys = mp->m_alt != NULL
2572                        ? xmemdupz(mp->m_alt->m_keys, (size_t)save_alt_m_keylen)
2573                        : NULL;
2574      map_str = eval_map_expr(mp, NUL);
2575
2576      if ((map_str == NULL || *map_str == NUL)) {
2577        // If an error was displayed and the expression returns an empty
2578        // string, generate a <Nop> to allow for a redraw.
2579        if (prev_did_emsg != did_emsg) {
2580          char buf[4];
2581          xfree(map_str);
2582          buf[0] = (char)K_SPECIAL;
2583          buf[1] = (char)KS_EXTRA;
2584          buf[2] = KE_IGNORE;
2585          buf[3] = NUL;
2586          map_str = xmemdupz(buf, 3);
2587          if (State & MODE_CMDLINE) {
2588            // redraw the command below the error
2589            msg_didout = true;
2590            msg_row = MAX(msg_row, cmdline_row);
2591            redrawcmd();
2592          }
2593        } else if (State & (MODE_NORMAL | MODE_INSERT)) {
2594          // otherwise, just put back the cursor
2595          setcursor();
2596        }
2597      }
2598
2599      vgetc_busy = save_vgetc_busy;
2600      may_garbage_collect = save_may_garbage_collect;
2601    } else {
2602      map_str = mp->m_str;
2603    }
2604
2605    // Insert the 'to' part in the typebuf.tb_buf.
2606    // If 'from' field is the same as the start of the 'to' field, don't
2607    // remap the first character (but do allow abbreviations).
2608    // If m_noremap is set, don't remap the whole 'to' part.
2609    if (map_str == NULL) {
2610      i = FAIL;
2611    } else {
2612      int noremap;
2613
2614      // If this is a LANGMAP mapping, then we didn't record the keys
2615      // at the start of the function and have to record them now.
2616      if (keylen > typebuf.tb_maplen && (mp->m_mode & MODE_LANGMAP) != 0) {
2617        gotchars((uint8_t *)map_str, strlen(map_str));
2618      }
2619
2620      if (save_m_noremap != REMAP_YES) {
2621        noremap = save_m_noremap;
2622      } else if (save_m_expr
2623                 ? strncmp(map_str, save_m_keys, (size_t)keylen) == 0
2624                 || (save_alt_m_keys != NULL
2625                     && strncmp(map_str, save_alt_m_keys,
2626                                (size_t)save_alt_m_keylen) == 0)
2627                 : strncmp(map_str, mp->m_keys, (size_t)keylen) == 0
2628                 || (mp->m_alt != NULL
2629                     && strncmp(map_str, mp->m_alt->m_keys,
2630                                (size_t)mp->m_alt->m_keylen) == 0)) {
2631        noremap = REMAP_SKIP;
2632      } else {
2633        noremap = REMAP_YES;
2634      }
2635      i = ins_typebuf(map_str, noremap, 0, true, cmd_silent || save_m_silent);
2636      if (save_m_expr) {
2637        xfree(map_str);
2638      }
2639    }
2640    xfree(save_m_keys);
2641    xfree(save_alt_m_keys);
2642    *keylenp = keylen;
2643    if (i == FAIL) {
2644      return map_result_fail;
2645    }
2646    return map_result_retry;
2647  }
2648
2649  *keylenp = keylen;
2650  return map_result_nomatch;
2651}
2652
2653/// unget one character (can only be done once!)
2654/// If the character was stuffed, vgetc() will get it next time it is called.
2655/// Otherwise vgetc() will only get it when the stuff buffer is empty.
2656void vungetc(int c)
2657{
2658  ungot = (UngotKey){
2659    .c = c,
2660    .mod_mask = mod_mask,
2661    .mouse_grid = mouse_grid,
2662    .mouse_row = mouse_row,
2663    .mouse_col = mouse_col,
2664    .stuffed = KeyStuffed,
2665  };
2666}
2667
2668/// When peeking and not getting a character, reg_executing cannot be cleared
2669/// yet, so set a flag to clear it later.
2670void check_end_reg_executing(bool advance)
2671{
2672  if (reg_executing != 0 && (typebuf.tb_maplen == 0 || pending_end_reg_executing)) {
2673    if (advance) {
2674      reg_executing = 0;
2675      pending_end_reg_executing = false;
2676    } else {
2677      pending_end_reg_executing = true;
2678    }
2679  }
2680}
2681
2682/// Gets a byte:
2683/// 1. from the stuffbuffer
2684///    This is used for abbreviated commands like "D" -> "d$".
2685///    Also used to redo a command for ".".
2686/// 2. from the typeahead buffer
2687///    Stores text obtained previously but not used yet.
2688///    Also stores the result of mappings.
2689///    Also used for the ":normal" command.
2690/// 3. from the user
2691///    This may do a blocking wait if "advance" is true.
2692///
2693/// if "advance" is true (vgetc()):
2694///    Really get the character.
2695///    KeyTyped is set to true in the case the user typed the key.
2696///    KeyStuffed is true if the character comes from the stuff buffer.
2697/// if "advance" is false (vpeekc()):
2698///    Just look whether there is a character available.
2699///    Return NUL if not.
2700///
2701/// When `no_mapping` (global) is zero, checks for mappings in the current mode.
2702/// Only returns one byte (of a multi-byte character).
2703/// K_SPECIAL may be escaped, need to get two more bytes then.
2704static int vgetorpeek(bool advance)
2705{
2706  int c;
2707  bool timedout = false;  // waited for more than 'timeoutlen'
2708                          // for mapping to complete or
2709                          // 'ttimeoutlen' for complete key code
2710  int mapdepth = 0;  // check for recursive mapping
2711  bool mode_deleted = false;  // set when mode has been deleted
2712
2713  // This function doesn't work very well when called recursively.  This may
2714  // happen though, because of:
2715  // 1. The call to add_to_showcmd().   char_avail() is then used to check if
2716  // there is a character available, which calls this function.  In that
2717  // case we must return NUL, to indicate no character is available.
2718  // 2. A GUI callback function writes to the screen, causing a
2719  // wait_return().
2720  // Using ":normal" can also do this, but it saves the typeahead buffer,
2721  // thus it should be OK.  But don't get a key from the user then.
2722  if (vgetc_busy > 0 && ex_normal_busy == 0) {
2723    return NUL;
2724  }
2725
2726  vgetc_busy++;
2727
2728  if (advance) {
2729    KeyStuffed = false;
2730    typebuf_was_empty = false;
2731  }
2732
2733  init_typebuf();
2734  start_stuff();
2735  check_end_reg_executing(advance);
2736  do {
2737    // get a character: 1. from the stuffbuffer
2738    if (typeahead_char != 0) {
2739      c = typeahead_char;
2740      if (advance) {
2741        typeahead_char = 0;
2742      }
2743    } else {
2744      c = read_readbuffers(advance);
2745    }
2746    if (c != NUL && !got_int) {
2747      if (advance) {
2748        // KeyTyped = false;  When the command that stuffed something
2749        // was typed, behave like the stuffed command was typed.
2750        // needed for CTRL-W CTRL-] to open a fold, for example.
2751        KeyStuffed = true;
2752      }
2753      if (typebuf.tb_no_abbr_cnt == 0) {
2754        typebuf.tb_no_abbr_cnt = 1;  // no abbreviations now
2755      }
2756    } else {
2757      // Loop until we either find a matching mapped key, or we
2758      // are sure that it is not a mapped key.
2759      // If a mapped key sequence is found we go back to the start to
2760      // try re-mapping.
2761      while (true) {
2762        check_end_reg_executing(advance);
2763        // os_breakcheck() is slow, don't use it too often when
2764        // inside a mapping.  But call it each time for typed
2765        // characters.
2766        if (typebuf.tb_maplen) {
2767          line_breakcheck();
2768        } else {
2769          // os_breakcheck() can call input_enqueue()
2770          if ((mapped_ctrl_c | curbuf->b_mapped_ctrl_c) & get_real_state()) {
2771            ctrl_c_interrupts = false;
2772          }
2773          os_breakcheck();  // check for CTRL-C
2774          ctrl_c_interrupts = true;
2775        }
2776        int keylen = 0;
2777        if (got_int) {
2778          // flush all input
2779          c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0);
2780
2781          // If inchar() returns true (script file was active) or we
2782          // are inside a mapping, get out of Insert mode.
2783          // Otherwise we behave like having gotten a CTRL-C.
2784          // As a result typing CTRL-C in insert mode will
2785          // really insert a CTRL-C.
2786          if ((c || typebuf.tb_maplen)
2787              && (State & (MODE_INSERT | MODE_CMDLINE))) {
2788            c = ESC;
2789          } else {
2790            c = Ctrl_C;
2791          }
2792          flush_buffers(FLUSH_INPUT);  // flush all typeahead
2793
2794          if (advance) {
2795            // Also record this character, it might be needed to
2796            // get out of Insert mode.
2797            *typebuf.tb_buf = (uint8_t)c;
2798            gotchars(typebuf.tb_buf, 1);
2799          }
2800          cmd_silent = false;
2801
2802          break;
2803        } else if (typebuf.tb_len > 0) {
2804          // Check for a mapping in "typebuf".
2805          map_result_T result = (map_result_T)handle_mapping(&keylen, &timedout, &mapdepth,
2806                                                             advance);
2807
2808          if (result == map_result_retry) {
2809            // try mapping again
2810            continue;
2811          }
2812
2813          if (result == map_result_fail) {
2814            atom_composite_abort();
2815            // failed, use the outer loop
2816            c = -1;
2817            break;
2818          }
2819
2820          if (result == map_result_get) {
2821            // get a character: 2. from the typeahead buffer
2822            c = typebuf.tb_buf[typebuf.tb_off];
2823            if (advance) {  // remove chars from tb_buf
2824              cmd_silent = (typebuf.tb_silent > 0);
2825              if (typebuf.tb_maplen > 0) {
2826                KeyTyped = false;
2827              } else {
2828                KeyTyped = true;
2829                // write char to script file(s)
2830                gotchars(typebuf.tb_buf + typebuf.tb_off, 1);
2831              }
2832              KeyNoremap = (unsigned char)typebuf.tb_noremap[typebuf.tb_off];
2833              del_typebuf(1, 0);
2834            }
2835            break;  // got character, break the for loop
2836          }
2837
2838          // not enough characters, get more
2839        }
2840
2841        // get a character: 3. from the user - handle <Esc> in Insert mode
2842
2843        // special case: if we get an <ESC> in insert mode and there
2844        // are no more characters at once, we pretend to go out of
2845        // insert mode.  This prevents the one second delay after
2846        // typing an <ESC>.  If we get something after all, we may
2847        // have to redisplay the mode. That the cursor is in the wrong
2848        // place does not matter.
2849        c = 0;
2850        int new_wcol = curwin->w_wcol;
2851        int new_wrow = curwin->w_wrow;
2852        if (advance
2853            && typebuf.tb_len == 1
2854            && typebuf.tb_buf[typebuf.tb_off] == ESC
2855            && !no_mapping
2856            && ex_normal_busy == 0
2857            && typebuf.tb_maplen == 0
2858            && (State & MODE_INSERT)
2859            && (p_timeout || (keylen == KEYLEN_PART_KEY && p_ttimeout))
2860            && (c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len, 3, 25)) == 0) {
2861          if (mode_displayed) {
2862            unshowmode(true);
2863            mode_deleted = true;
2864          }
2865          validate_cursor(curwin);
2866          int old_wcol = curwin->w_wcol;
2867          int old_wrow = curwin->w_wrow;
2868
2869          // move cursor left, if possible
2870          if (curwin->w_cursor.col != 0) {
2871            colnr_T col = 0;
2872            char *ptr;
2873            if (curwin->w_wcol > 0) {
2874              // After auto-indenting and no text is following,
2875              // we are expecting to truncate the trailing
2876              // white-space, so find the last non-white
2877              // character -- webb
2878              if (Ins.did_ai && *skipwhite(get_cursor_line_ptr() + curwin->w_cursor.col) == NUL) {
2879                curwin->w_wcol = 0;
2880                ptr = get_cursor_line_ptr();
2881                char *endptr = ptr + curwin->w_cursor.col;
2882
2883                CharsizeArg csarg;
2884                CSType cstype = init_charsize_arg(&csarg, curwin, curwin->w_cursor.lnum, ptr);
2885                StrCharInfo ci = utf_ptr2StrCharInfo(ptr);
2886                int vcol = 0;
2887                while (ci.ptr < endptr) {
2888                  if (!ascii_iswhite(ci.chr.value)) {
2889                    curwin->w_wcol = vcol;
2890                  }
2891                  ClusterInfo cli = utf_ClusterInfo(ci);
2892                  vcol += win_charsize(cstype, vcol, ci.ptr, ci.chr.value, &csarg, cli.cells).width;
2893                  ci = cli.next;
2894                }
2895
2896                curwin->w_wrow = curwin->w_cline_row
2897                                 + curwin->w_wcol / curwin->w_view_width;
2898                curwin->w_wcol %= curwin->w_view_width;
2899                curwin->w_wcol += win_col_off(curwin);
2900                col = 0;  // no correction needed
2901              } else {
2902                curwin->w_wcol--;
2903                col = curwin->w_cursor.col - 1;
2904              }
2905            } else if (curwin->w_p_wrap && curwin->w_wrow) {
2906              curwin->w_wrow--;
2907              curwin->w_wcol = curwin->w_view_width - 1;
2908              col = curwin->w_cursor.col - 1;
2909            }
2910            if (col > 0 && curwin->w_wcol > 0) {
2911              // Correct when the cursor is on the right halve
2912              // of a double-wide character.
2913              ptr = get_cursor_line_ptr();
2914              col -= utf_head_off(ptr, ptr + col);
2915              if (utf_ptr2cells(ptr + col) > 1) {
2916                curwin->w_wcol--;
2917              }
2918            }
2919          }
2920          setcursor();
2921          ui_flush();
2922          new_wcol = curwin->w_wcol;
2923          new_wrow = curwin->w_wrow;
2924          curwin->w_wcol = old_wcol;
2925          curwin->w_wrow = old_wrow;
2926        }
2927        if (c < 0) {
2928          continue;  // end of input script reached
2929        }
2930
2931        // Allow mapping for just typed characters. When we get here c
2932        // is the number of extra bytes and typebuf.tb_len is 1.
2933        for (int n = 1; n <= c; n++) {
2934          typebuf.tb_noremap[typebuf.tb_off + n] = RM_YES;
2935        }
2936        typebuf.tb_len += c;
2937
2938        // buffer full, don't map
2939        if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN) {
2940          timedout = true;
2941          continue;
2942        }
2943
2944        if (ex_normal_busy > 0) {
2945          static int tc = 0;
2946
2947          // No typeahead left and inside ":normal".  Must return
2948          // something to avoid getting stuck.  When an incomplete
2949          // mapping is present, behave like it timed out.
2950          if (typebuf.tb_len > 0) {
2951            timedout = true;
2952            continue;
2953          }
2954
2955          // For the command line only CTRL-C always breaks it.
2956          // For the cmdline window: Alternate between ESC and
2957          // CTRL-C: ESC for most situations and CTRL-C to close the
2958          // cmdline window.
2959          c = ((State & MODE_CMDLINE) || (cmdwin_type > 0 && tc == ESC)) ? Ctrl_C : ESC;
2960          tc = c;
2961
2962          // set a flag to indicate this wasn't a normal char
2963          if (advance) {
2964            typebuf_was_empty = true;
2965          }
2966
2967          // no chars to block abbreviations for
2968          typebuf.tb_no_abbr_cnt = 0;
2969
2970          break;
2971        }
2972
2973        // get a character: 3. from the user - update display
2974
2975        // In insert mode a screen update is skipped when characters
2976        // are still available.  But when those available characters
2977        // are part of a mapping, and we are going to do a blocking
2978        // wait here.  Need to update the screen to display the
2979        // changed text so far. Also for when 'lazyredraw' is set and
2980        // redrawing was postponed because there was something in the
2981        // input buffer (e.g., termresponse).
2982        if (((State & MODE_INSERT) != 0 || p_lz) && (State & MODE_CMDLINE) == 0
2983            && advance && must_redraw != 0 && !need_wait_return) {
2984          update_screen();
2985          setcursor();  // put cursor back where it belongs
2986        }
2987
2988        // If we have a partial match (and are going to wait for more
2989        // input from the user), show the partially matched characters
2990        // to the user with showcmd.
2991        int showcmd_idx = 0;
2992        bool showing_partial = false;
2993        if (typebuf.tb_len > 0 && advance) {
2994          if (((State & (MODE_NORMAL | MODE_INSERT)) || State == MODE_LANGMAP)
2995              && State != MODE_HITRETURN) {
2996            // this looks nice when typing a dead character map
2997            if (State & MODE_INSERT
2998                && ptr2cells((char *)typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len - 1) == 1) {
2999              edit_putchar(typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1], false);
3000              setcursor();  // put cursor back where it belongs
3001              showing_partial = true;
3002            }
3003            // need to use the col and row from above here
3004            int old_wcol = curwin->w_wcol;
3005            int old_wrow = curwin->w_wrow;
3006            curwin->w_wcol = new_wcol;
3007            curwin->w_wrow = new_wrow;
3008            push_showcmd();
3009            if (typebuf.tb_len > SHOWCMD_COLS) {
3010              showcmd_idx = typebuf.tb_len - SHOWCMD_COLS;
3011            }
3012            while (showcmd_idx < typebuf.tb_len) {
3013              add_byte_to_showcmd(typebuf.tb_buf[typebuf.tb_off + showcmd_idx++]);
3014            }
3015            curwin->w_wcol = old_wcol;
3016            curwin->w_wrow = old_wrow;
3017          }
3018
3019          // This looks nice when typing a dead character map.
3020          // There is no actual command line for get_number().
3021          if ((State & MODE_CMDLINE)
3022              && get_cmdline_info()->cmdbuff != NULL
3023              && cmdline_star == 0) {
3024            char *p = (char *)typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len - 1;
3025            if (ptr2cells(p) == 1 && (uint8_t)(*p) < 128) {
3026              putcmdline(*p, false);
3027              showing_partial = true;
3028            }
3029          }
3030        }
3031
3032        // get a character: 3. from the user - get it
3033        if (typebuf.tb_len == 0) {
3034          // timedout may have been set if a mapping with empty RHS
3035          // fully matched while longer mappings timed out.
3036          timedout = false;
3037        }
3038
3039        int wait_time = 0;
3040
3041        if (advance) {
3042          if (typebuf.tb_len == 0 || !(p_timeout || (p_ttimeout && keylen == KEYLEN_PART_KEY))) {
3043            // blocking wait
3044            wait_time = -1;
3045          } else if (keylen == KEYLEN_PART_KEY && p_ttm >= 0) {
3046            wait_time = (int)p_ttm;
3047          } else {
3048            wait_time = (int)p_tm;
3049          }
3050        }
3051
3052        int wait_tb_len = typebuf.tb_len;
3053        c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
3054                   typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
3055                   wait_time);
3056
3057        if (showcmd_idx != 0) {
3058          pop_showcmd();
3059        }
3060        if (showing_partial == 1) {
3061          if (State & MODE_INSERT) {
3062            edit_unputchar();
3063          }
3064          if ((State & MODE_CMDLINE)
3065              && get_cmdline_info()->cmdbuff != NULL) {
3066            unputcmdline();
3067          } else {
3068            setcursor();  // put cursor back where it belongs
3069          }
3070        }
3071
3072        if (c < 0) {
3073          continue;  // end of input script reached
3074        }
3075        if (c == NUL) {  // no character available
3076          if (!advance) {
3077            break;
3078          }
3079          if (wait_tb_len > 0) {  // timed out
3080            timedout = true;
3081            continue;
3082          }
3083        } else {  // allow mapping for just typed characters
3084          while (typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] != NUL) {
3085            typebuf.tb_noremap[typebuf.tb_off + typebuf.tb_len++] = RM_YES;
3086          }
3087        }
3088      }  // while (true)
3089    }  // if (!character from stuffbuf)
3090
3091    // if advance is false don't loop on NULs
3092  } while (c < 0 || (advance && c == NUL));
3093
3094  // The "INSERT" message is taken care of here:
3095  //     if we return an ESC to exit insert mode, the message is deleted
3096  //     if we don't return an ESC but deleted the message before, redisplay it
3097  if (advance && p_smd && msg_silent == 0 && (State & MODE_INSERT)) {
3098    if (c == ESC && !mode_deleted && !no_mapping && mode_displayed) {
3099      if (typebuf.tb_len && !KeyTyped) {
3100        redraw_cmdline = true;  // delete mode later
3101      } else {
3102        unshowmode(false);
3103      }
3104    } else if (c != ESC && mode_deleted) {
3105      if (typebuf.tb_len && !KeyTyped) {
3106        redraw_cmdline = true;  // show mode later
3107      } else {
3108        showmode();
3109      }
3110    }
3111  }
3112
3113  if (timedout && c == ESC) {
3114    // When recording there will be no timeout.  Add an <Ignore> after the
3115    // ESC to avoid that it forms a key code with following characters.
3116    gotchars_ignore();
3117  }
3118
3119  vgetc_busy--;
3120
3121  return c;
3122}
3123
3124/// inchar() - get one character from
3125///      1. a scriptfile
3126///      2. the keyboard
3127///
3128///  As many characters as we can get (up to 'maxlen') are put in "buf" and
3129///  NUL terminated (buffer length must be 'maxlen' + 1).
3130///  Minimum for "maxlen" is 3!!!!
3131///
3132///  "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
3133///  it.  When typebuf.tb_change_cnt changes (e.g., when a message is received
3134///  from a remote client) "buf" can no longer be used.  "tb_change_cnt" is 0
3135///  otherwise.
3136///
3137///  If we got an interrupt all input is read until none is available.
3138///
3139///  If wait_time == 0  there is no waiting for the char.
3140///  If wait_time == n  we wait for n msec for a character to arrive.
3141///  If wait_time == -1 we wait forever for a character to arrive.
3142///
3143///  Return the number of obtained characters.
3144///  Return -1 when end of input script reached.
3145///
3146/// @param wait_time  milliseconds
3147static int inchar(uint8_t *buf, int maxlen, long wait_time)
3148{
3149  int len = 0;  // Init for GCC.
3150  int retesc = false;  // Return ESC with gotint.
3151  const int tb_change_cnt = typebuf.tb_change_cnt;
3152
3153  if (wait_time == -1 || wait_time > 100) {
3154    // flush output before waiting
3155    ui_flush();
3156  }
3157
3158  // Don't reset these when at the hit-return prompt, otherwise an endless
3159  // recursive loop may result (write error in swapfile, hit-return, timeout
3160  // on char wait, flush swapfile, write error....).
3161  if (State != MODE_HITRETURN) {
3162    did_outofmem_msg = false;       // display out of memory message (again)
3163    did_swapwrite_msg = false;      // display swap file write error again
3164  }
3165
3166  // Get a character from a script file if there is one.
3167  // If interrupted: Stop reading script files, close them all.
3168  ptrdiff_t read_size = -1;
3169  while (curscript >= 0 && read_size <= 0 && !ignore_script) {
3170    char script_char;
3171    if (got_int
3172        || (read_size = file_read(&scriptin[curscript], &script_char, 1)) != 1) {
3173      // Reached EOF or some error occurred.
3174      // Careful: closescript() frees typebuf.tb_buf[] and buf[] may
3175      // point inside typebuf.tb_buf[].  Don't use buf[] after this!
3176      closescript();
3177      // When reading script file is interrupted, return an ESC to get
3178      // back to normal mode.
3179      // Otherwise return -1, because typebuf.tb_buf[] has changed.
3180      if (got_int) {
3181        retesc = true;
3182      } else {
3183        return -1;
3184      }
3185    } else {
3186      buf[0] = (uint8_t)script_char;
3187      len = 1;
3188    }
3189  }
3190
3191  if (read_size <= 0) {  // Did not get a character from script.
3192    // If we got an interrupt, skip all previously typed characters and
3193    // return true if quit reading script file.
3194    // Stop reading typeahead when a single CTRL-C was read,
3195    // fill_input_buf() returns this when not able to read from stdin.
3196    // Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
3197    // and buf may be pointing inside typebuf.tb_buf[].
3198    if (got_int) {
3199#define DUM_LEN (MAXMAPLEN * 3 + 3)
3200      uint8_t dum[DUM_LEN + 1];
3201
3202      while (true) {
3203        len = input_get(dum, DUM_LEN, 0, 0, NULL);
3204        if (len == 0 || (len == 1 && dum[0] == Ctrl_C)) {
3205          break;
3206        }
3207      }
3208      return retesc;
3209    }
3210
3211    // Always flush the output characters when getting input characters
3212    // from the user and not just peeking.
3213    if (wait_time == -1 || wait_time > 10) {
3214      ui_flush();
3215    }
3216
3217    // Fill up to a third of the buffer, because each character may be
3218    // tripled below.
3219    len = input_get(buf, maxlen / 3, (int)wait_time, tb_change_cnt, NULL);
3220  }
3221
3222  // If the typebuf was changed further down, it is like nothing was added by
3223  // this call.
3224  if (typebuf_changed(tb_change_cnt)) {
3225    return 0;
3226  }
3227
3228  // Note the change in the typeahead buffer, this matters for when
3229  // vgetorpeek() is called recursively, e.g. using getchar(1) in a timer
3230  // function.
3231  if (len > 0 && ++typebuf.tb_change_cnt == 0) {
3232    typebuf.tb_change_cnt = 1;
3233  }
3234
3235  return fix_input_buffer(buf, len);
3236}
3237
3238/// Fix typed characters for use by vgetc().
3239/// "buf[]" must have room to triple the number of bytes!
3240/// Returns the new length.
3241int fix_input_buffer(uint8_t *buf, int len)
3242  FUNC_ATTR_NONNULL_ALL
3243{
3244  if (!using_script()) {
3245    // Should not escape K_SPECIAL reading input from the user because vim
3246    // key codes keys are processed in input.c/input_enqueue.
3247    buf[len] = NUL;
3248    return len;
3249  }
3250
3251  // Reading from script, need to process special bytes
3252  uint8_t *p = buf;
3253
3254  // Two characters are special: NUL and K_SPECIAL.
3255  // Replace       NUL by K_SPECIAL KS_ZERO    KE_FILLER
3256  // Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
3257  for (int i = len; --i >= 0; p++) {
3258    if (p[0] == NUL
3259        || (p[0] == K_SPECIAL
3260            && (i < 2 || p[1] != KS_EXTRA))) {
3261      memmove(p + 3, p + 1, (size_t)i);
3262      p[2] = (uint8_t)K_THIRD(p[0]);
3263      p[1] = (uint8_t)K_SECOND(p[0]);
3264      p[0] = K_SPECIAL;
3265      p += 2;
3266      len += 2;
3267    }
3268  }
3269  *p = NUL;  // add trailing NUL
3270  return len;
3271}
3272
3273/// Get a key stroke directly from the user.
3274///
3275/// Ignores mouse clicks and scrollbar events, except a click for the left
3276/// button (used at the more prompt).
3277/// Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3278/// Disadvantage: typeahead is ignored.
3279/// Translates the interrupt character for unix to ESC.
3280int get_keystroke(MultiQueue *events)
3281{
3282  uint8_t *buf = NULL;
3283  int buflen = 150;
3284  int len = 0;
3285  int n;
3286  int save_mapped_ctrl_c = mapped_ctrl_c;
3287
3288  mod_mask = 0;
3289  mapped_ctrl_c = 0;        // mappings are not used here
3290  while (true) {
3291    // flush output before waiting
3292    ui_flush();
3293    // Leave some room for check_termcode() to insert a key code into (max
3294    // 5 chars plus NUL).  And fix_input_buffer() can triple the number of
3295    // bytes.
3296    int maxlen = (buflen - 6 - len) / 3;
3297    if (buf == NULL) {
3298      buf = xmalloc((size_t)buflen);
3299    } else if (maxlen < 10) {
3300      // Need some more space. This might happen when receiving a long
3301      // escape sequence.
3302      buflen += 100;
3303      buf = xrealloc(buf, (size_t)buflen);
3304      maxlen = (buflen - 6 - len) / 3;
3305    }
3306
3307    // First time: blocking wait.  Second time: wait up to 100ms for a
3308    // terminal code to complete.
3309    n = input_get(buf + len, maxlen, len == 0 ? -1 : 100, 0, events);
3310    if (n > 0) {
3311      // Replace zero and K_SPECIAL by a special key code.
3312      n = fix_input_buffer(buf + len, n);
3313      len += n;
3314    }
3315
3316    if (n > 0) {  // found a termcode: adjust length
3317      len = n;
3318    }
3319    if (len == 0) {  // nothing typed yet
3320      continue;
3321    }
3322
3323    // Handle modifier and/or special key code.
3324    n = buf[0];
3325    if (n == K_SPECIAL) {
3326      n = TO_SPECIAL(buf[1], buf[2]);
3327      if (buf[1] == KS_MODIFIER
3328          || n == K_IGNORE
3329          || (is_mouse_key(n) && n != K_LEFTMOUSE)) {
3330        if (buf[1] == KS_MODIFIER) {
3331          mod_mask = buf[2];
3332        }
3333        len -= 3;
3334        if (len > 0) {
3335          memmove(buf, buf + 3, (size_t)len);
3336        }
3337        continue;
3338      }
3339      break;
3340    }
3341    if (MB_BYTE2LEN(n) > len) {
3342      // more bytes to get.
3343      continue;
3344    }
3345    buf[len >= buflen ? buflen - 1 : len] = NUL;
3346    n = utf_ptr2char((char *)buf);
3347    break;
3348  }
3349  xfree(buf);
3350
3351  mapped_ctrl_c = save_mapped_ctrl_c;
3352  return merge_modifiers(n, &mod_mask);
3353}
3354
3355/// Function passed to do_cmdline() to get the command after a <Cmd> key from
3356/// typeahead.
3357char *getcmdkeycmd(int promptc, void *cookie, int indent, bool do_concat)
3358{
3359  garray_T line_ga;
3360  int c1 = -1;
3361  int cmod = 0;
3362  bool aborted = false;
3363
3364  ga_init(&line_ga, 1, 32);
3365
3366  // no mapping for these characters
3367  no_mapping++;
3368
3369  got_int = false;
3370  while (c1 != NUL && !aborted) {
3371    ga_grow(&line_ga, 32);
3372
3373    if (vgetorpeek(false) == NUL) {
3374      // incomplete <Cmd> is an error, because there is not much the user
3375      // could do in this state.
3376      emsg(_(e_cmd_mapping_must_end_with_cr));
3377      aborted = true;
3378      break;
3379    }
3380
3381    // Get one character at a time.
3382    c1 = vgetorpeek(true);
3383
3384    // Get two extra bytes for special keys
3385    if (c1 == K_SPECIAL) {
3386      c1 = vgetorpeek(true);
3387      int c2 = vgetorpeek(true);
3388      if (c1 == KS_MODIFIER) {
3389        cmod = c2;
3390        continue;
3391      }
3392      c1 = TO_SPECIAL(c1, c2);
3393    }
3394
3395    if (got_int) {
3396      aborted = true;
3397    } else if (c1 == '\r' || c1 == '\n') {
3398      c1 = NUL;  // end the line
3399    } else if (c1 == ESC) {
3400      aborted = true;
3401    } else if (c1 == K_COMMAND) {
3402      // give a nicer error message for this special case
3403      emsg(_(e_cmd_mapping_must_end_with_cr_before_second_cmd));
3404      aborted = true;
3405    } else if (c1 == K_SNR) {
3406      GA_CONCAT_LITERAL(&line_ga, "<SNR>");
3407    } else {
3408      if (cmod != 0) {
3409        ga_append(&line_ga, K_SPECIAL);
3410        ga_append(&line_ga, KS_MODIFIER);
3411        ga_append(&line_ga, (uint8_t)cmod);
3412      }
3413      if (IS_SPECIAL(c1)) {
3414        ga_append(&line_ga, K_SPECIAL);
3415        ga_append(&line_ga, (uint8_t)K_SECOND(c1));
3416        ga_append(&line_ga, (uint8_t)K_THIRD(c1));
3417      } else {
3418        ga_append(&line_ga, (uint8_t)c1);
3419      }
3420    }
3421
3422    cmod = 0;
3423  }
3424
3425  no_mapping--;
3426
3427  if (aborted) {
3428    ga_clear(&line_ga);
3429  } else if (promptc == ':') {
3430    // Executing (do_cmdline()), not discarding (vim.on_key()): capture the payload.
3431    atom_cmdline_set(K_COMMAND, line_ga.ga_data, (size_t)line_ga.ga_len);
3432  }
3433
3434  return line_ga.ga_data;
3435}
3436
3437/// Handle a Lua mapping: get its id from typeahead and execute its callback.
3438///
3439/// @param may_repeat  Save the mapping-id for redoing with "." later
3440/// @param discard     Discard the keys instead of executing the callback.
3441///
3442/// @return  false if getting the id was aborted or mapping no longer exists, true otherwise.
3443bool map_execute_lua(bool may_repeat, bool discard)
3444{
3445  garray_T line_ga;
3446  int c1 = -1;
3447  bool aborted = false;
3448
3449  ga_init(&line_ga, 1, 32);
3450
3451  no_mapping++;
3452
3453  got_int = false;
3454  while (c1 != NUL && !aborted) {
3455    ga_grow(&line_ga, 32);
3456    // Get one character at a time.
3457    c1 = vgetorpeek(true);
3458    if (got_int) {
3459      aborted = true;
3460    } else if (c1 == '\r' || c1 == '\n') {
3461      c1 = NUL;  // end the line
3462    } else {
3463      ga_append(&line_ga, (uint8_t)c1);
3464    }
3465  }
3466
3467  no_mapping--;
3468
3469  if (aborted || discard) {
3470    ga_clear(&line_ga);
3471    return !aborted;
3472  }
3473
3474  const int id = atoi(line_ga.ga_data);
3475  const LuaRef ref = map_luaid_get(id);
3476  if (ref == LUA_NOREF) {
3477    ga_clear(&line_ga);
3478    emsg(_(e_lua_mapping_gone));
3479    return false;
3480  }
3481  if (may_repeat) {
3482    repeat_luamap = id;
3483  }
3484
3485  Error err = ERROR_INIT;
3486  Array args = ARRAY_DICT_INIT;
3487  nlua_call_ref(ref, NULL, args, kRetNilBool, NULL, &err);
3488  if (ERROR_SET(&err)) {
3489    semsg_multiline("emsg", "E5108: %s", err.msg);
3490    api_clear_error(&err);
3491  }
3492
3493  ga_clear(&line_ga);
3494  return true;
3495}
3496
3497/// Wraps pasted text stream with K_PASTE_START and K_PASTE_END, and
3498/// appends to redo buffer and/or record buffer if needed.
3499/// Escapes all K_SPECIAL and NUL bytes in the content.
3500///
3501/// @param state  kFalse for the start of a paste
3502///               kTrue for the end of a paste
3503///               kNone for the content of a paste
3504/// @param str    the content of the paste (only used when state is kNone)
3505void paste_store(const uint64_t channel_id, const TriState state, const String str, const bool crlf)
3506{
3507  if (State & MODE_CMDLINE) {
3508    return;
3509  }
3510
3511  const bool need_redo = !block_redo;
3512  const bool need_record = reg_recording != 0 && !is_internal_call(channel_id);
3513
3514  if (!need_redo && !need_record) {
3515    return;
3516  }
3517
3518  if (state != kNone) {
3519    const int c = state == kFalse ? K_PASTE_START : K_PASTE_END;
3520    if (need_redo) {
3521      if (state == kFalse && !(State & MODE_INSERT)) {
3522        redo_new((CmdSpec){ 0 });
3523      }
3524      sb_add_char(&redobuff.cur.body, c);
3525    }
3526    if (need_record) {
3527      sb_add_char(&recordbuff, c);
3528    }
3529    return;
3530  }
3531
3532  const char *s = str.data;
3533  const char *const str_end = str.data + str.size;
3534
3535  while (s < str_end) {
3536    const char *start = s;
3537    while (s < str_end && (uint8_t)(*s) != K_SPECIAL && *s != NUL
3538           && *s != NL && !(crlf && *s == CAR)) {
3539      s++;
3540    }
3541
3542    if (s > start) {
3543      if (need_redo) {
3544        kv_concat_len(redobuff.cur.body, start, (size_t)(s - start));
3545      }
3546      if (need_record) {
3547        kv_concat_len(recordbuff, start, (size_t)(s - start));
3548      }
3549    }
3550
3551    if (s < str_end) {
3552      int c = (uint8_t)(*s++);
3553      if (crlf && c == CAR) {
3554        if (s < str_end && *s == NL) {
3555          s++;
3556        }
3557        c = NL;
3558      }
3559      if (need_redo) {
3560        sb_add_byte(&redobuff.cur.body, c);
3561      }
3562      if (need_record) {
3563        sb_add_byte(&recordbuff, c);
3564      }
3565    }
3566  }
3567}
3568
3569/// Gets a paste stored by paste_store() from typeahead and repeats it.
3570void paste_repeat(int count)
3571{
3572  garray_T ga = GA_INIT(1, 32);
3573  bool aborted = false;
3574
3575  no_mapping++;
3576
3577  got_int = false;
3578  while (!aborted) {
3579    ga_grow(&ga, 32);
3580    uint8_t c1 = (uint8_t)vgetorpeek(true);
3581    if (c1 == K_SPECIAL) {
3582      c1 = (uint8_t)vgetorpeek(true);
3583      uint8_t c2 = (uint8_t)vgetorpeek(true);
3584      int c = TO_SPECIAL(c1, c2);
3585      if (c == K_PASTE_END) {
3586        break;
3587      } else if (c == K_ZERO) {
3588        ga_append(&ga, NUL);
3589      } else if (c == K_SPECIAL) {
3590        ga_append(&ga, K_SPECIAL);
3591      } else {
3592        ga_append(&ga, K_SPECIAL);
3593        ga_append(&ga, c1);
3594        ga_append(&ga, c2);
3595      }
3596    } else {
3597      ga_append(&ga, c1);
3598    }
3599    aborted = got_int;
3600  }
3601
3602  no_mapping--;
3603
3604  String str = cbuf_as_string(ga.ga_data, (size_t)ga.ga_len);
3605  Arena arena = ARENA_EMPTY;
3606  Error err = ERROR_INIT;
3607  for (int i = 0; !aborted && i < count; i++) {
3608    nvim_paste(LUA_INTERNAL_CALL, str, false, -1, &arena, &err);
3609    aborted = ERROR_SET(&err);
3610  }
3611  api_clear_error(&err);
3612  arena_mem_free(arena_finish(&arena));
3613  ga_clear(&ga);
3614}