robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
31.0 KiB925 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <limits.h>
4#include <stdbool.h>
5#include <stdio.h>
6#include <string.h>
7#include <uv.h>
8
9#include "nvim/api/private/defs.h"
10#include "nvim/ascii_defs.h"
11#include "nvim/charset.h"
12#include "nvim/errors.h"
13#include "nvim/eval/typval_defs.h"
14#include "nvim/eval/vars.h"
15#include "nvim/gettext_defs.h"
16#include "nvim/globals.h"
17#include "nvim/keycodes.h"
18#include "nvim/macros_defs.h"
19#include "nvim/mbyte.h"
20#include "nvim/mbyte_defs.h"
21#include "nvim/memory.h"
22#include "nvim/message.h"
23#include "nvim/mouse.h"
24#include "nvim/option_vars.h"
25#include "nvim/strings.h"
26
27#include "keycode_names.generated.h"
28#include "keycodes.c.generated.h"
29
30// Some useful tables.
31const struct modmasktable mod_mask_table[] = {
32  { MOD_MASK_ALT,              MOD_MASK_ALT,           'M' },
33  { MOD_MASK_META,             MOD_MASK_META,          'T' },
34  { MOD_MASK_CTRL,             MOD_MASK_CTRL,          'C' },
35  { MOD_MASK_SHIFT,            MOD_MASK_SHIFT,         'S' },
36  { MOD_MASK_MULTI_CLICK,      MOD_MASK_2CLICK,        '2' },
37  { MOD_MASK_MULTI_CLICK,      MOD_MASK_3CLICK,        '3' },
38  { MOD_MASK_MULTI_CLICK,      MOD_MASK_4CLICK,        '4' },
39  { MOD_MASK_CMD,              MOD_MASK_CMD,           'D' },
40  // 'A' must be the last one
41  { MOD_MASK_ALT,              MOD_MASK_ALT,           'A' },
42  { 0, 0, NUL }
43  // NOTE: when adding an entry, update MAX_KEY_NAME_LEN!
44};
45
46// Shifted key terminal codes and their unshifted equivalent.
47// Don't add mouse codes here, they are handled separately!
48
49#define MOD_KEYS_ENTRY_SIZE 5
50
51static uint8_t modifier_keys_table[] = {
52  //  mod mask      with modifier               without modifier
53  MOD_MASK_SHIFT, '&', '9',                   '@', '1',         // begin
54  MOD_MASK_SHIFT, '&', '0',                   '@', '2',         // cancel
55  MOD_MASK_SHIFT, '*', '1',                   '@', '4',         // command
56  MOD_MASK_SHIFT, '*', '2',                   '@', '5',         // copy
57  MOD_MASK_SHIFT, '*', '3',                   '@', '6',         // create
58  MOD_MASK_SHIFT, '*', '4',                   'k', 'D',         // delete char
59  MOD_MASK_SHIFT, '*', '5',                   'k', 'L',         // delete line
60  MOD_MASK_SHIFT, '*', '7',                   '@', '7',         // end
61  MOD_MASK_CTRL,  KS_EXTRA, KE_C_END,         '@', '7',         // end
62  MOD_MASK_SHIFT, '*', '9',                   '@', '9',         // exit
63  MOD_MASK_SHIFT, '*', '0',                   '@', '0',         // find
64  MOD_MASK_SHIFT, '#', '1',                   '%', '1',         // help
65  MOD_MASK_SHIFT, '#', '2',                   'k', 'h',         // home
66  MOD_MASK_CTRL,  KS_EXTRA, KE_C_HOME,        'k', 'h',         // home
67  MOD_MASK_SHIFT, '#', '3',                   'k', 'I',         // insert
68  MOD_MASK_SHIFT, '#', '4',                   'k', 'l',         // left arrow
69  MOD_MASK_CTRL,  KS_EXTRA, KE_C_LEFT,        'k', 'l',         // left arrow
70  MOD_MASK_SHIFT, '%', 'a',                   '%', '3',         // message
71  MOD_MASK_SHIFT, '%', 'b',                   '%', '4',         // move
72  MOD_MASK_SHIFT, '%', 'c',                   '%', '5',         // next
73  MOD_MASK_SHIFT, '%', 'd',                   '%', '7',         // options
74  MOD_MASK_SHIFT, '%', 'e',                   '%', '8',         // previous
75  MOD_MASK_SHIFT, '%', 'f',                   '%', '9',         // print
76  MOD_MASK_SHIFT, '%', 'g',                   '%', '0',         // redo
77  MOD_MASK_SHIFT, '%', 'h',                   '&', '3',         // replace
78  MOD_MASK_SHIFT, '%', 'i',                   'k', 'r',         // right arr.
79  MOD_MASK_CTRL,  KS_EXTRA, KE_C_RIGHT,       'k', 'r',         // right arr.
80  MOD_MASK_SHIFT, '%', 'j',                   '&', '5',         // resume
81  MOD_MASK_SHIFT, '!', '1',                   '&', '6',         // save
82  MOD_MASK_SHIFT, '!', '2',                   '&', '7',         // suspend
83  MOD_MASK_SHIFT, '!', '3',                   '&', '8',         // undo
84  MOD_MASK_SHIFT, KS_EXTRA, KE_S_UP,          'k', 'u',         // up arrow
85  MOD_MASK_SHIFT, KS_EXTRA, KE_S_DOWN,        'k', 'd',         // down arrow
86
87  // vt100 F1
88  MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF1,         KS_EXTRA, KE_XF1,
89  MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF2,         KS_EXTRA, KE_XF2,
90  MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF3,         KS_EXTRA, KE_XF3,
91  MOD_MASK_SHIFT, KS_EXTRA, KE_S_XF4,         KS_EXTRA, KE_XF4,
92
93  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F1,          'k', '1',         // F1
94  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F2,          'k', '2',
95  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F3,          'k', '3',
96  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F4,          'k', '4',
97  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F5,          'k', '5',
98  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F6,          'k', '6',
99  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F7,          'k', '7',
100  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F8,          'k', '8',
101  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F9,          'k', '9',
102  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F10,         'k', ';',         // F10
103
104  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F11,         'F', '1',
105  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F12,         'F', '2',
106  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F13,         'F', '3',
107  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F14,         'F', '4',
108  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F15,         'F', '5',
109  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F16,         'F', '6',
110  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F17,         'F', '7',
111  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F18,         'F', '8',
112  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F19,         'F', '9',
113  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F20,         'F', 'A',
114
115  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F21,         'F', 'B',
116  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F22,         'F', 'C',
117  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F23,         'F', 'D',
118  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F24,         'F', 'E',
119  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F25,         'F', 'F',
120  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F26,         'F', 'G',
121  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F27,         'F', 'H',
122  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F28,         'F', 'I',
123  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F29,         'F', 'J',
124  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F30,         'F', 'K',
125
126  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F31,         'F', 'L',
127  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F32,         'F', 'M',
128  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F33,         'F', 'N',
129  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F34,         'F', 'O',
130  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F35,         'F', 'P',
131  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F36,         'F', 'Q',
132  MOD_MASK_SHIFT, KS_EXTRA, KE_S_F37,         'F', 'R',
133
134  // TAB pseudo code
135  MOD_MASK_SHIFT, 'k', 'B',                   KS_EXTRA, KE_TAB,
136
137  NUL
138};
139
140static struct mousetable {
141  int pseudo_code;            // Code for pseudo mouse event
142  int button;                 // Which mouse button is it?
143  bool is_click;              // Is it a mouse button click event?
144  bool is_drag;               // Is it a mouse drag event?
145} mouse_table[] = {
146  { KE_LEFTMOUSE,        MOUSE_LEFT,     true,   false },
147  { KE_LEFTDRAG,         MOUSE_LEFT,     false,  true },
148  { KE_LEFTRELEASE,      MOUSE_LEFT,     false,  false },
149  { KE_MIDDLEMOUSE,      MOUSE_MIDDLE,   true,   false },
150  { KE_MIDDLEDRAG,       MOUSE_MIDDLE,   false,  true },
151  { KE_MIDDLERELEASE,    MOUSE_MIDDLE,   false,  false },
152  { KE_RIGHTMOUSE,       MOUSE_RIGHT,    true,   false },
153  { KE_RIGHTDRAG,        MOUSE_RIGHT,    false,  true },
154  { KE_RIGHTRELEASE,     MOUSE_RIGHT,    false,  false },
155  { KE_X1MOUSE,          MOUSE_X1,       true,   false },
156  { KE_X1DRAG,           MOUSE_X1,       false,  true },
157  { KE_X1RELEASE,        MOUSE_X1,       false,  false },
158  { KE_X2MOUSE,          MOUSE_X2,       true,   false },
159  { KE_X2DRAG,           MOUSE_X2,       false,  true },
160  { KE_X2RELEASE,        MOUSE_X2,       false,  false },
161  // DRAG without CLICK
162  { KE_MOUSEMOVE,        MOUSE_RELEASE,  false,  true },
163  // RELEASE without CLICK
164  { KE_IGNORE,           MOUSE_RELEASE,  false,  false },
165  { 0,                   0,              0,      0 },
166};
167
168/// Return the modifier mask bit (#MOD_MASK_*) corresponding to mod name
169///
170/// E.g. 'S' for shift, 'C' for ctrl.
171int name_to_mod_mask(int c)
172  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
173{
174  c = TOUPPER_ASC(c);
175  for (size_t i = 0; mod_mask_table[i].mod_mask != 0; i++) {
176    if (c == (uint8_t)mod_mask_table[i].name) {
177      return mod_mask_table[i].mod_flag;
178    }
179  }
180  return 0;
181}
182
183/// Check if there is a special key code for "key" with specified modifiers
184///
185/// @param[in]  key  Initial key code.
186/// @param[in,out]  modifiers  Initial modifiers, is adjusted to have simplified
187///                            modifiers.
188///
189/// @return Simplified key code.
190int simplify_key(const int key, int *modifiers)
191  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
192{
193  if (!(*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL))) {
194    return key;
195  }
196
197  // TAB is a special case.
198  if (key == TAB && (*modifiers & MOD_MASK_SHIFT)) {
199    *modifiers &= ~MOD_MASK_SHIFT;
200    return K_S_TAB;
201  }
202  const int key0 = KEY2TERMCAP0(key);
203  const int key1 = KEY2TERMCAP1(key);
204  for (int i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE) {
205    if (key0 == modifier_keys_table[i + 3]
206        && key1 == modifier_keys_table[i + 4]
207        && (*modifiers & modifier_keys_table[i])) {
208      *modifiers &= ~modifier_keys_table[i];
209      return TERMCAP2KEY(modifier_keys_table[i + 1],
210                         modifier_keys_table[i + 2]);
211    }
212  }
213  return key;
214}
215
216/// Inverse of simplify_key().
217int unsimplify_key(const int c, int *modifiers)
218  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
219{
220  if (!IS_SPECIAL(c)) {
221    return c;
222  }
223
224  for (int i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE) {
225    if (KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
226        && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2]) {
227      *modifiers |= modifier_keys_table[i];
228      return TERMCAP2KEY(modifier_keys_table[i + 3], modifier_keys_table[i + 4]);
229    }
230  }
231
232  return c;
233}
234
235/// Change <xKey> to <Key>
236int handle_x_keys(const int key)
237  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
238{
239  switch (key) {
240  case K_XUP:
241    return K_UP;
242  case K_XDOWN:
243    return K_DOWN;
244  case K_XLEFT:
245    return K_LEFT;
246  case K_XRIGHT:
247    return K_RIGHT;
248  case K_XHOME:
249    return K_HOME;
250  case K_ZHOME:
251    return K_HOME;
252  case K_XEND:
253    return K_END;
254  case K_ZEND:
255    return K_END;
256  case K_XF1:
257    return K_F1;
258  case K_XF2:
259    return K_F2;
260  case K_XF3:
261    return K_F3;
262  case K_XF4:
263    return K_F4;
264  case K_S_XF1:
265    return K_S_F1;
266  case K_S_XF2:
267    return K_S_F2;
268  case K_S_XF3:
269    return K_S_F3;
270  case K_S_XF4:
271    return K_S_F4;
272  }
273  return key;
274}
275
276/// Gets a key "chord" (key + modifiers) as a string, and optionally as structured `data`.
277char *get_special_key(int c, int modifiers, struct keychord *data)
278{
279  static char string[MAX_KEY_NAME_LEN + 1];
280  bool is_ascii_ctrl = false;
281
282  string[0] = '<';
283  int idx = 1;
284
285  // Key that stands for a normal character.
286  if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY) {
287    c = KEY2TERMCAP1(c);
288  }
289
290  // Translate shifted special keys into unshifted keys and set modifier.
291  // Same for CTRL and ALT modifiers.
292  c = unsimplify_key(c, &modifiers);
293
294  // try to find the key in the special key table
295  int table_idx = find_special_key_in_table(c);
296
297  // When not a known special key, and not a printable character, try to
298  // extract modifiers.
299  if (c > 0
300      && utf_char2len(c) == 1) {
301    if (table_idx < 0 && !vim_isprintc(c) && c < ' ') {
302      c += '@';
303      modifiers |= MOD_MASK_CTRL;
304
305      is_ascii_ctrl = true;
306    }
307  }
308
309  if (data) {
310    data->mods = 0;
311  }
312
313  // translate the modifier into a string
314  for (int i = 0; mod_mask_table[i].name != 'A'; i++) {
315    if ((modifiers & mod_mask_table[i].mod_mask)
316        == mod_mask_table[i].mod_flag) {
317      string[idx++] = mod_mask_table[i].name;
318      string[idx++] = '-';
319
320      if (data) {
321        data->mods |= mod_mask_table[i].mod_flag;
322      }
323    }
324  }
325
326  if (table_idx < 0) {          // unknown special key, may output t_xx
327    if (IS_SPECIAL(c)) {
328      if (data) {
329        data->key_alt = (String){ NULL, 0 };
330        data->key = (String){ &string[idx], 4 };
331      }
332
333      string[idx++] = 't';
334      string[idx++] = '_';
335      string[idx++] = (char)(uint8_t)KEY2TERMCAP0(c);
336      string[idx++] = (char)(uint8_t)KEY2TERMCAP1(c);
337    } else {
338      // Not a special key, only modifiers, output directly.
339      int len = utf_char2len(c);
340      if (len == 1 && vim_isprintc(c)) {
341        if (data) {
342          if ('A' <= c && c <= 'Z') {
343            data->key_mem = (char)c + 32;
344            data->key = (String){ &data->key_mem, 1 };
345            if (!is_ascii_ctrl) {
346              data->mods |= MOD_MASK_SHIFT;
347            }
348            data->key_alt = (String){ &string[idx], (size_t)len };
349          } else {
350            data->key_alt = (String){ NULL, 0 };
351            data->key = (String){ &string[idx], (size_t)len };
352          }
353        }
354
355        string[idx++] = (char)(uint8_t)c;
356      } else if (len > 1) {
357        if (data) {
358          data->key = (String){ &string[idx], (size_t)len };
359          data->key_alt = (String){ NULL, 0 };
360        }
361
362        idx += utf_char2bytes(c, string + idx);
363      } else {
364        char *s = transchar(c);
365
366        if (data) {
367          data->key_mem = (char)c;
368          data->key = (String){ &data->key_mem, 1 };
369          data->key_alt = (String){ &string[idx], strlen(s) };
370        }
371
372        while (*s) {
373          string[idx++] = *s++;
374        }
375      }
376    }
377  } else {            // use name of special key
378    const String *s = &key_names_table[table_idx].name;
379
380    if (data) {
381      if (0 <= c && c <= 0x7f) {
382        data->key_mem = (char)c;
383        data->key = (String){ &data->key_mem, 1 };
384        data->key_alt = *s;
385      } else {
386        data->key = *s;
387        data->key_alt = (String){ NULL, 0 };
388      }
389    }
390
391    if ((int)s->size + idx + 2 <= MAX_KEY_NAME_LEN) {
392      memcpy(string + idx, s->data, s->size);
393      idx += (int)s->size;
394    }
395  }
396  string[idx++] = '>';
397  string[idx] = NUL;
398
399  return string;
400}
401
402/// @return  String representing the key "chord" (key + modifiers).
403char *get_special_key_name(int c, int modifiers)
404{
405  return get_special_key(c, modifiers, NULL);
406}
407
408/// Try translating a <> name ("keycode").
409///
410/// @param[in,out]  srcp  Source from which <> are translated. Is advanced to
411///                       after the <> name if there is a match.
412/// @param[in]  src_len  Length of the srcp.
413/// @param[out]  dst  Location where translation result will be kept. It must
414//                    be at least 19 bytes per "<x>" form.
415/// @param[in]  flags  FSK_ values
416/// @param[in]  escape_ks  escape K_SPECIAL bytes in the character
417/// @param[out]  did_simplify  found <C-H>, etc.
418///
419/// @return Number of characters added to dst, zero for no match.
420unsigned trans_special(const char **const srcp, const size_t src_len, char *const dst,
421                       const int flags, const bool escape_ks, bool *const did_simplify)
422  FUNC_ATTR_NONNULL_ARG(1, 3) FUNC_ATTR_WARN_UNUSED_RESULT
423{
424  int modifiers = 0;
425  int key = find_special_key(srcp, src_len, &modifiers, flags, did_simplify);
426  if (key == 0) {
427    return 0;
428  }
429
430  return special_to_buf(key, modifiers, escape_ks, dst);
431}
432
433/// Put the character sequence for "key" with "modifiers" into "dst" and return
434/// the resulting length.
435/// When "escape_ks" is true escape K_SPECIAL bytes in the character.
436/// The sequence is not NUL terminated.
437/// This is how characters in a string are encoded.
438unsigned special_to_buf(int key, int modifiers, bool escape_ks, char *dst)
439{
440  unsigned dlen = 0;
441
442  // Put the appropriate modifier in a string.
443  if (modifiers != 0) {
444    dst[dlen++] = (char)(uint8_t)K_SPECIAL;
445    dst[dlen++] = (char)(uint8_t)KS_MODIFIER;
446    dst[dlen++] = (char)(uint8_t)modifiers;
447  }
448
449  if (IS_SPECIAL(key)) {
450    dst[dlen++] = (char)(uint8_t)K_SPECIAL;
451    dst[dlen++] = (char)(uint8_t)KEY2TERMCAP0(key);
452    dst[dlen++] = (char)(uint8_t)KEY2TERMCAP1(key);
453  } else if (escape_ks) {
454    char *after = add_char2buf(key, dst + dlen);
455    assert(after >= dst && (uintmax_t)(after - dst) <= UINT_MAX);
456    dlen = (unsigned)(after - dst);
457  } else {
458    dlen += (unsigned)utf_char2bytes(key, dst + dlen);
459  }
460
461  return dlen;
462}
463
464/// Try translating a <> name
465///
466/// @param[in,out]  srcp  Translated <> name. Is advanced to after the <> name.
467/// @param[in]  src_len  srcp length.
468/// @param[out]  modp  Location where information about modifiers is saved.
469/// @param[in]  flags  FSK_ values
470/// @param[out]  did_simplify  FSK_SIMPLIFY and found <C-H>, etc.
471///
472/// @return Key and modifiers or 0 if there is no match.
473int find_special_key(const char **const srcp, const size_t src_len, int *const modp,
474                     const int flags, bool *const did_simplify)
475  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 3)
476{
477  const char *bp;
478  const char *const end = *srcp + src_len - 1;
479  const bool in_string = flags & FSK_IN_STRING;
480  uvarnumber_T n;
481  int l;
482
483  if (src_len == 0) {
484    return 0;
485  }
486
487  const char *src = *srcp;
488  if (src[0] != '<') {
489    return 0;
490  }
491  if (src[1] == '*') {  // <*xxx>: do not simplify
492    src++;
493  }
494
495  // Find end of modifier list
496  const char *last_dash = src;
497  for (bp = src + 1; bp <= end && (*bp == '-' || ascii_isident(*bp)); bp++) {
498    if (*bp == '-') {
499      last_dash = bp;
500      if (bp + 1 <= end) {
501        l = utfc_ptr2len_len(bp + 1, (int)(end - bp) + 1);
502        // Anything accepted, like <C-?>.
503        // <C-"> or <M-"> are not special in strings as " is
504        // the string delimiter. With a backslash it works: <M-\">
505        if (end - bp > l && !(in_string && bp[1] == '"') && bp[l + 1] == '>') {
506          bp += l;
507        } else if (end - bp > 2 && in_string && bp[1] == '\\'
508                   && bp[2] == '"' && bp[3] == '>') {
509          bp += 2;
510        }
511      }
512    }
513    if (end - bp > 3 && bp[0] == 't' && bp[1] == '_') {
514      bp += 3;  // skip t_xx, xx may be '-' or '>'
515    } else if (end - bp > 4 && STRNICMP(bp, "char-", 5) == 0) {
516      vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, true, NULL);
517      if (l == 0) {
518        emsg(_(e_invarg));
519        return 0;
520      }
521      bp += l + 5;
522      break;
523    }
524  }
525
526  if (bp <= end && *bp == '>') {  // found matching '>'
527    int key;
528    const char *end_of_name = bp + 1;
529
530    // Which modifiers are given?
531    int modifiers = 0x0;
532    for (bp = src + 1; bp < last_dash; bp++) {
533      if (*bp != '-') {
534        int bit = name_to_mod_mask((uint8_t)(*bp));
535        if (bit == 0x0) {
536          break;                // Illegal modifier name
537        }
538        modifiers |= bit;
539      }
540    }
541
542    // Legal modifier name.
543    if (bp >= last_dash) {
544      if (STRNICMP(last_dash + 1, "char-", 5) == 0
545          && ascii_isdigit(last_dash[6])) {
546        // <Char-123> or <Char-033> or <Char-0x33>
547        vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, true, NULL);
548        if (l == 0) {
549          emsg(_(e_invarg));
550          return 0;
551        }
552        key = (int)n;
553      } else {
554        int off = 1;
555
556        // Modifier with single letter, or special key name.
557        if (in_string && last_dash[1] == '\\' && last_dash[2] == '"') {
558          // Special case for a double-quoted string
559          off = l = 2;
560        } else {
561          l = utfc_ptr2len(last_dash + 1);
562        }
563        if (modifiers != 0 && last_dash[l + 1] == '>') {
564          key = utf_ptr2char(last_dash + off);
565        } else {
566          key = get_special_key_code(last_dash + off);
567          if (!(flags & FSK_KEEP_X_KEY)) {
568            key = handle_x_keys(key);
569          }
570        }
571      }
572
573      // get_special_key_code() may return NUL for invalid
574      // special key name.
575      if (key != NUL) {
576        // Only use a modifier when there is no special key code that
577        // includes the modifier.
578        key = simplify_key(key, &modifiers);
579
580        if (!(flags & FSK_KEYCODE)) {
581          // don't want keycode, use single byte code
582          if (key == K_BS) {
583            key = BS;
584          } else if (key == K_DEL || key == K_KDEL) {
585            key = DEL;
586          }
587        }
588
589        // Normal Key with modifier:
590        // Try to make a single byte code (except for Alt/Meta modifiers).
591        if (!IS_SPECIAL(key)) {
592          key = extract_modifiers(key, &modifiers, flags & FSK_SIMPLIFY, did_simplify);
593        }
594
595        *modp = modifiers;
596        *srcp = end_of_name;
597        return key;
598      }  // else { ELOG("unknown key: '%s'", src); }
599    }
600  }
601  return 0;
602}
603
604/// Try to include modifiers (except alt/meta) in the key.
605/// Changes "Shift-a" to 'A', "Ctrl-@" to <Nul>, etc.
606/// @param[in]  simplify  if false, don't do Ctrl
607/// @param[out]  did_simplify  set when it is not NULL and "simplify" is true and
608///                            Ctrl is removed from modifiers
609static int extract_modifiers(int key, int *modp, const bool simplify, bool *const did_simplify)
610{
611  int modifiers = *modp;
612
613  if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key)) {
614    key = TOUPPER_ASC(key);
615    // With <C-S-a> we keep the shift modifier.
616    // With <S-a>, <A-S-a> and <S-A> we don't keep the shift modifier.
617    if (!(modifiers & MOD_MASK_CTRL)) {
618      modifiers &= ~MOD_MASK_SHIFT;
619    }
620  }
621
622  // <C-H> and <C-h> mean the same thing, always use "H"
623  if ((modifiers & MOD_MASK_CTRL) && ASCII_ISALPHA(key)) {
624    key = TOUPPER_ASC(key);
625  }
626
627  if (simplify && (modifiers & MOD_MASK_CTRL)
628      && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))) {
629    key = CTRL_CHR(key);
630    modifiers &= ~MOD_MASK_CTRL;
631    if (key == NUL) {  // <C-@> is <Nul>
632      key = K_ZERO;
633    }
634    if (did_simplify != NULL) {
635      *did_simplify = true;
636    }
637  }
638
639  *modp = modifiers;
640  return key;
641}
642
643/// Try to find key "c" in the special key table.
644/// @return  the index when found, -1 when not found.
645int find_special_key_in_table(int c)
646{
647  for (int i = 0; i < (int)ARRAY_SIZE(key_names_table); i++) {
648    if (c == key_names_table[i].key && !key_names_table[i].is_alt) {
649      return i;
650    }
651  }
652
653  return -1;
654}
655
656/// Find the special key with the given name
657///
658/// @param[in]  name  Name of the special. Does not have to end with NUL, it is
659///                   assumed to end before the first non-idchar. If name starts
660///                   with "t_" the next two characters are interpreted as
661///                   a termcap name.
662///
663/// @return Key code or 0 if not found.
664int get_special_key_code(const char *name)
665  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
666{
667  if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL) {
668    return TERMCAP2KEY((uint8_t)name[2], (uint8_t)name[3]);
669  }
670
671  const char *name_end = name;
672  while (ascii_isident(*name_end)) {
673    name_end++;
674  }
675
676  int idx = get_special_key_code_hash(name, (size_t)(name_end - name));
677  return idx >= 0 ? key_names_table[idx].key : 0;
678}
679
680/// Look up the given mouse code to return the relevant information in the other arguments.
681/// @return  which button is down or was released.
682int get_mouse_button(int code, bool *is_click, bool *is_drag)
683{
684  for (int i = 0; mouse_table[i].pseudo_code; i++) {
685    if (code == mouse_table[i].pseudo_code) {
686      *is_click = mouse_table[i].is_click;
687      *is_drag = mouse_table[i].is_drag;
688      return mouse_table[i].button;
689    }
690  }
691  return 0;         // Shouldn't get here
692}
693
694/// Encode `<key>` notation into Nvim's internal key representation. (Does NOT process raw terminal
695/// escape sequences, despite the legacy "termcode" terminology.)
696///
697/// Parses keycode notation like `<C-Up>`, `<CR>`, `<Esc>`, `<F1>`, `<Leader>`, `<SID>`, and emits
698/// the corresponding K_SPECIAL byte sequences. Used for the lhs/rhs of mappings, the rhs of menu
699/// commands, and feedkeys input. K_SPECIAL by itself is replaced by K_SPECIAL KS_SPECIAL KE_FILLER.
700///
701/// Also handles `<C-v>` / backslash literal escapes (per 'cpoptions'), `<Leader>`/`<LocalLeader>`
702/// expansion, `<SID>` script-id substitution, and (unless REPTERM_NO_SIMPLIFY) simplifications like
703/// `<C-H>` => 0x08.
704///
705/// When "flags" has REPTERM_FROM_PART, trailing <C-v> is included, otherwise it is removed (to make
706/// ":map xx ^V" map xx to nothing). When cpo_val contains kCpoBslash, a backslash can be used in
707/// place of <C-v>. All other <C-v> characters are removed.
708///
709/// @param[in]  from  What characters to replace.
710/// @param[in]  from_len  Length of the "from" argument.
711/// @param[out]  bufp  Location where results were saved in case of success (allocated).
712///                    If `*bufp` is non-NULL, it will be used directly,
713///                    and is assumed to be 128 bytes long (enough for transcoding LHS of mapping),
714///                    and will be set to NULL in case of failure.
715/// @param[in]  sid_arg  Script ID to use for <SID>, or 0 to use current_sctx
716/// @param[in]  flags  REPTERM_FROM_PART    see above
717///                    REPTERM_DO_LT        also translate <lt>
718///                    REPTERM_NO_SPECIAL   do not accept <key> notation
719///                    REPTERM_NO_SIMPLIFY  do not simplify <C-H> into 0x08, etc.
720/// @param[out]  did_simplify  set when some <C-H> code was simplified, unless it is NULL.
721/// @param[in]  cpo_val  The value of 'cpoptions' to use. Only kCpoBslash matters.
722///
723/// @return  The same as what `*bufp` is set to.
724char *replace_termcodes(const char *const from, const size_t from_len, char **const bufp,
725                        const scid_T sid_arg, const int flags, bool *const did_simplify,
726                        const char *const cpo_val)
727  FUNC_ATTR_NONNULL_ARG(1, 3, 7)
728{
729  size_t dlen = 0;
730  const char *const end = from + from_len - 1;
731
732  // backslash is a special character
733  const bool do_backslash = (vim_strchr(cpo_val, kCpoBslash) == NULL);
734  const bool do_special = !(flags & REPTERM_NO_SPECIAL);
735
736  bool allocated = (*bufp == NULL);
737
738  // Allocate space for the translation.  Worst case a single character is
739  // replaced by 6 bytes (shifted special key), plus a NUL at the end.
740  const size_t buf_len = allocated ? from_len * 6 + 1 : 128;
741  char *result = allocated ? xmalloc(buf_len) : *bufp;  // buffer for resulting string
742
743  const char *src = from;
744
745  // Copy each byte from *from to result[dlen]
746  while (src <= end) {
747    if (!allocated && dlen + 64 > buf_len) {
748      return NULL;
749    }
750    // Check for special <> keycodes, like "<C-S-LeftMouse>"
751    if (do_special && ((flags & REPTERM_DO_LT) || ((end - src) >= 3
752                                                   && strncmp(src, "<lt>", 4) != 0))) {
753      // Change <SID>Func to K_SNR <script-nr> _Func.  This name is used
754      // for script-local user functions.
755      // (room: 5 * 6 = 30 bytes; needed: 3 + <nr> + 1 <= 14)
756      if (end - src >= 4 && STRNICMP(src, "<SID>", 5) == 0) {
757        if (sid_arg < 0 || (sid_arg == 0 && current_sctx.sc_sid <= 0)) {
758          emsg(_(e_usingsid));
759        } else {
760          const scid_T sid = sid_arg != 0 ? sid_arg : current_sctx.sc_sid;
761          src += 5;
762          result[dlen++] = (char)K_SPECIAL;
763          result[dlen++] = (char)KS_EXTRA;
764          result[dlen++] = KE_SNR;
765          snprintf(result + dlen, buf_len - dlen, "%" PRIdSCID, sid);
766          dlen += strlen(result + dlen);
767          result[dlen++] = '_';
768          continue;
769        }
770      }
771
772      size_t slen = trans_special(&src, (size_t)(end - src) + 1, result + dlen,
773                                  FSK_KEYCODE | ((flags & REPTERM_NO_SIMPLIFY) ? 0 : FSK_SIMPLIFY),
774                                  true, did_simplify);
775      if (slen) {
776        dlen += slen;
777        continue;
778      }
779    }
780
781    if (do_special) {
782      char *p, *s;
783      int len;
784
785      // Replace <Leader> by the value of "mapleader".
786      // Replace <LocalLeader> by the value of "maplocalleader".
787      // If "mapleader" or "maplocalleader" isn't set use a backslash.
788      if (end - src >= 7 && STRNICMP(src, "<Leader>", 8) == 0) {
789        len = 8;
790        p = get_var_value("g:mapleader");
791      } else if (end - src >= 12 && STRNICMP(src, "<LocalLeader>", 13) == 0) {
792        len = 13;
793        p = get_var_value("g:maplocalleader");
794      } else {
795        len = 0;
796        p = NULL;
797      }
798
799      if (len != 0) {
800        // Allow up to 8 * 6 characters for "mapleader".
801        if (p == NULL || *p == NUL || strlen(p) > 8 * 6) {
802          s = "\\";
803        } else {
804          s = p;
805        }
806        while (*s != NUL) {
807          result[dlen++] = *s++;
808        }
809        src += len;
810        continue;
811      }
812    }
813
814    // Remove CTRL-V and ignore the next character.
815    // For "from" side the CTRL-V at the end is included, for the "to"
816    // part it is removed.
817    // If 'cpoptions' does not contain 'B', also accept a backslash.
818    char key = *src;
819    if (key == Ctrl_V || (do_backslash && key == '\\')) {
820      src++;  // skip CTRL-V or backslash
821      if (src > end) {
822        if (flags & REPTERM_FROM_PART) {
823          result[dlen++] = key;
824        }
825        break;
826      }
827    }
828
829    // skip multibyte char correctly
830    for (ssize_t i = utfc_ptr2len_len(src, (int)(end - src) + 1); i > 0; i--) {
831      // If the character is K_SPECIAL, replace it with K_SPECIAL
832      // KS_SPECIAL KE_FILLER.
833      if (*src == (char)K_SPECIAL) {
834        result[dlen++] = (char)K_SPECIAL;
835        result[dlen++] = (char)KS_SPECIAL;
836        result[dlen++] = KE_FILLER;
837      } else {
838        result[dlen++] = *src;
839      }
840      src++;
841    }
842  }
843  result[dlen] = NUL;
844
845  if (allocated) {
846    *bufp = xrealloc(result, dlen + 1);
847  }
848
849  return *bufp;
850}
851
852/// Add character "c" to buffer "s"
853///
854/// Escapes the special meaning of K_SPECIAL, handles multi-byte
855/// characters.
856///
857/// @param[in]  c  Character to add.
858/// @param[out]  s  Buffer to add to. Must have at least MB_MAXBYTES + 1 bytes.
859///
860/// @return Pointer to after the added bytes.
861char *add_char2buf(int c, char *s)
862  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
863{
864  char temp[MB_MAXBYTES + 1];
865  const int len = utf_char2bytes(c, temp);
866  for (int i = 0; i < len; i++) {
867    c = (uint8_t)temp[i];
868    // Need to escape K_SPECIAL like in the typeahead buffer.
869    if (c == K_SPECIAL) {
870      *s++ = (char)(uint8_t)K_SPECIAL;
871      *s++ = (char)(uint8_t)KS_SPECIAL;
872      *s++ = KE_FILLER;
873    } else {
874      *s++ = (char)(uint8_t)c;
875    }
876  }
877  return s;
878}
879
880/// Copy "p" to allocated memory, escaping K_SPECIAL so that the result
881/// can be put in the typeahead buffer.
882char *vim_strsave_escape_ks(char *p)
883{
884  // Need a buffer to hold up to three times as much.  Four in case of an
885  // illegal utf-8 byte:
886  // 0xc0 -> 0xc3 - 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
887  char *res = xmalloc(strlen(p) * 4 + 1);
888  char *d = res;
889  for (char *s = p; *s != NUL;) {
890    if ((uint8_t)s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL) {
891      // Copy special key unmodified.
892      *d++ = *s++;
893      *d++ = *s++;
894      *d++ = *s++;
895    } else {
896      // Add character, possibly multi-byte to destination, escaping
897      // K_SPECIAL. Be careful, it can be an illegal byte!
898      d = add_char2buf(utf_ptr2char(s), d);
899      s += utf_ptr2len(s);
900    }
901  }
902  *d = NUL;
903
904  return res;
905}
906
907/// Remove escaping from K_SPECIAL characters.  Reverse of
908/// vim_strsave_escape_ks().  Works in-place.
909/// Returns the number of bytes in the unescaped string.
910size_t vim_unescape_ks(char *p)
911{
912  uint8_t *s = (uint8_t *)p;
913  uint8_t *d = (uint8_t *)p;
914
915  while (*s != NUL) {
916    if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER) {
917      *d++ = K_SPECIAL;
918      s += 3;
919    } else {
920      *d++ = *s++;
921    }
922  }
923  *d = NUL;
924  return (size_t)((char *)d - p);
925}