neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

getchar.c (103068B)


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