blob: 594c934d23e1f78597a039d0f93aadb3904e912f [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;
1266 int hash;
1267 int count;
1268 int round;
1269 char_u *p;
1270 int i;
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001271 int fuzzy;
1272 int match;
1273 int score;
1274 fuzmatch_str_T *fuzmatch = NULL;
1275
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
1283 // round == 1: Count the matches.
1284 // round == 2: Build the array to keep the matches.
1285 for (round = 1; round <= 2; ++round)
1286 {
1287 count = 0;
1288
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001289 // First search in map modifier arguments
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001290 for (i = 0; i < 7; ++i)
1291 {
1292 if (i == 0)
1293 p = (char_u *)"<silent>";
1294 else if (i == 1)
1295 p = (char_u *)"<unique>";
1296#ifdef FEAT_EVAL
1297 else if (i == 2)
1298 p = (char_u *)"<script>";
1299 else if (i == 3)
1300 p = (char_u *)"<expr>";
1301#endif
1302 else if (i == 4 && !expand_buffer)
1303 p = (char_u *)"<buffer>";
1304 else if (i == 5)
1305 p = (char_u *)"<nowait>";
1306 else if (i == 6)
1307 p = (char_u *)"<special>";
1308 else
1309 continue;
1310
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001311 if (!fuzzy)
1312 match = vim_regexec(regmatch, p, (colnr_T)0);
1313 else
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001314 {
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001315 score = fuzzy_match_str(p, pat);
1316 match = (score != 0);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001317 }
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001318
1319 if (!match)
1320 continue;
1321
1322 if (round == 2)
1323 {
1324 if (fuzzy)
1325 {
1326 fuzmatch[count].idx = count;
1327 fuzmatch[count].str = vim_strsave(p);
1328 fuzmatch[count].score = score;
1329 }
1330 else
1331 (*matches)[count] = vim_strsave(p);
1332 }
1333 ++count;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001334 }
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 {
1352 p = translate_mapping(mp->m_keys);
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001353 if (p != NULL)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001354 {
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001355 if (!fuzzy)
1356 match = vim_regexec(regmatch, p, (colnr_T)0);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001357 else
1358 {
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001359 score = fuzzy_match_str(p, pat);
1360 match = (score != 0);
1361 }
1362
1363 if (match)
1364 {
1365 if (round == 2)
1366 {
1367 if (fuzzy)
1368 {
1369 fuzmatch[count].idx = count;
1370 fuzmatch[count].str = p;
1371 fuzmatch[count].score = score;
1372 }
1373 else
1374 (*matches)[count] = p;
1375 p = NULL;
1376 }
1377 ++count;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001378 }
1379 }
1380 vim_free(p);
1381 }
1382 } // for (mp)
1383 } // for (hash)
1384
1385 if (count == 0) // no match found
1386 break; // for (round)
1387
1388 if (round == 1)
1389 {
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001390 if (fuzzy)
1391 {
1392 fuzmatch = ALLOC_MULT(fuzmatch_str_T, count);
1393 if (fuzmatch == NULL)
1394 return FAIL;
1395 }
1396 else
1397 {
1398 *matches = ALLOC_MULT(char_u *, count);
1399 if (*matches == NULL)
1400 return FAIL;
1401 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001402 }
1403 } // for (round)
1404
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001405 if (fuzzy && fuzzymatches_to_strmatches(fuzmatch, matches, count,
1406 FALSE) == FAIL)
1407 return FAIL;
1408
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001409 if (count > 1)
1410 {
1411 char_u **ptr1;
1412 char_u **ptr2;
1413 char_u **ptr3;
1414
1415 // Sort the matches
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001416 // Fuzzy matching already sorts the matches
1417 if (!fuzzy)
1418 sort_strings(*matches, count);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001419
1420 // Remove multiple entries
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001421 ptr1 = *matches;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001422 ptr2 = ptr1 + 1;
1423 ptr3 = ptr1 + count;
1424
1425 while (ptr2 < ptr3)
1426 {
1427 if (STRCMP(*ptr1, *ptr2))
1428 *++ptr1 = *ptr2++;
1429 else
1430 {
1431 vim_free(*ptr2++);
1432 count--;
1433 }
1434 }
1435 }
1436
Yegappan Lakshmanan6caeda22022-02-27 12:07:30 +00001437 *numMatches = count;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001438 return (count == 0 ? FAIL : OK);
1439}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001440
1441/*
1442 * Check for an abbreviation.
1443 * Cursor is at ptr[col].
1444 * When inserting, mincol is where insert started.
1445 * For the command line, mincol is what is to be skipped over.
1446 * "c" is the character typed before check_abbr was called. It may have
1447 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1448 *
1449 * Historic vi practice: The last character of an abbreviation must be an id
1450 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1451 * characters or all non-id characters. This allows for abbr. "#i" to
1452 * "#include".
1453 *
1454 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1455 * Then there must be white space before the abbr.
1456 *
1457 * return TRUE if there is an abbreviation, FALSE if not
1458 */
1459 int
1460check_abbr(
1461 int c,
1462 char_u *ptr,
1463 int col,
1464 int mincol)
1465{
1466 int len;
1467 int scol; // starting column of the abbr.
1468 int j;
1469 char_u *s;
1470 char_u tb[MB_MAXBYTES + 4];
1471 mapblock_T *mp;
1472 mapblock_T *mp2;
1473 int clen = 0; // length in characters
1474 int is_id = TRUE;
1475 int vim_abbr;
1476
1477 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1478 return FALSE;
1479
1480 // no remapping implies no abbreviation, except for CTRL-]
1481 if (noremap_keys() && c != Ctrl_RSB)
1482 return FALSE;
1483
1484 // Check for word before the cursor: If it ends in a keyword char all
1485 // chars before it must be keyword chars or non-keyword chars, but not
1486 // white space. If it ends in a non-keyword char we accept any characters
1487 // before it except white space.
1488 if (col == 0) // cannot be an abbr.
1489 return FALSE;
1490
1491 if (has_mbyte)
1492 {
1493 char_u *p;
1494
1495 p = mb_prevptr(ptr, ptr + col);
1496 if (!vim_iswordp(p))
1497 vim_abbr = TRUE; // Vim added abbr.
1498 else
1499 {
1500 vim_abbr = FALSE; // vi compatible abbr.
1501 if (p > ptr)
1502 is_id = vim_iswordp(mb_prevptr(ptr, p));
1503 }
1504 clen = 1;
1505 while (p > ptr + mincol)
1506 {
1507 p = mb_prevptr(ptr, p);
1508 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1509 {
1510 p += (*mb_ptr2len)(p);
1511 break;
1512 }
1513 ++clen;
1514 }
1515 scol = (int)(p - ptr);
1516 }
1517 else
1518 {
1519 if (!vim_iswordc(ptr[col - 1]))
1520 vim_abbr = TRUE; // Vim added abbr.
1521 else
1522 {
1523 vim_abbr = FALSE; // vi compatible abbr.
1524 if (col > 1)
1525 is_id = vim_iswordc(ptr[col - 2]);
1526 }
1527 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1528 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1529 ;
1530 }
1531
1532 if (scol < mincol)
1533 scol = mincol;
1534 if (scol < col) // there is a word in front of the cursor
1535 {
1536 ptr += scol;
1537 len = col - scol;
1538 mp = curbuf->b_first_abbr;
1539 mp2 = first_abbr;
1540 if (mp == NULL)
1541 {
1542 mp = mp2;
1543 mp2 = NULL;
1544 }
1545 for ( ; mp; mp->m_next == NULL
1546 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1547 {
1548 int qlen = mp->m_keylen;
1549 char_u *q = mp->m_keys;
1550 int match;
1551
1552 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1553 {
1554 char_u *qe = vim_strsave(mp->m_keys);
1555
1556 // might have CSI escaped mp->m_keys
1557 if (qe != NULL)
1558 {
1559 q = qe;
1560 vim_unescape_csi(q);
1561 qlen = (int)STRLEN(q);
1562 }
1563 }
1564
1565 // find entries with right mode and keys
1566 match = (mp->m_mode & State)
1567 && qlen == len
1568 && !STRNCMP(q, ptr, (size_t)len);
1569 if (q != mp->m_keys)
1570 vim_free(q);
1571 if (match)
1572 break;
1573 }
1574 if (mp != NULL)
1575 {
Bram Moolenaar94075b22022-01-18 20:30:39 +00001576 int noremap;
1577 int silent;
1578#ifdef FEAT_EVAL
1579 int expr;
1580#endif
1581
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001582 // Found a match:
1583 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1584 // This goes from end to start.
1585 //
1586 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1587 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1588 // Characters where IS_SPECIAL() == TRUE: key codes, need
1589 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1590 //
1591 // Character CTRL-] is treated specially - it completes the
1592 // abbreviation, but is not inserted into the input stream.
1593 j = 0;
1594 if (c != Ctrl_RSB)
1595 {
1596 // special key code, split up
1597 if (IS_SPECIAL(c) || c == K_SPECIAL)
1598 {
1599 tb[j++] = K_SPECIAL;
1600 tb[j++] = K_SECOND(c);
1601 tb[j++] = K_THIRD(c);
1602 }
1603 else
1604 {
1605 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1606 tb[j++] = Ctrl_V; // special char needs CTRL-V
1607 if (has_mbyte)
1608 {
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001609 int newlen;
1610 char_u *escaped;
1611
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001612 // if ABBR_OFF has been added, remove it here
1613 if (c >= ABBR_OFF)
1614 c -= ABBR_OFF;
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001615 newlen = (*mb_char2bytes)(c, tb + j);
1616 tb[j + newlen] = NUL;
1617 // Need to escape K_SPECIAL.
1618 escaped = vim_strsave_escape_csi(tb + j);
1619 if (escaped != NULL)
1620 {
Bram Moolenaar551c1ae2021-05-03 18:57:05 +02001621 newlen = (int)STRLEN(escaped);
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001622 mch_memmove(tb + j, escaped, newlen);
1623 j += newlen;
1624 vim_free(escaped);
1625 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001626 }
1627 else
1628 tb[j++] = c;
1629 }
1630 tb[j] = NUL;
1631 // insert the last typed char
1632 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1633 }
Bram Moolenaar94075b22022-01-18 20:30:39 +00001634
1635 // copy values here, calling eval_map_expr() may make "mp" invalid!
1636 noremap = mp->m_noremap;
1637 silent = mp->m_silent;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001638#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001639 expr = mp->m_expr;
1640
1641 if (expr)
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001642 s = eval_map_expr(mp, c);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001643 else
1644#endif
1645 s = mp->m_str;
1646 if (s != NULL)
1647 {
1648 // insert the to string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001649 (void)ins_typebuf(s, noremap, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001650 // no abbrev. for these chars
1651 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1652#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001653 if (expr)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001654 vim_free(s);
1655#endif
1656 }
1657
1658 tb[0] = Ctrl_H;
1659 tb[1] = NUL;
1660 if (has_mbyte)
1661 len = clen; // Delete characters instead of bytes
1662 while (len-- > 0) // delete the from string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001663 (void)ins_typebuf(tb, 1, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001664 return TRUE;
1665 }
1666 }
1667 return FALSE;
1668}
1669
1670#ifdef FEAT_EVAL
1671/*
1672 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1673 * special characters.
Bram Moolenaar94075b22022-01-18 20:30:39 +00001674 * Careful: after this "mp" will be invalid if the mapping was deleted.
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001675 */
1676 char_u *
1677eval_map_expr(
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001678 mapblock_T *mp,
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001679 int c) // NUL or typed character for abbreviation
1680{
1681 char_u *res;
1682 char_u *p;
1683 char_u *expr;
1684 pos_T save_cursor;
1685 int save_msg_col;
1686 int save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001687 scid_T save_sctx_sid = current_sctx.sc_sid;
1688 int save_sctx_version = current_sctx.sc_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001689
1690 // Remove escaping of CSI, because "str" is in a format to be used as
1691 // typeahead.
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001692 expr = vim_strsave(mp->m_str);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001693 if (expr == NULL)
1694 return NULL;
1695 vim_unescape_csi(expr);
1696
1697 // Forbid changing text or using ":normal" to avoid most of the bad side
1698 // effects. Also restore the cursor position.
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001699 ++textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001700 ++ex_normal_lock;
1701 set_vim_var_char(c); // set v:char to the typed character
1702 save_cursor = curwin->w_cursor;
1703 save_msg_col = msg_col;
1704 save_msg_row = msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001705 if (mp->m_script_ctx.sc_version == SCRIPT_VERSION_VIM9)
1706 {
1707 current_sctx.sc_sid = mp->m_script_ctx.sc_sid;
1708 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
1709 }
1710
1711 // Note: the evaluation may make "mp" invalid.
Bram Moolenaarb171fb12020-06-24 20:34:03 +02001712 p = eval_to_string(expr, FALSE);
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001713
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001714 --textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001715 --ex_normal_lock;
1716 curwin->w_cursor = save_cursor;
1717 msg_col = save_msg_col;
1718 msg_row = save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001719 current_sctx.sc_sid = save_sctx_sid;
1720 current_sctx.sc_version = save_sctx_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001721
1722 vim_free(expr);
1723
1724 if (p == NULL)
1725 return NULL;
1726 // Escape CSI in the result to be able to use the string as typeahead.
1727 res = vim_strsave_escape_csi(p);
1728 vim_free(p);
1729
1730 return res;
1731}
1732#endif
1733
1734/*
1735 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1736 * can be put in the typeahead buffer.
1737 * Returns NULL when out of memory.
1738 */
1739 char_u *
Bram Moolenaar957cf672020-11-12 14:21:06 +01001740vim_strsave_escape_csi(char_u *p)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001741{
1742 char_u *res;
1743 char_u *s, *d;
1744
1745 // Need a buffer to hold up to three times as much. Four in case of an
1746 // illegal utf-8 byte:
1747 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1748 res = alloc(STRLEN(p) * 4 + 1);
1749 if (res != NULL)
1750 {
1751 d = res;
1752 for (s = p; *s != NUL; )
1753 {
1754 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1755 {
1756 // Copy special key unmodified.
1757 *d++ = *s++;
1758 *d++ = *s++;
1759 *d++ = *s++;
1760 }
1761 else
1762 {
1763 // Add character, possibly multi-byte to destination, escaping
1764 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1765 d = add_char2buf(PTR2CHAR(s), d);
1766 s += MB_CPTR2LEN(s);
1767 }
1768 }
1769 *d = NUL;
1770 }
1771 return res;
1772}
1773
1774/*
1775 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1776 * vim_strsave_escape_csi(). Works in-place.
1777 */
1778 void
1779vim_unescape_csi(char_u *p)
1780{
1781 char_u *s = p, *d = p;
1782
1783 while (*s != NUL)
1784 {
1785 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1786 {
1787 *d++ = K_SPECIAL;
1788 s += 3;
1789 }
1790 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1791 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1792 {
1793 *d++ = CSI;
1794 s += 3;
1795 }
1796 else
1797 *d++ = *s++;
1798 }
1799 *d = NUL;
1800}
1801
1802/*
1803 * Write map commands for the current mappings to an .exrc file.
1804 * Return FAIL on error, OK otherwise.
1805 */
1806 int
1807makemap(
1808 FILE *fd,
1809 buf_T *buf) // buffer for local mappings or NULL
1810{
1811 mapblock_T *mp;
1812 char_u c1, c2, c3;
1813 char_u *p;
1814 char *cmd;
1815 int abbr;
1816 int hash;
1817 int did_cpo = FALSE;
1818 int i;
1819
1820 validate_maphash();
1821
1822 // Do the loop twice: Once for mappings, once for abbreviations.
1823 // Then loop over all map hash lists.
1824 for (abbr = 0; abbr < 2; ++abbr)
1825 for (hash = 0; hash < 256; ++hash)
1826 {
1827 if (abbr)
1828 {
1829 if (hash > 0) // there is only one abbr list
1830 break;
1831 if (buf != NULL)
1832 mp = buf->b_first_abbr;
1833 else
1834 mp = first_abbr;
1835 }
1836 else
1837 {
1838 if (buf != NULL)
1839 mp = buf->b_maphash[hash];
1840 else
1841 mp = maphash[hash];
1842 }
1843
1844 for ( ; mp; mp = mp->m_next)
1845 {
1846 // skip script-local mappings
1847 if (mp->m_noremap == REMAP_SCRIPT)
1848 continue;
1849
1850 // skip mappings that contain a <SNR> (script-local thing),
1851 // they probably don't work when loaded again
1852 for (p = mp->m_str; *p != NUL; ++p)
1853 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1854 && p[2] == (int)KE_SNR)
1855 break;
1856 if (*p != NUL)
1857 continue;
1858
1859 // It's possible to create a mapping and then ":unmap" certain
1860 // modes. We recreate this here by mapping the individual
1861 // modes, which requires up to three of them.
1862 c1 = NUL;
1863 c2 = NUL;
1864 c3 = NUL;
1865 if (abbr)
1866 cmd = "abbr";
1867 else
1868 cmd = "map";
1869 switch (mp->m_mode)
1870 {
1871 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1872 break;
1873 case NORMAL:
1874 c1 = 'n';
1875 break;
1876 case VISUAL:
1877 c1 = 'x';
1878 break;
1879 case SELECTMODE:
1880 c1 = 's';
1881 break;
1882 case OP_PENDING:
1883 c1 = 'o';
1884 break;
1885 case NORMAL + VISUAL:
1886 c1 = 'n';
1887 c2 = 'x';
1888 break;
1889 case NORMAL + SELECTMODE:
1890 c1 = 'n';
1891 c2 = 's';
1892 break;
1893 case NORMAL + OP_PENDING:
1894 c1 = 'n';
1895 c2 = 'o';
1896 break;
1897 case VISUAL + SELECTMODE:
1898 c1 = 'v';
1899 break;
1900 case VISUAL + OP_PENDING:
1901 c1 = 'x';
1902 c2 = 'o';
1903 break;
1904 case SELECTMODE + OP_PENDING:
1905 c1 = 's';
1906 c2 = 'o';
1907 break;
1908 case NORMAL + VISUAL + SELECTMODE:
1909 c1 = 'n';
1910 c2 = 'v';
1911 break;
1912 case NORMAL + VISUAL + OP_PENDING:
1913 c1 = 'n';
1914 c2 = 'x';
1915 c3 = 'o';
1916 break;
1917 case NORMAL + SELECTMODE + OP_PENDING:
1918 c1 = 'n';
1919 c2 = 's';
1920 c3 = 'o';
1921 break;
1922 case VISUAL + SELECTMODE + OP_PENDING:
1923 c1 = 'v';
1924 c2 = 'o';
1925 break;
1926 case CMDLINE + INSERT:
1927 if (!abbr)
1928 cmd = "map!";
1929 break;
1930 case CMDLINE:
1931 c1 = 'c';
1932 break;
1933 case INSERT:
1934 c1 = 'i';
1935 break;
1936 case LANGMAP:
1937 c1 = 'l';
1938 break;
1939 case TERMINAL:
1940 c1 = 't';
1941 break;
1942 default:
Bram Moolenaar6d057012021-12-31 18:49:43 +00001943 iemsg(_(e_makemap_illegal_mode));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001944 return FAIL;
1945 }
1946 do // do this twice if c2 is set, 3 times with c3
1947 {
1948 // When outputting <> form, need to make sure that 'cpo'
1949 // is set to the Vim default.
1950 if (!did_cpo)
1951 {
1952 if (*mp->m_str == NUL) // will use <Nop>
1953 did_cpo = TRUE;
1954 else
1955 for (i = 0; i < 2; ++i)
1956 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1957 if (*p == K_SPECIAL || *p == NL)
1958 did_cpo = TRUE;
1959 if (did_cpo)
1960 {
1961 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1962 || put_eol(fd) < 0
1963 || fprintf(fd, "set cpo&vim") < 0
1964 || put_eol(fd) < 0)
1965 return FAIL;
1966 }
1967 }
1968 if (c1 && putc(c1, fd) < 0)
1969 return FAIL;
1970 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1971 return FAIL;
1972 if (fputs(cmd, fd) < 0)
1973 return FAIL;
1974 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1975 return FAIL;
1976 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1977 return FAIL;
1978 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1979 return FAIL;
1980#ifdef FEAT_EVAL
1981 if (mp->m_noremap == REMAP_SCRIPT
1982 && fputs("<script>", fd) < 0)
1983 return FAIL;
1984 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1985 return FAIL;
1986#endif
1987
1988 if ( putc(' ', fd) < 0
1989 || put_escstr(fd, mp->m_keys, 0) == FAIL
1990 || putc(' ', fd) < 0
1991 || put_escstr(fd, mp->m_str, 1) == FAIL
1992 || put_eol(fd) < 0)
1993 return FAIL;
1994 c1 = c2;
1995 c2 = c3;
1996 c3 = NUL;
1997 } while (c1 != NUL);
1998 }
1999 }
2000
2001 if (did_cpo)
2002 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
2003 || put_eol(fd) < 0
2004 || fprintf(fd, "unlet s:cpo_save") < 0
2005 || put_eol(fd) < 0)
2006 return FAIL;
2007 return OK;
2008}
2009
2010/*
2011 * write escape string to file
2012 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
2013 *
2014 * return FAIL for failure, OK otherwise
2015 */
2016 int
2017put_escstr(FILE *fd, char_u *strstart, int what)
2018{
2019 char_u *str = strstart;
2020 int c;
2021 int modifiers;
2022
2023 // :map xx <Nop>
2024 if (*str == NUL && what == 1)
2025 {
2026 if (fprintf(fd, "<Nop>") < 0)
2027 return FAIL;
2028 return OK;
2029 }
2030
2031 for ( ; *str != NUL; ++str)
2032 {
2033 char_u *p;
2034
2035 // Check for a multi-byte character, which may contain escaped
2036 // K_SPECIAL and CSI bytes
2037 p = mb_unescape(&str);
2038 if (p != NULL)
2039 {
2040 while (*p != NUL)
2041 if (fputc(*p++, fd) < 0)
2042 return FAIL;
2043 --str;
2044 continue;
2045 }
2046
2047 c = *str;
2048 // Special key codes have to be translated to be able to make sense
2049 // when they are read back.
2050 if (c == K_SPECIAL && what != 2)
2051 {
Bram Moolenaar02c037a2020-08-30 19:26:45 +02002052 modifiers = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002053 if (str[1] == KS_MODIFIER)
2054 {
2055 modifiers = str[2];
2056 str += 3;
2057 c = *str;
2058 }
2059 if (c == K_SPECIAL)
2060 {
2061 c = TO_SPECIAL(str[1], str[2]);
2062 str += 2;
2063 }
2064 if (IS_SPECIAL(c) || modifiers) // special key
2065 {
2066 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
2067 return FAIL;
2068 continue;
2069 }
2070 }
2071
2072 // A '\n' in a map command should be written as <NL>.
2073 // A '\n' in a set command should be written as \^V^J.
2074 if (c == NL)
2075 {
2076 if (what == 2)
2077 {
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002078 if (fprintf(fd, "\\\026\n") < 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002079 return FAIL;
2080 }
2081 else
2082 {
2083 if (fprintf(fd, "<NL>") < 0)
2084 return FAIL;
2085 }
2086 continue;
2087 }
2088
2089 // Some characters have to be escaped with CTRL-V to
2090 // prevent them from misinterpreted in DoOneCmd().
2091 // A space, Tab and '"' has to be escaped with a backslash to
2092 // prevent it to be misinterpreted in do_set().
2093 // A space has to be escaped with a CTRL-V when it's at the start of a
2094 // ":map" rhs.
2095 // A '<' has to be escaped with a CTRL-V to prevent it being
2096 // interpreted as the start of a special key name.
2097 // A space in the lhs of a :map needs a CTRL-V.
2098 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2099 {
2100 if (putc('\\', fd) < 0)
2101 return FAIL;
2102 }
2103 else if (c < ' ' || c > '~' || c == '|'
2104 || (what == 0 && c == ' ')
2105 || (what == 1 && str == strstart && c == ' ')
2106 || (what != 2 && c == '<'))
2107 {
2108 if (putc(Ctrl_V, fd) < 0)
2109 return FAIL;
2110 }
2111 if (putc(c, fd) < 0)
2112 return FAIL;
2113 }
2114 return OK;
2115}
2116
2117/*
2118 * Check all mappings for the presence of special key codes.
2119 * Used after ":set term=xxx".
2120 */
2121 void
2122check_map_keycodes(void)
2123{
2124 mapblock_T *mp;
2125 char_u *p;
2126 int i;
2127 char_u buf[3];
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002128 int abbr;
2129 int hash;
2130 buf_T *bp;
Bram Moolenaare31ee862020-01-07 20:59:34 +01002131 ESTACK_CHECK_DECLARATION
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002132
2133 validate_maphash();
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002134 // avoids giving error messages
2135 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
Bram Moolenaare31ee862020-01-07 20:59:34 +01002136 ESTACK_CHECK_SETUP
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002137
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002138 // Do this once for each buffer, and then once for global
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002139 // mappings/abbreviations with bp == NULL
2140 for (bp = firstbuf; ; bp = bp->b_next)
2141 {
2142 // Do the loop twice: Once for mappings, once for abbreviations.
2143 // Then loop over all map hash lists.
2144 for (abbr = 0; abbr <= 1; ++abbr)
2145 for (hash = 0; hash < 256; ++hash)
2146 {
2147 if (abbr)
2148 {
2149 if (hash) // there is only one abbr list
2150 break;
2151 if (bp != NULL)
2152 mp = bp->b_first_abbr;
2153 else
2154 mp = first_abbr;
2155 }
2156 else
2157 {
2158 if (bp != NULL)
2159 mp = bp->b_maphash[hash];
2160 else
2161 mp = maphash[hash];
2162 }
2163 for ( ; mp != NULL; mp = mp->m_next)
2164 {
2165 for (i = 0; i <= 1; ++i) // do this twice
2166 {
2167 if (i == 0)
2168 p = mp->m_keys; // once for the "from" part
2169 else
2170 p = mp->m_str; // and once for the "to" part
2171 while (*p)
2172 {
2173 if (*p == K_SPECIAL)
2174 {
2175 ++p;
2176 if (*p < 128) // for "normal" tcap entries
2177 {
2178 buf[0] = p[0];
2179 buf[1] = p[1];
2180 buf[2] = NUL;
2181 (void)add_termcap_entry(buf, FALSE);
2182 }
2183 ++p;
2184 }
2185 ++p;
2186 }
2187 }
2188 }
2189 }
2190 if (bp == NULL)
2191 break;
2192 }
Bram Moolenaare31ee862020-01-07 20:59:34 +01002193 ESTACK_CHECK_NOW
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002194 estack_pop();
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002195}
2196
2197#if defined(FEAT_EVAL) || defined(PROTO)
2198/*
2199 * Check the string "keys" against the lhs of all mappings.
2200 * Return pointer to rhs of mapping (mapblock->m_str).
2201 * NULL when no mapping found.
2202 */
2203 char_u *
2204check_map(
2205 char_u *keys,
2206 int mode,
2207 int exact, // require exact match
2208 int ign_mod, // ignore preceding modifier
2209 int abbr, // do abbreviations
2210 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2211 int *local_ptr) // return: buffer-local mapping or NULL
2212{
2213 int hash;
2214 int len, minlen;
2215 mapblock_T *mp;
2216 char_u *s;
2217 int local;
2218
2219 validate_maphash();
2220
2221 len = (int)STRLEN(keys);
2222 for (local = 1; local >= 0; --local)
2223 // loop over all hash lists
2224 for (hash = 0; hash < 256; ++hash)
2225 {
2226 if (abbr)
2227 {
2228 if (hash > 0) // there is only one list.
2229 break;
2230 if (local)
2231 mp = curbuf->b_first_abbr;
2232 else
2233 mp = first_abbr;
2234 }
2235 else if (local)
2236 mp = curbuf->b_maphash[hash];
2237 else
2238 mp = maphash[hash];
2239 for ( ; mp != NULL; mp = mp->m_next)
2240 {
2241 // skip entries with wrong mode, wrong length and not matching
2242 // ones
2243 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2244 {
2245 if (len > mp->m_keylen)
2246 minlen = mp->m_keylen;
2247 else
2248 minlen = len;
2249 s = mp->m_keys;
2250 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2251 && s[2] != NUL)
2252 {
2253 s += 3;
2254 if (len > mp->m_keylen - 3)
2255 minlen = mp->m_keylen - 3;
2256 }
2257 if (STRNCMP(s, keys, minlen) == 0)
2258 {
2259 if (mp_ptr != NULL)
2260 *mp_ptr = mp;
2261 if (local_ptr != NULL)
2262 *local_ptr = local;
2263 return mp->m_str;
2264 }
2265 }
2266 }
2267 }
2268
2269 return NULL;
2270}
2271
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002272 static void
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002273get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2274{
2275 char_u *keys;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002276 char_u *keys_simplified;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002277 char_u *which;
2278 char_u buf[NUMBUFLEN];
2279 char_u *keys_buf = NULL;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002280 char_u *alt_keys_buf = NULL;
2281 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002282 char_u *rhs;
2283 int mode;
2284 int abbr = FALSE;
2285 int get_dict = FALSE;
2286 mapblock_T *mp;
Bram Moolenaara55ba062020-05-27 21:29:04 +02002287 mapblock_T *mp_simplified = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002288 int buffer_local;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002289 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002290
2291 // return empty string for failure
2292 rettv->v_type = VAR_STRING;
2293 rettv->vval.v_string = NULL;
2294
2295 keys = tv_get_string(&argvars[0]);
2296 if (*keys == NUL)
2297 return;
2298
2299 if (argvars[1].v_type != VAR_UNKNOWN)
2300 {
2301 which = tv_get_string_buf_chk(&argvars[1], buf);
2302 if (argvars[2].v_type != VAR_UNKNOWN)
2303 {
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002304 abbr = (int)tv_get_bool(&argvars[2]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002305 if (argvars[3].v_type != VAR_UNKNOWN)
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002306 get_dict = (int)tv_get_bool(&argvars[3]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002307 }
2308 }
2309 else
2310 which = (char_u *)"";
2311 if (which == NULL)
2312 return;
2313
2314 mode = get_map_mode(&which, 0);
2315
Bram Moolenaar9c652532020-05-24 13:10:18 +02002316 keys_simplified = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
2317 rhs = check_map(keys_simplified, mode, exact, FALSE, abbr,
2318 &mp, &buffer_local);
2319 if (did_simplify)
2320 {
2321 // When the lhs is being simplified the not-simplified keys are
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002322 // preferred for printing, like in do_map().
Bram Moolenaar9c652532020-05-24 13:10:18 +02002323 // The "rhs" and "buffer_local" values are not expected to change.
2324 mp_simplified = mp;
2325 (void)replace_termcodes(keys, &alt_keys_buf,
2326 flags | REPTERM_NO_SIMPLIFY, NULL);
2327 rhs = check_map(alt_keys_buf, mode, exact, FALSE, abbr, &mp,
2328 &buffer_local);
2329 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002330
2331 if (!get_dict)
2332 {
2333 // Return a string.
2334 if (rhs != NULL)
2335 {
2336 if (*rhs == NUL)
2337 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2338 else
2339 rettv->vval.v_string = str2special_save(rhs, FALSE);
2340 }
2341
2342 }
2343 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2344 {
2345 // Return a dictionary.
2346 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2347 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2348 dict_T *dict = rettv->vval.v_dict;
2349
2350 dict_add_string(dict, "lhs", lhs);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002351 vim_free(lhs);
2352 dict_add_string(dict, "lhsraw", mp->m_keys);
2353 if (did_simplify)
2354 // Also add the value for the simplified entry.
2355 dict_add_string(dict, "lhsrawalt", mp_simplified->m_keys);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002356 dict_add_string(dict, "rhs", mp->m_orig_str);
2357 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
Bram Moolenaar2da0f0c2020-04-01 19:22:12 +02002358 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2359 ? 1L : 0L);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002360 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2361 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2362 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
Bram Moolenaara9528b32022-01-18 20:51:35 +00002363 dict_add_number(dict, "scriptversion",
2364 (long)mp->m_script_ctx.sc_version);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002365 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2366 dict_add_number(dict, "buffer", (long)buffer_local);
2367 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2368 dict_add_string(dict, "mode", mapmode);
2369
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002370 vim_free(mapmode);
2371 }
Bram Moolenaar9c652532020-05-24 13:10:18 +02002372
2373 vim_free(keys_buf);
2374 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002375}
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002376
2377/*
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002378 * "maparg()" function
2379 */
2380 void
2381f_maparg(typval_T *argvars, typval_T *rettv)
2382{
2383 if (in_vim9script()
2384 && (check_for_string_arg(argvars, 0) == FAIL
2385 || check_for_opt_string_arg(argvars, 1) == FAIL
2386 || (argvars[1].v_type != VAR_UNKNOWN
2387 && (check_for_opt_bool_arg(argvars, 2) == FAIL
2388 || (argvars[2].v_type != VAR_UNKNOWN
2389 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
2390 return;
2391
2392 get_maparg(argvars, rettv, TRUE);
2393}
2394
2395/*
2396 * "mapcheck()" function
2397 */
2398 void
2399f_mapcheck(typval_T *argvars, typval_T *rettv)
2400{
2401 if (in_vim9script()
2402 && (check_for_string_arg(argvars, 0) == FAIL
2403 || check_for_opt_string_arg(argvars, 1) == FAIL
2404 || (argvars[1].v_type != VAR_UNKNOWN
2405 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2406 return;
2407
2408 get_maparg(argvars, rettv, FALSE);
2409}
2410
2411/*
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002412 * "mapset()" function
2413 */
2414 void
2415f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2416{
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002417 char_u *keys_buf = NULL;
2418 char_u *which;
2419 int mode;
2420 char_u buf[NUMBUFLEN];
2421 int is_abbr;
2422 dict_T *d;
2423 char_u *lhs;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002424 char_u *lhsraw;
2425 char_u *lhsrawalt;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002426 char_u *rhs;
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002427 char_u *orig_rhs;
2428 char_u *arg_buf = NULL;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002429 int noremap;
2430 int expr;
2431 int silent;
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002432 int buffer;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002433 scid_T sid;
Bram Moolenaara9528b32022-01-18 20:51:35 +00002434 int scriptversion;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002435 linenr_T lnum;
2436 mapblock_T **map_table = maphash;
2437 mapblock_T **abbr_table = &first_abbr;
2438 int nowait;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002439 char_u *arg;
2440
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002441 if (in_vim9script()
2442 && (check_for_string_arg(argvars, 0) == FAIL
2443 || check_for_bool_arg(argvars, 1) == FAIL
2444 || check_for_dict_arg(argvars, 2) == FAIL))
2445 return;
2446
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002447 which = tv_get_string_buf_chk(&argvars[0], buf);
Bram Moolenaar1b912982020-09-29 21:45:41 +02002448 if (which == NULL)
2449 return;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002450 mode = get_map_mode(&which, 0);
Bram Moolenaar74273e62020-10-01 21:37:21 +02002451 is_abbr = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002452
2453 if (argvars[2].v_type != VAR_DICT)
2454 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002455 emsg(_(e_key_not_present_in_dictionary));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002456 return;
2457 }
2458 d = argvars[2].vval.v_dict;
2459
2460 // Get the values in the same order as above in get_maparg().
2461 lhs = dict_get_string(d, (char_u *)"lhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002462 lhsraw = dict_get_string(d, (char_u *)"lhsraw", FALSE);
2463 lhsrawalt = dict_get_string(d, (char_u *)"lhsrawalt", FALSE);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002464 rhs = dict_get_string(d, (char_u *)"rhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002465 if (lhs == NULL || lhsraw == NULL || rhs == NULL)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002466 {
Bram Moolenaarb09feaa2022-01-02 20:20:45 +00002467 emsg(_(e_entries_missing_in_mapset_dict_argument));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002468 return;
2469 }
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002470 orig_rhs = rhs;
2471 rhs = replace_termcodes(rhs, &arg_buf,
2472 REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002473
2474 noremap = dict_get_number(d, (char_u *)"noremap") ? REMAP_NONE: 0;
2475 if (dict_get_number(d, (char_u *)"script") != 0)
2476 noremap = REMAP_SCRIPT;
2477 expr = dict_get_number(d, (char_u *)"expr") != 0;
2478 silent = dict_get_number(d, (char_u *)"silent") != 0;
2479 sid = dict_get_number(d, (char_u *)"sid");
Bram Moolenaara9528b32022-01-18 20:51:35 +00002480 scriptversion = dict_get_number(d, (char_u *)"scriptversion");
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002481 lnum = dict_get_number(d, (char_u *)"lnum");
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002482 buffer = dict_get_number(d, (char_u *)"buffer");
2483 nowait = dict_get_number(d, (char_u *)"nowait") != 0;
2484 // mode from the dict is not used
2485
2486 if (buffer)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002487 {
2488 map_table = curbuf->b_maphash;
2489 abbr_table = &curbuf->b_first_abbr;
2490 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002491
2492 // Delete any existing mapping for this lhs and mode.
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002493 if (buffer)
2494 {
2495 arg = alloc(STRLEN(lhs) + STRLEN("<buffer>") + 1);
2496 if (arg == NULL)
2497 return;
2498 STRCPY(arg, "<buffer>");
2499 STRCPY(arg + 8, lhs);
2500 }
2501 else
2502 {
2503 arg = vim_strsave(lhs);
2504 if (arg == NULL)
2505 return;
2506 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002507 do_map(1, arg, mode, is_abbr);
2508 vim_free(arg);
2509
Bram Moolenaar9c652532020-05-24 13:10:18 +02002510 (void)map_add(map_table, abbr_table, lhsraw, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002511 nowait, silent, mode, is_abbr, expr, sid, scriptversion, lnum, 0);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002512 if (lhsrawalt != NULL)
2513 (void)map_add(map_table, abbr_table, lhsrawalt, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002514 nowait, silent, mode, is_abbr, expr, sid, scriptversion,
2515 lnum, 1);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002516 vim_free(keys_buf);
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002517 vim_free(arg_buf);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002518}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002519#endif
2520
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002521
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002522#if defined(MSWIN) || defined(MACOS_X)
2523
2524# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2525
2526/*
2527 * Default mappings for some often used keys.
2528 */
2529struct initmap
2530{
2531 char_u *arg;
2532 int mode;
2533};
2534
2535# ifdef FEAT_GUI_MSWIN
2536// Use the Windows (CUA) keybindings. (GUI)
2537static struct initmap initmappings[] =
2538{
2539 // paste, copy and cut
2540 {(char_u *)"<S-Insert> \"*P", NORMAL},
2541 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2542 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2543 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2544 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2545 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2546 {(char_u *)"<C-X> \"*d", VIS_SEL},
2547 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2548};
2549# endif
2550
2551# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2552// Use the Windows (CUA) keybindings. (Console)
2553static struct initmap cinitmappings[] =
2554{
2555 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2556 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2557 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2558 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2559
2560 // paste, copy and cut
2561# ifdef FEAT_CLIPBOARD
2562 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2563 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2564 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2565 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2566 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2567 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2568 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2569# else
2570 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2571 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2572 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2573 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2574 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2575 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2576# endif
2577};
2578# endif
2579
2580# if defined(MACOS_X)
2581static struct initmap initmappings[] =
2582{
2583 // Use the Standard MacOS binding.
2584 // paste, copy and cut
2585 {(char_u *)"<D-v> \"*P", NORMAL},
2586 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2587 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2588 {(char_u *)"<D-c> \"*y", VIS_SEL},
2589 {(char_u *)"<D-x> \"*d", VIS_SEL},
2590 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2591};
2592# endif
2593
2594# undef VIS_SEL
2595#endif
2596
2597/*
2598 * Set up default mappings.
2599 */
2600 void
2601init_mappings(void)
2602{
2603#if defined(MSWIN) || defined(MACOS_X)
2604 int i;
2605
2606# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2607# ifdef VIMDLL
2608 if (!gui.starting)
2609# endif
2610 {
K.Takataeeec2542021-06-02 13:28:16 +02002611 for (i = 0; i < (int)ARRAY_LENGTH(cinitmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002612 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2613 }
2614# endif
2615# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
K.Takataeeec2542021-06-02 13:28:16 +02002616 for (i = 0; i < (int)ARRAY_LENGTH(initmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002617 add_map(initmappings[i].arg, initmappings[i].mode);
2618# endif
2619#endif
2620}
2621
2622#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2623 || defined(PROTO)
2624/*
2625 * Add a mapping "map" for mode "mode".
2626 * Need to put string in allocated memory, because do_map() will modify it.
2627 */
2628 void
2629add_map(char_u *map, int mode)
2630{
2631 char_u *s;
2632 char_u *cpo_save = p_cpo;
2633
Bram Moolenaare5a2dc82021-01-03 19:52:05 +01002634 p_cpo = empty_option; // Allow <> notation
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002635 s = vim_strsave(map);
2636 if (s != NULL)
2637 {
2638 (void)do_map(0, s, mode, FALSE);
2639 vim_free(s);
2640 }
2641 p_cpo = cpo_save;
2642}
2643#endif
2644
Bram Moolenaare677df82019-09-02 22:31:11 +02002645#if defined(FEAT_LANGMAP) || defined(PROTO)
2646/*
2647 * Any character has an equivalent 'langmap' character. This is used for
2648 * keyboards that have a special language mode that sends characters above
2649 * 128 (although other characters can be translated too). The "to" field is a
2650 * Vim command character. This avoids having to switch the keyboard back to
2651 * ASCII mode when leaving Insert mode.
2652 *
2653 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2654 * commands.
2655 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2656 * same as langmap_mapchar[] for characters >= 256.
2657 *
2658 * Use growarray for 'langmap' chars >= 256
2659 */
2660typedef struct
2661{
2662 int from;
2663 int to;
2664} langmap_entry_T;
2665
2666static garray_T langmap_mapga;
2667
2668/*
2669 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2670 * field. If not found insert a new entry at the appropriate location.
2671 */
2672 static void
2673langmap_set_entry(int from, int to)
2674{
2675 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2676 int a = 0;
2677 int b = langmap_mapga.ga_len;
2678
2679 // Do a binary search for an existing entry.
2680 while (a != b)
2681 {
2682 int i = (a + b) / 2;
2683 int d = entries[i].from - from;
2684
2685 if (d == 0)
2686 {
2687 entries[i].to = to;
2688 return;
2689 }
2690 if (d < 0)
2691 a = i + 1;
2692 else
2693 b = i;
2694 }
2695
2696 if (ga_grow(&langmap_mapga, 1) != OK)
2697 return; // out of memory
2698
2699 // insert new entry at position "a"
2700 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2701 mch_memmove(entries + 1, entries,
2702 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2703 ++langmap_mapga.ga_len;
2704 entries[0].from = from;
2705 entries[0].to = to;
2706}
2707
2708/*
2709 * Apply 'langmap' to multi-byte character "c" and return the result.
2710 */
2711 int
2712langmap_adjust_mb(int c)
2713{
2714 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2715 int a = 0;
2716 int b = langmap_mapga.ga_len;
2717
2718 while (a != b)
2719 {
2720 int i = (a + b) / 2;
2721 int d = entries[i].from - c;
2722
2723 if (d == 0)
2724 return entries[i].to; // found matching entry
2725 if (d < 0)
2726 a = i + 1;
2727 else
2728 b = i;
2729 }
2730 return c; // no entry found, return "c" unmodified
2731}
2732
2733 void
2734langmap_init(void)
2735{
2736 int i;
2737
2738 for (i = 0; i < 256; i++)
2739 langmap_mapchar[i] = i; // we init with a one-to-one map
2740 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
2741}
2742
2743/*
2744 * Called when langmap option is set; the language map can be
2745 * changed at any time!
2746 */
2747 void
2748langmap_set(void)
2749{
2750 char_u *p;
2751 char_u *p2;
2752 int from, to;
2753
2754 ga_clear(&langmap_mapga); // clear the previous map first
2755 langmap_init(); // back to one-to-one map
2756
2757 for (p = p_langmap; p[0] != NUL; )
2758 {
2759 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2760 MB_PTR_ADV(p2))
2761 {
2762 if (p2[0] == '\\' && p2[1] != NUL)
2763 ++p2;
2764 }
2765 if (p2[0] == ';')
2766 ++p2; // abcd;ABCD form, p2 points to A
2767 else
2768 p2 = NULL; // aAbBcCdD form, p2 is NULL
2769 while (p[0])
2770 {
2771 if (p[0] == ',')
2772 {
2773 ++p;
2774 break;
2775 }
2776 if (p[0] == '\\' && p[1] != NUL)
2777 ++p;
2778 from = (*mb_ptr2char)(p);
2779 to = NUL;
2780 if (p2 == NULL)
2781 {
2782 MB_PTR_ADV(p);
2783 if (p[0] != ',')
2784 {
2785 if (p[0] == '\\')
2786 ++p;
2787 to = (*mb_ptr2char)(p);
2788 }
2789 }
2790 else
2791 {
2792 if (p2[0] != ',')
2793 {
2794 if (p2[0] == '\\')
2795 ++p2;
2796 to = (*mb_ptr2char)(p2);
2797 }
2798 }
2799 if (to == NUL)
2800 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002801 semsg(_(e_langmap_matching_character_missing_for_str),
Bram Moolenaare677df82019-09-02 22:31:11 +02002802 transchar(from));
2803 return;
2804 }
2805
2806 if (from >= 256)
2807 langmap_set_entry(from, to);
2808 else
2809 langmap_mapchar[from & 255] = to;
2810
2811 // Advance to next pair
2812 MB_PTR_ADV(p);
2813 if (p2 != NULL)
2814 {
2815 MB_PTR_ADV(p2);
2816 if (*p == ';')
2817 {
2818 p = p2;
2819 if (p[0] != NUL)
2820 {
2821 if (p[0] != ',')
2822 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002823 semsg(_(e_langmap_extra_characters_after_semicolon_str), p);
Bram Moolenaare677df82019-09-02 22:31:11 +02002824 return;
2825 }
2826 ++p;
2827 }
2828 break;
2829 }
2830 }
2831 }
2832 }
2833}
2834#endif
2835
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002836 static void
2837do_exmap(exarg_T *eap, int isabbrev)
2838{
2839 int mode;
2840 char_u *cmdp;
2841
2842 cmdp = eap->cmd;
2843 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2844
2845 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2846 eap->arg, mode, isabbrev))
2847 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002848 case 1: emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002849 break;
Bram Moolenaare29a27f2021-07-20 21:07:36 +02002850 case 2: emsg((isabbrev ? _(e_no_such_abbreviation)
2851 : _(e_no_such_mapping)));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002852 break;
2853 }
2854}
2855
2856/*
2857 * ":abbreviate" and friends.
2858 */
2859 void
2860ex_abbreviate(exarg_T *eap)
2861{
2862 do_exmap(eap, TRUE); // almost the same as mapping
2863}
2864
2865/*
2866 * ":map" and friends.
2867 */
2868 void
2869ex_map(exarg_T *eap)
2870{
2871 // If we are sourcing .exrc or .vimrc in current directory we
2872 // print the mappings for security reasons.
2873 if (secure)
2874 {
2875 secure = 2;
2876 msg_outtrans(eap->cmd);
2877 msg_putchar('\n');
2878 }
2879 do_exmap(eap, FALSE);
2880}
2881
2882/*
2883 * ":unmap" and friends.
2884 */
2885 void
2886ex_unmap(exarg_T *eap)
2887{
2888 do_exmap(eap, FALSE);
2889}
2890
2891/*
2892 * ":mapclear" and friends.
2893 */
2894 void
2895ex_mapclear(exarg_T *eap)
2896{
2897 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2898}
2899
2900/*
2901 * ":abclear" and friends.
2902 */
2903 void
2904ex_abclear(exarg_T *eap)
2905{
2906 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2907}