blob: d99a84fc398226e9ab5f10a77cb635b23204484e [file] [log] [blame]
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
zeertzjqa3f83fe2021-11-22 12:47:39 +000011 * map.c: Code for mappings and abbreviations.
Bram Moolenaarb66bab32019-08-01 14:28:24 +020012 */
13
14#include "vim.h"
15
16/*
17 * List used for abbreviations.
18 */
19static mapblock_T *first_abbr = NULL; // first entry in abbrlist
20
21/*
22 * Each mapping is put in one of the 256 hash lists, to speed up finding it.
23 */
24static mapblock_T *(maphash[256]);
25static int maphash_valid = FALSE;
26
27/*
28 * Make a hash value for a mapping.
29 * "mode" is the lower 4 bits of the State for the mapping.
30 * "c1" is the first character of the "lhs".
31 * Returns a value between 0 and 255, index in maphash.
32 * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
33 */
34#define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING + TERMINAL)) ? (c1) : ((c1) ^ 0x80))
35
36/*
37 * Get the start of the hashed map list for "state" and first character "c".
38 */
39 mapblock_T *
40get_maphash_list(int state, int c)
41{
42 return maphash[MAP_HASH(state, c)];
43}
44
45/*
46 * Get the buffer-local hashed map list for "state" and first character "c".
47 */
48 mapblock_T *
49get_buf_maphash_list(int state, int c)
50{
51 return curbuf->b_maphash[MAP_HASH(state, c)];
52}
53
54 int
55is_maphash_valid(void)
56{
57 return maphash_valid;
58}
59
60/*
61 * Initialize maphash[] for first use.
62 */
63 static void
64validate_maphash(void)
65{
66 if (!maphash_valid)
67 {
Bram Moolenaara80faa82020-04-12 19:37:17 +020068 CLEAR_FIELD(maphash);
Bram Moolenaarb66bab32019-08-01 14:28:24 +020069 maphash_valid = TRUE;
70 }
71}
72
73/*
74 * Delete one entry from the abbrlist or maphash[].
75 * "mpp" is a pointer to the m_next field of the PREVIOUS entry!
76 */
77 static void
78map_free(mapblock_T **mpp)
79{
80 mapblock_T *mp;
81
82 mp = *mpp;
83 vim_free(mp->m_keys);
84 vim_free(mp->m_str);
85 vim_free(mp->m_orig_str);
86 *mpp = mp->m_next;
Bram Moolenaard648c012022-01-16 14:58:34 +000087#ifdef FEAT_EVAL
Bram Moolenaarf61c89d2022-01-19 22:51:48 +000088 reset_last_used_map(mp);
Bram Moolenaard648c012022-01-16 14:58:34 +000089#endif
Bram Moolenaar8aa0e6c2022-01-20 11:27:58 +000090 vim_free(mp);
Bram Moolenaarb66bab32019-08-01 14:28:24 +020091}
92
93/*
94 * Return characters to represent the map mode in an allocated string.
95 * Returns NULL when out of memory.
96 */
97 static char_u *
98map_mode_to_chars(int mode)
99{
100 garray_T mapmode;
101
102 ga_init2(&mapmode, 1, 7);
103
104 if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
105 ga_append(&mapmode, '!'); // :map!
106 else if (mode & INSERT)
107 ga_append(&mapmode, 'i'); // :imap
108 else if (mode & LANGMAP)
109 ga_append(&mapmode, 'l'); // :lmap
110 else if (mode & CMDLINE)
111 ga_append(&mapmode, 'c'); // :cmap
112 else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
113 == NORMAL + VISUAL + SELECTMODE + OP_PENDING)
114 ga_append(&mapmode, ' '); // :map
115 else
116 {
117 if (mode & NORMAL)
118 ga_append(&mapmode, 'n'); // :nmap
119 if (mode & OP_PENDING)
120 ga_append(&mapmode, 'o'); // :omap
121 if (mode & TERMINAL)
122 ga_append(&mapmode, 't'); // :tmap
123 if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
124 ga_append(&mapmode, 'v'); // :vmap
125 else
126 {
127 if (mode & VISUAL)
128 ga_append(&mapmode, 'x'); // :xmap
129 if (mode & SELECTMODE)
130 ga_append(&mapmode, 's'); // :smap
131 }
132 }
133
134 ga_append(&mapmode, NUL);
135 return (char_u *)mapmode.ga_data;
136}
137
138 static void
139showmap(
140 mapblock_T *mp,
141 int local) // TRUE for buffer-local map
142{
143 int len = 1;
144 char_u *mapchars;
145
146 if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
147 return;
148
149 if (msg_didout || msg_silent != 0)
150 {
151 msg_putchar('\n');
152 if (got_int) // 'q' typed at MORE prompt
153 return;
154 }
155
156 mapchars = map_mode_to_chars(mp->m_mode);
157 if (mapchars != NULL)
158 {
159 msg_puts((char *)mapchars);
160 len = (int)STRLEN(mapchars);
161 vim_free(mapchars);
162 }
163
164 while (++len <= 3)
165 msg_putchar(' ');
166
167 // Display the LHS. Get length of what we write.
168 len = msg_outtrans_special(mp->m_keys, TRUE, 0);
169 do
170 {
171 msg_putchar(' '); // padd with blanks
172 ++len;
173 } while (len < 12);
174
175 if (mp->m_noremap == REMAP_NONE)
176 msg_puts_attr("*", HL_ATTR(HLF_8));
177 else if (mp->m_noremap == REMAP_SCRIPT)
178 msg_puts_attr("&", HL_ATTR(HLF_8));
179 else
180 msg_putchar(' ');
181
182 if (local)
183 msg_putchar('@');
184 else
185 msg_putchar(' ');
186
187 // Use FALSE below if we only want things like <Up> to show up as such on
188 // the rhs, and not M-x etc, TRUE gets both -- webb
189 if (*mp->m_str == NUL)
190 msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
191 else
192 {
193 // Remove escaping of CSI, because "m_str" is in a format to be used
194 // as typeahead.
195 char_u *s = vim_strsave(mp->m_str);
196 if (s != NULL)
197 {
198 vim_unescape_csi(s);
199 msg_outtrans_special(s, FALSE, 0);
200 vim_free(s);
201 }
202 }
203#ifdef FEAT_EVAL
204 if (p_verbose > 0)
205 last_set_msg(mp->m_script_ctx);
206#endif
Bram Moolenaard288eaa2022-02-16 18:27:55 +0000207 msg_clr_eos();
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200208 out_flush(); // show one line at a time
209}
210
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200211 static int
212map_add(
213 mapblock_T **map_table,
214 mapblock_T **abbr_table,
215 char_u *keys,
216 char_u *rhs,
217 char_u *orig_rhs,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200218 int noremap,
219 int nowait,
220 int silent,
221 int mode,
222 int is_abbr,
223#ifdef FEAT_EVAL
Bram Moolenaar5a80f8a2020-05-22 13:38:18 +0200224 int expr,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200225 scid_T sid, // -1 to use current_sctx
Bram Moolenaara9528b32022-01-18 20:51:35 +0000226 int scriptversion,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200227 linenr_T lnum,
228#endif
229 int simplified)
230{
Bram Moolenaar94075b22022-01-18 20:30:39 +0000231 mapblock_T *mp = ALLOC_CLEAR_ONE(mapblock_T);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200232
233 if (mp == NULL)
234 return FAIL;
235
236 // If CTRL-C has been mapped, don't always use it for Interrupting.
237 if (*keys == Ctrl_C)
238 {
239 if (map_table == curbuf->b_maphash)
240 curbuf->b_mapped_ctrl_c |= mode;
241 else
242 mapped_ctrl_c |= mode;
243 }
244
245 mp->m_keys = vim_strsave(keys);
246 mp->m_str = vim_strsave(rhs);
247 mp->m_orig_str = vim_strsave(orig_rhs);
248 if (mp->m_keys == NULL || mp->m_str == NULL)
249 {
250 vim_free(mp->m_keys);
251 vim_free(mp->m_str);
252 vim_free(mp->m_orig_str);
253 vim_free(mp);
254 return FAIL;
255 }
256 mp->m_keylen = (int)STRLEN(mp->m_keys);
257 mp->m_noremap = noremap;
258 mp->m_nowait = nowait;
259 mp->m_silent = silent;
260 mp->m_mode = mode;
261 mp->m_simplified = simplified;
262#ifdef FEAT_EVAL
263 mp->m_expr = expr;
Bram Moolenaara9528b32022-01-18 20:51:35 +0000264 if (sid > 0)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200265 {
266 mp->m_script_ctx.sc_sid = sid;
267 mp->m_script_ctx.sc_lnum = lnum;
Bram Moolenaara9528b32022-01-18 20:51:35 +0000268 mp->m_script_ctx.sc_version = scriptversion;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200269 }
270 else
271 {
272 mp->m_script_ctx = current_sctx;
273 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
274 }
275#endif
276
277 // add the new entry in front of the abbrlist or maphash[] list
278 if (is_abbr)
279 {
280 mp->m_next = *abbr_table;
281 *abbr_table = mp;
282 }
283 else
284 {
285 int n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
286
287 mp->m_next = map_table[n];
288 map_table[n] = mp;
289 }
290 return OK;
291}
292
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200293/*
294 * map[!] : show all key mappings
295 * map[!] {lhs} : show key mapping for {lhs}
296 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
297 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
298 * unmap[!] {lhs} : remove key mapping for {lhs}
299 * abbr : show all abbreviations
300 * abbr {lhs} : show abbreviations for {lhs}
301 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
302 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
303 * unabbr {lhs} : remove abbreviation for {lhs}
304 *
305 * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
306 *
307 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
308 * it will be modified.
309 *
310 * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
311 * for :map! mode is INSERT + CMDLINE
312 * for :cmap mode is CMDLINE
313 * for :imap mode is INSERT
314 * for :lmap mode is LANGMAP
315 * for :nmap mode is NORMAL
316 * for :vmap mode is VISUAL + SELECTMODE
317 * for :xmap mode is VISUAL
318 * for :smap mode is SELECTMODE
319 * for :omap mode is OP_PENDING
320 * for :tmap mode is TERMINAL
321 *
322 * for :abbr mode is INSERT + CMDLINE
323 * for :iabbr mode is INSERT
324 * for :cabbr mode is CMDLINE
325 *
326 * Return 0 for success
327 * 1 for invalid arguments
328 * 2 for no match
329 * 4 for out of mem
330 * 5 for entry not unique
331 */
332 int
333do_map(
334 int maptype,
335 char_u *arg,
336 int mode,
337 int abbrev) // not a mapping but an abbreviation
338{
339 char_u *keys;
340 mapblock_T *mp, **mpp;
341 char_u *rhs;
342 char_u *p;
343 int n;
344 int len = 0; // init for GCC
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200345 int hasarg;
346 int haskey;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200347 int do_print;
348 int keyround;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200349 char_u *keys_buf = NULL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200350 char_u *alt_keys_buf = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200351 char_u *arg_buf = NULL;
352 int retval = 0;
353 int do_backslash;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200354 mapblock_T **abbr_table;
355 mapblock_T **map_table;
356 int unique = FALSE;
357 int nowait = FALSE;
358 int silent = FALSE;
359 int special = FALSE;
360#ifdef FEAT_EVAL
361 int expr = FALSE;
362#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200363 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200364 int noremap;
365 char_u *orig_rhs;
366
367 keys = arg;
368 map_table = maphash;
369 abbr_table = &first_abbr;
370
371 // For ":noremap" don't remap, otherwise do remap.
372 if (maptype == 2)
373 noremap = REMAP_NONE;
374 else
375 noremap = REMAP_YES;
376
377 // Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
378 // any order.
379 for (;;)
380 {
381 // Check for "<buffer>": mapping local to buffer.
382 if (STRNCMP(keys, "<buffer>", 8) == 0)
383 {
384 keys = skipwhite(keys + 8);
385 map_table = curbuf->b_maphash;
386 abbr_table = &curbuf->b_first_abbr;
387 continue;
388 }
389
390 // Check for "<nowait>": don't wait for more characters.
391 if (STRNCMP(keys, "<nowait>", 8) == 0)
392 {
393 keys = skipwhite(keys + 8);
394 nowait = TRUE;
395 continue;
396 }
397
398 // Check for "<silent>": don't echo commands.
399 if (STRNCMP(keys, "<silent>", 8) == 0)
400 {
401 keys = skipwhite(keys + 8);
402 silent = TRUE;
403 continue;
404 }
405
406 // Check for "<special>": accept special keys in <>
407 if (STRNCMP(keys, "<special>", 9) == 0)
408 {
409 keys = skipwhite(keys + 9);
410 special = TRUE;
411 continue;
412 }
413
414#ifdef FEAT_EVAL
415 // Check for "<script>": remap script-local mappings only
416 if (STRNCMP(keys, "<script>", 8) == 0)
417 {
418 keys = skipwhite(keys + 8);
419 noremap = REMAP_SCRIPT;
420 continue;
421 }
422
423 // Check for "<expr>": {rhs} is an expression.
424 if (STRNCMP(keys, "<expr>", 6) == 0)
425 {
426 keys = skipwhite(keys + 6);
427 expr = TRUE;
428 continue;
429 }
430#endif
431 // Check for "<unique>": don't overwrite an existing mapping.
432 if (STRNCMP(keys, "<unique>", 8) == 0)
433 {
434 keys = skipwhite(keys + 8);
435 unique = TRUE;
436 continue;
437 }
438 break;
439 }
440
441 validate_maphash();
442
443 // Find end of keys and skip CTRL-Vs (and backslashes) in it.
444 // Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
445 // with :unmap white space is included in the keys, no argument possible.
446 p = keys;
447 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
448 while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
449 {
450 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
451 p[1] != NUL)
452 ++p; // skip CTRL-V or backslash
453 ++p;
454 }
455 if (*p != NUL)
456 *p++ = NUL;
457
458 p = skipwhite(p);
459 rhs = p;
460 hasarg = (*rhs != NUL);
461 haskey = (*keys != NUL);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200462 do_print = !haskey || (maptype != 1 && !hasarg);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200463
464 // check for :unmap without argument
465 if (maptype == 1 && !haskey)
466 {
467 retval = 1;
468 goto theend;
469 }
470
471 // If mapping has been given as ^V<C_UP> say, then replace the term codes
472 // with the appropriate two bytes. If it is a shifted special key, unshift
473 // it too, giving another two bytes.
474 // replace_termcodes() may move the result to allocated memory, which
475 // needs to be freed later (*keys_buf and *arg_buf).
476 // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
Bram Moolenaar459fd782019-10-13 16:43:39 +0200477 // If something like <C-H> is simplified to 0x08 then mark it as simplified
478 // and also add a n entry with a modifier, which will work when
479 // modifyOtherKeys is working.
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200480 if (haskey)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200481 {
482 char_u *new_keys;
483 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
484
485 if (special)
486 flags |= REPTERM_SPECIAL;
487 new_keys = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
488 if (did_simplify)
489 (void)replace_termcodes(keys, &alt_keys_buf,
490 flags | REPTERM_NO_SIMPLIFY, NULL);
491 keys = new_keys;
492 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200493 orig_rhs = rhs;
494 if (hasarg)
495 {
496 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
497 rhs = (char_u *)"";
498 else
Bram Moolenaar459fd782019-10-13 16:43:39 +0200499 rhs = replace_termcodes(rhs, &arg_buf,
500 REPTERM_DO_LT | (special ? REPTERM_SPECIAL : 0), NULL);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200501 }
502
Bram Moolenaar459fd782019-10-13 16:43:39 +0200503 /*
504 * The following is done twice if we have two versions of keys:
505 * "alt_keys_buf" is not NULL.
506 */
507 for (keyround = 1; keyround <= 2; ++keyround)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200508 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200509 int did_it = FALSE;
510 int did_local = FALSE;
511 int round;
512 int hash;
513 int new_hash;
514
515 if (keyround == 2)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200516 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200517 if (alt_keys_buf == NULL)
518 break;
519 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200520 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200521 else if (alt_keys_buf != NULL && do_print)
522 // when printing always use the not-simplified map
523 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200524
Bram Moolenaar459fd782019-10-13 16:43:39 +0200525 // check arguments and translate function keys
526 if (haskey)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200527 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200528 len = (int)STRLEN(keys);
529 if (len > MAXMAPLEN) // maximum length of MAXMAPLEN chars
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200530 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200531 retval = 1;
532 goto theend;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200533 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200534
535 if (abbrev && maptype != 1)
536 {
537 // If an abbreviation ends in a keyword character, the
538 // rest must be all keyword-char or all non-keyword-char.
539 // Otherwise we won't be able to find the start of it in a
540 // vi-compatible way.
541 if (has_mbyte)
542 {
543 int first, last;
544 int same = -1;
545
546 first = vim_iswordp(keys);
547 last = first;
548 p = keys + (*mb_ptr2len)(keys);
549 n = 1;
550 while (p < keys + len)
551 {
552 ++n; // nr of (multi-byte) chars
553 last = vim_iswordp(p); // type of last char
554 if (same == -1 && last != first)
555 same = n - 1; // count of same char type
556 p += (*mb_ptr2len)(p);
557 }
558 if (last && n > 2 && same >= 0 && same < n - 1)
559 {
560 retval = 1;
561 goto theend;
562 }
563 }
564 else if (vim_iswordc(keys[len - 1]))
565 // ends in keyword char
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200566 for (n = 0; n < len - 2; ++n)
567 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
568 {
569 retval = 1;
570 goto theend;
571 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200572 // An abbreviation cannot contain white space.
573 for (n = 0; n < len; ++n)
574 if (VIM_ISWHITE(keys[n]))
575 {
576 retval = 1;
577 goto theend;
578 }
579 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200580 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200581
Bram Moolenaar459fd782019-10-13 16:43:39 +0200582 if (haskey && hasarg && abbrev) // if we will add an abbreviation
583 no_abbr = FALSE; // reset flag that indicates there are
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200584 // no abbreviations
585
Bram Moolenaar459fd782019-10-13 16:43:39 +0200586 if (do_print)
587 msg_start();
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200588
Bram Moolenaar459fd782019-10-13 16:43:39 +0200589 // Check if a new local mapping wasn't already defined globally.
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200590 if (unique && map_table == curbuf->b_maphash
591 && haskey && hasarg && maptype != 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200592 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200593 // need to loop over all global hash lists
594 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200595 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200596 if (abbrev)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200597 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200598 if (hash != 0) // there is only one abbreviation list
599 break;
600 mp = first_abbr;
601 }
602 else
603 mp = maphash[hash];
604 for ( ; mp != NULL && !got_int; mp = mp->m_next)
605 {
606 // check entries with the same mode
607 if ((mp->m_mode & mode) != 0
608 && mp->m_keylen == len
Bram Moolenaar459fd782019-10-13 16:43:39 +0200609 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
610 {
611 if (abbrev)
Bram Moolenaar6d057012021-12-31 18:49:43 +0000612 semsg(
613 _(e_global_abbreviation_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200614 mp->m_keys);
615 else
Bram Moolenaar6d057012021-12-31 18:49:43 +0000616 semsg(_(e_global_mapping_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200617 mp->m_keys);
618 retval = 5;
619 goto theend;
620 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200621 }
622 }
623 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200624
Bram Moolenaar459fd782019-10-13 16:43:39 +0200625 // When listing global mappings, also list buffer-local ones here.
626 if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200627 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200628 // need to loop over all global hash lists
629 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200630 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200631 if (abbrev)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200632 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200633 if (hash != 0) // there is only one abbreviation list
634 break;
635 mp = curbuf->b_first_abbr;
636 }
637 else
638 mp = curbuf->b_maphash[hash];
639 for ( ; mp != NULL && !got_int; mp = mp->m_next)
640 {
641 // check entries with the same mode
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200642 if (!mp->m_simplified && (mp->m_mode & mode) != 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200643 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200644 if (!haskey) // show all entries
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200645 {
646 showmap(mp, TRUE);
647 did_local = TRUE;
648 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200649 else
650 {
651 n = mp->m_keylen;
652 if (STRNCMP(mp->m_keys, keys,
653 (size_t)(n < len ? n : len)) == 0)
654 {
655 showmap(mp, TRUE);
656 did_local = TRUE;
657 }
658 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200659 }
660 }
661 }
662 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200663
Bram Moolenaar459fd782019-10-13 16:43:39 +0200664 // Find an entry in the maphash[] list that matches.
665 // For :unmap we may loop two times: once to try to unmap an entry with
666 // a matching 'from' part, a second time, if the first fails, to unmap
zeertzjqa3f83fe2021-11-22 12:47:39 +0000667 // an entry with a matching 'to' part. This was done to allow
668 // ":ab foo bar" to be unmapped by typing ":unab foo", where "foo" will
669 // be replaced by "bar" because of the abbreviation.
Bram Moolenaar459fd782019-10-13 16:43:39 +0200670 for (round = 0; (round == 0 || maptype == 1) && round <= 1
671 && !did_it && !got_int; ++round)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200672 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200673 // need to loop over all hash lists
674 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200675 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200676 if (abbrev)
677 {
678 if (hash > 0) // there is only one abbreviation list
679 break;
680 mpp = abbr_table;
681 }
682 else
683 mpp = &(map_table[hash]);
684 for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
685 {
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200686
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200687 if ((mp->m_mode & mode) == 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200688 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200689 // skip entries with wrong mode
Bram Moolenaar459fd782019-10-13 16:43:39 +0200690 mpp = &(mp->m_next);
691 continue;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200692 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200693 if (!haskey) // show all entries
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200694 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200695 if (!mp->m_simplified)
696 {
697 showmap(mp, map_table != maphash);
698 did_it = TRUE;
699 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200700 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200701 else // do we have a match?
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200702 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200703 if (round) // second round: Try unmap "rhs" string
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200704 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200705 n = (int)STRLEN(mp->m_str);
706 p = mp->m_str;
707 }
708 else
709 {
710 n = mp->m_keylen;
711 p = mp->m_keys;
712 }
713 if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
714 {
715 if (maptype == 1)
716 {
717 // Delete entry.
718 // Only accept a full match. For abbreviations
719 // we ignore trailing space when matching with
720 // the "lhs", since an abbreviation can't have
721 // trailing space.
722 if (n != len && (!abbrev || round || n > len
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200723 || *skipwhite(keys + n) != NUL))
Bram Moolenaar459fd782019-10-13 16:43:39 +0200724 {
725 mpp = &(mp->m_next);
726 continue;
727 }
728 // We reset the indicated mode bits. If nothing
729 // is left the entry is deleted below.
730 mp->m_mode &= ~mode;
731 did_it = TRUE; // remember we did something
732 }
733 else if (!hasarg) // show matching entry
734 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200735 if (!mp->m_simplified)
736 {
737 showmap(mp, map_table != maphash);
738 did_it = TRUE;
739 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200740 }
741 else if (n != len) // new entry is ambiguous
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200742 {
743 mpp = &(mp->m_next);
744 continue;
745 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200746 else if (unique)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200747 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200748 if (abbrev)
Bram Moolenaar6d057012021-12-31 18:49:43 +0000749 semsg(
750 _(e_abbreviation_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200751 p);
752 else
Bram Moolenaar6d057012021-12-31 18:49:43 +0000753 semsg(_(e_mapping_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200754 p);
755 retval = 5;
756 goto theend;
757 }
758 else
759 {
760 // new rhs for existing entry
761 mp->m_mode &= ~mode; // remove mode bits
762 if (mp->m_mode == 0 && !did_it) // reuse entry
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200763 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200764 char_u *newstr = vim_strsave(rhs);
765
766 if (newstr == NULL)
767 {
768 retval = 4; // no mem
769 goto theend;
770 }
771 vim_free(mp->m_str);
772 mp->m_str = newstr;
773 vim_free(mp->m_orig_str);
774 mp->m_orig_str = vim_strsave(orig_rhs);
775 mp->m_noremap = noremap;
776 mp->m_nowait = nowait;
777 mp->m_silent = silent;
778 mp->m_mode = mode;
779 mp->m_simplified =
780 did_simplify && keyround == 1;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200781#ifdef FEAT_EVAL
Bram Moolenaar459fd782019-10-13 16:43:39 +0200782 mp->m_expr = expr;
783 mp->m_script_ctx = current_sctx;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +0100784 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200785#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200786 did_it = TRUE;
787 }
788 }
789 if (mp->m_mode == 0) // entry can be deleted
790 {
791 map_free(mpp);
792 continue; // continue with *mpp
793 }
794
795 // May need to put this entry into another hash
796 // list.
797 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
798 if (!abbrev && new_hash != hash)
799 {
800 *mpp = mp->m_next;
801 mp->m_next = map_table[new_hash];
802 map_table[new_hash] = mp;
803
804 continue; // continue with *mpp
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200805 }
806 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200807 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200808 mpp = &(mp->m_next);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200809 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200810 }
811 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200812
Bram Moolenaar459fd782019-10-13 16:43:39 +0200813 if (maptype == 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200814 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200815 // delete entry
816 if (!did_it)
817 retval = 2; // no match
818 else if (*keys == Ctrl_C)
819 {
820 // If CTRL-C has been unmapped, reuse it for Interrupting.
821 if (map_table == curbuf->b_maphash)
822 curbuf->b_mapped_ctrl_c &= ~mode;
823 else
824 mapped_ctrl_c &= ~mode;
825 }
826 continue;
827 }
828
829 if (!haskey || !hasarg)
830 {
831 // print entries
832 if (!did_it && !did_local)
833 {
834 if (abbrev)
835 msg(_("No abbreviation found"));
836 else
837 msg(_("No mapping found"));
838 }
839 goto theend; // listing finished
840 }
841
842 if (did_it)
843 continue; // have added the new entry already
844
845 // Get here when adding a new entry to the maphash[] list or abbrlist.
Bram Moolenaar5a80f8a2020-05-22 13:38:18 +0200846 if (map_add(map_table, abbr_table, keys, rhs, orig_rhs,
847 noremap, nowait, silent, mode, abbrev,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200848#ifdef FEAT_EVAL
Bram Moolenaara9528b32022-01-18 20:51:35 +0000849 expr, /* sid */ -1, /* scriptversion */ 0, /* lnum */ 0,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200850#endif
851 did_simplify && keyround == 1) == FAIL)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200852 {
853 retval = 4; // no mem
854 goto theend;
855 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200856 }
857
858theend:
859 vim_free(keys_buf);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200860 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200861 vim_free(arg_buf);
862 return retval;
863}
864
865/*
866 * Get the mapping mode from the command name.
867 */
868 static int
869get_map_mode(char_u **cmdp, int forceit)
870{
871 char_u *p;
872 int modec;
873 int mode;
874
875 p = *cmdp;
876 modec = *p++;
877 if (modec == 'i')
878 mode = INSERT; // :imap
879 else if (modec == 'l')
880 mode = LANGMAP; // :lmap
881 else if (modec == 'c')
882 mode = CMDLINE; // :cmap
883 else if (modec == 'n' && *p != 'o') // avoid :noremap
884 mode = NORMAL; // :nmap
885 else if (modec == 'v')
886 mode = VISUAL + SELECTMODE; // :vmap
887 else if (modec == 'x')
888 mode = VISUAL; // :xmap
889 else if (modec == 's')
890 mode = SELECTMODE; // :smap
891 else if (modec == 'o')
892 mode = OP_PENDING; // :omap
893 else if (modec == 't')
894 mode = TERMINAL; // :tmap
895 else
896 {
897 --p;
898 if (forceit)
899 mode = INSERT + CMDLINE; // :map !
900 else
901 mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;// :map
902 }
903
904 *cmdp = p;
905 return mode;
906}
907
908/*
909 * Clear all mappings or abbreviations.
910 * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
911 */
912 static void
913map_clear(
914 char_u *cmdp,
915 char_u *arg UNUSED,
916 int forceit,
917 int abbr)
918{
919 int mode;
920 int local;
921
922 local = (STRCMP(arg, "<buffer>") == 0);
923 if (!local && *arg != NUL)
924 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000925 emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200926 return;
927 }
928
929 mode = get_map_mode(&cmdp, forceit);
930 map_clear_int(curbuf, mode, local, abbr);
931}
932
933/*
934 * Clear all mappings in "mode".
935 */
936 void
937map_clear_int(
938 buf_T *buf, // buffer for local mappings
939 int mode, // mode in which to delete
940 int local, // TRUE for buffer-local mappings
941 int abbr) // TRUE for abbreviations
942{
943 mapblock_T *mp, **mpp;
944 int hash;
945 int new_hash;
946
947 validate_maphash();
948
949 for (hash = 0; hash < 256; ++hash)
950 {
951 if (abbr)
952 {
953 if (hash > 0) // there is only one abbrlist
954 break;
955 if (local)
956 mpp = &buf->b_first_abbr;
957 else
958 mpp = &first_abbr;
959 }
960 else
961 {
962 if (local)
963 mpp = &buf->b_maphash[hash];
964 else
965 mpp = &maphash[hash];
966 }
967 while (*mpp != NULL)
968 {
969 mp = *mpp;
970 if (mp->m_mode & mode)
971 {
972 mp->m_mode &= ~mode;
973 if (mp->m_mode == 0) // entry can be deleted
974 {
975 map_free(mpp);
976 continue;
977 }
978 // May need to put this entry into another hash list.
979 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
980 if (!abbr && new_hash != hash)
981 {
982 *mpp = mp->m_next;
983 if (local)
984 {
985 mp->m_next = buf->b_maphash[new_hash];
986 buf->b_maphash[new_hash] = mp;
987 }
988 else
989 {
990 mp->m_next = maphash[new_hash];
991 maphash[new_hash] = mp;
992 }
993 continue; // continue with *mpp
994 }
995 }
996 mpp = &(mp->m_next);
997 }
998 }
999}
1000
1001#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001002 int
Bram Moolenaar581ba392019-09-03 22:08:33 +02001003mode_str2flags(char_u *modechars)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001004{
1005 int mode = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001006
1007 if (vim_strchr(modechars, 'n') != NULL)
1008 mode |= NORMAL;
1009 if (vim_strchr(modechars, 'v') != NULL)
1010 mode |= VISUAL + SELECTMODE;
1011 if (vim_strchr(modechars, 'x') != NULL)
1012 mode |= VISUAL;
1013 if (vim_strchr(modechars, 's') != NULL)
1014 mode |= SELECTMODE;
1015 if (vim_strchr(modechars, 'o') != NULL)
1016 mode |= OP_PENDING;
1017 if (vim_strchr(modechars, 'i') != NULL)
1018 mode |= INSERT;
1019 if (vim_strchr(modechars, 'l') != NULL)
1020 mode |= LANGMAP;
1021 if (vim_strchr(modechars, 'c') != NULL)
1022 mode |= CMDLINE;
1023
Bram Moolenaar581ba392019-09-03 22:08:33 +02001024 return mode;
1025}
1026
1027/*
1028 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
1029 * Recognize termcap codes in "str".
1030 * Also checks mappings local to the current buffer.
1031 */
1032 int
1033map_to_exists(char_u *str, char_u *modechars, int abbr)
1034{
1035 char_u *rhs;
1036 char_u *buf;
1037 int retval;
1038
Bram Moolenaar459fd782019-10-13 16:43:39 +02001039 rhs = replace_termcodes(str, &buf, REPTERM_DO_LT, NULL);
Bram Moolenaar581ba392019-09-03 22:08:33 +02001040
1041 retval = map_to_exists_mode(rhs, mode_str2flags(modechars), abbr);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001042 vim_free(buf);
1043
1044 return retval;
1045}
1046#endif
1047
1048/*
1049 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
1050 * Also checks mappings local to the current buffer.
1051 */
1052 int
1053map_to_exists_mode(char_u *rhs, int mode, int abbr)
1054{
1055 mapblock_T *mp;
1056 int hash;
1057 int exp_buffer = FALSE;
1058
1059 validate_maphash();
1060
1061 // Do it twice: once for global maps and once for local maps.
1062 for (;;)
1063 {
1064 for (hash = 0; hash < 256; ++hash)
1065 {
1066 if (abbr)
1067 {
1068 if (hash > 0) // there is only one abbr list
1069 break;
1070 if (exp_buffer)
1071 mp = curbuf->b_first_abbr;
1072 else
1073 mp = first_abbr;
1074 }
1075 else if (exp_buffer)
1076 mp = curbuf->b_maphash[hash];
1077 else
1078 mp = maphash[hash];
1079 for (; mp; mp = mp->m_next)
1080 {
1081 if ((mp->m_mode & mode)
1082 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
1083 return TRUE;
1084 }
1085 }
1086 if (exp_buffer)
1087 break;
1088 exp_buffer = TRUE;
1089 }
1090
1091 return FALSE;
1092}
1093
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001094/*
1095 * Used below when expanding mapping/abbreviation names.
1096 */
1097static int expand_mapmodes = 0;
1098static int expand_isabbrev = 0;
1099static int expand_buffer = FALSE;
1100
1101/*
Bram Moolenaar7f51bbe2020-01-24 20:21:19 +01001102 * Translate an internal mapping/abbreviation representation into the
1103 * corresponding external one recognized by :map/:abbrev commands.
1104 * Respects the current B/k/< settings of 'cpoption'.
1105 *
1106 * This function is called when expanding mappings/abbreviations on the
1107 * command-line.
1108 *
1109 * It uses a growarray to build the translation string since the latter can be
1110 * wider than the original description. The caller has to free the string
1111 * afterwards.
1112 *
1113 * Returns NULL when there is a problem.
1114 */
1115 static char_u *
1116translate_mapping(char_u *str)
1117{
1118 garray_T ga;
1119 int c;
1120 int modifiers;
1121 int cpo_bslash;
1122 int cpo_special;
1123
1124 ga_init(&ga);
1125 ga.ga_itemsize = 1;
1126 ga.ga_growsize = 40;
1127
1128 cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL);
1129 cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL);
1130
1131 for (; *str; ++str)
1132 {
1133 c = *str;
1134 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1135 {
1136 modifiers = 0;
1137 if (str[1] == KS_MODIFIER)
1138 {
1139 str++;
1140 modifiers = *++str;
1141 c = *++str;
1142 }
1143 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1144 {
1145 if (cpo_special)
1146 {
1147 ga_clear(&ga);
1148 return NULL;
1149 }
1150 c = TO_SPECIAL(str[1], str[2]);
1151 if (c == K_ZERO) // display <Nul> as ^@
1152 c = NUL;
1153 str += 2;
1154 }
1155 if (IS_SPECIAL(c) || modifiers) // special key
1156 {
1157 if (cpo_special)
1158 {
1159 ga_clear(&ga);
1160 return NULL;
1161 }
1162 ga_concat(&ga, get_special_key_name(c, modifiers));
1163 continue; // for (str)
1164 }
1165 }
1166 if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
1167 || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash))
1168 ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
1169 if (c)
1170 ga_append(&ga, c);
1171 }
1172 ga_append(&ga, NUL);
1173 return (char_u *)(ga.ga_data);
1174}
1175
1176/*
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001177 * Work out what to complete when doing command line completion of mapping
1178 * or abbreviation names.
1179 */
1180 char_u *
1181set_context_in_map_cmd(
1182 expand_T *xp,
1183 char_u *cmd,
1184 char_u *arg,
1185 int forceit, // TRUE if '!' given
1186 int isabbrev, // TRUE if abbreviation
1187 int isunmap, // TRUE if unmap/unabbrev command
1188 cmdidx_T cmdidx)
1189{
1190 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
1191 xp->xp_context = EXPAND_NOTHING;
1192 else
1193 {
1194 if (isunmap)
1195 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1196 else
1197 {
1198 expand_mapmodes = INSERT + CMDLINE;
1199 if (!isabbrev)
1200 expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
1201 }
1202 expand_isabbrev = isabbrev;
1203 xp->xp_context = EXPAND_MAPPINGS;
1204 expand_buffer = FALSE;
1205 for (;;)
1206 {
1207 if (STRNCMP(arg, "<buffer>", 8) == 0)
1208 {
1209 expand_buffer = TRUE;
1210 arg = skipwhite(arg + 8);
1211 continue;
1212 }
1213 if (STRNCMP(arg, "<unique>", 8) == 0)
1214 {
1215 arg = skipwhite(arg + 8);
1216 continue;
1217 }
1218 if (STRNCMP(arg, "<nowait>", 8) == 0)
1219 {
1220 arg = skipwhite(arg + 8);
1221 continue;
1222 }
1223 if (STRNCMP(arg, "<silent>", 8) == 0)
1224 {
1225 arg = skipwhite(arg + 8);
1226 continue;
1227 }
1228 if (STRNCMP(arg, "<special>", 9) == 0)
1229 {
1230 arg = skipwhite(arg + 9);
1231 continue;
1232 }
1233#ifdef FEAT_EVAL
1234 if (STRNCMP(arg, "<script>", 8) == 0)
1235 {
1236 arg = skipwhite(arg + 8);
1237 continue;
1238 }
1239 if (STRNCMP(arg, "<expr>", 6) == 0)
1240 {
1241 arg = skipwhite(arg + 6);
1242 continue;
1243 }
1244#endif
1245 break;
1246 }
1247 xp->xp_pattern = arg;
1248 }
1249
1250 return NULL;
1251}
1252
1253/*
1254 * Find all mapping/abbreviation names that match regexp "regmatch"'.
1255 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1256 * Return OK if matches found, FAIL otherwise.
1257 */
1258 int
1259ExpandMappings(
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001260 char_u *pat,
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001261 regmatch_T *regmatch,
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001262 int *numMatches,
1263 char_u ***matches)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001264{
1265 mapblock_T *mp;
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001266 garray_T ga;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001267 int hash;
1268 int count;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001269 char_u *p;
1270 int i;
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001271 int fuzzy;
1272 int match;
1273 int score;
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001274 fuzmatch_str_T *fuzmatch;
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001275
1276 fuzzy = cmdline_fuzzy_complete(pat);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001277
1278 validate_maphash();
1279
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001280 *numMatches = 0; // return values in case of FAIL
1281 *matches = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001282
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001283 if (!fuzzy)
1284 ga_init2(&ga, sizeof(char *), 3);
1285 else
1286 ga_init2(&ga, sizeof(fuzmatch_str_T), 3);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001287
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001288 // First search in map modifier arguments
1289 for (i = 0; i < 7; ++i)
1290 {
1291 if (i == 0)
1292 p = (char_u *)"<silent>";
1293 else if (i == 1)
1294 p = (char_u *)"<unique>";
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001295#ifdef FEAT_EVAL
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001296 else if (i == 2)
1297 p = (char_u *)"<script>";
1298 else if (i == 3)
1299 p = (char_u *)"<expr>";
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001300#endif
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001301 else if (i == 4 && !expand_buffer)
1302 p = (char_u *)"<buffer>";
1303 else if (i == 5)
1304 p = (char_u *)"<nowait>";
1305 else if (i == 6)
1306 p = (char_u *)"<special>";
1307 else
1308 continue;
1309
1310 if (!fuzzy)
1311 match = vim_regexec(regmatch, p, (colnr_T)0);
1312 else
1313 {
1314 score = fuzzy_match_str(p, pat);
1315 match = (score != 0);
1316 }
1317
1318 if (!match)
1319 continue;
1320
1321 if (ga_grow(&ga, 1) == FAIL)
1322 break;
1323
1324 if (fuzzy)
1325 {
1326 fuzmatch = &((fuzmatch_str_T *)ga.ga_data)[ga.ga_len];
1327 fuzmatch->idx = ga.ga_len;
1328 fuzmatch->str = vim_strsave(p);
1329 fuzmatch->score = score;
1330 }
1331 else
1332 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strsave(p);
1333 ++ga.ga_len;
1334 }
1335
1336 for (hash = 0; hash < 256; ++hash)
1337 {
1338 if (expand_isabbrev)
1339 {
1340 if (hash > 0) // only one abbrev list
1341 break; // for (hash)
1342 mp = first_abbr;
1343 }
1344 else if (expand_buffer)
1345 mp = curbuf->b_maphash[hash];
1346 else
1347 mp = maphash[hash];
1348 for (; mp; mp = mp->m_next)
1349 {
1350 if (!(mp->m_mode & expand_mapmodes))
1351 continue;
1352
1353 p = translate_mapping(mp->m_keys);
1354 if (p == NULL)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001355 continue;
1356
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001357 if (!fuzzy)
1358 match = vim_regexec(regmatch, p, (colnr_T)0);
1359 else
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001360 {
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001361 score = fuzzy_match_str(p, pat);
1362 match = (score != 0);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001363 }
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001364
1365 if (!match)
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001366 {
1367 vim_free(p);
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001368 continue;
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001369 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001370
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001371 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001372 {
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001373 vim_free(p);
1374 break;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001375 }
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001376
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001377 if (fuzzy)
1378 {
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001379 fuzmatch = &((fuzmatch_str_T *)ga.ga_data)[ga.ga_len];
1380 fuzmatch->idx = ga.ga_len;
1381 fuzmatch->str = p;
1382 fuzmatch->score = score;
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001383 }
1384 else
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001385 ((char_u **)ga.ga_data)[ga.ga_len] = p;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001386
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001387 ++ga.ga_len;
1388 } // for (mp)
1389 } // for (hash)
1390
1391 if (ga.ga_len == 0)
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001392 return FAIL;
1393
Yegappan Lakshmanan5de4c432022-02-28 13:28:38 +00001394 if (!fuzzy)
1395 {
1396 *matches = ga.ga_data;
1397 *numMatches = ga.ga_len;
1398 }
1399 else
1400 {
1401 if (fuzzymatches_to_strmatches(ga.ga_data, matches, ga.ga_len,
1402 FALSE) == FAIL)
1403 return FAIL;
1404 *numMatches = ga.ga_len;
1405 }
1406
1407 count = *numMatches;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001408 if (count > 1)
1409 {
1410 char_u **ptr1;
1411 char_u **ptr2;
1412 char_u **ptr3;
1413
1414 // Sort the matches
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001415 // Fuzzy matching already sorts the matches
1416 if (!fuzzy)
1417 sort_strings(*matches, count);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001418
1419 // Remove multiple entries
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001420 ptr1 = *matches;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001421 ptr2 = ptr1 + 1;
1422 ptr3 = ptr1 + count;
1423
1424 while (ptr2 < ptr3)
1425 {
1426 if (STRCMP(*ptr1, *ptr2))
1427 *++ptr1 = *ptr2++;
1428 else
1429 {
1430 vim_free(*ptr2++);
1431 count--;
1432 }
1433 }
1434 }
1435
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001436 *numMatches = count;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001437 return (count == 0 ? FAIL : OK);
1438}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001439
1440/*
1441 * Check for an abbreviation.
1442 * Cursor is at ptr[col].
1443 * When inserting, mincol is where insert started.
1444 * For the command line, mincol is what is to be skipped over.
1445 * "c" is the character typed before check_abbr was called. It may have
1446 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1447 *
1448 * Historic vi practice: The last character of an abbreviation must be an id
1449 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1450 * characters or all non-id characters. This allows for abbr. "#i" to
1451 * "#include".
1452 *
1453 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1454 * Then there must be white space before the abbr.
1455 *
1456 * return TRUE if there is an abbreviation, FALSE if not
1457 */
1458 int
1459check_abbr(
1460 int c,
1461 char_u *ptr,
1462 int col,
1463 int mincol)
1464{
1465 int len;
1466 int scol; // starting column of the abbr.
1467 int j;
1468 char_u *s;
1469 char_u tb[MB_MAXBYTES + 4];
1470 mapblock_T *mp;
1471 mapblock_T *mp2;
1472 int clen = 0; // length in characters
1473 int is_id = TRUE;
1474 int vim_abbr;
1475
1476 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1477 return FALSE;
1478
1479 // no remapping implies no abbreviation, except for CTRL-]
1480 if (noremap_keys() && c != Ctrl_RSB)
1481 return FALSE;
1482
1483 // Check for word before the cursor: If it ends in a keyword char all
1484 // chars before it must be keyword chars or non-keyword chars, but not
1485 // white space. If it ends in a non-keyword char we accept any characters
1486 // before it except white space.
1487 if (col == 0) // cannot be an abbr.
1488 return FALSE;
1489
1490 if (has_mbyte)
1491 {
1492 char_u *p;
1493
1494 p = mb_prevptr(ptr, ptr + col);
1495 if (!vim_iswordp(p))
1496 vim_abbr = TRUE; // Vim added abbr.
1497 else
1498 {
1499 vim_abbr = FALSE; // vi compatible abbr.
1500 if (p > ptr)
1501 is_id = vim_iswordp(mb_prevptr(ptr, p));
1502 }
1503 clen = 1;
1504 while (p > ptr + mincol)
1505 {
1506 p = mb_prevptr(ptr, p);
1507 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1508 {
1509 p += (*mb_ptr2len)(p);
1510 break;
1511 }
1512 ++clen;
1513 }
1514 scol = (int)(p - ptr);
1515 }
1516 else
1517 {
1518 if (!vim_iswordc(ptr[col - 1]))
1519 vim_abbr = TRUE; // Vim added abbr.
1520 else
1521 {
1522 vim_abbr = FALSE; // vi compatible abbr.
1523 if (col > 1)
1524 is_id = vim_iswordc(ptr[col - 2]);
1525 }
1526 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1527 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1528 ;
1529 }
1530
1531 if (scol < mincol)
1532 scol = mincol;
1533 if (scol < col) // there is a word in front of the cursor
1534 {
1535 ptr += scol;
1536 len = col - scol;
1537 mp = curbuf->b_first_abbr;
1538 mp2 = first_abbr;
1539 if (mp == NULL)
1540 {
1541 mp = mp2;
1542 mp2 = NULL;
1543 }
1544 for ( ; mp; mp->m_next == NULL
1545 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1546 {
1547 int qlen = mp->m_keylen;
1548 char_u *q = mp->m_keys;
1549 int match;
1550
1551 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1552 {
1553 char_u *qe = vim_strsave(mp->m_keys);
1554
1555 // might have CSI escaped mp->m_keys
1556 if (qe != NULL)
1557 {
1558 q = qe;
1559 vim_unescape_csi(q);
1560 qlen = (int)STRLEN(q);
1561 }
1562 }
1563
1564 // find entries with right mode and keys
1565 match = (mp->m_mode & State)
1566 && qlen == len
1567 && !STRNCMP(q, ptr, (size_t)len);
1568 if (q != mp->m_keys)
1569 vim_free(q);
1570 if (match)
1571 break;
1572 }
1573 if (mp != NULL)
1574 {
Bram Moolenaar94075b22022-01-18 20:30:39 +00001575 int noremap;
1576 int silent;
1577#ifdef FEAT_EVAL
1578 int expr;
1579#endif
1580
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001581 // Found a match:
1582 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1583 // This goes from end to start.
1584 //
1585 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1586 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1587 // Characters where IS_SPECIAL() == TRUE: key codes, need
1588 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1589 //
1590 // Character CTRL-] is treated specially - it completes the
1591 // abbreviation, but is not inserted into the input stream.
1592 j = 0;
1593 if (c != Ctrl_RSB)
1594 {
1595 // special key code, split up
1596 if (IS_SPECIAL(c) || c == K_SPECIAL)
1597 {
1598 tb[j++] = K_SPECIAL;
1599 tb[j++] = K_SECOND(c);
1600 tb[j++] = K_THIRD(c);
1601 }
1602 else
1603 {
1604 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1605 tb[j++] = Ctrl_V; // special char needs CTRL-V
1606 if (has_mbyte)
1607 {
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001608 int newlen;
1609 char_u *escaped;
1610
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001611 // if ABBR_OFF has been added, remove it here
1612 if (c >= ABBR_OFF)
1613 c -= ABBR_OFF;
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001614 newlen = (*mb_char2bytes)(c, tb + j);
1615 tb[j + newlen] = NUL;
1616 // Need to escape K_SPECIAL.
1617 escaped = vim_strsave_escape_csi(tb + j);
1618 if (escaped != NULL)
1619 {
Bram Moolenaar551c1ae2021-05-03 18:57:05 +02001620 newlen = (int)STRLEN(escaped);
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001621 mch_memmove(tb + j, escaped, newlen);
1622 j += newlen;
1623 vim_free(escaped);
1624 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001625 }
1626 else
1627 tb[j++] = c;
1628 }
1629 tb[j] = NUL;
1630 // insert the last typed char
1631 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1632 }
Bram Moolenaar94075b22022-01-18 20:30:39 +00001633
1634 // copy values here, calling eval_map_expr() may make "mp" invalid!
1635 noremap = mp->m_noremap;
1636 silent = mp->m_silent;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001637#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001638 expr = mp->m_expr;
1639
1640 if (expr)
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001641 s = eval_map_expr(mp, c);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001642 else
1643#endif
1644 s = mp->m_str;
1645 if (s != NULL)
1646 {
1647 // insert the to string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001648 (void)ins_typebuf(s, noremap, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001649 // no abbrev. for these chars
1650 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1651#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001652 if (expr)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001653 vim_free(s);
1654#endif
1655 }
1656
1657 tb[0] = Ctrl_H;
1658 tb[1] = NUL;
1659 if (has_mbyte)
1660 len = clen; // Delete characters instead of bytes
1661 while (len-- > 0) // delete the from string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001662 (void)ins_typebuf(tb, 1, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001663 return TRUE;
1664 }
1665 }
1666 return FALSE;
1667}
1668
1669#ifdef FEAT_EVAL
1670/*
1671 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1672 * special characters.
Bram Moolenaar94075b22022-01-18 20:30:39 +00001673 * Careful: after this "mp" will be invalid if the mapping was deleted.
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001674 */
1675 char_u *
1676eval_map_expr(
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001677 mapblock_T *mp,
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001678 int c) // NUL or typed character for abbreviation
1679{
1680 char_u *res;
1681 char_u *p;
1682 char_u *expr;
1683 pos_T save_cursor;
1684 int save_msg_col;
1685 int save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001686 scid_T save_sctx_sid = current_sctx.sc_sid;
1687 int save_sctx_version = current_sctx.sc_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001688
1689 // Remove escaping of CSI, because "str" is in a format to be used as
1690 // typeahead.
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001691 expr = vim_strsave(mp->m_str);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001692 if (expr == NULL)
1693 return NULL;
1694 vim_unescape_csi(expr);
1695
1696 // Forbid changing text or using ":normal" to avoid most of the bad side
1697 // effects. Also restore the cursor position.
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001698 ++textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001699 ++ex_normal_lock;
1700 set_vim_var_char(c); // set v:char to the typed character
1701 save_cursor = curwin->w_cursor;
1702 save_msg_col = msg_col;
1703 save_msg_row = msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001704 if (mp->m_script_ctx.sc_version == SCRIPT_VERSION_VIM9)
1705 {
1706 current_sctx.sc_sid = mp->m_script_ctx.sc_sid;
1707 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
1708 }
1709
1710 // Note: the evaluation may make "mp" invalid.
Bram Moolenaarb171fb12020-06-24 20:34:03 +02001711 p = eval_to_string(expr, FALSE);
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001712
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001713 --textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001714 --ex_normal_lock;
1715 curwin->w_cursor = save_cursor;
1716 msg_col = save_msg_col;
1717 msg_row = save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001718 current_sctx.sc_sid = save_sctx_sid;
1719 current_sctx.sc_version = save_sctx_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001720
1721 vim_free(expr);
1722
1723 if (p == NULL)
1724 return NULL;
1725 // Escape CSI in the result to be able to use the string as typeahead.
1726 res = vim_strsave_escape_csi(p);
1727 vim_free(p);
1728
1729 return res;
1730}
1731#endif
1732
1733/*
1734 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1735 * can be put in the typeahead buffer.
1736 * Returns NULL when out of memory.
1737 */
1738 char_u *
Bram Moolenaar957cf672020-11-12 14:21:06 +01001739vim_strsave_escape_csi(char_u *p)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001740{
1741 char_u *res;
1742 char_u *s, *d;
1743
1744 // Need a buffer to hold up to three times as much. Four in case of an
1745 // illegal utf-8 byte:
1746 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1747 res = alloc(STRLEN(p) * 4 + 1);
1748 if (res != NULL)
1749 {
1750 d = res;
1751 for (s = p; *s != NUL; )
1752 {
1753 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1754 {
1755 // Copy special key unmodified.
1756 *d++ = *s++;
1757 *d++ = *s++;
1758 *d++ = *s++;
1759 }
1760 else
1761 {
1762 // Add character, possibly multi-byte to destination, escaping
1763 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1764 d = add_char2buf(PTR2CHAR(s), d);
1765 s += MB_CPTR2LEN(s);
1766 }
1767 }
1768 *d = NUL;
1769 }
1770 return res;
1771}
1772
1773/*
1774 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1775 * vim_strsave_escape_csi(). Works in-place.
1776 */
1777 void
1778vim_unescape_csi(char_u *p)
1779{
1780 char_u *s = p, *d = p;
1781
1782 while (*s != NUL)
1783 {
1784 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1785 {
1786 *d++ = K_SPECIAL;
1787 s += 3;
1788 }
1789 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1790 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1791 {
1792 *d++ = CSI;
1793 s += 3;
1794 }
1795 else
1796 *d++ = *s++;
1797 }
1798 *d = NUL;
1799}
1800
1801/*
1802 * Write map commands for the current mappings to an .exrc file.
1803 * Return FAIL on error, OK otherwise.
1804 */
1805 int
1806makemap(
1807 FILE *fd,
1808 buf_T *buf) // buffer for local mappings or NULL
1809{
1810 mapblock_T *mp;
1811 char_u c1, c2, c3;
1812 char_u *p;
1813 char *cmd;
1814 int abbr;
1815 int hash;
1816 int did_cpo = FALSE;
1817 int i;
1818
1819 validate_maphash();
1820
1821 // Do the loop twice: Once for mappings, once for abbreviations.
1822 // Then loop over all map hash lists.
1823 for (abbr = 0; abbr < 2; ++abbr)
1824 for (hash = 0; hash < 256; ++hash)
1825 {
1826 if (abbr)
1827 {
1828 if (hash > 0) // there is only one abbr list
1829 break;
1830 if (buf != NULL)
1831 mp = buf->b_first_abbr;
1832 else
1833 mp = first_abbr;
1834 }
1835 else
1836 {
1837 if (buf != NULL)
1838 mp = buf->b_maphash[hash];
1839 else
1840 mp = maphash[hash];
1841 }
1842
1843 for ( ; mp; mp = mp->m_next)
1844 {
1845 // skip script-local mappings
1846 if (mp->m_noremap == REMAP_SCRIPT)
1847 continue;
1848
1849 // skip mappings that contain a <SNR> (script-local thing),
1850 // they probably don't work when loaded again
1851 for (p = mp->m_str; *p != NUL; ++p)
1852 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1853 && p[2] == (int)KE_SNR)
1854 break;
1855 if (*p != NUL)
1856 continue;
1857
1858 // It's possible to create a mapping and then ":unmap" certain
1859 // modes. We recreate this here by mapping the individual
1860 // modes, which requires up to three of them.
1861 c1 = NUL;
1862 c2 = NUL;
1863 c3 = NUL;
1864 if (abbr)
1865 cmd = "abbr";
1866 else
1867 cmd = "map";
1868 switch (mp->m_mode)
1869 {
1870 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1871 break;
1872 case NORMAL:
1873 c1 = 'n';
1874 break;
1875 case VISUAL:
1876 c1 = 'x';
1877 break;
1878 case SELECTMODE:
1879 c1 = 's';
1880 break;
1881 case OP_PENDING:
1882 c1 = 'o';
1883 break;
1884 case NORMAL + VISUAL:
1885 c1 = 'n';
1886 c2 = 'x';
1887 break;
1888 case NORMAL + SELECTMODE:
1889 c1 = 'n';
1890 c2 = 's';
1891 break;
1892 case NORMAL + OP_PENDING:
1893 c1 = 'n';
1894 c2 = 'o';
1895 break;
1896 case VISUAL + SELECTMODE:
1897 c1 = 'v';
1898 break;
1899 case VISUAL + OP_PENDING:
1900 c1 = 'x';
1901 c2 = 'o';
1902 break;
1903 case SELECTMODE + OP_PENDING:
1904 c1 = 's';
1905 c2 = 'o';
1906 break;
1907 case NORMAL + VISUAL + SELECTMODE:
1908 c1 = 'n';
1909 c2 = 'v';
1910 break;
1911 case NORMAL + VISUAL + OP_PENDING:
1912 c1 = 'n';
1913 c2 = 'x';
1914 c3 = 'o';
1915 break;
1916 case NORMAL + SELECTMODE + OP_PENDING:
1917 c1 = 'n';
1918 c2 = 's';
1919 c3 = 'o';
1920 break;
1921 case VISUAL + SELECTMODE + OP_PENDING:
1922 c1 = 'v';
1923 c2 = 'o';
1924 break;
1925 case CMDLINE + INSERT:
1926 if (!abbr)
1927 cmd = "map!";
1928 break;
1929 case CMDLINE:
1930 c1 = 'c';
1931 break;
1932 case INSERT:
1933 c1 = 'i';
1934 break;
1935 case LANGMAP:
1936 c1 = 'l';
1937 break;
1938 case TERMINAL:
1939 c1 = 't';
1940 break;
1941 default:
Bram Moolenaar6d057012021-12-31 18:49:43 +00001942 iemsg(_(e_makemap_illegal_mode));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001943 return FAIL;
1944 }
1945 do // do this twice if c2 is set, 3 times with c3
1946 {
1947 // When outputting <> form, need to make sure that 'cpo'
1948 // is set to the Vim default.
1949 if (!did_cpo)
1950 {
1951 if (*mp->m_str == NUL) // will use <Nop>
1952 did_cpo = TRUE;
1953 else
1954 for (i = 0; i < 2; ++i)
1955 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1956 if (*p == K_SPECIAL || *p == NL)
1957 did_cpo = TRUE;
1958 if (did_cpo)
1959 {
1960 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1961 || put_eol(fd) < 0
1962 || fprintf(fd, "set cpo&vim") < 0
1963 || put_eol(fd) < 0)
1964 return FAIL;
1965 }
1966 }
1967 if (c1 && putc(c1, fd) < 0)
1968 return FAIL;
1969 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1970 return FAIL;
1971 if (fputs(cmd, fd) < 0)
1972 return FAIL;
1973 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1974 return FAIL;
1975 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1976 return FAIL;
1977 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1978 return FAIL;
1979#ifdef FEAT_EVAL
1980 if (mp->m_noremap == REMAP_SCRIPT
1981 && fputs("<script>", fd) < 0)
1982 return FAIL;
1983 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1984 return FAIL;
1985#endif
1986
1987 if ( putc(' ', fd) < 0
1988 || put_escstr(fd, mp->m_keys, 0) == FAIL
1989 || putc(' ', fd) < 0
1990 || put_escstr(fd, mp->m_str, 1) == FAIL
1991 || put_eol(fd) < 0)
1992 return FAIL;
1993 c1 = c2;
1994 c2 = c3;
1995 c3 = NUL;
1996 } while (c1 != NUL);
1997 }
1998 }
1999
2000 if (did_cpo)
2001 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
2002 || put_eol(fd) < 0
2003 || fprintf(fd, "unlet s:cpo_save") < 0
2004 || put_eol(fd) < 0)
2005 return FAIL;
2006 return OK;
2007}
2008
2009/*
2010 * write escape string to file
2011 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
2012 *
2013 * return FAIL for failure, OK otherwise
2014 */
2015 int
2016put_escstr(FILE *fd, char_u *strstart, int what)
2017{
2018 char_u *str = strstart;
2019 int c;
2020 int modifiers;
2021
2022 // :map xx <Nop>
2023 if (*str == NUL && what == 1)
2024 {
2025 if (fprintf(fd, "<Nop>") < 0)
2026 return FAIL;
2027 return OK;
2028 }
2029
2030 for ( ; *str != NUL; ++str)
2031 {
2032 char_u *p;
2033
2034 // Check for a multi-byte character, which may contain escaped
2035 // K_SPECIAL and CSI bytes
2036 p = mb_unescape(&str);
2037 if (p != NULL)
2038 {
2039 while (*p != NUL)
2040 if (fputc(*p++, fd) < 0)
2041 return FAIL;
2042 --str;
2043 continue;
2044 }
2045
2046 c = *str;
2047 // Special key codes have to be translated to be able to make sense
2048 // when they are read back.
2049 if (c == K_SPECIAL && what != 2)
2050 {
Bram Moolenaar02c037a2020-08-30 19:26:45 +02002051 modifiers = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002052 if (str[1] == KS_MODIFIER)
2053 {
2054 modifiers = str[2];
2055 str += 3;
2056 c = *str;
2057 }
2058 if (c == K_SPECIAL)
2059 {
2060 c = TO_SPECIAL(str[1], str[2]);
2061 str += 2;
2062 }
2063 if (IS_SPECIAL(c) || modifiers) // special key
2064 {
2065 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
2066 return FAIL;
2067 continue;
2068 }
2069 }
2070
2071 // A '\n' in a map command should be written as <NL>.
2072 // A '\n' in a set command should be written as \^V^J.
2073 if (c == NL)
2074 {
2075 if (what == 2)
2076 {
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002077 if (fprintf(fd, "\\\026\n") < 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002078 return FAIL;
2079 }
2080 else
2081 {
2082 if (fprintf(fd, "<NL>") < 0)
2083 return FAIL;
2084 }
2085 continue;
2086 }
2087
2088 // Some characters have to be escaped with CTRL-V to
2089 // prevent them from misinterpreted in DoOneCmd().
2090 // A space, Tab and '"' has to be escaped with a backslash to
2091 // prevent it to be misinterpreted in do_set().
2092 // A space has to be escaped with a CTRL-V when it's at the start of a
2093 // ":map" rhs.
2094 // A '<' has to be escaped with a CTRL-V to prevent it being
2095 // interpreted as the start of a special key name.
2096 // A space in the lhs of a :map needs a CTRL-V.
2097 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2098 {
2099 if (putc('\\', fd) < 0)
2100 return FAIL;
2101 }
2102 else if (c < ' ' || c > '~' || c == '|'
2103 || (what == 0 && c == ' ')
2104 || (what == 1 && str == strstart && c == ' ')
2105 || (what != 2 && c == '<'))
2106 {
2107 if (putc(Ctrl_V, fd) < 0)
2108 return FAIL;
2109 }
2110 if (putc(c, fd) < 0)
2111 return FAIL;
2112 }
2113 return OK;
2114}
2115
2116/*
2117 * Check all mappings for the presence of special key codes.
2118 * Used after ":set term=xxx".
2119 */
2120 void
2121check_map_keycodes(void)
2122{
2123 mapblock_T *mp;
2124 char_u *p;
2125 int i;
2126 char_u buf[3];
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002127 int abbr;
2128 int hash;
2129 buf_T *bp;
Bram Moolenaare31ee862020-01-07 20:59:34 +01002130 ESTACK_CHECK_DECLARATION
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002131
2132 validate_maphash();
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002133 // avoids giving error messages
2134 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
Bram Moolenaare31ee862020-01-07 20:59:34 +01002135 ESTACK_CHECK_SETUP
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002136
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002137 // Do this once for each buffer, and then once for global
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002138 // mappings/abbreviations with bp == NULL
2139 for (bp = firstbuf; ; bp = bp->b_next)
2140 {
2141 // Do the loop twice: Once for mappings, once for abbreviations.
2142 // Then loop over all map hash lists.
2143 for (abbr = 0; abbr <= 1; ++abbr)
2144 for (hash = 0; hash < 256; ++hash)
2145 {
2146 if (abbr)
2147 {
2148 if (hash) // there is only one abbr list
2149 break;
2150 if (bp != NULL)
2151 mp = bp->b_first_abbr;
2152 else
2153 mp = first_abbr;
2154 }
2155 else
2156 {
2157 if (bp != NULL)
2158 mp = bp->b_maphash[hash];
2159 else
2160 mp = maphash[hash];
2161 }
2162 for ( ; mp != NULL; mp = mp->m_next)
2163 {
2164 for (i = 0; i <= 1; ++i) // do this twice
2165 {
2166 if (i == 0)
2167 p = mp->m_keys; // once for the "from" part
2168 else
2169 p = mp->m_str; // and once for the "to" part
2170 while (*p)
2171 {
2172 if (*p == K_SPECIAL)
2173 {
2174 ++p;
2175 if (*p < 128) // for "normal" tcap entries
2176 {
2177 buf[0] = p[0];
2178 buf[1] = p[1];
2179 buf[2] = NUL;
2180 (void)add_termcap_entry(buf, FALSE);
2181 }
2182 ++p;
2183 }
2184 ++p;
2185 }
2186 }
2187 }
2188 }
2189 if (bp == NULL)
2190 break;
2191 }
Bram Moolenaare31ee862020-01-07 20:59:34 +01002192 ESTACK_CHECK_NOW
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002193 estack_pop();
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002194}
2195
2196#if defined(FEAT_EVAL) || defined(PROTO)
2197/*
2198 * Check the string "keys" against the lhs of all mappings.
2199 * Return pointer to rhs of mapping (mapblock->m_str).
2200 * NULL when no mapping found.
2201 */
2202 char_u *
2203check_map(
2204 char_u *keys,
2205 int mode,
2206 int exact, // require exact match
2207 int ign_mod, // ignore preceding modifier
2208 int abbr, // do abbreviations
2209 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2210 int *local_ptr) // return: buffer-local mapping or NULL
2211{
2212 int hash;
2213 int len, minlen;
2214 mapblock_T *mp;
2215 char_u *s;
2216 int local;
2217
2218 validate_maphash();
2219
2220 len = (int)STRLEN(keys);
2221 for (local = 1; local >= 0; --local)
2222 // loop over all hash lists
2223 for (hash = 0; hash < 256; ++hash)
2224 {
2225 if (abbr)
2226 {
2227 if (hash > 0) // there is only one list.
2228 break;
2229 if (local)
2230 mp = curbuf->b_first_abbr;
2231 else
2232 mp = first_abbr;
2233 }
2234 else if (local)
2235 mp = curbuf->b_maphash[hash];
2236 else
2237 mp = maphash[hash];
2238 for ( ; mp != NULL; mp = mp->m_next)
2239 {
2240 // skip entries with wrong mode, wrong length and not matching
2241 // ones
2242 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2243 {
2244 if (len > mp->m_keylen)
2245 minlen = mp->m_keylen;
2246 else
2247 minlen = len;
2248 s = mp->m_keys;
2249 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2250 && s[2] != NUL)
2251 {
2252 s += 3;
2253 if (len > mp->m_keylen - 3)
2254 minlen = mp->m_keylen - 3;
2255 }
2256 if (STRNCMP(s, keys, minlen) == 0)
2257 {
2258 if (mp_ptr != NULL)
2259 *mp_ptr = mp;
2260 if (local_ptr != NULL)
2261 *local_ptr = local;
2262 return mp->m_str;
2263 }
2264 }
2265 }
2266 }
2267
2268 return NULL;
2269}
2270
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002271 static void
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002272get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2273{
2274 char_u *keys;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002275 char_u *keys_simplified;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002276 char_u *which;
2277 char_u buf[NUMBUFLEN];
2278 char_u *keys_buf = NULL;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002279 char_u *alt_keys_buf = NULL;
2280 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002281 char_u *rhs;
2282 int mode;
2283 int abbr = FALSE;
2284 int get_dict = FALSE;
2285 mapblock_T *mp;
Bram Moolenaara55ba062020-05-27 21:29:04 +02002286 mapblock_T *mp_simplified = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002287 int buffer_local;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002288 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002289
2290 // return empty string for failure
2291 rettv->v_type = VAR_STRING;
2292 rettv->vval.v_string = NULL;
2293
2294 keys = tv_get_string(&argvars[0]);
2295 if (*keys == NUL)
2296 return;
2297
2298 if (argvars[1].v_type != VAR_UNKNOWN)
2299 {
2300 which = tv_get_string_buf_chk(&argvars[1], buf);
2301 if (argvars[2].v_type != VAR_UNKNOWN)
2302 {
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002303 abbr = (int)tv_get_bool(&argvars[2]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002304 if (argvars[3].v_type != VAR_UNKNOWN)
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002305 get_dict = (int)tv_get_bool(&argvars[3]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002306 }
2307 }
2308 else
2309 which = (char_u *)"";
2310 if (which == NULL)
2311 return;
2312
2313 mode = get_map_mode(&which, 0);
2314
Bram Moolenaar9c652532020-05-24 13:10:18 +02002315 keys_simplified = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
2316 rhs = check_map(keys_simplified, mode, exact, FALSE, abbr,
2317 &mp, &buffer_local);
2318 if (did_simplify)
2319 {
2320 // When the lhs is being simplified the not-simplified keys are
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002321 // preferred for printing, like in do_map().
Bram Moolenaar9c652532020-05-24 13:10:18 +02002322 // The "rhs" and "buffer_local" values are not expected to change.
2323 mp_simplified = mp;
2324 (void)replace_termcodes(keys, &alt_keys_buf,
2325 flags | REPTERM_NO_SIMPLIFY, NULL);
2326 rhs = check_map(alt_keys_buf, mode, exact, FALSE, abbr, &mp,
2327 &buffer_local);
2328 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002329
2330 if (!get_dict)
2331 {
2332 // Return a string.
2333 if (rhs != NULL)
2334 {
2335 if (*rhs == NUL)
2336 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2337 else
2338 rettv->vval.v_string = str2special_save(rhs, FALSE);
2339 }
2340
2341 }
2342 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2343 {
2344 // Return a dictionary.
2345 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2346 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2347 dict_T *dict = rettv->vval.v_dict;
2348
2349 dict_add_string(dict, "lhs", lhs);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002350 vim_free(lhs);
2351 dict_add_string(dict, "lhsraw", mp->m_keys);
2352 if (did_simplify)
2353 // Also add the value for the simplified entry.
2354 dict_add_string(dict, "lhsrawalt", mp_simplified->m_keys);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002355 dict_add_string(dict, "rhs", mp->m_orig_str);
2356 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
Bram Moolenaar2da0f0c2020-04-01 19:22:12 +02002357 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2358 ? 1L : 0L);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002359 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2360 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2361 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
Bram Moolenaara9528b32022-01-18 20:51:35 +00002362 dict_add_number(dict, "scriptversion",
2363 (long)mp->m_script_ctx.sc_version);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002364 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2365 dict_add_number(dict, "buffer", (long)buffer_local);
2366 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2367 dict_add_string(dict, "mode", mapmode);
2368
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002369 vim_free(mapmode);
2370 }
Bram Moolenaar9c652532020-05-24 13:10:18 +02002371
2372 vim_free(keys_buf);
2373 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002374}
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002375
2376/*
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002377 * "maparg()" function
2378 */
2379 void
2380f_maparg(typval_T *argvars, typval_T *rettv)
2381{
2382 if (in_vim9script()
2383 && (check_for_string_arg(argvars, 0) == FAIL
2384 || check_for_opt_string_arg(argvars, 1) == FAIL
2385 || (argvars[1].v_type != VAR_UNKNOWN
2386 && (check_for_opt_bool_arg(argvars, 2) == FAIL
2387 || (argvars[2].v_type != VAR_UNKNOWN
2388 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
2389 return;
2390
2391 get_maparg(argvars, rettv, TRUE);
2392}
2393
2394/*
2395 * "mapcheck()" function
2396 */
2397 void
2398f_mapcheck(typval_T *argvars, typval_T *rettv)
2399{
2400 if (in_vim9script()
2401 && (check_for_string_arg(argvars, 0) == FAIL
2402 || check_for_opt_string_arg(argvars, 1) == FAIL
2403 || (argvars[1].v_type != VAR_UNKNOWN
2404 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2405 return;
2406
2407 get_maparg(argvars, rettv, FALSE);
2408}
2409
2410/*
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002411 * "mapset()" function
2412 */
2413 void
2414f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2415{
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002416 char_u *keys_buf = NULL;
2417 char_u *which;
2418 int mode;
2419 char_u buf[NUMBUFLEN];
2420 int is_abbr;
2421 dict_T *d;
2422 char_u *lhs;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002423 char_u *lhsraw;
2424 char_u *lhsrawalt;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002425 char_u *rhs;
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002426 char_u *orig_rhs;
2427 char_u *arg_buf = NULL;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002428 int noremap;
2429 int expr;
2430 int silent;
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002431 int buffer;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002432 scid_T sid;
Bram Moolenaara9528b32022-01-18 20:51:35 +00002433 int scriptversion;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002434 linenr_T lnum;
2435 mapblock_T **map_table = maphash;
2436 mapblock_T **abbr_table = &first_abbr;
2437 int nowait;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002438 char_u *arg;
2439
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002440 if (in_vim9script()
2441 && (check_for_string_arg(argvars, 0) == FAIL
2442 || check_for_bool_arg(argvars, 1) == FAIL
2443 || check_for_dict_arg(argvars, 2) == FAIL))
2444 return;
2445
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002446 which = tv_get_string_buf_chk(&argvars[0], buf);
Bram Moolenaar1b912982020-09-29 21:45:41 +02002447 if (which == NULL)
2448 return;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002449 mode = get_map_mode(&which, 0);
Bram Moolenaar74273e62020-10-01 21:37:21 +02002450 is_abbr = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002451
2452 if (argvars[2].v_type != VAR_DICT)
2453 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002454 emsg(_(e_key_not_present_in_dictionary));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002455 return;
2456 }
2457 d = argvars[2].vval.v_dict;
2458
2459 // Get the values in the same order as above in get_maparg().
2460 lhs = dict_get_string(d, (char_u *)"lhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002461 lhsraw = dict_get_string(d, (char_u *)"lhsraw", FALSE);
2462 lhsrawalt = dict_get_string(d, (char_u *)"lhsrawalt", FALSE);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002463 rhs = dict_get_string(d, (char_u *)"rhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002464 if (lhs == NULL || lhsraw == NULL || rhs == NULL)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002465 {
Bram Moolenaarb09feaa2022-01-02 20:20:45 +00002466 emsg(_(e_entries_missing_in_mapset_dict_argument));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002467 return;
2468 }
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002469 orig_rhs = rhs;
2470 rhs = replace_termcodes(rhs, &arg_buf,
2471 REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002472
2473 noremap = dict_get_number(d, (char_u *)"noremap") ? REMAP_NONE: 0;
2474 if (dict_get_number(d, (char_u *)"script") != 0)
2475 noremap = REMAP_SCRIPT;
2476 expr = dict_get_number(d, (char_u *)"expr") != 0;
2477 silent = dict_get_number(d, (char_u *)"silent") != 0;
2478 sid = dict_get_number(d, (char_u *)"sid");
Bram Moolenaara9528b32022-01-18 20:51:35 +00002479 scriptversion = dict_get_number(d, (char_u *)"scriptversion");
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002480 lnum = dict_get_number(d, (char_u *)"lnum");
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002481 buffer = dict_get_number(d, (char_u *)"buffer");
2482 nowait = dict_get_number(d, (char_u *)"nowait") != 0;
2483 // mode from the dict is not used
2484
2485 if (buffer)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002486 {
2487 map_table = curbuf->b_maphash;
2488 abbr_table = &curbuf->b_first_abbr;
2489 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002490
2491 // Delete any existing mapping for this lhs and mode.
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002492 if (buffer)
2493 {
2494 arg = alloc(STRLEN(lhs) + STRLEN("<buffer>") + 1);
2495 if (arg == NULL)
2496 return;
2497 STRCPY(arg, "<buffer>");
2498 STRCPY(arg + 8, lhs);
2499 }
2500 else
2501 {
2502 arg = vim_strsave(lhs);
2503 if (arg == NULL)
2504 return;
2505 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002506 do_map(1, arg, mode, is_abbr);
2507 vim_free(arg);
2508
Bram Moolenaar9c652532020-05-24 13:10:18 +02002509 (void)map_add(map_table, abbr_table, lhsraw, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002510 nowait, silent, mode, is_abbr, expr, sid, scriptversion, lnum, 0);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002511 if (lhsrawalt != NULL)
2512 (void)map_add(map_table, abbr_table, lhsrawalt, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002513 nowait, silent, mode, is_abbr, expr, sid, scriptversion,
2514 lnum, 1);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002515 vim_free(keys_buf);
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002516 vim_free(arg_buf);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002517}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002518#endif
2519
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002520
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002521#if defined(MSWIN) || defined(MACOS_X)
2522
2523# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2524
2525/*
2526 * Default mappings for some often used keys.
2527 */
2528struct initmap
2529{
2530 char_u *arg;
2531 int mode;
2532};
2533
2534# ifdef FEAT_GUI_MSWIN
2535// Use the Windows (CUA) keybindings. (GUI)
2536static struct initmap initmappings[] =
2537{
2538 // paste, copy and cut
2539 {(char_u *)"<S-Insert> \"*P", NORMAL},
2540 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2541 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2542 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2543 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2544 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2545 {(char_u *)"<C-X> \"*d", VIS_SEL},
2546 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2547};
2548# endif
2549
2550# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2551// Use the Windows (CUA) keybindings. (Console)
2552static struct initmap cinitmappings[] =
2553{
2554 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2555 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2556 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2557 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2558
2559 // paste, copy and cut
2560# ifdef FEAT_CLIPBOARD
2561 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2562 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2563 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2564 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2565 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2566 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2567 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2568# else
2569 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2570 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2571 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2572 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2573 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2574 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2575# endif
2576};
2577# endif
2578
2579# if defined(MACOS_X)
2580static struct initmap initmappings[] =
2581{
2582 // Use the Standard MacOS binding.
2583 // paste, copy and cut
2584 {(char_u *)"<D-v> \"*P", NORMAL},
2585 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2586 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2587 {(char_u *)"<D-c> \"*y", VIS_SEL},
2588 {(char_u *)"<D-x> \"*d", VIS_SEL},
2589 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2590};
2591# endif
2592
2593# undef VIS_SEL
2594#endif
2595
2596/*
2597 * Set up default mappings.
2598 */
2599 void
2600init_mappings(void)
2601{
2602#if defined(MSWIN) || defined(MACOS_X)
2603 int i;
2604
2605# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2606# ifdef VIMDLL
2607 if (!gui.starting)
2608# endif
2609 {
K.Takataeeec2542021-06-02 13:28:16 +02002610 for (i = 0; i < (int)ARRAY_LENGTH(cinitmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002611 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2612 }
2613# endif
2614# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
K.Takataeeec2542021-06-02 13:28:16 +02002615 for (i = 0; i < (int)ARRAY_LENGTH(initmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002616 add_map(initmappings[i].arg, initmappings[i].mode);
2617# endif
2618#endif
2619}
2620
2621#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2622 || defined(PROTO)
2623/*
2624 * Add a mapping "map" for mode "mode".
2625 * Need to put string in allocated memory, because do_map() will modify it.
2626 */
2627 void
2628add_map(char_u *map, int mode)
2629{
2630 char_u *s;
2631 char_u *cpo_save = p_cpo;
2632
Bram Moolenaare5a2dc82021-01-03 19:52:05 +01002633 p_cpo = empty_option; // Allow <> notation
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002634 s = vim_strsave(map);
2635 if (s != NULL)
2636 {
2637 (void)do_map(0, s, mode, FALSE);
2638 vim_free(s);
2639 }
2640 p_cpo = cpo_save;
2641}
2642#endif
2643
Bram Moolenaare677df82019-09-02 22:31:11 +02002644#if defined(FEAT_LANGMAP) || defined(PROTO)
2645/*
2646 * Any character has an equivalent 'langmap' character. This is used for
2647 * keyboards that have a special language mode that sends characters above
2648 * 128 (although other characters can be translated too). The "to" field is a
2649 * Vim command character. This avoids having to switch the keyboard back to
2650 * ASCII mode when leaving Insert mode.
2651 *
2652 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2653 * commands.
2654 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2655 * same as langmap_mapchar[] for characters >= 256.
2656 *
2657 * Use growarray for 'langmap' chars >= 256
2658 */
2659typedef struct
2660{
2661 int from;
2662 int to;
2663} langmap_entry_T;
2664
2665static garray_T langmap_mapga;
2666
2667/*
2668 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2669 * field. If not found insert a new entry at the appropriate location.
2670 */
2671 static void
2672langmap_set_entry(int from, int to)
2673{
2674 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2675 int a = 0;
2676 int b = langmap_mapga.ga_len;
2677
2678 // Do a binary search for an existing entry.
2679 while (a != b)
2680 {
2681 int i = (a + b) / 2;
2682 int d = entries[i].from - from;
2683
2684 if (d == 0)
2685 {
2686 entries[i].to = to;
2687 return;
2688 }
2689 if (d < 0)
2690 a = i + 1;
2691 else
2692 b = i;
2693 }
2694
2695 if (ga_grow(&langmap_mapga, 1) != OK)
2696 return; // out of memory
2697
2698 // insert new entry at position "a"
2699 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2700 mch_memmove(entries + 1, entries,
2701 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2702 ++langmap_mapga.ga_len;
2703 entries[0].from = from;
2704 entries[0].to = to;
2705}
2706
2707/*
2708 * Apply 'langmap' to multi-byte character "c" and return the result.
2709 */
2710 int
2711langmap_adjust_mb(int c)
2712{
2713 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2714 int a = 0;
2715 int b = langmap_mapga.ga_len;
2716
2717 while (a != b)
2718 {
2719 int i = (a + b) / 2;
2720 int d = entries[i].from - c;
2721
2722 if (d == 0)
2723 return entries[i].to; // found matching entry
2724 if (d < 0)
2725 a = i + 1;
2726 else
2727 b = i;
2728 }
2729 return c; // no entry found, return "c" unmodified
2730}
2731
2732 void
2733langmap_init(void)
2734{
2735 int i;
2736
2737 for (i = 0; i < 256; i++)
2738 langmap_mapchar[i] = i; // we init with a one-to-one map
2739 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
2740}
2741
2742/*
2743 * Called when langmap option is set; the language map can be
2744 * changed at any time!
2745 */
2746 void
2747langmap_set(void)
2748{
2749 char_u *p;
2750 char_u *p2;
2751 int from, to;
2752
2753 ga_clear(&langmap_mapga); // clear the previous map first
2754 langmap_init(); // back to one-to-one map
2755
2756 for (p = p_langmap; p[0] != NUL; )
2757 {
2758 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2759 MB_PTR_ADV(p2))
2760 {
2761 if (p2[0] == '\\' && p2[1] != NUL)
2762 ++p2;
2763 }
2764 if (p2[0] == ';')
2765 ++p2; // abcd;ABCD form, p2 points to A
2766 else
2767 p2 = NULL; // aAbBcCdD form, p2 is NULL
2768 while (p[0])
2769 {
2770 if (p[0] == ',')
2771 {
2772 ++p;
2773 break;
2774 }
2775 if (p[0] == '\\' && p[1] != NUL)
2776 ++p;
2777 from = (*mb_ptr2char)(p);
2778 to = NUL;
2779 if (p2 == NULL)
2780 {
2781 MB_PTR_ADV(p);
2782 if (p[0] != ',')
2783 {
2784 if (p[0] == '\\')
2785 ++p;
2786 to = (*mb_ptr2char)(p);
2787 }
2788 }
2789 else
2790 {
2791 if (p2[0] != ',')
2792 {
2793 if (p2[0] == '\\')
2794 ++p2;
2795 to = (*mb_ptr2char)(p2);
2796 }
2797 }
2798 if (to == NUL)
2799 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002800 semsg(_(e_langmap_matching_character_missing_for_str),
Bram Moolenaare677df82019-09-02 22:31:11 +02002801 transchar(from));
2802 return;
2803 }
2804
2805 if (from >= 256)
2806 langmap_set_entry(from, to);
2807 else
2808 langmap_mapchar[from & 255] = to;
2809
2810 // Advance to next pair
2811 MB_PTR_ADV(p);
2812 if (p2 != NULL)
2813 {
2814 MB_PTR_ADV(p2);
2815 if (*p == ';')
2816 {
2817 p = p2;
2818 if (p[0] != NUL)
2819 {
2820 if (p[0] != ',')
2821 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002822 semsg(_(e_langmap_extra_characters_after_semicolon_str), p);
Bram Moolenaare677df82019-09-02 22:31:11 +02002823 return;
2824 }
2825 ++p;
2826 }
2827 break;
2828 }
2829 }
2830 }
2831 }
2832}
2833#endif
2834
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002835 static void
2836do_exmap(exarg_T *eap, int isabbrev)
2837{
2838 int mode;
2839 char_u *cmdp;
2840
2841 cmdp = eap->cmd;
2842 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2843
2844 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2845 eap->arg, mode, isabbrev))
2846 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002847 case 1: emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002848 break;
Bram Moolenaare29a27f2021-07-20 21:07:36 +02002849 case 2: emsg((isabbrev ? _(e_no_such_abbreviation)
2850 : _(e_no_such_mapping)));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002851 break;
2852 }
2853}
2854
2855/*
2856 * ":abbreviate" and friends.
2857 */
2858 void
2859ex_abbreviate(exarg_T *eap)
2860{
2861 do_exmap(eap, TRUE); // almost the same as mapping
2862}
2863
2864/*
2865 * ":map" and friends.
2866 */
2867 void
2868ex_map(exarg_T *eap)
2869{
2870 // If we are sourcing .exrc or .vimrc in current directory we
2871 // print the mappings for security reasons.
2872 if (secure)
2873 {
2874 secure = 2;
2875 msg_outtrans(eap->cmd);
2876 msg_putchar('\n');
2877 }
2878 do_exmap(eap, FALSE);
2879}
2880
2881/*
2882 * ":unmap" and friends.
2883 */
2884 void
2885ex_unmap(exarg_T *eap)
2886{
2887 do_exmap(eap, FALSE);
2888}
2889
2890/*
2891 * ":mapclear" and friends.
2892 */
2893 void
2894ex_mapclear(exarg_T *eap)
2895{
2896 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2897}
2898
2899/*
2900 * ":abclear" and friends.
2901 */
2902 void
2903ex_abclear(exarg_T *eap)
2904{
2905 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2906}