robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
90.9 KiB2952 linesraw
1// mapping.c: Code for mappings and abbreviations.
2
3#include <assert.h>
4#include <lauxlib.h>
5#include <limits.h>
6#include <stdbool.h>
7#include <stdint.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include "klib/kvec.h"
13#include "nvim/api/keysets_defs.h"
14#include "nvim/api/private/converter.h"
15#include "nvim/api/private/defs.h"
16#include "nvim/api/private/dispatch.h"
17#include "nvim/api/private/helpers.h"
18#include "nvim/ascii_defs.h"
19#include "nvim/buffer_defs.h"
20#include "nvim/charset.h"
21#include "nvim/cmdexpand.h"
22#include "nvim/cmdexpand_defs.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/userfunc.h"
28#include "nvim/eval/vars.h"
29#include "nvim/ex_cmds.h"
30#include "nvim/ex_cmds_defs.h"
31#include "nvim/ex_session.h"
32#include "nvim/fuzzy.h"
33#include "nvim/garray.h"
34#include "nvim/garray_defs.h"
35#include "nvim/gettext_defs.h"
36#include "nvim/globals.h"
37#include "nvim/highlight_defs.h"
38#include "nvim/input.h"
39#include "nvim/input_defs.h"
40#include "nvim/keycodes.h"
41#include "nvim/lua/executor.h"
42#include "nvim/macros_defs.h"
43#include "nvim/mapping.h"
44#include "nvim/mapping_defs.h"
45#include "nvim/mbyte.h"
46#include "nvim/mbyte_defs.h"
47#include "nvim/memory.h"
48#include "nvim/memory_defs.h"
49#include "nvim/message.h"
50#include "nvim/option.h"
51#include "nvim/option_defs.h"
52#include "nvim/option_vars.h"
53#include "nvim/pos_defs.h"
54#include "nvim/regexp.h"
55#include "nvim/regexp_defs.h"
56#include "nvim/runtime.h"
57#include "nvim/state_defs.h"
58#include "nvim/strings.h"
59#include "nvim/types_defs.h"
60#include "nvim/ui.h"
61#include "nvim/ui_defs.h"
62#include "nvim/vim_defs.h"
63
64/// Global abbreviations (first entry in the linkedlist).
65static mapblock_T *first_abbr = NULL;
66
67/// Global mappings.
68/// Each mapping is put in one of the MAX_MAPHASH hash lists, to speed up finding it.
69static mapblock_T *(maphash[MAX_MAPHASH]) = { 0 };
70
71// Make a hash value for a mapping.
72// "mode" is the lower 4 bits of the State for the mapping.
73// "c1" is the first character of the "lhs".
74// Returns a value between 0 and 255, index in maphash.
75// Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
76#define MAP_HASH(mode, \
77                 c1) (((mode) & \
78                       (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | \
79                        MODE_OP_PENDING | MODE_TERMINAL)) ? (c1) : ((c1) ^ 0x80))
80
81/// All possible |:map-arguments| usable in a |:map| command.
82///
83/// The <special> argument has no effect on mappings and is excluded from this
84/// struct declaration. |:noremap| is included, since it behaves like a map
85/// argument when used in a mapping.
86///
87/// @see mapblock_T
88struct map_arguments {
89  bool buffer;
90  bool expr;
91  bool noremap;
92  bool nowait;
93  bool script;
94  bool silent;
95  bool unique;
96  bool replace_keycodes;
97
98  /// The {lhs} of the mapping.
99  ///
100  /// vim limits this to MAXMAPLEN characters, allowing us to use a static
101  /// buffer. Setting lhs_len to a value larger than MAXMAPLEN can signal
102  /// that {lhs} was too long and truncated.
103  char lhs[MAXMAPLEN + 1];
104  size_t lhs_len;
105
106  /// Unsimplifed {lhs} of the mapping. If no simplification has been done then alt_lhs_len is 0.
107  char alt_lhs[MAXMAPLEN + 1];
108  size_t alt_lhs_len;
109
110  char *rhs;  ///< The {rhs} of the mapping.
111  size_t rhs_len;
112  LuaRef rhs_lua;  ///< lua function as {rhs}
113  bool rhs_is_noop;  ///< True when the {rhs} should be <Nop>.
114
115  char *orig_rhs;  ///< The original text of the {rhs}.
116  size_t orig_rhs_len;
117  char *desc;  ///< map description
118};
119typedef struct map_arguments MapArguments;
120#define MAP_ARGUMENTS_INIT { false, false, false, false, false, false, false, false, \
121                             { 0 }, 0, { 0 }, 0, NULL, 0, LUA_NOREF, false, NULL, 0, NULL }
122
123#include "mapping.c.generated.h"
124
125static const char e_global_abbreviation_already_exists_for_str[]
126  = N_("E224: Global abbreviation already exists for %s");
127static const char e_global_mapping_already_exists_for_str[]
128  = N_("E225: Global mapping already exists for %s");
129static const char e_abbreviation_already_exists_for_str[]
130  = N_("E226: Abbreviation already exists for %s");
131static const char e_mapping_already_exists_for_str[]
132  = N_("E227: Mapping already exists for %s");
133static const char e_entries_missing_in_mapset_dict_argument[]
134  = N_("E460: Entries missing in mapset() dict argument");
135static const char e_illegal_map_mode_string_str[]
136  = N_("E1276: Illegal map mode string: '%s'");
137
138/// Get the start of the hashed map list for "state" and first character "c".
139mapblock_T *get_maphash_list(int state, int c)
140{
141  return maphash[MAP_HASH(state, c)];
142}
143
144/// Get the buffer-local hashed map list for "state" and first character "c".
145mapblock_T *get_buf_maphash_list(int state, int c)
146{
147  return curbuf->b_maphash[MAP_HASH(state, c)];
148}
149
150/// Finds the Lua mapping whose `m_str` embeds `id`.
151static mapblock_T *map_luaid_scan(mapblock_T *const *mappings, size_t size, int id)
152{
153  for (size_t i = 0; i < size; i++) {
154    for (mapblock_T *mp = mappings[i]; mp != NULL; mp = mp->m_next) {
155      // Find `id` in "<K_LUA><id><CR>".
156      if (mp->m_luaref != LUA_NOREF && atoi(mp->m_str + 3) == id) {
157        return mp;
158      }
159    }
160  }
161  return NULL;
162}
163
164/// Resolves a Lua-mapping id to its callback.
165///
166/// @return  Lua callback, or LUA_NOREF if the mapping no longer exists.
167LuaRef map_luaid_get(int n)
168{
169  mapblock_T *mp = map_luaid_scan(maphash, MAX_MAPHASH, n);
170  mp = mp != NULL ? mp : map_luaid_scan(&first_abbr, 1, n);
171  FOR_ALL_BUFFERS(fb) {
172    mp = mp != NULL ? mp : map_luaid_scan(fb->b_maphash, MAX_MAPHASH, n);
173    mp = mp != NULL ? mp : map_luaid_scan(&fb->b_first_abbr, 1, n);
174  }
175  return mp != NULL ? mp->m_luaref : LUA_NOREF;
176}
177
178/// Delete one entry from the abbrlist or maphash[].
179/// "mpp" is a pointer to the m_next field of the PREVIOUS entry!
180static void mapblock_free(mapblock_T **mpp)
181{
182  mapblock_T *mp = *mpp;
183  xfree(mp->m_keys);
184  if (mp->m_alt != NULL) {
185    mp->m_alt->m_alt = NULL;
186  } else {
187    NLUA_CLEAR_REF(mp->m_luaref);
188    xfree(mp->m_str);
189    xfree(mp->m_orig_str);
190    xfree(mp->m_desc);
191  }
192  *mpp = mp->m_next;
193  xfree(mp);
194}
195
196/// put characters to represent the map mode in a string buffer
197///
198/// @param[out] buf must be at least 7 bytes (including NUL)
199void map_mode_to_chars(int mode, char *buf)
200  FUNC_ATTR_NONNULL_ALL
201{
202  char *p = buf;
203  if ((mode & (MODE_INSERT | MODE_CMDLINE)) == (MODE_INSERT | MODE_CMDLINE)) {
204    *p++ = '!';                           // :map!
205  } else if (mode & MODE_INSERT) {
206    *p++ = 'i';                           // :imap
207  } else if (mode & MODE_LANGMAP) {
208    *p++ = 'l';                           // :lmap
209  } else if (mode & MODE_CMDLINE) {
210    *p++ = 'c';                           // :cmap
211  } else if ((mode & (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING))
212             == (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING)) {
213    *p++ = ' ';                           // :map
214  } else {
215    if (mode & MODE_NORMAL) {
216      *p++ = 'n';                         // :nmap
217    }
218    if (mode & MODE_OP_PENDING) {
219      *p++ = 'o';                         // :omap
220    }
221    if (mode & MODE_TERMINAL) {
222      *p++ = 't';                         // :tmap
223    }
224    if ((mode & (MODE_VISUAL | MODE_SELECT)) == (MODE_VISUAL | MODE_SELECT)) {
225      *p++ = 'v';                         // :vmap
226    } else {
227      if (mode & MODE_VISUAL) {
228        *p++ = 'x';                       // :xmap
229      }
230      if (mode & MODE_SELECT) {
231        *p++ = 's';                       // :smap
232      }
233    }
234  }
235
236  *p = NUL;
237}
238
239/// @param local  true for buffer-local map
240static void showmap(mapblock_T *mp, bool local)
241{
242  if (message_filtered(mp->m_keys) && message_filtered(mp->m_str)
243      && (mp->m_desc == NULL || message_filtered(mp->m_desc))) {
244    return;
245  }
246
247  if (msg_col > 0 || msg_silent != 0) {
248    msg_putchar('\n');
249    if (got_int) {          // 'q' typed at MORE prompt
250      return;
251    }
252  }
253
254  char mapchars[7];
255  map_mode_to_chars(mp->m_mode, mapchars);
256  msg_puts(mapchars);
257  size_t len = strlen(mapchars);
258
259  while (++len <= 3) {
260    msg_putchar(' ');
261  }
262
263  // Display the LHS.  Get length of what we write.
264  len = (size_t)msg_outtrans_special(mp->m_keys, true, 0);
265  do {
266    msg_putchar(' ');                   // pad with blanks
267    len++;
268  } while (len < 12);
269
270  if (mp->m_noremap == REMAP_NONE) {
271    msg_puts_hl("*", HLF_8, false);
272  } else if (mp->m_noremap == REMAP_SCRIPT) {
273    msg_puts_hl("&", HLF_8, false);
274  } else {
275    msg_putchar(' ');
276  }
277
278  if (local) {
279    msg_putchar('@');
280  } else {
281    msg_putchar(' ');
282  }
283
284  // Use false below if we only want things like <Up> to show up as such on
285  // the rhs, and not M-x etc, true gets both -- webb
286  if (mp->m_luaref != LUA_NOREF) {
287    char *str = nlua_funcref_str(mp->m_luaref, NULL, true);
288    msg_puts_hl(str, HLF_8, false);
289    xfree(str);
290  } else if (mp->m_str[0] == NUL) {
291    msg_puts_hl("<Nop>", HLF_8, false);
292  } else {
293    msg_outtrans_special(mp->m_str, false, 0);
294  }
295
296  if (mp->m_desc != NULL) {
297    msg_puts("\n                 ");  // Shift line to same level as rhs.
298    msg_puts(mp->m_desc);
299  }
300  if (p_verbose > 0) {
301    last_set_msg(mp->m_script_ctx);
302  }
303  msg_clr_eos();
304}
305
306/// Replace termcodes in the given LHS and RHS and store the results into the
307/// `lhs` and `rhs` of the given @ref MapArguments struct.
308///
309/// `rhs` and `orig_rhs` will both point to new allocated buffers. `orig_rhs`
310/// will hold a copy of the given `orig_rhs`.
311///
312/// The `*_len` variables will be set appropriately. If the length of
313/// the final `lhs` exceeds `MAXMAPLEN`, `lhs_len` will be set equal to the
314/// original larger length and `lhs` will be truncated.
315///
316/// If RHS should be <Nop>, `rhs` will be an empty string, `rhs_len` will be
317/// zero, and `rhs_is_noop` will be set to true.
318///
319/// Any memory allocated by @ref replace_termcodes is freed before this function
320/// returns.
321///
322/// @param[in] orig_lhs   Original mapping LHS, with characters to replace.
323/// @param[in] orig_lhs_len   `strlen` of orig_lhs.
324/// @param[in] orig_rhs   Original mapping RHS, with characters to replace.
325/// @param[in] rhs_lua   Lua reference for Lua mappings.
326/// @param[in] orig_rhs_len   `strlen` of orig_rhs.
327/// @param[in] cpo_val  See param docs for @ref replace_termcodes.
328/// @param[out] mapargs   MapArguments struct holding the replaced strings.
329static bool set_maparg_lhs_rhs(const char *const orig_lhs, const size_t orig_lhs_len,
330                               const char *const orig_rhs, const size_t orig_rhs_len,
331                               const LuaRef rhs_lua, const char *const cpo_val,
332                               MapArguments *const mapargs)
333{
334  mapargs->rhs_lua = rhs_lua;
335  char lhs_buf[128];
336
337  // If mapping has been given as ^V<C_UP> say, then replace the term codes
338  // with the appropriate two bytes. If it is a shifted special key, unshift
339  // it too, giving another two bytes.
340  //
341  // replace_termcodes() may move the result to allocated memory, which
342  // needs to be freed later (*lhs_buf and *rhs_buf).
343  // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
344  // If something like <C-H> is simplified to 0x08 then mark it as simplified
345  // and also add en entry with a modifier.
346  bool did_simplify = false;
347  const int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
348  char *bufarg = lhs_buf;
349  char *replaced = replace_termcodes(orig_lhs, orig_lhs_len, &bufarg, 0,
350                                     flags, &did_simplify, cpo_val);
351  if (replaced == NULL) {
352    return false;
353  }
354  mapargs->lhs_len = strlen(replaced);
355  xstrlcpy(mapargs->lhs, replaced, sizeof(mapargs->lhs));
356  if (did_simplify) {
357    replaced = replace_termcodes(orig_lhs, orig_lhs_len, &bufarg, 0,
358                                 flags | REPTERM_NO_SIMPLIFY, NULL, cpo_val);
359    if (replaced == NULL) {
360      return false;
361    }
362    mapargs->alt_lhs_len = strlen(replaced);
363    xstrlcpy(mapargs->alt_lhs, replaced, sizeof(mapargs->alt_lhs));
364  } else {
365    mapargs->alt_lhs_len = 0;
366  }
367
368  set_maparg_rhs(orig_rhs, orig_rhs_len, rhs_lua, 0, cpo_val, mapargs);
369
370  return true;
371}
372
373/// @see set_maparg_lhs_rhs
374static void set_maparg_rhs(const char *const orig_rhs, const size_t orig_rhs_len,
375                           const LuaRef rhs_lua, const scid_T sid, const char *const cpo_val,
376                           MapArguments *const mapargs)
377{
378  mapargs->rhs_lua = rhs_lua;
379
380  if (rhs_lua == LUA_NOREF) {
381    mapargs->orig_rhs_len = orig_rhs_len;
382    mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char));
383    xmemcpyz(mapargs->orig_rhs, orig_rhs, mapargs->orig_rhs_len);
384    if (STRICMP(orig_rhs, "<nop>") == 0) {  // "<Nop>" means nothing
385      mapargs->rhs = xcalloc(1, sizeof(char));  // single NUL-char
386      mapargs->rhs_len = 0;
387      mapargs->rhs_is_noop = true;
388    } else {
389      char *rhs_buf = NULL;
390      char *replaced = replace_termcodes(orig_rhs, orig_rhs_len, &rhs_buf, sid,
391                                         REPTERM_DO_LT, NULL, cpo_val);
392      mapargs->rhs_len = strlen(replaced);
393      // NB: replace_termcodes may produce an empty string even if orig_rhs is non-empty
394      // (e.g. a single ^V, see :h map-empty-rhs)
395      mapargs->rhs_is_noop = orig_rhs_len != 0 && mapargs->rhs_len == 0;
396      mapargs->rhs = replaced;
397    }
398  } else {
399    char tmp_buf[64];
400    // orig_rhs is not used for Lua mappings, but still needs to be a string.
401    mapargs->orig_rhs = xcalloc(1, sizeof(char));
402    mapargs->orig_rhs_len = 0;
403    // Stores "<K_LUA><lua-mapping-id><CR>" in map_str.
404    static int map_luaid = 0;
405    mapargs->rhs_len = (size_t)vim_snprintf(S_LEN(tmp_buf), "%c%c%c%d\r", K_SPECIAL,
406                                            KS_EXTRA, KE_LUA, ++map_luaid);
407    mapargs->rhs = xstrdup(tmp_buf);
408  }
409}
410
411/// Parse a string of |:map-arguments| into a @ref MapArguments struct.
412///
413/// Termcodes, backslashes, CTRL-V's, etc. inside the extracted {lhs} and
414/// {rhs} are replaced by @ref set_maparg_lhs_rhs.
415///
416/// rhs and orig_rhs in the returned mapargs will be set to null or a pointer
417/// to allocated memory and should be freed even on error.
418///
419/// @param[in]  strargs   String of map args, e.g. "<buffer> <expr><silent>".
420///                       May contain leading or trailing whitespace.
421/// @param[in]  is_unmap  True, if strargs should be parsed like an |:unmap|
422///                       command. |:unmap| commands interpret *all* text to the
423///                       right of the last map argument as the {lhs} of the
424///                       mapping, i.e. a literal ' ' character is treated like
425///                       a "<space>", rather than separating the {lhs} from the
426///                       {rhs}.
427/// @param[out] mapargs   MapArguments struct holding all extracted argument
428///                       values.
429/// @return 0 on success, 1 if invalid arguments are detected.
430static int str_to_mapargs(const char *strargs, bool is_unmap, MapArguments *mapargs)
431{
432  const char *to_parse = strargs;
433  to_parse = skipwhite(to_parse);
434  CLEAR_POINTER(mapargs);
435
436  // Accept <buffer>, <nowait>, <silent>, <expr>, <script>, and <unique> in
437  // any order.
438  while (true) {
439    if (strncmp(to_parse, "<buffer>", 8) == 0) {
440      to_parse = skipwhite(to_parse + 8);
441      mapargs->buffer = true;
442      continue;
443    }
444
445    if (strncmp(to_parse, "<nowait>", 8) == 0) {
446      to_parse = skipwhite(to_parse + 8);
447      mapargs->nowait = true;
448      continue;
449    }
450
451    if (strncmp(to_parse, "<silent>", 8) == 0) {
452      to_parse = skipwhite(to_parse + 8);
453      mapargs->silent = true;
454      continue;
455    }
456
457    // Ignore obsolete "<special>" modifier.
458    if (strncmp(to_parse, "<special>", 9) == 0) {
459      to_parse = skipwhite(to_parse + 9);
460      continue;
461    }
462
463    if (strncmp(to_parse, "<script>", 8) == 0) {
464      to_parse = skipwhite(to_parse + 8);
465      mapargs->script = true;
466      continue;
467    }
468
469    if (strncmp(to_parse, "<expr>", 6) == 0) {
470      to_parse = skipwhite(to_parse + 6);
471      mapargs->expr = true;
472      continue;
473    }
474
475    if (strncmp(to_parse, "<unique>", 8) == 0) {
476      to_parse = skipwhite(to_parse + 8);
477      mapargs->unique = true;
478      continue;
479    }
480    break;
481  }
482
483  // Find the next whitespace character, call that the end of {lhs}.
484  //
485  // If a character (e.g. whitespace) is immediately preceded by a CTRL-V,
486  // "scan past" that character, i.e. don't "terminate" LHS with that character
487  // if it's whitespace.
488  //
489  // Treat backslash like CTRL-V when 'cpoptions' does not contain 'B'.
490  //
491  // With :unmap, literal white space is included in the {lhs}; there is no
492  // separate {rhs}.
493  const char *lhs_end = to_parse;
494  bool do_backslash = (vim_strchr(p_cpo, kCpoBslash) == NULL);
495  while (*lhs_end && (is_unmap || !ascii_iswhite(*lhs_end))) {
496    if ((lhs_end[0] == Ctrl_V || (do_backslash && lhs_end[0] == '\\'))
497        && lhs_end[1] != NUL) {
498      lhs_end++;  // skip CTRL-V or backslash
499    }
500    lhs_end++;
501  }
502
503  // {lhs_end} is a pointer to the "terminating whitespace" after {lhs}.
504  // Use that to initialize {rhs_start}.
505  const char *rhs_start = skipwhite(lhs_end);
506
507  // Given {lhs} might be larger than MAXMAPLEN before replace_termcodes
508  // (e.g. "<Space>" is longer than ' '), so first copy into a buffer.
509  size_t orig_lhs_len = (size_t)(lhs_end - to_parse);
510  if (orig_lhs_len >= 256) {
511    return 1;
512  }
513  char lhs_to_replace[256];
514  xmemcpyz(lhs_to_replace, to_parse, orig_lhs_len);
515
516  size_t orig_rhs_len = strlen(rhs_start);
517  if (!set_maparg_lhs_rhs(lhs_to_replace, orig_lhs_len,
518                          rhs_start, orig_rhs_len, LUA_NOREF,
519                          p_cpo, mapargs)) {
520    return 1;
521  }
522
523  if (mapargs->lhs_len > MAXMAPLEN) {
524    return 1;
525  }
526  return 0;
527}
528
529/// @param args  "rhs", "rhs_lua", "orig_rhs", "expr", "silent", "nowait",
530///              "replace_keycodes" and "desc" fields are used.
531/// @param sid  0 to use current_sctx
532static mapblock_T *map_add(buf_T *buf, mapblock_T **map_table, mapblock_T **abbr_table,
533                           const char *keys, MapArguments *args, int noremap, int mode,
534                           bool is_abbr, scid_T sid, linenr_T lnum, bool simplified)
535  FUNC_ATTR_NONNULL_RET
536{
537  mapblock_T *mp = xcalloc(1, sizeof(mapblock_T));
538
539  // If CTRL-C has been mapped, don't always use it for Interrupting.
540  if (*keys == Ctrl_C) {
541    if (map_table == buf->b_maphash) {
542      buf->b_mapped_ctrl_c |= mode;
543    } else {
544      mapped_ctrl_c |= mode;
545    }
546  }
547
548  mp->m_keys = xstrdup(keys);
549  mp->m_str = args->rhs;
550  mp->m_orig_str = args->orig_rhs;
551  mp->m_luaref = args->rhs_lua;
552  mp->m_keylen = (int)strlen(mp->m_keys);
553  mp->m_noremap = noremap;
554  mp->m_nowait = args->nowait;
555  mp->m_silent = args->silent;
556  mp->m_mode = mode;
557  mp->m_simplified = simplified;
558  mp->m_expr = args->expr;
559  mp->m_replace_keycodes = args->replace_keycodes;
560  if (sid != 0) {
561    mp->m_script_ctx.sc_sid = sid;
562    mp->m_script_ctx.sc_lnum = lnum;
563  } else {
564    mp->m_script_ctx = current_sctx;
565    mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
566    nlua_set_sctx(&mp->m_script_ctx);
567  }
568  mp->m_desc = args->desc;
569
570  // add the new entry in front of the abbrlist or maphash[] list
571  if (is_abbr) {
572    mp->m_next = *abbr_table;
573    *abbr_table = mp;
574  } else {
575    const int n = MAP_HASH(mp->m_mode, (uint8_t)mp->m_keys[0]);
576    mp->m_next = map_table[n];
577    map_table[n] = mp;
578  }
579  return mp;
580}
581
582/// Sets or removes a mapping or abbreviation in buffer `buf`.
583///
584/// @param maptype    @see do_map
585/// @param args  Fully parsed and "preprocessed" arguments for the
586///              (un)map/abbrev command. Termcodes should have already been
587///              replaced; whitespace, `<` and `>` signs, etc. in {lhs} and
588///              {rhs} are assumed to be literal components of the mapping.
589/// @param mode       @see do_map
590/// @param is_abbrev  @see do_map
591/// @param buf        Target Buffer
592static int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T *buf)
593{
594  int retval = 0;
595
596  // If <buffer> was given, we'll be searching through the buffer's
597  // mappings/abbreviations, not the globals.
598  mapblock_T **map_table = args->buffer ? buf->b_maphash : maphash;
599  mapblock_T **abbr_table = args->buffer ? &buf->b_first_abbr : &first_abbr;
600  mapblock_T *mp_result[2] = { NULL, NULL };
601
602  bool unmap_lhs_only = false;
603  if (maptype == MAPTYPE_UNMAP_LHS) {
604    unmap_lhs_only = true;
605    maptype = MAPTYPE_UNMAP;
606  }
607
608  // For ":noremap" don't remap, otherwise do remap.
609  int noremap = args->script ? REMAP_SCRIPT
610                             : maptype == MAPTYPE_NOREMAP ? REMAP_NONE : REMAP_YES;
611
612  const bool has_lhs = (args->lhs[0] != NUL);
613  const bool has_rhs = args->rhs_lua != LUA_NOREF || (args->rhs[0] != NUL) || args->rhs_is_noop;
614  const bool do_print = !has_lhs || (maptype != MAPTYPE_UNMAP && !has_rhs);
615  if (do_print) {
616    msg_ext_set_kind("list_cmd");
617  }
618
619  // check for :unmap without argument
620  if (maptype == MAPTYPE_UNMAP && !has_lhs) {
621    retval = 1;
622    goto theend;
623  }
624
625  const char *lhs = (char *)&args->lhs;
626  const bool did_simplify = args->alt_lhs_len != 0;
627
628  // The following is done twice if we have two versions of keys
629  for (int keyround = 1; keyround <= 2; keyround++) {
630    bool did_it = false;
631    bool did_local = false;
632    bool keyround1_simplified = keyround == 1 && did_simplify;
633    int len = (int)args->lhs_len;
634
635    if (keyround == 2) {
636      if (!did_simplify) {
637        break;
638      }
639      lhs = (char *)&args->alt_lhs;
640      len = (int)args->alt_lhs_len;
641    } else if (did_simplify && do_print) {
642      // when printing always use the not-simplified map
643      lhs = (char *)&args->alt_lhs;
644      len = (int)args->alt_lhs_len;
645    }
646
647    // check arguments and translate function keys
648    if (has_lhs) {
649      if (len > MAXMAPLEN) {
650        retval = 1;
651        goto theend;
652      }
653
654      if (is_abbrev && maptype != MAPTYPE_UNMAP) {
655        // If an abbreviation ends in a keyword character, the
656        // rest must be all keyword-char or all non-keyword-char.
657        // Otherwise we won't be able to find the start of it in a
658        // vi-compatible way.
659        int same = -1;
660
661        char keys_unescaped[MAXMAPLEN + 1];
662        xmemcpyz(keys_unescaped, lhs, (size_t)len);
663        size_t keys_unescaped_len = vim_unescape_ks(keys_unescaped);
664        const char *p = keys_unescaped;
665
666        const int first = vim_iswordp(p);
667        int last = first;
668        MB_PTR_ADV(p);
669        int n = 1;
670        while (p < keys_unescaped + keys_unescaped_len) {
671          n++;                                  // nr of (multi-byte) chars
672          last = vim_iswordp(p);                // type of last char
673          if (same == -1 && last != first) {
674            same = n - 1;                       // count of same char type
675          }
676          MB_PTR_ADV(p);
677        }
678        if (last && n > 2 && same >= 0 && same < n - 1) {
679          retval = 1;
680          goto theend;
681        }
682
683        // An abbreviation cannot contain white space.
684        for (n = 0; n < len; n++) {
685          if (ascii_iswhite(lhs[n])) {
686            retval = 1;
687            goto theend;
688          }
689        }  // for
690      }
691    }
692
693    if (has_lhs && has_rhs && is_abbrev) {  // if we will add an abbreviation,
694      no_abbr = false;  // reset flag that indicates there are no abbreviations
695    }
696
697    if (do_print) {
698      msg_start();
699    }
700
701    // Check if a new local mapping wasn't already defined globally.
702    if (args->unique && map_table == buf->b_maphash && has_lhs && has_rhs
703        && maptype != MAPTYPE_UNMAP) {
704      // need to loop over all global hash lists
705      for (int hash = 0; hash < 256 && !got_int; hash++) {
706        mapblock_T *mp;
707        if (is_abbrev) {
708          if (hash != 0) {  // there is only one abbreviation list
709            break;
710          }
711          mp = first_abbr;
712        } else {
713          mp = maphash[hash];
714        }
715        for (; mp != NULL && !got_int; mp = mp->m_next) {
716          // check entries with the same mode
717          if ((mp->m_mode & mode) != 0
718              && mp->m_keylen == len
719              && strncmp(mp->m_keys, lhs, (size_t)len) == 0) {
720            retval = 6;
721            goto theend;
722          }
723        }
724      }
725    }
726
727    // When listing global mappings, also list buffer-local ones here.
728    if (map_table != buf->b_maphash && !has_rhs && maptype != MAPTYPE_UNMAP) {
729      // need to loop over all global hash lists
730      for (int hash = 0; hash < 256 && !got_int; hash++) {
731        mapblock_T *mp;
732        if (is_abbrev) {
733          if (hash != 0) {  // there is only one abbreviation list
734            break;
735          }
736          mp = buf->b_first_abbr;
737        } else {
738          mp = buf->b_maphash[hash];
739        }
740        for (; mp != NULL && !got_int; mp = mp->m_next) {
741          // check entries with the same mode
742          if (!mp->m_simplified && (mp->m_mode & mode) != 0) {
743            if (!has_lhs) {  // show all entries
744              showmap(mp, true);
745              did_local = true;
746            } else {
747              int n = mp->m_keylen;
748              if (strncmp(mp->m_keys, lhs, (size_t)(n < len ? n : len)) == 0) {
749                showmap(mp, true);
750                did_local = true;
751              }
752            }
753          }
754        }
755      }
756    }
757
758    // Find an entry in the maphash[] list that matches.
759    // For :unmap we may loop two times: once to try to unmap an entry with a
760    // matching 'from' part, a second time, if the first fails, to unmap an
761    // entry with a matching 'to' part. This was done to allow ":ab foo bar"
762    // to be unmapped by typing ":unab foo", where "foo" will be replaced by
763    // "bar" because of the abbreviation.
764    const int num_rounds = maptype == MAPTYPE_UNMAP && !unmap_lhs_only ? 2 : 1;
765    for (int round = 0; round < num_rounds && !did_it && !got_int; round++) {
766      int hash_start, hash_end;
767      if ((round == 0 && has_lhs) || is_abbrev) {
768        // just use one hash
769        hash_start = is_abbrev ? 0 : MAP_HASH(mode, (uint8_t)lhs[0]);
770        hash_end = hash_start + 1;
771      } else {
772        // need to loop over all hash lists
773        hash_start = 0;
774        hash_end = 256;
775      }
776      for (int hash = hash_start; hash < hash_end && !got_int; hash++) {
777        mapblock_T **mpp = is_abbrev ? abbr_table : &(map_table[hash]);
778        for (mapblock_T *mp = *mpp; mp != NULL && !got_int; mp = *mpp) {
779          if ((mp->m_mode & mode) == 0) {
780            // skip entries with wrong mode
781            mpp = &(mp->m_next);
782            continue;
783          }
784          if (!has_lhs) {                      // show all entries
785            if (!mp->m_simplified) {
786              showmap(mp, map_table != maphash);
787              did_it = true;
788            }
789          } else {                          // do we have a match?
790            int n;
791            const char *p;
792            if (round) {              // second round: Try unmap "rhs" string
793              n = (int)strlen(mp->m_str);
794              p = mp->m_str;
795            } else {
796              n = mp->m_keylen;
797              p = mp->m_keys;
798            }
799            if (strncmp(p, lhs, (size_t)(n < len ? n : len)) == 0) {
800              if (maptype == MAPTYPE_UNMAP) {
801                // Delete entry.
802                // Only accept a full match.  For abbreviations
803                // we ignore trailing space when matching with
804                // the "lhs", since an abbreviation can't have
805                // trailing space.
806                if (n != len && (!is_abbrev || round || n > len || *skipwhite(lhs + n) != NUL)) {
807                  mpp = &(mp->m_next);
808                  continue;
809                }
810                // In keyround for simplified keys, don't unmap
811                // a mapping without m_simplified flag.
812                if (keyround1_simplified && !mp->m_simplified) {
813                  break;
814                }
815                // We reset the indicated mode bits. If nothing
816                // is left the entry is deleted below.
817                mp->m_mode &= ~mode;
818                did_it = true;  // remember we did something
819              } else if (!has_rhs) {  // show matching entry
820                if (!mp->m_simplified) {
821                  showmap(mp, map_table != maphash);
822                  did_it = true;
823                }
824              } else if (n != len) {  // new entry is ambiguous
825                mpp = &(mp->m_next);
826                continue;
827              } else if (keyround1_simplified && !mp->m_simplified) {
828                // In keyround for simplified keys, don't replace
829                // a mapping without m_simplified flag.
830                did_it = true;
831                break;
832              } else if (args->unique) {
833                retval = 5;
834                goto theend;
835              } else {
836                // new rhs for existing entry
837                mp->m_mode &= ~mode;  // remove mode bits
838                if (mp->m_mode == 0 && !did_it) {  // reuse entry
839                  if (mp->m_alt != NULL) {
840                    mp->m_alt = mp->m_alt->m_alt = NULL;
841                  } else {
842                    NLUA_CLEAR_REF(mp->m_luaref);
843                    xfree(mp->m_str);
844                    xfree(mp->m_orig_str);
845                    xfree(mp->m_desc);
846                  }
847                  mp->m_str = args->rhs;
848                  mp->m_orig_str = args->orig_rhs;
849                  mp->m_luaref = args->rhs_lua;
850                  mp->m_noremap = noremap;
851                  mp->m_nowait = args->nowait;
852                  mp->m_silent = args->silent;
853                  mp->m_mode = mode;
854                  mp->m_simplified = keyround1_simplified;
855                  mp->m_expr = args->expr;
856                  mp->m_replace_keycodes = args->replace_keycodes;
857                  mp->m_script_ctx = current_sctx;
858                  mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
859                  nlua_set_sctx(&mp->m_script_ctx);
860                  mp->m_desc = args->desc;
861                  mp_result[keyround - 1] = mp;
862                  did_it = true;
863                }
864              }
865              if (mp->m_mode == 0) {  // entry can be deleted
866                mapblock_free(mpp);
867                continue;  // continue with *mpp
868              }
869
870              // May need to put this entry into another hash list.
871              int new_hash = MAP_HASH(mp->m_mode, (uint8_t)mp->m_keys[0]);
872              if (!is_abbrev && new_hash != hash) {
873                *mpp = mp->m_next;
874                mp->m_next = map_table[new_hash];
875                map_table[new_hash] = mp;
876
877                continue;  // continue with *mpp
878              }
879            }
880          }
881          mpp = &(mp->m_next);
882        }
883      }
884    }
885
886    if (maptype == MAPTYPE_UNMAP) {
887      // delete entry
888      if (!did_it) {
889        if (!keyround1_simplified) {
890          retval = 2;  // no match
891        }
892      } else if (*lhs == Ctrl_C) {
893        // If CTRL-C has been unmapped, reuse it for Interrupting.
894        if (map_table == buf->b_maphash) {
895          buf->b_mapped_ctrl_c &= ~mode;
896        } else {
897          mapped_ctrl_c &= ~mode;
898        }
899      }
900      continue;
901    }
902
903    if (!has_lhs || !has_rhs) {
904      // print entries
905      if (!did_it && !did_local) {
906        if (is_abbrev) {
907          msg(_("No abbreviation found"), 0);
908        } else {
909          msg(_("No mapping found"), 0);
910        }
911      }
912      goto theend;  // listing finished
913    }
914
915    if (did_it) {
916      continue;  // have added the new entry already
917    }
918
919    // Get here when adding a new entry to the maphash[] list or abbrlist.
920    mp_result[keyround - 1] = map_add(buf, map_table, abbr_table, lhs,
921                                      args, noremap, mode, is_abbrev,
922                                      0,  // sid
923                                      0,  // lnum
924                                      keyround1_simplified);
925  }
926
927  if (mp_result[0] != NULL && mp_result[1] != NULL) {
928    mp_result[0]->m_alt = mp_result[1];
929    mp_result[1]->m_alt = mp_result[0];
930  }
931
932theend:
933  if (mp_result[0] != NULL || mp_result[1] != NULL) {
934    args->rhs = NULL;
935    args->orig_rhs = NULL;
936    args->rhs_lua = LUA_NOREF;
937    args->desc = NULL;
938  }
939  return retval;
940}
941
942/// Set or remove a mapping or an abbreviation in the current buffer, OR
943/// display (matching) mappings/abbreviations.
944///
945/// ```vim
946/// map[!]                          " show all key mappings
947/// map[!] {lhs}                    " show key mapping for {lhs}
948/// map[!] {lhs} {rhs}              " set key mapping for {lhs} to {rhs}
949/// noremap[!] {lhs} {rhs}          " same, but no remapping for {rhs}
950/// unmap[!] {lhs}                  " remove key mapping for {lhs}
951/// abbr                            " show all abbreviations
952/// abbr {lhs}                      " show abbreviations for {lhs}
953/// abbr {lhs} {rhs}                " set abbreviation for {lhs} to {rhs}
954/// noreabbr {lhs} {rhs}            " same, but no remapping for {rhs}
955/// unabbr {lhs}                    " remove abbreviation for {lhs}
956///
957/// for :map   mode is MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING
958/// for :map!  mode is MODE_INSERT | MODE_CMDLINE
959/// for :cmap  mode is MODE_CMDLINE
960/// for :imap  mode is MODE_INSERT
961/// for :lmap  mode is MODE_LANGMAP
962/// for :nmap  mode is MODE_NORMAL
963/// for :vmap  mode is MODE_VISUAL | MODE_SELECT
964/// for :xmap  mode is MODE_VISUAL
965/// for :smap  mode is MODE_SELECT
966/// for :omap  mode is MODE_OP_PENDING
967/// for :tmap  mode is MODE_TERMINAL
968///
969/// for :abbr  mode is MODE_INSERT | MODE_CMDLINE
970/// for :iabbr mode is MODE_INSERT
971/// for :cabbr mode is MODE_CMDLINE
972/// ```
973///
974/// @param maptype  MAPTYPE_MAP for |:map| or |:abbr|
975///                 MAPTYPE_UNMAP for |:unmap| or |:unabbr|
976///                 MAPTYPE_NOREMAP for |:noremap| or |:noreabbr|
977///                 MAPTYPE_UNMAP_LHS is like MAPTYPE_UNMAP, but doesn't try to match
978///                 with {rhs} if there is no match with {lhs}.
979/// @param arg      C-string containing the arguments of the map/abbrev
980///                 command, i.e. everything except the initial `:[X][nore]map`.
981///                 - Cannot be a read-only string; it will be modified.
982/// @param mode   Bitflags representing the mode in which to set the mapping.
983///               See @ref get_map_mode.
984/// @param is_abbrev  True if setting an abbreviation, false otherwise.
985///
986/// @return 0 on success. On failure, will return one of the following:
987///         - 1 for invalid arguments
988///         - 2 for no match
989///         - 4 for out of mem (deprecated, WON'T HAPPEN)
990///         - 5 for entry not unique
991///         - 6 for buflocal unique entry conflicts with global entry
992///
993int do_map(int maptype, char *arg, int mode, bool is_abbrev)
994{
995  MapArguments parsed_args;
996  int result = str_to_mapargs(arg, maptype == MAPTYPE_UNMAP, &parsed_args);
997  switch (result) {
998  case 0:
999    break;
1000  case 1:
1001    // invalid arguments
1002    goto free_and_return;
1003  default:
1004    assert(false && "Unknown return code from str_to_mapargs!");
1005    result = -1;
1006    goto free_and_return;
1007  }  // switch
1008
1009  result = buf_do_map(maptype, &parsed_args, mode, is_abbrev, curbuf);
1010
1011free_and_return:
1012  xfree(parsed_args.rhs);
1013  xfree(parsed_args.orig_rhs);
1014  return result;
1015}
1016
1017/// Get the mapping mode from the command name.
1018static int get_map_mode(char **cmdp, bool forceit)
1019{
1020  int mode;
1021
1022  char *p = *cmdp;
1023  int modec = (uint8_t)(*p++);
1024  if (modec == 'i') {
1025    mode = MODE_INSERT;                                                  // :imap
1026  } else if (modec == 'l') {
1027    mode = MODE_LANGMAP;                                                 // :lmap
1028  } else if (modec == 'c') {
1029    mode = MODE_CMDLINE;                                                 // :cmap
1030  } else if (modec == 'n' && *p != 'o') {  // avoid :noremap
1031    mode = MODE_NORMAL;                                                  // :nmap
1032  } else if (modec == 'v') {
1033    mode = MODE_VISUAL | MODE_SELECT;                                    // :vmap
1034  } else if (modec == 'x') {
1035    mode = MODE_VISUAL;                                                  // :xmap
1036  } else if (modec == 's') {
1037    mode = MODE_SELECT;                                                  // :smap
1038  } else if (modec == 'o') {
1039    mode = MODE_OP_PENDING;                                              // :omap
1040  } else if (modec == 't') {
1041    mode = MODE_TERMINAL;                                                // :tmap
1042  } else {
1043    p--;
1044    if (forceit) {
1045      mode = MODE_INSERT | MODE_CMDLINE;                                 // :map !
1046    } else {
1047      mode = MODE_VISUAL | MODE_SELECT | MODE_NORMAL | MODE_OP_PENDING;  // :map
1048    }
1049  }
1050
1051  *cmdp = p;
1052  return mode;
1053}
1054
1055/// Clear all mappings (":mapclear") or abbreviations (":abclear").
1056/// "abbr" should be false for mappings, true for abbreviations.
1057/// This function used to be called map_clear().
1058static void do_mapclear(char *cmdp, char *arg, int forceit, int abbr)
1059{
1060  bool local = strcmp(arg, "<buffer>") == 0;
1061  if (!local && *arg != NUL) {
1062    emsg(_(e_invarg));
1063    return;
1064  }
1065
1066  int mode = get_map_mode(&cmdp, forceit);
1067  map_clear_mode(curbuf, mode, local, abbr);
1068}
1069
1070/// Clear all mappings in "mode".
1071///
1072/// @param buf,  buffer for local mappings
1073/// @param mode  mode in which to delete
1074/// @param local  true for buffer-local mappings
1075/// @param abbr  true for abbreviations
1076void map_clear_mode(buf_T *buf, int mode, bool local, bool abbr)
1077{
1078  for (int hash = 0; hash < 256; hash++) {
1079    mapblock_T **mpp;
1080    if (abbr) {
1081      if (hash > 0) {           // there is only one abbrlist
1082        break;
1083      }
1084      if (local) {
1085        mpp = &buf->b_first_abbr;
1086      } else {
1087        mpp = &first_abbr;
1088      }
1089    } else {
1090      if (local) {
1091        mpp = &buf->b_maphash[hash];
1092      } else {
1093        mpp = &maphash[hash];
1094      }
1095    }
1096    while (*mpp != NULL) {
1097      mapblock_T *mp = *mpp;
1098      if (mp->m_mode & mode) {
1099        mp->m_mode &= ~mode;
1100        if (mp->m_mode == 0) {       // entry can be deleted
1101          mapblock_free(mpp);
1102          continue;
1103        }
1104        // May need to put this entry into another hash list.
1105        int new_hash = MAP_HASH(mp->m_mode, (uint8_t)mp->m_keys[0]);
1106        if (!abbr && new_hash != hash) {
1107          *mpp = mp->m_next;
1108          if (local) {
1109            mp->m_next = buf->b_maphash[new_hash];
1110            buf->b_maphash[new_hash] = mp;
1111          } else {
1112            mp->m_next = maphash[new_hash];
1113            maphash[new_hash] = mp;
1114          }
1115          continue;                     // continue with *mpp
1116        }
1117      }
1118      mpp = &(mp->m_next);
1119    }
1120  }
1121}
1122
1123/// Check if a map exists that has given string in the rhs
1124///
1125/// Also checks mappings local to the current buffer.
1126///
1127/// @param[in]  str  String which mapping must have in the rhs. Termcap codes
1128///                  are recognized in this argument.
1129/// @param[in]  modechars  Mode(s) in which mappings are checked.
1130/// @param[in]  abbr  true if checking abbreviations in place of mappings.
1131///
1132/// @return true if there is at least one mapping with given parameters.
1133bool map_to_exists(const char *const str, const char *const modechars, const bool abbr)
1134  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1135{
1136  int mode = 0;
1137
1138  char *buf = NULL;
1139  const char *const rhs = replace_termcodes(str, strlen(str), &buf, 0,
1140                                            REPTERM_DO_LT, NULL, p_cpo);
1141
1142#define MAPMODE(mode, modechars, chr, modeflags) \
1143  do { \
1144    if (strchr(modechars, chr) != NULL) { \
1145      (mode) |= (modeflags); \
1146    } \
1147  } while (0)
1148  MAPMODE(mode, modechars, 'n', MODE_NORMAL);
1149  MAPMODE(mode, modechars, 'v', MODE_VISUAL | MODE_SELECT);
1150  MAPMODE(mode, modechars, 'x', MODE_VISUAL);
1151  MAPMODE(mode, modechars, 's', MODE_SELECT);
1152  MAPMODE(mode, modechars, 'o', MODE_OP_PENDING);
1153  MAPMODE(mode, modechars, 'i', MODE_INSERT);
1154  MAPMODE(mode, modechars, 'l', MODE_LANGMAP);
1155  MAPMODE(mode, modechars, 'c', MODE_CMDLINE);
1156#undef MAPMODE
1157
1158  bool retval = map_to_exists_mode(rhs, mode, abbr);
1159  xfree(buf);
1160
1161  return retval;
1162}
1163
1164/// Check if a map exists that has given string in the rhs
1165///
1166/// Also checks mappings local to the current buffer.
1167///
1168/// @param[in]  rhs  String which mapping must have in the rhs. Termcap codes
1169///                  are recognized in this argument.
1170/// @param[in]  mode  Mode(s) in which mappings are checked.
1171/// @param[in]  abbr  true if checking abbreviations in place of mappings.
1172///
1173/// @return true if there is at least one mapping with given parameters.
1174bool map_to_exists_mode(const char *const rhs, const int mode, const bool abbr)
1175{
1176  bool exp_buffer = false;
1177
1178  // Do it twice: once for global maps and once for local maps.
1179  while (true) {
1180    for (int hash = 0; hash < 256; hash++) {
1181      mapblock_T *mp;
1182      if (abbr) {
1183        if (hash > 0) {  // There is only one abbr list.
1184          break;
1185        }
1186        if (exp_buffer) {
1187          mp = curbuf->b_first_abbr;
1188        } else {
1189          mp = first_abbr;
1190        }
1191      } else if (exp_buffer) {
1192        mp = curbuf->b_maphash[hash];
1193      } else {
1194        mp = maphash[hash];
1195      }
1196      for (; mp; mp = mp->m_next) {
1197        if ((mp->m_mode & mode) && strstr(mp->m_str, rhs) != NULL) {
1198          return true;
1199        }
1200      }
1201    }
1202    if (exp_buffer) {
1203      break;
1204    }
1205    exp_buffer = true;
1206  }
1207
1208  return false;
1209}
1210
1211/// Used below when expanding mapping/abbreviation names.
1212static int expand_mapmodes = 0;
1213static bool expand_isabbrev = false;
1214static bool expand_buffer = false;
1215
1216/// Translate an internal mapping/abbreviation representation into the
1217/// corresponding external one recognized by :map/:abbrev commands.
1218///
1219/// This function is called when expanding mappings/abbreviations on the
1220/// command-line.
1221///
1222/// It uses a growarray to build the translation string since the latter can be
1223/// wider than the original description. The caller has to free the string
1224/// afterwards.
1225///
1226/// @param[in] cpo_val  See param docs for @ref replace_termcodes.
1227///
1228/// @return  NULL when there is a problem.
1229static char *translate_mapping(const char *const str_in, const char *const cpo_val)
1230{
1231  const uint8_t *str = (const uint8_t *)str_in;
1232  garray_T ga;
1233  ga_init(&ga, 1, 40);
1234
1235  const bool cpo_bslash = (vim_strchr(cpo_val, kCpoBslash) != NULL);
1236
1237  for (; *str; str++) {
1238    int c = *str;
1239    if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) {
1240      int modifiers = 0;
1241      if (str[1] == KS_MODIFIER) {
1242        str++;
1243        modifiers = *++str;
1244        c = *++str;
1245      }
1246
1247      if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) {
1248        c = TO_SPECIAL(str[1], str[2]);
1249        if (c == K_ZERO) {
1250          // display <Nul> as ^@
1251          c = NUL;
1252        }
1253        str += 2;
1254      }
1255      if (IS_SPECIAL(c) || modifiers) {         // special key
1256        ga_concat(&ga, get_special_key_name(c, modifiers));
1257        continue;         // for (str)
1258      }
1259    }
1260
1261    if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
1262        || c == '<' || (c == '\\' && !cpo_bslash)) {
1263      ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
1264    }
1265
1266    if (c) {
1267      ga_append(&ga, (uint8_t)c);
1268    }
1269  }
1270  ga_append(&ga, NUL);
1271  return (char *)ga.ga_data;
1272}
1273
1274/// Work out what to complete when doing command line completion of mapping
1275/// or abbreviation names.
1276///
1277/// @param forceit  true if '!' given
1278/// @param isabbrev  true if abbreviation
1279/// @param isunmap  true if unmap/unabbrev command
1280char *set_context_in_map_cmd(expand_T *xp, char *cmd, char *arg, bool forceit, bool isabbrev,
1281                             bool isunmap, cmdidx_T cmdidx)
1282{
1283  if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap) {
1284    xp->xp_context = EXPAND_NOTHING;
1285  } else {
1286    if (isunmap) {
1287      expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1288    } else {
1289      expand_mapmodes = MODE_INSERT | MODE_CMDLINE;
1290      if (!isabbrev) {
1291        expand_mapmodes |= MODE_VISUAL | MODE_SELECT | MODE_NORMAL | MODE_OP_PENDING;
1292      }
1293    }
1294    expand_isabbrev = isabbrev;
1295    xp->xp_context = EXPAND_MAPPINGS;
1296    expand_buffer = false;
1297    while (true) {
1298      if (strncmp(arg, "<buffer>", 8) == 0) {
1299        expand_buffer = true;
1300        arg = skipwhite(arg + 8);
1301        continue;
1302      }
1303      if (strncmp(arg, "<unique>", 8) == 0) {
1304        arg = skipwhite(arg + 8);
1305        continue;
1306      }
1307      if (strncmp(arg, "<nowait>", 8) == 0) {
1308        arg = skipwhite(arg + 8);
1309        continue;
1310      }
1311      if (strncmp(arg, "<silent>", 8) == 0) {
1312        arg = skipwhite(arg + 8);
1313        continue;
1314      }
1315      if (strncmp(arg, "<special>", 9) == 0) {
1316        arg = skipwhite(arg + 9);
1317        continue;
1318      }
1319      if (strncmp(arg, "<script>", 8) == 0) {
1320        arg = skipwhite(arg + 8);
1321        continue;
1322      }
1323      if (strncmp(arg, "<expr>", 6) == 0) {
1324        arg = skipwhite(arg + 6);
1325        continue;
1326      }
1327      break;
1328    }
1329    xp->xp_pattern = arg;
1330  }
1331
1332  return NULL;
1333}
1334
1335/// Find all mapping/abbreviation names that match regexp "regmatch".
1336/// For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1337/// @return OK if matches found, FAIL otherwise.
1338int ExpandMappings(char *pat, regmatch_T *regmatch, int *numMatches, char ***matches)
1339{
1340  const bool fuzzy = cmdline_fuzzy_complete(pat);
1341
1342  *numMatches = 0;                    // return values in case of FAIL
1343  *matches = NULL;
1344
1345  garray_T ga;
1346  if (!fuzzy) {
1347    ga_init(&ga, sizeof(char *), 3);
1348  } else {
1349    ga_init(&ga, sizeof(fuzmatch_str_T), 3);
1350  }
1351
1352  // First search in map modifier arguments
1353  for (int i = 0; i < 7; i++) {
1354    char *p;
1355    if (i == 0) {
1356      p = "<silent>";
1357    } else if (i == 1) {
1358      p = "<unique>";
1359    } else if (i == 2) {
1360      p = "<script>";
1361    } else if (i == 3) {
1362      p = "<expr>";
1363    } else if (i == 4 && !expand_buffer) {
1364      p = "<buffer>";
1365    } else if (i == 5) {
1366      p = "<nowait>";
1367    } else if (i == 6) {
1368      p = "<special>";
1369    } else {
1370      continue;
1371    }
1372
1373    bool match;
1374    int score = 0;
1375    if (!fuzzy) {
1376      match = vim_regexec(regmatch, p, 0);
1377    } else {
1378      score = fuzzy_match_str(p, pat);
1379      match = (score != FUZZY_SCORE_NONE);
1380    }
1381
1382    if (!match) {
1383      continue;
1384    }
1385
1386    if (fuzzy) {
1387      GA_APPEND(fuzmatch_str_T, &ga, ((fuzmatch_str_T){
1388        .idx = ga.ga_len,
1389        .str = xstrdup(p),
1390        .score = score,
1391      }));
1392    } else {
1393      GA_APPEND(char *, &ga, xstrdup(p));
1394    }
1395  }
1396
1397  for (int hash = 0; hash < 256; hash++) {
1398    mapblock_T *mp;
1399    if (expand_isabbrev) {
1400      if (hash > 0) {    // only one abbrev list
1401        break;  // for (hash)
1402      }
1403      mp = first_abbr;
1404    } else if (expand_buffer) {
1405      mp = curbuf->b_maphash[hash];
1406    } else {
1407      mp = maphash[hash];
1408    }
1409    for (; mp; mp = mp->m_next) {
1410      if (mp->m_simplified || !(mp->m_mode & expand_mapmodes)) {
1411        continue;
1412      }
1413
1414      char *p = translate_mapping(mp->m_keys, p_cpo);
1415      if (p == NULL) {
1416        continue;
1417      }
1418
1419      bool match;
1420      int score = 0;
1421      if (!fuzzy) {
1422        match = vim_regexec(regmatch, p, 0);
1423      } else {
1424        score = fuzzy_match_str(p, pat);
1425        match = (score != FUZZY_SCORE_NONE);
1426      }
1427
1428      if (!match) {
1429        xfree(p);
1430        continue;
1431      }
1432
1433      if (fuzzy) {
1434        GA_APPEND(fuzmatch_str_T, &ga, ((fuzmatch_str_T){
1435          .idx = ga.ga_len,
1436          .str = p,
1437          .score = score,
1438        }));
1439      } else {
1440        GA_APPEND(char *, &ga, p);
1441      }
1442    }  // for (mp)
1443  }  // for (hash)
1444
1445  if (ga.ga_len == 0) {
1446    return FAIL;
1447  }
1448
1449  if (!fuzzy) {
1450    *matches = ga.ga_data;
1451    *numMatches = ga.ga_len;
1452  } else {
1453    fuzzymatches_to_strmatches(ga.ga_data, matches, ga.ga_len, false);
1454    *numMatches = ga.ga_len;
1455  }
1456
1457  int count = *numMatches;
1458  if (count > 1) {
1459    // Sort the matches
1460    // Fuzzy matching already sorts the matches
1461    if (!fuzzy) {
1462      sort_strings(*matches, count);
1463    }
1464
1465    // Remove multiple entries
1466    char **ptr1 = *matches;
1467    char **ptr2 = ptr1 + 1;
1468    char **ptr3 = ptr1 + count;
1469
1470    while (ptr2 < ptr3) {
1471      if (strcmp(*ptr1, *ptr2) != 0) {
1472        *++ptr1 = *ptr2++;
1473      } else {
1474        xfree(*ptr2++);
1475        count--;
1476      }
1477    }
1478  }
1479
1480  *numMatches = count;
1481  return count == 0 ? FAIL : OK;
1482}
1483
1484// Check for an abbreviation.
1485// Cursor is at ptr[col].
1486// When inserting, mincol is where insert started.
1487// For the command line, mincol is what is to be skipped over.
1488// "c" is the character typed before check_abbr was called.  It may have
1489// ABBR_OFF added to avoid prepending a CTRL-V to it.
1490//
1491// Historic vi practice: The last character of an abbreviation must be an id
1492// character ([a-zA-Z0-9_]). The characters in front of it must be all id
1493// characters or all non-id characters. This allows for abbr. "#i" to
1494// "#include".
1495//
1496// Vim addition: Allow for abbreviations that end in a non-keyword character.
1497// Then there must be white space before the abbr.
1498//
1499// Return true if there is an abbreviation, false if not.
1500bool check_abbr(int c, char *ptr, int col, int mincol)
1501{
1502  uint8_t tb[MB_MAXBYTES + 4];
1503  int clen = 0;                 // length in characters
1504
1505  if (typebuf.tb_no_abbr_cnt) {  // abbrev. are not recursive
1506    return false;
1507  }
1508
1509  // no remapping implies no abbreviation, except for CTRL-]
1510  if (noremap_keys() && c != Ctrl_RSB) {
1511    return false;
1512  }
1513
1514  // Check for word before the cursor: If it ends in a keyword char all
1515  // chars before it must be keyword chars or non-keyword chars, but not
1516  // white space. If it ends in a non-keyword char we accept any characters
1517  // before it except white space.
1518  if (col == 0) {  // cannot be an abbr.
1519    return false;
1520  }
1521
1522  int scol;  // starting column of the abbr.
1523
1524  {
1525    bool is_id = true;
1526    bool vim_abbr;
1527    char *p = mb_prevptr(ptr, ptr + col);
1528    if (!vim_iswordp(p)) {
1529      vim_abbr = true;    // Vim added abbr.
1530    } else {
1531      vim_abbr = false;   // vi compatible abbr.
1532      if (p > ptr) {
1533        is_id = vim_iswordp(mb_prevptr(ptr, p));
1534      }
1535    }
1536    clen = 1;
1537    while (p > ptr + mincol) {
1538      p = mb_prevptr(ptr, p);
1539      if (ascii_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p))) {
1540        p += utfc_ptr2len(p);
1541        break;
1542      }
1543      clen++;
1544    }
1545    scol = (int)(p - ptr);
1546  }
1547
1548  if (scol < mincol) {
1549    scol = mincol;
1550  }
1551  if (scol < col) {             // there is a word in front of the cursor
1552    ptr += scol;
1553    int len = col - scol;
1554    mapblock_T *mp = curbuf->b_first_abbr;
1555    mapblock_T *mp2 = first_abbr;
1556    if (mp == NULL) {
1557      mp = mp2;
1558      mp2 = NULL;
1559    }
1560    for (; mp;
1561         mp->m_next == NULL ? (mp = mp2, mp2 = NULL)
1562                            : (mp = mp->m_next)) {
1563      int qlen = mp->m_keylen;
1564      char *q = mp->m_keys;
1565
1566      if (strchr(mp->m_keys, K_SPECIAL) != NULL) {
1567        // Might have K_SPECIAL escaped mp->m_keys.
1568        q = xstrdup(mp->m_keys);
1569        qlen = (int)vim_unescape_ks(q);
1570      }
1571      // find entries with right mode and keys
1572      int match = (mp->m_mode & State)
1573                  && qlen == len
1574                  && strncmp(q, ptr, (size_t)len) == 0;
1575      if (q != mp->m_keys) {
1576        xfree(q);
1577      }
1578      if (match) {
1579        break;
1580      }
1581    }
1582    if (mp != NULL) {
1583      // Found a match:
1584      // Insert the rest of the abbreviation in typebuf.tb_buf[].
1585      // This goes from end to start.
1586      //
1587      // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1588      // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1589      // Characters where IS_SPECIAL() == true: key codes, need
1590      // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1591      //
1592      // Character CTRL-] is treated specially - it completes the
1593      // abbreviation, but is not inserted into the input stream.
1594      int j = 0;
1595      if (c != Ctrl_RSB) {
1596        // special key code, split up
1597        if (IS_SPECIAL(c) || c == K_SPECIAL) {
1598          tb[j++] = K_SPECIAL;
1599          tb[j++] = (uint8_t)K_SECOND(c);
1600          tb[j++] = (uint8_t)K_THIRD(c);
1601        } else {
1602          if (c < ABBR_OFF && (c < ' ' || c > '~')) {
1603            tb[j++] = Ctrl_V;                   // special char needs CTRL-V
1604          }
1605          // if ABBR_OFF has been added, remove it here.
1606          if (c >= ABBR_OFF) {
1607            c -= ABBR_OFF;
1608          }
1609          int newlen = utf_char2bytes(c, (char *)tb + j);
1610          tb[j + newlen] = NUL;
1611          // Need to escape K_SPECIAL.
1612          char *escaped = vim_strsave_escape_ks((char *)tb + j);
1613          if (escaped != NULL) {
1614            newlen = (int)strlen(escaped);
1615            memmove(tb + j, escaped, (size_t)newlen);
1616            j += newlen;
1617            xfree(escaped);
1618          }
1619        }
1620        tb[j] = NUL;
1621        // insert the last typed char
1622        ins_typebuf((char *)tb, 1, 0, true, mp->m_silent);
1623      }
1624
1625      // copy values here, calling eval_map_expr() may make "mp" invalid!
1626      const int noremap = mp->m_noremap;
1627      const bool silent = mp->m_silent;
1628      const bool expr = mp->m_expr;
1629
1630      char *s;
1631      if (expr) {
1632        s = eval_map_expr(mp, c);
1633      } else {
1634        s = mp->m_str;
1635      }
1636      if (s != NULL) {
1637        // insert the to string
1638        ins_typebuf(s, noremap, 0, true, silent);
1639        // no abbrev. for these chars
1640        typebuf.tb_no_abbr_cnt += (int)strlen(s) + j + 1;
1641        if (expr) {
1642          xfree(s);
1643        }
1644      }
1645
1646      tb[0] = Ctrl_H;
1647      tb[1] = NUL;
1648      len = clen;  // Delete characters instead of bytes
1649      while (len-- > 0) {  // delete the from string
1650        ins_typebuf((char *)tb, 1, 0, true, silent);
1651      }
1652      return true;
1653    }
1654  }
1655  return false;
1656}
1657
1658/// Evaluate the RHS of a mapping or abbreviations and take care of escaping
1659/// special characters.
1660/// Careful: after this "mp" will be invalid if the mapping was deleted.
1661///
1662/// @param c  NUL or typed character for abbreviation
1663char *eval_map_expr(mapblock_T *mp, int c)
1664{
1665  char *p = NULL;
1666  char *expr = NULL;
1667
1668  // Remove escaping of K_SPECIAL, because "str" is in a format to be used as
1669  // typeahead.
1670  if (mp->m_luaref == LUA_NOREF) {
1671    expr = xstrdup(mp->m_str);
1672    vim_unescape_ks(expr);
1673  }
1674
1675  const bool replace_keycodes = mp->m_replace_keycodes;
1676
1677  // Forbid changing text or using ":normal" to avoid most of the bad side
1678  // effects.  Also restore the cursor position.
1679  expr_map_lock++;
1680  set_vim_var_char(c);    // set v:char to the typed character
1681  const pos_T save_cursor = curwin->w_cursor;
1682  const int save_msg_col = msg_col;
1683  const int save_msg_row = msg_row;
1684  if (mp->m_luaref != LUA_NOREF) {
1685    Error err = ERROR_INIT;
1686    Array args = ARRAY_DICT_INIT;
1687    Object ret = nlua_call_ref(mp->m_luaref, NULL, args, kRetObject, NULL, &err);
1688    if (ret.type == kObjectTypeString) {
1689      p = string_to_cstr(ret.data.string);
1690    }
1691    api_free_object(ret);
1692    if (ERROR_SET(&err)) {
1693      semsg_multiline("emsg", "E5108: %s", err.msg);
1694      api_clear_error(&err);
1695    }
1696  } else {
1697    p = eval_to_string(expr, false, false);
1698    xfree(expr);
1699  }
1700  expr_map_lock--;
1701  curwin->w_cursor = save_cursor;
1702  msg_col = save_msg_col;
1703  msg_row = save_msg_row;
1704
1705  if (p == NULL) {
1706    return NULL;
1707  }
1708
1709  char *res = NULL;
1710
1711  if (replace_keycodes) {
1712    replace_termcodes(p, strlen(p), &res, 0, REPTERM_DO_LT, NULL, p_cpo);
1713  } else {
1714    // Escape K_SPECIAL in the result to be able to use the string as typeahead.
1715    res = vim_strsave_escape_ks(p);
1716  }
1717  xfree(p);
1718
1719  return res;
1720}
1721
1722/// Write map commands for the current mappings to an .exrc file.
1723/// Return FAIL on error, OK otherwise.
1724///
1725/// @param buf  buffer for local mappings or NULL
1726int makemap(FILE *fd, buf_T *buf)
1727{
1728  bool did_cpo = false;
1729
1730  // Do the loop twice: Once for mappings, once for abbreviations.
1731  // Then loop over all map hash lists.
1732  for (int abbr = 0; abbr < 2; abbr++) {
1733    for (int hash = 0; hash < 256; hash++) {
1734      mapblock_T *mp;
1735      if (abbr) {
1736        if (hash > 0) {                 // there is only one abbr list
1737          break;
1738        }
1739        if (buf != NULL) {
1740          mp = buf->b_first_abbr;
1741        } else {
1742          mp = first_abbr;
1743        }
1744      } else {
1745        if (buf != NULL) {
1746          mp = buf->b_maphash[hash];
1747        } else {
1748          mp = maphash[hash];
1749        }
1750      }
1751
1752      for (; mp; mp = mp->m_next) {
1753        // simplified map blocks are not created explicitly
1754        if (mp->m_simplified) {
1755          continue;
1756        }
1757
1758        // skip script-local mappings
1759        if (mp->m_noremap == REMAP_SCRIPT) {
1760          continue;
1761        }
1762
1763        // skip Lua mappings and mappings that contain a <SNR> (script-local thing),
1764        // they probably don't work when loaded again
1765        if (mp->m_luaref != LUA_NOREF) {
1766          continue;
1767        }
1768        char *p;
1769        for (p = mp->m_str; *p != NUL; p++) {
1770          if ((uint8_t)p[0] == K_SPECIAL && (uint8_t)p[1] == KS_EXTRA
1771              && p[2] == KE_SNR) {
1772            break;
1773          }
1774        }
1775        if (*p != NUL) {
1776          continue;
1777        }
1778
1779        // It's possible to create a mapping and then ":unmap" certain
1780        // modes.  We recreate this here by mapping the individual
1781        // modes, which requires up to three of them.
1782        char c1 = NUL;
1783        char c2 = NUL;
1784        char c3 = NUL;
1785        char *cmd = abbr ? "abbr" : "map";
1786        switch (mp->m_mode) {
1787        case MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING:
1788          break;
1789        case MODE_NORMAL:
1790          c1 = 'n';
1791          break;
1792        case MODE_VISUAL:
1793          c1 = 'x';
1794          break;
1795        case MODE_SELECT:
1796          c1 = 's';
1797          break;
1798        case MODE_OP_PENDING:
1799          c1 = 'o';
1800          break;
1801        case MODE_NORMAL | MODE_VISUAL:
1802          c1 = 'n';
1803          c2 = 'x';
1804          break;
1805        case MODE_NORMAL | MODE_SELECT:
1806          c1 = 'n';
1807          c2 = 's';
1808          break;
1809        case MODE_NORMAL | MODE_OP_PENDING:
1810          c1 = 'n';
1811          c2 = 'o';
1812          break;
1813        case MODE_VISUAL | MODE_SELECT:
1814          c1 = 'v';
1815          break;
1816        case MODE_VISUAL | MODE_OP_PENDING:
1817          c1 = 'x';
1818          c2 = 'o';
1819          break;
1820        case MODE_SELECT | MODE_OP_PENDING:
1821          c1 = 's';
1822          c2 = 'o';
1823          break;
1824        case MODE_NORMAL | MODE_VISUAL | MODE_SELECT:
1825          c1 = 'n';
1826          c2 = 'v';
1827          break;
1828        case MODE_NORMAL | MODE_VISUAL | MODE_OP_PENDING:
1829          c1 = 'n';
1830          c2 = 'x';
1831          c3 = 'o';
1832          break;
1833        case MODE_NORMAL | MODE_SELECT | MODE_OP_PENDING:
1834          c1 = 'n';
1835          c2 = 's';
1836          c3 = 'o';
1837          break;
1838        case MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING:
1839          c1 = 'v';
1840          c2 = 'o';
1841          break;
1842        case MODE_CMDLINE | MODE_INSERT:
1843          if (!abbr) {
1844            cmd = "map!";
1845          }
1846          break;
1847        case MODE_CMDLINE:
1848          c1 = 'c';
1849          break;
1850        case MODE_INSERT:
1851          c1 = 'i';
1852          break;
1853        case MODE_LANGMAP:
1854          c1 = 'l';
1855          break;
1856        case MODE_TERMINAL:
1857          c1 = 't';
1858          break;
1859        default:
1860          iemsg(_("E228: makemap: Illegal mode"));
1861          return FAIL;
1862        }
1863        do {  // do this twice if c2 is set, 3 times with c3
1864          // When outputting <> form, need to make sure that 'cpo'
1865          // is set to the Vim default.
1866          if (!did_cpo) {
1867            if (*mp->m_str == NUL) {  // Will use <Nop>.
1868              did_cpo = true;
1869            } else {
1870              const char specials[] = { (char)(uint8_t)K_SPECIAL, NL, NUL };
1871              if (strpbrk(mp->m_str, specials) != NULL || strpbrk(mp->m_keys, specials) != NULL) {
1872                did_cpo = true;
1873              }
1874            }
1875            if (did_cpo) {
1876              if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1877                  || put_eol(fd) < 0
1878                  || fprintf(fd, "set cpo&vim") < 0
1879                  || put_eol(fd) < 0) {
1880                return FAIL;
1881              }
1882            }
1883          }
1884          if (c1 && putc(c1, fd) < 0) {
1885            return FAIL;
1886          }
1887          if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0) {
1888            return FAIL;
1889          }
1890          if (fputs(cmd, fd) < 0) {
1891            return FAIL;
1892          }
1893          if (buf != NULL && fputs(" <buffer>", fd) < 0) {
1894            return FAIL;
1895          }
1896          if (mp->m_nowait && fputs(" <nowait>", fd) < 0) {
1897            return FAIL;
1898          }
1899          if (mp->m_silent && fputs(" <silent>", fd) < 0) {
1900            return FAIL;
1901          }
1902          if (mp->m_expr && fputs(" <expr>", fd) < 0) {
1903            return FAIL;
1904          }
1905
1906          if (putc(' ', fd) < 0
1907              || put_escstr(fd, mp->m_keys, 0) == FAIL
1908              || putc(' ', fd) < 0
1909              || put_escstr(fd, mp->m_str, 1) == FAIL
1910              || put_eol(fd) < 0) {
1911            return FAIL;
1912          }
1913          c1 = c2;
1914          c2 = c3;
1915          c3 = NUL;
1916        } while (c1 != NUL);
1917      }
1918    }
1919  }
1920  if (did_cpo) {
1921    if (fprintf(fd, "let &cpo=s:cpo_save") < 0
1922        || put_eol(fd) < 0
1923        || fprintf(fd, "unlet s:cpo_save") < 0
1924        || put_eol(fd) < 0) {
1925      return FAIL;
1926    }
1927  }
1928  return OK;
1929}
1930
1931// write escape string to file
1932// "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
1933//
1934// return FAIL for failure, OK otherwise
1935int put_escstr(FILE *fd, const char *strstart, int what)
1936{
1937  uint8_t *str = (uint8_t *)strstart;
1938
1939  // :map xx <Nop>
1940  if (*str == NUL && what == 1) {
1941    if (fprintf(fd, "<Nop>") < 0) {
1942      return FAIL;
1943    }
1944    return OK;
1945  }
1946
1947  for (; *str != NUL; str++) {
1948    // Check for a multi-byte character, which may contain escaped
1949    // K_SPECIAL bytes.
1950    const char *p = mb_unescape((const char **)&str);
1951    if (p != NULL) {
1952      while (*p != NUL) {
1953        if (fputc(*p++, fd) < 0) {
1954          return FAIL;
1955        }
1956      }
1957      str--;
1958      continue;
1959    }
1960
1961    int c = *str;
1962    // Special key codes have to be translated to be able to make sense
1963    // when they are read back.
1964    if (c == K_SPECIAL && what != 2) {
1965      int modifiers = 0;
1966      if (str[1] == KS_MODIFIER) {
1967        modifiers = str[2];
1968        str += 3;
1969
1970        // Modifiers can be applied too to multi-byte characters.
1971        p = mb_unescape((const char **)&str);
1972
1973        if (p == NULL) {
1974          c = *str;
1975        } else {
1976          // retrieve codepoint (character number) from unescaped string
1977          c = utf_ptr2char(p);
1978          str--;
1979        }
1980      }
1981      if (c == K_SPECIAL) {
1982        c = TO_SPECIAL(str[1], str[2]);
1983        str += 2;
1984      }
1985      if (IS_SPECIAL(c) || modifiers) {         // special key
1986        if (fputs(get_special_key_name(c, modifiers), fd) < 0) {
1987          return FAIL;
1988        }
1989        continue;
1990      }
1991    }
1992
1993    // A '\n' in a map command should be written as <NL>.
1994    // A '\n' in a set command should be written as \^V^J.
1995    if (c == NL) {
1996      if (what == 2) {
1997        if (fprintf(fd, "\\\026\n") < 0) {
1998          return FAIL;
1999        }
2000      } else {
2001        if (fprintf(fd, "<NL>") < 0) {
2002          return FAIL;
2003        }
2004      }
2005      continue;
2006    }
2007
2008    // Some characters have to be escaped with CTRL-V to
2009    // prevent them from misinterpreted in DoOneCmd().
2010    // A space, Tab and '"' has to be escaped with a backslash to
2011    // prevent it to be misinterpreted in do_set().
2012    // A space has to be escaped with a CTRL-V when it's at the start of a
2013    // ":map" rhs.
2014    // A '<' has to be escaped with a CTRL-V to prevent it being
2015    // interpreted as the start of a special key name.
2016    // A space in the lhs of a :map needs a CTRL-V.
2017    if (what == 2 && (ascii_iswhite(c) || c == '"' || c == '\\')) {
2018      if (putc('\\', fd) < 0) {
2019        return FAIL;
2020      }
2021    } else if (c < ' ' || c > '~' || c == '|'
2022               || (what == 0 && c == ' ')
2023               || (what == 1 && str == (uint8_t *)strstart && c == ' ')
2024               || (what != 2 && c == '<')) {
2025      if (putc(Ctrl_V, fd) < 0) {
2026        return FAIL;
2027      }
2028    }
2029    if (putc(c, fd) < 0) {
2030      return FAIL;
2031    }
2032  }
2033  return OK;
2034}
2035
2036/// Check the string "keys" against the lhs of all mappings.
2037/// Return pointer to rhs of mapping (mapblock->m_str).
2038/// NULL when no mapping found.
2039///
2040/// @param exact  require exact match
2041/// @param ign_mod  ignore preceding modifier
2042/// @param abbr  do abbreviations
2043/// @param mp_ptr  return: pointer to mapblock or NULL
2044/// @param local_ptr  return: buffer-local mapping or NULL
2045char *check_map(char *keys, int mode, int exact, int ign_mod, int abbr, mapblock_T **mp_ptr,
2046                int *local_ptr, int *rhs_lua)
2047{
2048  *rhs_lua = LUA_NOREF;
2049
2050  int len = (int)strlen(keys);
2051  for (int local = 1; local >= 0; local--) {
2052    // loop over all hash lists
2053    for (int hash = 0; hash < 256; hash++) {
2054      mapblock_T *mp;
2055      if (abbr) {
2056        if (hash > 0) {                 // there is only one list.
2057          break;
2058        }
2059        if (local) {
2060          mp = curbuf->b_first_abbr;
2061        } else {
2062          mp = first_abbr;
2063        }
2064      } else if (local) {
2065        mp = curbuf->b_maphash[hash];
2066      } else {
2067        mp = maphash[hash];
2068      }
2069      for (; mp != NULL; mp = mp->m_next) {
2070        // skip entries with wrong mode, wrong length and not matching ones
2071        if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len)) {
2072          char *s = mp->m_keys;
2073          int keylen = mp->m_keylen;
2074          if (ign_mod && keylen >= 3
2075              && (uint8_t)s[0] == K_SPECIAL && (uint8_t)s[1] == KS_MODIFIER) {
2076            s += 3;
2077            keylen -= 3;
2078          }
2079          int minlen = keylen < len ? keylen : len;
2080          if (strncmp(s, keys, (size_t)minlen) == 0) {
2081            if (mp_ptr != NULL) {
2082              *mp_ptr = mp;
2083            }
2084            if (local_ptr != NULL) {
2085              *local_ptr = local;
2086            }
2087            *rhs_lua = mp->m_luaref;
2088            return mp->m_luaref == LUA_NOREF ? mp->m_str : NULL;
2089          }
2090        }
2091      }
2092    }
2093  }
2094
2095  return NULL;
2096}
2097
2098/// "hasmapto()" function
2099void f_hasmapto(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2100{
2101  const char *mode;
2102  const char *const name = tv_get_string(&argvars[0]);
2103  bool abbr = false;
2104  char buf[NUMBUFLEN];
2105  if (argvars[1].v_type == VAR_UNKNOWN) {
2106    mode = "nvo";
2107  } else {
2108    mode = tv_get_string_buf(&argvars[1], buf);
2109    if (argvars[2].v_type != VAR_UNKNOWN) {
2110      abbr = tv_get_bool(&argvars[2]);
2111    }
2112  }
2113
2114  rettv->vval.v_number = map_to_exists(name, mode, abbr);
2115}
2116
2117/// Fill a Dict with all applicable maparg() like dictionaries
2118///
2119/// @param mp            The maphash that contains the mapping information
2120/// @param buffer_value  The "buffer" value
2121/// @param abbr          True if abbreviation
2122/// @param compatible    True for compatible with old maparg() dict
2123///
2124/// @return  Dict.
2125static Dict mapblock_fill_dict(const mapblock_T *const mp, const char *lhsrawalt,
2126                               const int buffer_value, const bool abbr, const bool compatible,
2127                               Arena *arena)
2128  FUNC_ATTR_NONNULL_ARG(1)
2129{
2130  Dict dict = arena_dict(arena, 20);
2131  char *const lhs = str2special_arena(mp->m_keys, compatible, compatible ? kFalse : kNone, arena);
2132  char *mapmode = arena_alloc(arena, 7, false);
2133  map_mode_to_chars(mp->m_mode, mapmode);
2134  int noremap_value;
2135
2136  if (compatible) {
2137    // Keep old compatible behavior
2138    // This is unable to determine whether a mapping is a <script> mapping
2139    noremap_value = !!mp->m_noremap;
2140  } else {
2141    // Distinguish between <script> mapping
2142    // If it's not a <script> mapping, check if it's a noremap
2143    noremap_value = mp->m_noremap == REMAP_SCRIPT ? 2 : !!mp->m_noremap;
2144  }
2145
2146  if (mp->m_luaref != LUA_NOREF) {
2147    PUT_C(dict, "callback", LUAREF_OBJ(api_new_luaref(mp->m_luaref)));
2148  } else {
2149    String rhs = cstr_as_string(compatible
2150                                ? mp->m_orig_str
2151                                : str2special_arena(mp->m_str, false, kNone, arena));
2152    PUT_C(dict, "rhs", STRING_OBJ(rhs));
2153  }
2154  if (mp->m_desc != NULL) {
2155    PUT_C(dict, "desc", CSTR_AS_OBJ(mp->m_desc));
2156  }
2157  PUT_C(dict, "lhs", CSTR_AS_OBJ(lhs));
2158  PUT_C(dict, "lhsraw", CSTR_AS_OBJ(mp->m_keys));
2159  if (lhsrawalt != NULL) {
2160    // Also add the value for the simplified entry.
2161    PUT_C(dict, "lhsrawalt", CSTR_AS_OBJ(lhsrawalt));
2162  }
2163  PUT_C(dict, "noremap", INTEGER_OBJ(noremap_value));
2164  PUT_C(dict, "script", INTEGER_OBJ(mp->m_noremap == REMAP_SCRIPT ? 1 : 0));
2165  PUT_C(dict, "expr", INTEGER_OBJ(mp->m_expr ? 1 : 0));
2166  PUT_C(dict, "silent", INTEGER_OBJ(mp->m_silent ? 1 : 0));
2167  PUT_C(dict, "sid", INTEGER_OBJ(mp->m_script_ctx.sc_sid));
2168  PUT_C(dict, "scriptversion", INTEGER_OBJ(1));
2169  PUT_C(dict, "lnum", INTEGER_OBJ(mp->m_script_ctx.sc_lnum));
2170  PUT_C(dict, "buffer", INTEGER_OBJ(buffer_value));
2171  if (!compatible) {
2172    PUT_C(dict, "buf", INTEGER_OBJ(buffer_value));
2173  }
2174  PUT_C(dict, "nowait", INTEGER_OBJ(mp->m_nowait ? 1 : 0));
2175  PUT_C(dict, "replace_keycodes", INTEGER_OBJ(mp->m_replace_keycodes ? 1 : 0));
2176  PUT_C(dict, "mode", CSTR_AS_OBJ(mapmode));
2177  PUT_C(dict, "abbr", INTEGER_OBJ(abbr ? 1 : 0));
2178  PUT_C(dict, "mode_bits", INTEGER_OBJ(mp->m_mode));
2179
2180  return dict;
2181}
2182
2183static void get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2184{
2185  // Return empty string for failure.
2186  rettv->v_type = VAR_STRING;
2187  rettv->vval.v_string = NULL;
2188
2189  char *keys = (char *)tv_get_string(&argvars[0]);
2190  if (*keys == NUL) {
2191    return;
2192  }
2193
2194  const char *which;
2195  char buf[NUMBUFLEN];
2196  bool abbr = false;
2197  bool get_dict = false;
2198
2199  if (argvars[1].v_type != VAR_UNKNOWN) {
2200    which = tv_get_string_buf_chk(&argvars[1], buf);
2201    if (argvars[2].v_type != VAR_UNKNOWN) {
2202      abbr = (bool)tv_get_bool(&argvars[2]);
2203      if (argvars[3].v_type != VAR_UNKNOWN) {
2204        get_dict = (bool)tv_get_bool(&argvars[3]);
2205      }
2206    }
2207  } else {
2208    which = "";
2209  }
2210  if (which == NULL) {
2211    return;
2212  }
2213
2214  char *keys_buf = NULL;
2215  char *alt_keys_buf = NULL;
2216  bool did_simplify = false;
2217  const int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
2218  const int mode = get_map_mode((char **)&which, 0);
2219
2220  char *keys_simplified = replace_termcodes(keys, strlen(keys), &keys_buf, 0,
2221                                            flags, &did_simplify, p_cpo);
2222  mapblock_T *mp = NULL;
2223  int buffer_local;
2224  LuaRef rhs_lua;
2225  char *rhs = check_map(keys_simplified, mode, exact, false, abbr, &mp, &buffer_local,
2226                        &rhs_lua);
2227  if (did_simplify) {
2228    // When the lhs is being simplified the not-simplified keys are
2229    // preferred for printing, like in do_map().
2230    replace_termcodes(keys, strlen(keys), &alt_keys_buf, 0,
2231                      flags | REPTERM_NO_SIMPLIFY, NULL, p_cpo);
2232    rhs = check_map(alt_keys_buf, mode, exact, false, abbr, &mp, &buffer_local, &rhs_lua);
2233  }
2234
2235  if (!get_dict) {
2236    // Return a string.
2237    if (rhs != NULL) {
2238      if (*rhs == NUL) {
2239        rettv->vval.v_string = xstrdup("<Nop>");
2240      } else {
2241        rettv->vval.v_string = str2special_save(rhs, false, false);
2242      }
2243    } else if (rhs_lua != LUA_NOREF) {
2244      rettv->vval.v_string = nlua_funcref_str(mp->m_luaref, NULL, true);
2245    }
2246  } else {
2247    // Return a dictionary.
2248    if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF)) {
2249      Arena arena = ARENA_EMPTY;
2250      Dict dict = mapblock_fill_dict(mp, did_simplify ? keys_simplified : NULL,
2251                                     buffer_local, abbr, true, &arena);
2252      object_to_vim_take_luaref(&DICT_OBJ(dict), rettv, true, NULL);
2253      arena_mem_free(arena_finish(&arena));
2254    } else {
2255      // Return an empty dictionary.
2256      tv_dict_alloc_ret(rettv);
2257    }
2258  }
2259
2260  xfree(keys_buf);
2261  xfree(alt_keys_buf);
2262}
2263
2264/// Get the mapping mode from the mode string.
2265/// It may contain multiple characters, eg "nox", or "!", or ' '
2266/// Return 0 if there is an error.
2267static int get_map_mode_string(const char *const mode_string, const bool abbr)
2268{
2269  const char *p = mode_string;
2270  const int MASK_V = MODE_VISUAL | MODE_SELECT;
2271  const int MASK_MAP = MODE_VISUAL | MODE_SELECT | MODE_NORMAL | MODE_OP_PENDING;
2272  const int MASK_BANG = MODE_INSERT | MODE_CMDLINE;
2273
2274  if (*p == NUL) {
2275    p = " ";  // compatibility
2276  }
2277  int mode = 0;
2278  int modec;
2279  while ((modec = (uint8_t)(*p++))) {
2280    int tmode;
2281    switch (modec) {
2282    case 'i':
2283      tmode = MODE_INSERT; break;
2284    case 'l':
2285      tmode = MODE_LANGMAP; break;
2286    case 'c':
2287      tmode = MODE_CMDLINE; break;
2288    case 'n':
2289      tmode = MODE_NORMAL; break;
2290    case 'x':
2291      tmode = MODE_VISUAL; break;
2292    case 's':
2293      tmode = MODE_SELECT; break;
2294    case 'o':
2295      tmode = MODE_OP_PENDING; break;
2296    case 't':
2297      tmode = MODE_TERMINAL; break;
2298    case 'v':
2299      tmode = MASK_V; break;
2300    case '!':
2301      tmode = MASK_BANG; break;
2302    case ' ':
2303      tmode = MASK_MAP; break;
2304    default:
2305      return 0;  // error, unknown mode character
2306    }
2307    mode |= tmode;
2308  }
2309  if ((abbr && (mode & ~MASK_BANG) != 0)
2310      || (!abbr && (mode & (mode - 1)) != 0  // more than one bit set
2311          && (
2312              // false if multiple bits set in mode and mode is fully
2313              // contained in one mask
2314              !(((mode & MASK_BANG) != 0 && (mode & ~MASK_BANG) == 0)
2315                || ((mode & MASK_MAP) != 0 && (mode & ~MASK_MAP) == 0))))) {
2316    return 0;
2317  }
2318
2319  return mode;
2320}
2321
2322/// "mapset()" function
2323void f_mapset(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2324{
2325  if (check_secure()) {
2326    return;
2327  }
2328
2329  const char *which;
2330  char buf[NUMBUFLEN];
2331  int is_abbr;
2332  dict_T *d;
2333
2334  // If first arg is a dict, then that's the only arg permitted.
2335  const bool dict_only = argvars[0].v_type == VAR_DICT;
2336
2337  if (dict_only) {
2338    d = argvars[0].vval.v_dict;
2339    which = tv_dict_get_string(d, "mode", false);
2340    is_abbr = (int)tv_dict_get_bool(d, "abbr", -1);
2341    if (which == NULL || is_abbr < 0) {
2342      emsg(_(e_entries_missing_in_mapset_dict_argument));
2343      return;
2344    }
2345  } else {
2346    which = tv_get_string_buf_chk(&argvars[0], buf);
2347    if (which == NULL) {
2348      return;
2349    }
2350    is_abbr = (int)tv_get_bool(&argvars[1]);
2351    if (tv_check_for_dict_arg(argvars, 2) == FAIL) {
2352      return;
2353    }
2354    d = argvars[2].vval.v_dict;
2355  }
2356  const int mode = get_map_mode_string(which, is_abbr);
2357  if (mode == 0) {
2358    semsg(_(e_illegal_map_mode_string_str), which);
2359    return;
2360  }
2361
2362  // Get the values in the same order as above in get_maparg().
2363  char *lhs = tv_dict_get_string(d, "lhs", false);
2364  char *lhsraw = tv_dict_get_string(d, "lhsraw", false);
2365  char *lhsrawalt = tv_dict_get_string(d, "lhsrawalt", false);
2366  char *orig_rhs = tv_dict_get_string(d, "rhs", false);
2367  LuaRef rhs_lua = LUA_NOREF;
2368  dictitem_T *callback_di = tv_dict_find(d, S_LEN("callback"));
2369  if (callback_di != NULL) {
2370    if (callback_di->di_tv.v_type == VAR_FUNC) {
2371      ufunc_T *fp = find_func(callback_di->di_tv.vval.v_string);
2372      if (fp != NULL && (fp->uf_flags & FC_LUAREF)) {
2373        rhs_lua = api_new_luaref(fp->uf_luaref);
2374        orig_rhs = "";
2375      }
2376    }
2377  }
2378  if (lhs == NULL || lhsraw == NULL || orig_rhs == NULL) {
2379    emsg(_(e_entries_missing_in_mapset_dict_argument));
2380    api_free_luaref(rhs_lua);
2381    return;
2382  }
2383
2384  int noremap = tv_dict_get_number(d, "noremap") != 0 ? REMAP_NONE : 0;
2385  if (tv_dict_get_number(d, "script") != 0) {
2386    noremap = REMAP_SCRIPT;
2387  }
2388  MapArguments args = {
2389    .expr = tv_dict_get_number(d, "expr") != 0,
2390    .silent = tv_dict_get_number(d, "silent") != 0,
2391    .nowait = tv_dict_get_number(d, "nowait") != 0,
2392    .replace_keycodes = tv_dict_get_number(d, "replace_keycodes") != 0,
2393    .desc = tv_dict_get_string(d, "desc", true),
2394  };
2395  scid_T sid = (scid_T)tv_dict_get_number(d, "sid");
2396  linenr_T lnum = (linenr_T)tv_dict_get_number(d, "lnum");
2397  bool buffer = tv_dict_get_number(d, "buffer") != 0;
2398  // mode from the dict is not used
2399
2400  set_maparg_rhs(orig_rhs, strlen(orig_rhs), rhs_lua, sid, p_cpo, &args);
2401
2402  mapblock_T **map_table = buffer ? curbuf->b_maphash : maphash;
2403  mapblock_T **abbr_table = buffer ? &curbuf->b_first_abbr : &first_abbr;
2404
2405  // Delete any existing mapping for this lhs and mode.
2406  MapArguments unmap_args = MAP_ARGUMENTS_INIT;
2407  set_maparg_lhs_rhs(lhs, strlen(lhs), "", 0, LUA_NOREF, p_cpo, &unmap_args);
2408  unmap_args.buffer = buffer;
2409  buf_do_map(MAPTYPE_UNMAP_LHS, &unmap_args, mode, is_abbr, curbuf);
2410  xfree(unmap_args.rhs);
2411  xfree(unmap_args.orig_rhs);
2412
2413  mapblock_T *mp_result[2] = { NULL, NULL };
2414
2415  mp_result[0] = map_add(curbuf, map_table, abbr_table, lhsraw, &args,
2416                         noremap, mode, is_abbr, sid, lnum, false);
2417  if (lhsrawalt != NULL) {
2418    mp_result[1] = map_add(curbuf, map_table, abbr_table, lhsrawalt, &args,
2419                           noremap, mode, is_abbr, sid, lnum, true);
2420  }
2421
2422  if (mp_result[0] != NULL && mp_result[1] != NULL) {
2423    mp_result[0]->m_alt = mp_result[1];
2424    mp_result[1]->m_alt = mp_result[0];
2425  }
2426}
2427
2428/// "maplist()" function
2429void f_maplist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2430{
2431  const int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
2432  const bool abbr = argvars[0].v_type != VAR_UNKNOWN && tv_get_bool(&argvars[0]);
2433
2434  tv_list_alloc_ret(rettv, kListLenUnknown);
2435
2436  // Do it twice: once for global maps and once for local maps.
2437  for (int buffer_local = 0; buffer_local <= 1; buffer_local++) {
2438    for (int hash = 0; hash < 256; hash++) {
2439      mapblock_T *mp;
2440      if (abbr) {
2441        if (hash > 0) {  // there is only one abbr list
2442          break;
2443        }
2444        if (buffer_local) {
2445          mp = curbuf->b_first_abbr;
2446        } else {
2447          mp = first_abbr;
2448        }
2449      } else if (buffer_local) {
2450        mp = curbuf->b_maphash[hash];
2451      } else {
2452        mp = maphash[hash];
2453      }
2454      for (; mp; mp = mp->m_next) {
2455        if (mp->m_simplified) {
2456          continue;
2457        }
2458
2459        char *keys_buf = NULL;
2460        bool did_simplify = false;
2461
2462        Arena arena = ARENA_EMPTY;
2463        char *lhs = str2special_arena(mp->m_keys, true, false, &arena);
2464        replace_termcodes(lhs, strlen(lhs), &keys_buf, 0, flags, &did_simplify,
2465                          p_cpo);
2466
2467        Dict dict = mapblock_fill_dict(mp, did_simplify ? keys_buf : NULL, buffer_local, abbr, true,
2468                                       &arena);
2469        typval_T d = TV_INITIAL_VALUE;
2470        object_to_vim_take_luaref(&DICT_OBJ(dict), &d, true, NULL);
2471        assert(d.v_type == VAR_DICT);
2472        tv_list_append_dict(rettv->vval.v_list, d.vval.v_dict);
2473        arena_mem_free(arena_finish(&arena));
2474        xfree(keys_buf);
2475      }
2476    }
2477  }
2478}
2479
2480/// "maparg()" function
2481void f_maparg(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2482{
2483  get_maparg(argvars, rettv, true);
2484}
2485
2486/// "mapcheck()" function
2487void f_mapcheck(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2488{
2489  get_maparg(argvars, rettv, false);
2490}
2491
2492/// Add a mapping. Unlike @ref do_map this copies the string arguments, so
2493/// static or read-only strings can be used.
2494///
2495/// @param lhs  C-string containing the lhs of the mapping
2496/// @param rhs  C-string containing the rhs of the mapping
2497/// @param mode  Bitflags representing the mode in which to set the mapping.
2498///              See @ref get_map_mode.
2499/// @param buffer  If true, make a buffer-local mapping for curbuf
2500void add_map(char *lhs, char *rhs, int mode, bool buffer)
2501{
2502  MapArguments args = MAP_ARGUMENTS_INIT;
2503  set_maparg_lhs_rhs(lhs, strlen(lhs), rhs, strlen(rhs), LUA_NOREF, p_cpo, &args);
2504  args.buffer = buffer;
2505
2506  buf_do_map(MAPTYPE_NOREMAP, &args, mode, false, curbuf);
2507  xfree(args.rhs);
2508  xfree(args.orig_rhs);
2509}
2510
2511/// Any character has an equivalent 'langmap' character.  This is used for
2512/// keyboards that have a special language mode that sends characters above
2513/// 128 (although other characters can be translated too).  The "to" field is a
2514/// Vim command character.  This avoids having to switch the keyboard back to
2515/// ASCII mode when leaving Insert mode.
2516///
2517/// langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2518/// commands.
2519/// langmap_mapga.ga_data is a sorted table of langmap_entry_T.
2520/// This does the same as langmap_mapchar[] for characters >= 256.
2521///
2522/// With multi-byte support use growarray for 'langmap' chars >= 256
2523typedef struct {
2524  int from;
2525  int to;
2526} langmap_entry_T;
2527
2528static garray_T langmap_mapga = GA_EMPTY_INIT_VALUE;
2529
2530/// Search for an entry in "langmap_mapga" for "from".  If found set the "to"
2531/// field.  If not found insert a new entry at the appropriate location.
2532static void langmap_set_entry(int from, int to)
2533{
2534  langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2535  unsigned a = 0;
2536  assert(langmap_mapga.ga_len >= 0);
2537  unsigned b = (unsigned)langmap_mapga.ga_len;
2538
2539  // Do a binary search for an existing entry.
2540  while (a != b) {
2541    unsigned i = (a + b) / 2;
2542    int d = entries[i].from - from;
2543
2544    if (d == 0) {
2545      entries[i].to = to;
2546      return;
2547    }
2548    if (d < 0) {
2549      a = i + 1;
2550    } else {
2551      b = i;
2552    }
2553  }
2554
2555  ga_grow(&langmap_mapga, 1);
2556
2557  // insert new entry at position "a"
2558  entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2559  memmove(entries + 1, entries,
2560          ((unsigned)langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2561  langmap_mapga.ga_len++;
2562  entries[0].from = from;
2563  entries[0].to = to;
2564}
2565
2566/// Apply 'langmap' to multi-byte character "c" and return the result.
2567int langmap_adjust_mb(int c)
2568{
2569  langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2570  int a = 0;
2571  int b = langmap_mapga.ga_len;
2572
2573  while (a != b) {
2574    int i = (a + b) / 2;
2575    int d = entries[i].from - c;
2576
2577    if (d == 0) {
2578      return entries[i].to;        // found matching entry
2579    }
2580    if (d < 0) {
2581      a = i + 1;
2582    } else {
2583      b = i;
2584    }
2585  }
2586  return c;    // no entry found, return "c" unmodified
2587}
2588
2589void langmap_init(void)
2590{
2591  for (int i = 0; i < 256; i++) {
2592    langmap_mapchar[i] = (uint8_t)i;      // we init with a one-to-one map
2593  }
2594  ga_init(&langmap_mapga, sizeof(langmap_entry_T), 8);
2595}
2596
2597/// Called when langmap option is set; the language map can be
2598/// changed at any time!
2599const char *did_set_langmap(optset_T *args)
2600{
2601  ga_clear(&langmap_mapga);  // clear the previous map first
2602  langmap_init();            // back to one-to-one map
2603
2604  for (char *p = p_langmap; p[0] != NUL;) {
2605    char *p2;
2606    for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2607         MB_PTR_ADV(p2)) {
2608      if (p2[0] == '\\' && p2[1] != NUL) {
2609        p2++;
2610      }
2611    }
2612    if (p2[0] == ';') {
2613      p2++;                 // abcd;ABCD form, p2 points to A
2614    } else {
2615      p2 = NULL;            // aAbBcCdD form, p2 is NULL
2616    }
2617    while (p[0]) {
2618      if (p[0] == ',') {
2619        p++;
2620        break;
2621      }
2622      if (p[0] == '\\' && p[1] != NUL) {
2623        p++;
2624      }
2625      int from = utf_ptr2char(p);
2626      const char *const from_ptr = p;
2627      int to = NUL;
2628      const char *to_ptr = "";
2629      if (p2 == NULL) {
2630        MB_PTR_ADV(p);
2631        if (p[0] != ',') {
2632          if (p[0] == '\\') {
2633            p++;
2634          }
2635          to = utf_ptr2char(to_ptr = p);
2636        }
2637      } else {
2638        if (p2[0] != ',') {
2639          if (p2[0] == '\\') {
2640            p2++;
2641          }
2642          to = utf_ptr2char(to_ptr = p2);
2643        }
2644      }
2645      if (to == NUL) {
2646        return opt_error(args->os_errbuf, N_("E357: 'langmap': Matching character missing for %s"),
2647                         transchar(from));
2648      }
2649
2650      if (from >= 256) {
2651        langmap_set_entry(from, to);
2652      } else {
2653        if (to > UCHAR_MAX) {
2654          swmsg(true, "'langmap': Mapping from %.*s to %.*s will not work properly",
2655                utf_ptr2len(from_ptr), from_ptr, utf_ptr2len(to_ptr), to_ptr);
2656        }
2657        langmap_mapchar[from & 255] = (uint8_t)to;
2658      }
2659
2660      // Advance to next pair
2661      MB_PTR_ADV(p);
2662      if (p2 != NULL) {
2663        MB_PTR_ADV(p2);
2664        if (*p == ';') {
2665          p = p2;
2666          if (p[0] != NUL) {
2667            if (p[0] != ',') {
2668              return opt_error(args->os_errbuf,
2669                               N_("E358: 'langmap': Extra characters after semicolon: %s"), p);
2670            }
2671            p++;
2672          }
2673          break;
2674        }
2675      }
2676    }
2677  }
2678
2679  return NULL;
2680}
2681
2682static void do_exmap(exarg_T *eap, int isabbrev)
2683{
2684  char *cmdp = eap->cmd;
2685  int mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2686
2687  int maptype;
2688  if (*cmdp == 'n') {
2689    maptype = MAPTYPE_NOREMAP;
2690  } else if (*cmdp == 'u') {
2691    maptype = MAPTYPE_UNMAP;
2692  } else {
2693    maptype = MAPTYPE_MAP;
2694  }
2695  MapArguments parsed_args;
2696  int result = str_to_mapargs(eap->arg, maptype == MAPTYPE_UNMAP, &parsed_args);
2697  switch (result) {
2698  case 0:
2699    break;
2700  case 1:
2701    emsg(_(e_invarg));
2702    goto free_rhs;
2703    break;
2704  default:
2705    assert(false && "Unknown return code from str_to_mapargs!");
2706    goto free_rhs;
2707  }
2708  switch (buf_do_map(maptype, &parsed_args, mode, isabbrev, curbuf)) {
2709  case 1:
2710    emsg(_(e_invarg));
2711    break;
2712  case 2:
2713    emsg(isabbrev ? _(e_noabbr) : _(e_nomap));
2714    break;
2715  case 5:
2716    semsg(isabbrev ? _(e_abbreviation_already_exists_for_str)
2717                   : _(e_mapping_already_exists_for_str),
2718          parsed_args.lhs);
2719    break;
2720  case 6:
2721    semsg(isabbrev ? _(e_global_abbreviation_already_exists_for_str)
2722                   : _(e_global_mapping_already_exists_for_str),
2723          parsed_args.lhs);
2724  }
2725free_rhs:
2726  xfree(parsed_args.rhs);
2727  xfree(parsed_args.orig_rhs);
2728}
2729
2730/// ":abbreviate" and friends.
2731void ex_abbreviate(exarg_T *eap)
2732{
2733  do_exmap(eap, true);          // almost the same as mapping
2734}
2735
2736/// ":map" and friends.
2737void ex_map(exarg_T *eap)
2738{
2739  // If we are in a secure mode we print the mappings for security reasons.
2740  if (secure) {
2741    secure = 2;
2742    msg_outtrans(eap->cmd, 0, false);
2743    msg_putchar('\n');
2744  }
2745  do_exmap(eap, false);
2746}
2747
2748/// ":unmap" and friends.
2749void ex_unmap(exarg_T *eap)
2750{
2751  do_exmap(eap, false);
2752}
2753
2754/// ":mapclear" and friends.
2755void ex_mapclear(exarg_T *eap)
2756{
2757  do_mapclear(eap->cmd, eap->arg, eap->forceit, false);
2758}
2759
2760/// ":abclear" and friends.
2761void ex_abclear(exarg_T *eap)
2762{
2763  do_mapclear(eap->cmd, eap->arg, true, true);
2764}
2765
2766/// Set, tweak, or remove a mapping in a mode. Acts as the implementation for
2767/// functions like @ref nvim_buf_set_keymap.
2768///
2769/// Arguments are handled like @ref nvim_set_keymap unless noted.
2770/// @param  buffer    Buffer handle for a specific buffer, or 0 for the current
2771///                   buffer, or -1 to signify global behavior ("all buffers")
2772/// @param  maptype   MAPTYPE_MAP to set a mapping, MAPTYPE_UNMAP to remove the mapping that
2773///                   matches {lhs} or {rhs}, MAPTYPE_UNMAP_LHS to only match {lhs}.
2774void modify_keymap(uint64_t channel_id, Buffer buffer, int maptype, String mode, String lhs,
2775                   String rhs, Dict(keymap) *opts, Error *err)
2776{
2777  LuaRef lua_funcref = LUA_NOREF;
2778  bool is_unmap = maptype == MAPTYPE_UNMAP || maptype == MAPTYPE_UNMAP_LHS;
2779  bool global = (buffer == -1);
2780  if (global) {
2781    buffer = 0;
2782  }
2783  buf_T *target_buf = find_buffer_by_handle(buffer, err);
2784
2785  if (!target_buf) {
2786    return;
2787  }
2788
2789  const sctx_T save_current_sctx = api_set_sctx(channel_id);
2790
2791  MapArguments parsed_args = MAP_ARGUMENTS_INIT;
2792  if (opts) {
2793    parsed_args.nowait = opts->nowait;
2794    parsed_args.noremap = opts->noremap;
2795    parsed_args.silent = opts->silent;
2796    parsed_args.script = opts->script;
2797    parsed_args.expr = opts->expr;
2798    parsed_args.unique = opts->unique;
2799    parsed_args.replace_keycodes = opts->replace_keycodes;
2800    if (HAS_KEY(opts, keymap, callback)) {
2801      lua_funcref = opts->callback;
2802      opts->callback = LUA_NOREF;
2803    }
2804    if (HAS_KEY(opts, keymap, desc)) {
2805      parsed_args.desc = string_to_cstr(opts->desc);
2806    }
2807  }
2808  parsed_args.buffer = !global;
2809
2810  if (parsed_args.replace_keycodes && !parsed_args.expr) {
2811    api_set_error(err, kErrorTypeValidation,  "\"replace_keycodes\" requires \"expr\"");
2812    goto fail_and_free;
2813  }
2814
2815  if (!set_maparg_lhs_rhs(lhs.data, lhs.size,
2816                          rhs.data, rhs.size, lua_funcref,
2817                          p_cpo, &parsed_args)) {
2818    api_set_error(err, kErrorTypeValidation,  "LHS exceeds maximum map length: %s", lhs.data);
2819    goto fail_and_free;
2820  }
2821
2822  if (parsed_args.lhs_len > MAXMAPLEN || parsed_args.alt_lhs_len > MAXMAPLEN) {
2823    api_set_error(err, kErrorTypeValidation,  "LHS exceeds maximum map length: %s", lhs.data);
2824    goto fail_and_free;
2825  }
2826
2827  char *p = mode.size > 0 ? mode.data : "m";
2828  bool forceit = *p == '!';
2829  // integer value of the mapping mode, to be passed to do_map()
2830  int mode_val = get_map_mode(&p, forceit);
2831  if (forceit) {
2832    assert(p == mode.data);
2833    p++;
2834  }
2835  bool is_abbrev = (mode_val & (MODE_INSERT | MODE_CMDLINE)) != 0 && *p == 'a';
2836  if (is_abbrev) {
2837    p++;
2838  }
2839  if (mode.size > 0 && (size_t)(p - mode.data) != mode.size) {
2840    api_set_error(err, kErrorTypeValidation, "Invalid mode shortname: \"%s\"", mode.data);
2841    goto fail_and_free;
2842  }
2843
2844  if (parsed_args.lhs_len == 0) {
2845    api_set_error(err, kErrorTypeValidation, "Invalid (empty) LHS");
2846    goto fail_and_free;
2847  }
2848
2849  bool is_noremap = parsed_args.noremap;
2850  assert(!(is_unmap && is_noremap));
2851
2852  if (!is_unmap && lua_funcref == LUA_NOREF
2853      && (parsed_args.rhs_len == 0 && !parsed_args.rhs_is_noop)) {
2854    if (rhs.size == 0) {  // assume that the user wants RHS to be a <Nop>
2855      parsed_args.rhs_is_noop = true;
2856    } else {
2857      abort();  // should never happen
2858    }
2859  } else if (is_unmap && (parsed_args.rhs_len || parsed_args.rhs_lua != LUA_NOREF)) {
2860    if (parsed_args.rhs_len) {
2861      api_set_error(err, kErrorTypeValidation,
2862                    "Gave nonempty RHS in unmap command: %s", parsed_args.rhs);
2863    } else {
2864      api_set_error(err, kErrorTypeValidation, "Gave nonempty RHS for unmap");
2865    }
2866    goto fail_and_free;
2867  }
2868
2869  // buf_do_map() reads noremap/unmap as its own argument.
2870  if (maptype == MAPTYPE_MAP && is_noremap) {
2871    maptype = MAPTYPE_NOREMAP;
2872  }
2873
2874  switch (buf_do_map(maptype, &parsed_args, mode_val, is_abbrev, target_buf)) {
2875  case 0:
2876    break;
2877  case 1:
2878    api_set_error(err, kErrorTypeException, e_invarg, 0);
2879    goto fail_and_free;
2880  case 2:
2881    api_set_error(err, kErrorTypeException, e_nomap, 0);
2882    goto fail_and_free;
2883  case 5:
2884    api_set_error(err, kErrorTypeException,
2885                  is_abbrev ? e_abbreviation_already_exists_for_str
2886                            : e_mapping_already_exists_for_str, lhs.data);
2887    goto fail_and_free;
2888    break;
2889  case 6:
2890    api_set_error(err, kErrorTypeException,
2891                  is_abbrev ? e_global_abbreviation_already_exists_for_str
2892                            : e_global_mapping_already_exists_for_str, lhs.data);
2893    goto fail_and_free;
2894  default:
2895    assert(false && "Unrecognized return code!");
2896    goto fail_and_free;
2897  }  // switch
2898
2899fail_and_free:
2900  current_sctx = save_current_sctx;
2901  NLUA_CLEAR_REF(parsed_args.rhs_lua);
2902  xfree(parsed_args.rhs);
2903  xfree(parsed_args.orig_rhs);
2904  xfree(parsed_args.desc);
2905}
2906
2907/// Get an array containing dictionaries describing mappings
2908/// based on mode and buffer id
2909///
2910/// @param  mode  The abbreviation for the mode
2911/// @param  buf  The buffer to get the mapping array. NULL for global
2912/// @returns Array of maparg()-like dictionaries describing mappings
2913ArrayOf(Dict) keymap_array(String mode, buf_T *buf, Arena *arena)
2914{
2915  ArrayBuilder mappings = KV_INITIAL_VALUE;
2916  kvi_init(mappings);
2917
2918  char *p = mode.size > 0 ? mode.data : "m";
2919  bool forceit = *p == '!';
2920  // Convert the string mode to the integer mode stored within each mapblock.
2921  int int_mode = get_map_mode(&p, forceit);
2922  if (forceit) {
2923    assert(p == mode.data);
2924    p++;
2925  }
2926  bool is_abbrev = (int_mode & (MODE_INSERT | MODE_CMDLINE)) != 0 && *p == 'a';
2927
2928  // Determine the desired buffer value
2929  int buffer_value = (buf == NULL) ? 0 : buf->handle;
2930
2931  for (int i = 0; i < (is_abbrev ? 1 : MAX_MAPHASH); i++) {
2932    for (const mapblock_T *current_maphash = is_abbrev
2933                                             ? (buf ? buf->b_first_abbr : first_abbr)
2934                                             : (buf ? buf->b_maphash[i] : maphash[i]);
2935         current_maphash;
2936         current_maphash = current_maphash->m_next) {
2937      if (current_maphash->m_simplified) {
2938        continue;
2939      }
2940      // Check for correct mode
2941      if (int_mode & current_maphash->m_mode) {
2942        kvi_push(mappings, DICT_OBJ(mapblock_fill_dict(current_maphash,
2943                                                       current_maphash->m_alt
2944                                                       ? current_maphash->m_alt->m_keys : NULL,
2945                                                       buffer_value,
2946                                                       is_abbrev, false, arena)));
2947      }
2948    }
2949  }
2950
2951  return arena_take_arraybuilder(arena, &mappings);
2952}