blob: b681d2ff2b32996979e02f9e46918dc034979d67 [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(
1260 regmatch_T *regmatch,
1261 int *num_file,
1262 char_u ***file)
1263{
1264 mapblock_T *mp;
1265 int hash;
1266 int count;
1267 int round;
1268 char_u *p;
1269 int i;
1270
1271 validate_maphash();
1272
1273 *num_file = 0; // return values in case of FAIL
1274 *file = NULL;
1275
1276 // round == 1: Count the matches.
1277 // round == 2: Build the array to keep the matches.
1278 for (round = 1; round <= 2; ++round)
1279 {
1280 count = 0;
1281
1282 for (i = 0; i < 7; ++i)
1283 {
1284 if (i == 0)
1285 p = (char_u *)"<silent>";
1286 else if (i == 1)
1287 p = (char_u *)"<unique>";
1288#ifdef FEAT_EVAL
1289 else if (i == 2)
1290 p = (char_u *)"<script>";
1291 else if (i == 3)
1292 p = (char_u *)"<expr>";
1293#endif
1294 else if (i == 4 && !expand_buffer)
1295 p = (char_u *)"<buffer>";
1296 else if (i == 5)
1297 p = (char_u *)"<nowait>";
1298 else if (i == 6)
1299 p = (char_u *)"<special>";
1300 else
1301 continue;
1302
1303 if (vim_regexec(regmatch, p, (colnr_T)0))
1304 {
1305 if (round == 1)
1306 ++count;
1307 else
1308 (*file)[count++] = vim_strsave(p);
1309 }
1310 }
1311
1312 for (hash = 0; hash < 256; ++hash)
1313 {
1314 if (expand_isabbrev)
1315 {
1316 if (hash > 0) // only one abbrev list
1317 break; // for (hash)
1318 mp = first_abbr;
1319 }
1320 else if (expand_buffer)
1321 mp = curbuf->b_maphash[hash];
1322 else
1323 mp = maphash[hash];
1324 for (; mp; mp = mp->m_next)
1325 {
1326 if (mp->m_mode & expand_mapmodes)
1327 {
1328 p = translate_mapping(mp->m_keys);
1329 if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
1330 {
1331 if (round == 1)
1332 ++count;
1333 else
1334 {
1335 (*file)[count++] = p;
1336 p = NULL;
1337 }
1338 }
1339 vim_free(p);
1340 }
1341 } // for (mp)
1342 } // for (hash)
1343
1344 if (count == 0) // no match found
1345 break; // for (round)
1346
1347 if (round == 1)
1348 {
1349 *file = ALLOC_MULT(char_u *, count);
1350 if (*file == NULL)
1351 return FAIL;
1352 }
1353 } // for (round)
1354
1355 if (count > 1)
1356 {
1357 char_u **ptr1;
1358 char_u **ptr2;
1359 char_u **ptr3;
1360
1361 // Sort the matches
1362 sort_strings(*file, count);
1363
1364 // Remove multiple entries
1365 ptr1 = *file;
1366 ptr2 = ptr1 + 1;
1367 ptr3 = ptr1 + count;
1368
1369 while (ptr2 < ptr3)
1370 {
1371 if (STRCMP(*ptr1, *ptr2))
1372 *++ptr1 = *ptr2++;
1373 else
1374 {
1375 vim_free(*ptr2++);
1376 count--;
1377 }
1378 }
1379 }
1380
1381 *num_file = count;
1382 return (count == 0 ? FAIL : OK);
1383}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001384
1385/*
1386 * Check for an abbreviation.
1387 * Cursor is at ptr[col].
1388 * When inserting, mincol is where insert started.
1389 * For the command line, mincol is what is to be skipped over.
1390 * "c" is the character typed before check_abbr was called. It may have
1391 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1392 *
1393 * Historic vi practice: The last character of an abbreviation must be an id
1394 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1395 * characters or all non-id characters. This allows for abbr. "#i" to
1396 * "#include".
1397 *
1398 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1399 * Then there must be white space before the abbr.
1400 *
1401 * return TRUE if there is an abbreviation, FALSE if not
1402 */
1403 int
1404check_abbr(
1405 int c,
1406 char_u *ptr,
1407 int col,
1408 int mincol)
1409{
1410 int len;
1411 int scol; // starting column of the abbr.
1412 int j;
1413 char_u *s;
1414 char_u tb[MB_MAXBYTES + 4];
1415 mapblock_T *mp;
1416 mapblock_T *mp2;
1417 int clen = 0; // length in characters
1418 int is_id = TRUE;
1419 int vim_abbr;
1420
1421 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1422 return FALSE;
1423
1424 // no remapping implies no abbreviation, except for CTRL-]
1425 if (noremap_keys() && c != Ctrl_RSB)
1426 return FALSE;
1427
1428 // Check for word before the cursor: If it ends in a keyword char all
1429 // chars before it must be keyword chars or non-keyword chars, but not
1430 // white space. If it ends in a non-keyword char we accept any characters
1431 // before it except white space.
1432 if (col == 0) // cannot be an abbr.
1433 return FALSE;
1434
1435 if (has_mbyte)
1436 {
1437 char_u *p;
1438
1439 p = mb_prevptr(ptr, ptr + col);
1440 if (!vim_iswordp(p))
1441 vim_abbr = TRUE; // Vim added abbr.
1442 else
1443 {
1444 vim_abbr = FALSE; // vi compatible abbr.
1445 if (p > ptr)
1446 is_id = vim_iswordp(mb_prevptr(ptr, p));
1447 }
1448 clen = 1;
1449 while (p > ptr + mincol)
1450 {
1451 p = mb_prevptr(ptr, p);
1452 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1453 {
1454 p += (*mb_ptr2len)(p);
1455 break;
1456 }
1457 ++clen;
1458 }
1459 scol = (int)(p - ptr);
1460 }
1461 else
1462 {
1463 if (!vim_iswordc(ptr[col - 1]))
1464 vim_abbr = TRUE; // Vim added abbr.
1465 else
1466 {
1467 vim_abbr = FALSE; // vi compatible abbr.
1468 if (col > 1)
1469 is_id = vim_iswordc(ptr[col - 2]);
1470 }
1471 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1472 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1473 ;
1474 }
1475
1476 if (scol < mincol)
1477 scol = mincol;
1478 if (scol < col) // there is a word in front of the cursor
1479 {
1480 ptr += scol;
1481 len = col - scol;
1482 mp = curbuf->b_first_abbr;
1483 mp2 = first_abbr;
1484 if (mp == NULL)
1485 {
1486 mp = mp2;
1487 mp2 = NULL;
1488 }
1489 for ( ; mp; mp->m_next == NULL
1490 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1491 {
1492 int qlen = mp->m_keylen;
1493 char_u *q = mp->m_keys;
1494 int match;
1495
1496 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1497 {
1498 char_u *qe = vim_strsave(mp->m_keys);
1499
1500 // might have CSI escaped mp->m_keys
1501 if (qe != NULL)
1502 {
1503 q = qe;
1504 vim_unescape_csi(q);
1505 qlen = (int)STRLEN(q);
1506 }
1507 }
1508
1509 // find entries with right mode and keys
1510 match = (mp->m_mode & State)
1511 && qlen == len
1512 && !STRNCMP(q, ptr, (size_t)len);
1513 if (q != mp->m_keys)
1514 vim_free(q);
1515 if (match)
1516 break;
1517 }
1518 if (mp != NULL)
1519 {
Bram Moolenaar94075b22022-01-18 20:30:39 +00001520 int noremap;
1521 int silent;
1522#ifdef FEAT_EVAL
1523 int expr;
1524#endif
1525
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001526 // Found a match:
1527 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1528 // This goes from end to start.
1529 //
1530 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1531 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1532 // Characters where IS_SPECIAL() == TRUE: key codes, need
1533 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1534 //
1535 // Character CTRL-] is treated specially - it completes the
1536 // abbreviation, but is not inserted into the input stream.
1537 j = 0;
1538 if (c != Ctrl_RSB)
1539 {
1540 // special key code, split up
1541 if (IS_SPECIAL(c) || c == K_SPECIAL)
1542 {
1543 tb[j++] = K_SPECIAL;
1544 tb[j++] = K_SECOND(c);
1545 tb[j++] = K_THIRD(c);
1546 }
1547 else
1548 {
1549 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1550 tb[j++] = Ctrl_V; // special char needs CTRL-V
1551 if (has_mbyte)
1552 {
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001553 int newlen;
1554 char_u *escaped;
1555
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001556 // if ABBR_OFF has been added, remove it here
1557 if (c >= ABBR_OFF)
1558 c -= ABBR_OFF;
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001559 newlen = (*mb_char2bytes)(c, tb + j);
1560 tb[j + newlen] = NUL;
1561 // Need to escape K_SPECIAL.
1562 escaped = vim_strsave_escape_csi(tb + j);
1563 if (escaped != NULL)
1564 {
Bram Moolenaar551c1ae2021-05-03 18:57:05 +02001565 newlen = (int)STRLEN(escaped);
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001566 mch_memmove(tb + j, escaped, newlen);
1567 j += newlen;
1568 vim_free(escaped);
1569 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001570 }
1571 else
1572 tb[j++] = c;
1573 }
1574 tb[j] = NUL;
1575 // insert the last typed char
1576 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1577 }
Bram Moolenaar94075b22022-01-18 20:30:39 +00001578
1579 // copy values here, calling eval_map_expr() may make "mp" invalid!
1580 noremap = mp->m_noremap;
1581 silent = mp->m_silent;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001582#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001583 expr = mp->m_expr;
1584
1585 if (expr)
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001586 s = eval_map_expr(mp, c);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001587 else
1588#endif
1589 s = mp->m_str;
1590 if (s != NULL)
1591 {
1592 // insert the to string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001593 (void)ins_typebuf(s, noremap, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001594 // no abbrev. for these chars
1595 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1596#ifdef FEAT_EVAL
Bram Moolenaar94075b22022-01-18 20:30:39 +00001597 if (expr)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001598 vim_free(s);
1599#endif
1600 }
1601
1602 tb[0] = Ctrl_H;
1603 tb[1] = NUL;
1604 if (has_mbyte)
1605 len = clen; // Delete characters instead of bytes
1606 while (len-- > 0) // delete the from string
Bram Moolenaar94075b22022-01-18 20:30:39 +00001607 (void)ins_typebuf(tb, 1, 0, TRUE, silent);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001608 return TRUE;
1609 }
1610 }
1611 return FALSE;
1612}
1613
1614#ifdef FEAT_EVAL
1615/*
1616 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1617 * special characters.
Bram Moolenaar94075b22022-01-18 20:30:39 +00001618 * Careful: after this "mp" will be invalid if the mapping was deleted.
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001619 */
1620 char_u *
1621eval_map_expr(
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001622 mapblock_T *mp,
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001623 int c) // NUL or typed character for abbreviation
1624{
1625 char_u *res;
1626 char_u *p;
1627 char_u *expr;
1628 pos_T save_cursor;
1629 int save_msg_col;
1630 int save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001631 scid_T save_sctx_sid = current_sctx.sc_sid;
1632 int save_sctx_version = current_sctx.sc_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001633
1634 // Remove escaping of CSI, because "str" is in a format to be used as
1635 // typeahead.
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001636 expr = vim_strsave(mp->m_str);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001637 if (expr == NULL)
1638 return NULL;
1639 vim_unescape_csi(expr);
1640
1641 // Forbid changing text or using ":normal" to avoid most of the bad side
1642 // effects. Also restore the cursor position.
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001643 ++textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001644 ++ex_normal_lock;
1645 set_vim_var_char(c); // set v:char to the typed character
1646 save_cursor = curwin->w_cursor;
1647 save_msg_col = msg_col;
1648 save_msg_row = msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001649 if (mp->m_script_ctx.sc_version == SCRIPT_VERSION_VIM9)
1650 {
1651 current_sctx.sc_sid = mp->m_script_ctx.sc_sid;
1652 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
1653 }
1654
1655 // Note: the evaluation may make "mp" invalid.
Bram Moolenaarb171fb12020-06-24 20:34:03 +02001656 p = eval_to_string(expr, FALSE);
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001657
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001658 --textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001659 --ex_normal_lock;
1660 curwin->w_cursor = save_cursor;
1661 msg_col = save_msg_col;
1662 msg_row = save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001663 current_sctx.sc_sid = save_sctx_sid;
1664 current_sctx.sc_version = save_sctx_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001665
1666 vim_free(expr);
1667
1668 if (p == NULL)
1669 return NULL;
1670 // Escape CSI in the result to be able to use the string as typeahead.
1671 res = vim_strsave_escape_csi(p);
1672 vim_free(p);
1673
1674 return res;
1675}
1676#endif
1677
1678/*
1679 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1680 * can be put in the typeahead buffer.
1681 * Returns NULL when out of memory.
1682 */
1683 char_u *
Bram Moolenaar957cf672020-11-12 14:21:06 +01001684vim_strsave_escape_csi(char_u *p)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001685{
1686 char_u *res;
1687 char_u *s, *d;
1688
1689 // Need a buffer to hold up to three times as much. Four in case of an
1690 // illegal utf-8 byte:
1691 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1692 res = alloc(STRLEN(p) * 4 + 1);
1693 if (res != NULL)
1694 {
1695 d = res;
1696 for (s = p; *s != NUL; )
1697 {
1698 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1699 {
1700 // Copy special key unmodified.
1701 *d++ = *s++;
1702 *d++ = *s++;
1703 *d++ = *s++;
1704 }
1705 else
1706 {
1707 // Add character, possibly multi-byte to destination, escaping
1708 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1709 d = add_char2buf(PTR2CHAR(s), d);
1710 s += MB_CPTR2LEN(s);
1711 }
1712 }
1713 *d = NUL;
1714 }
1715 return res;
1716}
1717
1718/*
1719 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1720 * vim_strsave_escape_csi(). Works in-place.
1721 */
1722 void
1723vim_unescape_csi(char_u *p)
1724{
1725 char_u *s = p, *d = p;
1726
1727 while (*s != NUL)
1728 {
1729 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1730 {
1731 *d++ = K_SPECIAL;
1732 s += 3;
1733 }
1734 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1735 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1736 {
1737 *d++ = CSI;
1738 s += 3;
1739 }
1740 else
1741 *d++ = *s++;
1742 }
1743 *d = NUL;
1744}
1745
1746/*
1747 * Write map commands for the current mappings to an .exrc file.
1748 * Return FAIL on error, OK otherwise.
1749 */
1750 int
1751makemap(
1752 FILE *fd,
1753 buf_T *buf) // buffer for local mappings or NULL
1754{
1755 mapblock_T *mp;
1756 char_u c1, c2, c3;
1757 char_u *p;
1758 char *cmd;
1759 int abbr;
1760 int hash;
1761 int did_cpo = FALSE;
1762 int i;
1763
1764 validate_maphash();
1765
1766 // Do the loop twice: Once for mappings, once for abbreviations.
1767 // Then loop over all map hash lists.
1768 for (abbr = 0; abbr < 2; ++abbr)
1769 for (hash = 0; hash < 256; ++hash)
1770 {
1771 if (abbr)
1772 {
1773 if (hash > 0) // there is only one abbr list
1774 break;
1775 if (buf != NULL)
1776 mp = buf->b_first_abbr;
1777 else
1778 mp = first_abbr;
1779 }
1780 else
1781 {
1782 if (buf != NULL)
1783 mp = buf->b_maphash[hash];
1784 else
1785 mp = maphash[hash];
1786 }
1787
1788 for ( ; mp; mp = mp->m_next)
1789 {
1790 // skip script-local mappings
1791 if (mp->m_noremap == REMAP_SCRIPT)
1792 continue;
1793
1794 // skip mappings that contain a <SNR> (script-local thing),
1795 // they probably don't work when loaded again
1796 for (p = mp->m_str; *p != NUL; ++p)
1797 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1798 && p[2] == (int)KE_SNR)
1799 break;
1800 if (*p != NUL)
1801 continue;
1802
1803 // It's possible to create a mapping and then ":unmap" certain
1804 // modes. We recreate this here by mapping the individual
1805 // modes, which requires up to three of them.
1806 c1 = NUL;
1807 c2 = NUL;
1808 c3 = NUL;
1809 if (abbr)
1810 cmd = "abbr";
1811 else
1812 cmd = "map";
1813 switch (mp->m_mode)
1814 {
1815 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1816 break;
1817 case NORMAL:
1818 c1 = 'n';
1819 break;
1820 case VISUAL:
1821 c1 = 'x';
1822 break;
1823 case SELECTMODE:
1824 c1 = 's';
1825 break;
1826 case OP_PENDING:
1827 c1 = 'o';
1828 break;
1829 case NORMAL + VISUAL:
1830 c1 = 'n';
1831 c2 = 'x';
1832 break;
1833 case NORMAL + SELECTMODE:
1834 c1 = 'n';
1835 c2 = 's';
1836 break;
1837 case NORMAL + OP_PENDING:
1838 c1 = 'n';
1839 c2 = 'o';
1840 break;
1841 case VISUAL + SELECTMODE:
1842 c1 = 'v';
1843 break;
1844 case VISUAL + OP_PENDING:
1845 c1 = 'x';
1846 c2 = 'o';
1847 break;
1848 case SELECTMODE + OP_PENDING:
1849 c1 = 's';
1850 c2 = 'o';
1851 break;
1852 case NORMAL + VISUAL + SELECTMODE:
1853 c1 = 'n';
1854 c2 = 'v';
1855 break;
1856 case NORMAL + VISUAL + OP_PENDING:
1857 c1 = 'n';
1858 c2 = 'x';
1859 c3 = 'o';
1860 break;
1861 case NORMAL + SELECTMODE + OP_PENDING:
1862 c1 = 'n';
1863 c2 = 's';
1864 c3 = 'o';
1865 break;
1866 case VISUAL + SELECTMODE + OP_PENDING:
1867 c1 = 'v';
1868 c2 = 'o';
1869 break;
1870 case CMDLINE + INSERT:
1871 if (!abbr)
1872 cmd = "map!";
1873 break;
1874 case CMDLINE:
1875 c1 = 'c';
1876 break;
1877 case INSERT:
1878 c1 = 'i';
1879 break;
1880 case LANGMAP:
1881 c1 = 'l';
1882 break;
1883 case TERMINAL:
1884 c1 = 't';
1885 break;
1886 default:
Bram Moolenaar6d057012021-12-31 18:49:43 +00001887 iemsg(_(e_makemap_illegal_mode));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001888 return FAIL;
1889 }
1890 do // do this twice if c2 is set, 3 times with c3
1891 {
1892 // When outputting <> form, need to make sure that 'cpo'
1893 // is set to the Vim default.
1894 if (!did_cpo)
1895 {
1896 if (*mp->m_str == NUL) // will use <Nop>
1897 did_cpo = TRUE;
1898 else
1899 for (i = 0; i < 2; ++i)
1900 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1901 if (*p == K_SPECIAL || *p == NL)
1902 did_cpo = TRUE;
1903 if (did_cpo)
1904 {
1905 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1906 || put_eol(fd) < 0
1907 || fprintf(fd, "set cpo&vim") < 0
1908 || put_eol(fd) < 0)
1909 return FAIL;
1910 }
1911 }
1912 if (c1 && putc(c1, fd) < 0)
1913 return FAIL;
1914 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1915 return FAIL;
1916 if (fputs(cmd, fd) < 0)
1917 return FAIL;
1918 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1919 return FAIL;
1920 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1921 return FAIL;
1922 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1923 return FAIL;
1924#ifdef FEAT_EVAL
1925 if (mp->m_noremap == REMAP_SCRIPT
1926 && fputs("<script>", fd) < 0)
1927 return FAIL;
1928 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1929 return FAIL;
1930#endif
1931
1932 if ( putc(' ', fd) < 0
1933 || put_escstr(fd, mp->m_keys, 0) == FAIL
1934 || putc(' ', fd) < 0
1935 || put_escstr(fd, mp->m_str, 1) == FAIL
1936 || put_eol(fd) < 0)
1937 return FAIL;
1938 c1 = c2;
1939 c2 = c3;
1940 c3 = NUL;
1941 } while (c1 != NUL);
1942 }
1943 }
1944
1945 if (did_cpo)
1946 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
1947 || put_eol(fd) < 0
1948 || fprintf(fd, "unlet s:cpo_save") < 0
1949 || put_eol(fd) < 0)
1950 return FAIL;
1951 return OK;
1952}
1953
1954/*
1955 * write escape string to file
1956 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
1957 *
1958 * return FAIL for failure, OK otherwise
1959 */
1960 int
1961put_escstr(FILE *fd, char_u *strstart, int what)
1962{
1963 char_u *str = strstart;
1964 int c;
1965 int modifiers;
1966
1967 // :map xx <Nop>
1968 if (*str == NUL && what == 1)
1969 {
1970 if (fprintf(fd, "<Nop>") < 0)
1971 return FAIL;
1972 return OK;
1973 }
1974
1975 for ( ; *str != NUL; ++str)
1976 {
1977 char_u *p;
1978
1979 // Check for a multi-byte character, which may contain escaped
1980 // K_SPECIAL and CSI bytes
1981 p = mb_unescape(&str);
1982 if (p != NULL)
1983 {
1984 while (*p != NUL)
1985 if (fputc(*p++, fd) < 0)
1986 return FAIL;
1987 --str;
1988 continue;
1989 }
1990
1991 c = *str;
1992 // Special key codes have to be translated to be able to make sense
1993 // when they are read back.
1994 if (c == K_SPECIAL && what != 2)
1995 {
Bram Moolenaar02c037a2020-08-30 19:26:45 +02001996 modifiers = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001997 if (str[1] == KS_MODIFIER)
1998 {
1999 modifiers = str[2];
2000 str += 3;
2001 c = *str;
2002 }
2003 if (c == K_SPECIAL)
2004 {
2005 c = TO_SPECIAL(str[1], str[2]);
2006 str += 2;
2007 }
2008 if (IS_SPECIAL(c) || modifiers) // special key
2009 {
2010 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
2011 return FAIL;
2012 continue;
2013 }
2014 }
2015
2016 // A '\n' in a map command should be written as <NL>.
2017 // A '\n' in a set command should be written as \^V^J.
2018 if (c == NL)
2019 {
2020 if (what == 2)
2021 {
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002022 if (fprintf(fd, "\\\026\n") < 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002023 return FAIL;
2024 }
2025 else
2026 {
2027 if (fprintf(fd, "<NL>") < 0)
2028 return FAIL;
2029 }
2030 continue;
2031 }
2032
2033 // Some characters have to be escaped with CTRL-V to
2034 // prevent them from misinterpreted in DoOneCmd().
2035 // A space, Tab and '"' has to be escaped with a backslash to
2036 // prevent it to be misinterpreted in do_set().
2037 // A space has to be escaped with a CTRL-V when it's at the start of a
2038 // ":map" rhs.
2039 // A '<' has to be escaped with a CTRL-V to prevent it being
2040 // interpreted as the start of a special key name.
2041 // A space in the lhs of a :map needs a CTRL-V.
2042 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2043 {
2044 if (putc('\\', fd) < 0)
2045 return FAIL;
2046 }
2047 else if (c < ' ' || c > '~' || c == '|'
2048 || (what == 0 && c == ' ')
2049 || (what == 1 && str == strstart && c == ' ')
2050 || (what != 2 && c == '<'))
2051 {
2052 if (putc(Ctrl_V, fd) < 0)
2053 return FAIL;
2054 }
2055 if (putc(c, fd) < 0)
2056 return FAIL;
2057 }
2058 return OK;
2059}
2060
2061/*
2062 * Check all mappings for the presence of special key codes.
2063 * Used after ":set term=xxx".
2064 */
2065 void
2066check_map_keycodes(void)
2067{
2068 mapblock_T *mp;
2069 char_u *p;
2070 int i;
2071 char_u buf[3];
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002072 int abbr;
2073 int hash;
2074 buf_T *bp;
Bram Moolenaare31ee862020-01-07 20:59:34 +01002075 ESTACK_CHECK_DECLARATION
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002076
2077 validate_maphash();
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002078 // avoids giving error messages
2079 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
Bram Moolenaare31ee862020-01-07 20:59:34 +01002080 ESTACK_CHECK_SETUP
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002081
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002082 // Do this once for each buffer, and then once for global
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002083 // mappings/abbreviations with bp == NULL
2084 for (bp = firstbuf; ; bp = bp->b_next)
2085 {
2086 // Do the loop twice: Once for mappings, once for abbreviations.
2087 // Then loop over all map hash lists.
2088 for (abbr = 0; abbr <= 1; ++abbr)
2089 for (hash = 0; hash < 256; ++hash)
2090 {
2091 if (abbr)
2092 {
2093 if (hash) // there is only one abbr list
2094 break;
2095 if (bp != NULL)
2096 mp = bp->b_first_abbr;
2097 else
2098 mp = first_abbr;
2099 }
2100 else
2101 {
2102 if (bp != NULL)
2103 mp = bp->b_maphash[hash];
2104 else
2105 mp = maphash[hash];
2106 }
2107 for ( ; mp != NULL; mp = mp->m_next)
2108 {
2109 for (i = 0; i <= 1; ++i) // do this twice
2110 {
2111 if (i == 0)
2112 p = mp->m_keys; // once for the "from" part
2113 else
2114 p = mp->m_str; // and once for the "to" part
2115 while (*p)
2116 {
2117 if (*p == K_SPECIAL)
2118 {
2119 ++p;
2120 if (*p < 128) // for "normal" tcap entries
2121 {
2122 buf[0] = p[0];
2123 buf[1] = p[1];
2124 buf[2] = NUL;
2125 (void)add_termcap_entry(buf, FALSE);
2126 }
2127 ++p;
2128 }
2129 ++p;
2130 }
2131 }
2132 }
2133 }
2134 if (bp == NULL)
2135 break;
2136 }
Bram Moolenaare31ee862020-01-07 20:59:34 +01002137 ESTACK_CHECK_NOW
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002138 estack_pop();
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002139}
2140
2141#if defined(FEAT_EVAL) || defined(PROTO)
2142/*
2143 * Check the string "keys" against the lhs of all mappings.
2144 * Return pointer to rhs of mapping (mapblock->m_str).
2145 * NULL when no mapping found.
2146 */
2147 char_u *
2148check_map(
2149 char_u *keys,
2150 int mode,
2151 int exact, // require exact match
2152 int ign_mod, // ignore preceding modifier
2153 int abbr, // do abbreviations
2154 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2155 int *local_ptr) // return: buffer-local mapping or NULL
2156{
2157 int hash;
2158 int len, minlen;
2159 mapblock_T *mp;
2160 char_u *s;
2161 int local;
2162
2163 validate_maphash();
2164
2165 len = (int)STRLEN(keys);
2166 for (local = 1; local >= 0; --local)
2167 // loop over all hash lists
2168 for (hash = 0; hash < 256; ++hash)
2169 {
2170 if (abbr)
2171 {
2172 if (hash > 0) // there is only one list.
2173 break;
2174 if (local)
2175 mp = curbuf->b_first_abbr;
2176 else
2177 mp = first_abbr;
2178 }
2179 else if (local)
2180 mp = curbuf->b_maphash[hash];
2181 else
2182 mp = maphash[hash];
2183 for ( ; mp != NULL; mp = mp->m_next)
2184 {
2185 // skip entries with wrong mode, wrong length and not matching
2186 // ones
2187 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2188 {
2189 if (len > mp->m_keylen)
2190 minlen = mp->m_keylen;
2191 else
2192 minlen = len;
2193 s = mp->m_keys;
2194 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2195 && s[2] != NUL)
2196 {
2197 s += 3;
2198 if (len > mp->m_keylen - 3)
2199 minlen = mp->m_keylen - 3;
2200 }
2201 if (STRNCMP(s, keys, minlen) == 0)
2202 {
2203 if (mp_ptr != NULL)
2204 *mp_ptr = mp;
2205 if (local_ptr != NULL)
2206 *local_ptr = local;
2207 return mp->m_str;
2208 }
2209 }
2210 }
2211 }
2212
2213 return NULL;
2214}
2215
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002216 static void
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002217get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2218{
2219 char_u *keys;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002220 char_u *keys_simplified;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002221 char_u *which;
2222 char_u buf[NUMBUFLEN];
2223 char_u *keys_buf = NULL;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002224 char_u *alt_keys_buf = NULL;
2225 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002226 char_u *rhs;
2227 int mode;
2228 int abbr = FALSE;
2229 int get_dict = FALSE;
2230 mapblock_T *mp;
Bram Moolenaara55ba062020-05-27 21:29:04 +02002231 mapblock_T *mp_simplified = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002232 int buffer_local;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002233 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002234
2235 // return empty string for failure
2236 rettv->v_type = VAR_STRING;
2237 rettv->vval.v_string = NULL;
2238
2239 keys = tv_get_string(&argvars[0]);
2240 if (*keys == NUL)
2241 return;
2242
2243 if (argvars[1].v_type != VAR_UNKNOWN)
2244 {
2245 which = tv_get_string_buf_chk(&argvars[1], buf);
2246 if (argvars[2].v_type != VAR_UNKNOWN)
2247 {
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002248 abbr = (int)tv_get_bool(&argvars[2]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002249 if (argvars[3].v_type != VAR_UNKNOWN)
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002250 get_dict = (int)tv_get_bool(&argvars[3]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002251 }
2252 }
2253 else
2254 which = (char_u *)"";
2255 if (which == NULL)
2256 return;
2257
2258 mode = get_map_mode(&which, 0);
2259
Bram Moolenaar9c652532020-05-24 13:10:18 +02002260 keys_simplified = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
2261 rhs = check_map(keys_simplified, mode, exact, FALSE, abbr,
2262 &mp, &buffer_local);
2263 if (did_simplify)
2264 {
2265 // When the lhs is being simplified the not-simplified keys are
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002266 // preferred for printing, like in do_map().
Bram Moolenaar9c652532020-05-24 13:10:18 +02002267 // The "rhs" and "buffer_local" values are not expected to change.
2268 mp_simplified = mp;
2269 (void)replace_termcodes(keys, &alt_keys_buf,
2270 flags | REPTERM_NO_SIMPLIFY, NULL);
2271 rhs = check_map(alt_keys_buf, mode, exact, FALSE, abbr, &mp,
2272 &buffer_local);
2273 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002274
2275 if (!get_dict)
2276 {
2277 // Return a string.
2278 if (rhs != NULL)
2279 {
2280 if (*rhs == NUL)
2281 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2282 else
2283 rettv->vval.v_string = str2special_save(rhs, FALSE);
2284 }
2285
2286 }
2287 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2288 {
2289 // Return a dictionary.
2290 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2291 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2292 dict_T *dict = rettv->vval.v_dict;
2293
2294 dict_add_string(dict, "lhs", lhs);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002295 vim_free(lhs);
2296 dict_add_string(dict, "lhsraw", mp->m_keys);
2297 if (did_simplify)
2298 // Also add the value for the simplified entry.
2299 dict_add_string(dict, "lhsrawalt", mp_simplified->m_keys);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002300 dict_add_string(dict, "rhs", mp->m_orig_str);
2301 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
Bram Moolenaar2da0f0c2020-04-01 19:22:12 +02002302 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2303 ? 1L : 0L);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002304 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2305 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2306 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
Bram Moolenaara9528b32022-01-18 20:51:35 +00002307 dict_add_number(dict, "scriptversion",
2308 (long)mp->m_script_ctx.sc_version);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002309 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2310 dict_add_number(dict, "buffer", (long)buffer_local);
2311 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2312 dict_add_string(dict, "mode", mapmode);
2313
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002314 vim_free(mapmode);
2315 }
Bram Moolenaar9c652532020-05-24 13:10:18 +02002316
2317 vim_free(keys_buf);
2318 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002319}
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002320
2321/*
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002322 * "maparg()" function
2323 */
2324 void
2325f_maparg(typval_T *argvars, typval_T *rettv)
2326{
2327 if (in_vim9script()
2328 && (check_for_string_arg(argvars, 0) == FAIL
2329 || check_for_opt_string_arg(argvars, 1) == FAIL
2330 || (argvars[1].v_type != VAR_UNKNOWN
2331 && (check_for_opt_bool_arg(argvars, 2) == FAIL
2332 || (argvars[2].v_type != VAR_UNKNOWN
2333 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
2334 return;
2335
2336 get_maparg(argvars, rettv, TRUE);
2337}
2338
2339/*
2340 * "mapcheck()" function
2341 */
2342 void
2343f_mapcheck(typval_T *argvars, typval_T *rettv)
2344{
2345 if (in_vim9script()
2346 && (check_for_string_arg(argvars, 0) == FAIL
2347 || check_for_opt_string_arg(argvars, 1) == FAIL
2348 || (argvars[1].v_type != VAR_UNKNOWN
2349 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2350 return;
2351
2352 get_maparg(argvars, rettv, FALSE);
2353}
2354
2355/*
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002356 * "mapset()" function
2357 */
2358 void
2359f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2360{
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002361 char_u *keys_buf = NULL;
2362 char_u *which;
2363 int mode;
2364 char_u buf[NUMBUFLEN];
2365 int is_abbr;
2366 dict_T *d;
2367 char_u *lhs;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002368 char_u *lhsraw;
2369 char_u *lhsrawalt;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002370 char_u *rhs;
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002371 char_u *orig_rhs;
2372 char_u *arg_buf = NULL;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002373 int noremap;
2374 int expr;
2375 int silent;
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002376 int buffer;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002377 scid_T sid;
Bram Moolenaara9528b32022-01-18 20:51:35 +00002378 int scriptversion;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002379 linenr_T lnum;
2380 mapblock_T **map_table = maphash;
2381 mapblock_T **abbr_table = &first_abbr;
2382 int nowait;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002383 char_u *arg;
2384
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002385 if (in_vim9script()
2386 && (check_for_string_arg(argvars, 0) == FAIL
2387 || check_for_bool_arg(argvars, 1) == FAIL
2388 || check_for_dict_arg(argvars, 2) == FAIL))
2389 return;
2390
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002391 which = tv_get_string_buf_chk(&argvars[0], buf);
Bram Moolenaar1b912982020-09-29 21:45:41 +02002392 if (which == NULL)
2393 return;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002394 mode = get_map_mode(&which, 0);
Bram Moolenaar74273e62020-10-01 21:37:21 +02002395 is_abbr = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002396
2397 if (argvars[2].v_type != VAR_DICT)
2398 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002399 emsg(_(e_key_not_present_in_dictionary));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002400 return;
2401 }
2402 d = argvars[2].vval.v_dict;
2403
2404 // Get the values in the same order as above in get_maparg().
2405 lhs = dict_get_string(d, (char_u *)"lhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002406 lhsraw = dict_get_string(d, (char_u *)"lhsraw", FALSE);
2407 lhsrawalt = dict_get_string(d, (char_u *)"lhsrawalt", FALSE);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002408 rhs = dict_get_string(d, (char_u *)"rhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002409 if (lhs == NULL || lhsraw == NULL || rhs == NULL)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002410 {
Bram Moolenaarb09feaa2022-01-02 20:20:45 +00002411 emsg(_(e_entries_missing_in_mapset_dict_argument));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002412 return;
2413 }
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002414 orig_rhs = rhs;
2415 rhs = replace_termcodes(rhs, &arg_buf,
2416 REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002417
2418 noremap = dict_get_number(d, (char_u *)"noremap") ? REMAP_NONE: 0;
2419 if (dict_get_number(d, (char_u *)"script") != 0)
2420 noremap = REMAP_SCRIPT;
2421 expr = dict_get_number(d, (char_u *)"expr") != 0;
2422 silent = dict_get_number(d, (char_u *)"silent") != 0;
2423 sid = dict_get_number(d, (char_u *)"sid");
Bram Moolenaara9528b32022-01-18 20:51:35 +00002424 scriptversion = dict_get_number(d, (char_u *)"scriptversion");
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002425 lnum = dict_get_number(d, (char_u *)"lnum");
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002426 buffer = dict_get_number(d, (char_u *)"buffer");
2427 nowait = dict_get_number(d, (char_u *)"nowait") != 0;
2428 // mode from the dict is not used
2429
2430 if (buffer)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002431 {
2432 map_table = curbuf->b_maphash;
2433 abbr_table = &curbuf->b_first_abbr;
2434 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002435
2436 // Delete any existing mapping for this lhs and mode.
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002437 if (buffer)
2438 {
2439 arg = alloc(STRLEN(lhs) + STRLEN("<buffer>") + 1);
2440 if (arg == NULL)
2441 return;
2442 STRCPY(arg, "<buffer>");
2443 STRCPY(arg + 8, lhs);
2444 }
2445 else
2446 {
2447 arg = vim_strsave(lhs);
2448 if (arg == NULL)
2449 return;
2450 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002451 do_map(1, arg, mode, is_abbr);
2452 vim_free(arg);
2453
Bram Moolenaar9c652532020-05-24 13:10:18 +02002454 (void)map_add(map_table, abbr_table, lhsraw, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002455 nowait, silent, mode, is_abbr, expr, sid, scriptversion, lnum, 0);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002456 if (lhsrawalt != NULL)
2457 (void)map_add(map_table, abbr_table, lhsrawalt, rhs, orig_rhs, noremap,
Bram Moolenaara9528b32022-01-18 20:51:35 +00002458 nowait, silent, mode, is_abbr, expr, sid, scriptversion,
2459 lnum, 1);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002460 vim_free(keys_buf);
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002461 vim_free(arg_buf);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002462}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002463#endif
2464
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002465
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002466#if defined(MSWIN) || defined(MACOS_X)
2467
2468# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2469
2470/*
2471 * Default mappings for some often used keys.
2472 */
2473struct initmap
2474{
2475 char_u *arg;
2476 int mode;
2477};
2478
2479# ifdef FEAT_GUI_MSWIN
2480// Use the Windows (CUA) keybindings. (GUI)
2481static struct initmap initmappings[] =
2482{
2483 // paste, copy and cut
2484 {(char_u *)"<S-Insert> \"*P", NORMAL},
2485 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2486 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2487 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2488 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2489 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2490 {(char_u *)"<C-X> \"*d", VIS_SEL},
2491 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2492};
2493# endif
2494
2495# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2496// Use the Windows (CUA) keybindings. (Console)
2497static struct initmap cinitmappings[] =
2498{
2499 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2500 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2501 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2502 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2503
2504 // paste, copy and cut
2505# ifdef FEAT_CLIPBOARD
2506 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2507 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2508 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2509 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2510 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2511 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2512 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2513# else
2514 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2515 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2516 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2517 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2518 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2519 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2520# endif
2521};
2522# endif
2523
2524# if defined(MACOS_X)
2525static struct initmap initmappings[] =
2526{
2527 // Use the Standard MacOS binding.
2528 // paste, copy and cut
2529 {(char_u *)"<D-v> \"*P", NORMAL},
2530 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2531 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2532 {(char_u *)"<D-c> \"*y", VIS_SEL},
2533 {(char_u *)"<D-x> \"*d", VIS_SEL},
2534 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2535};
2536# endif
2537
2538# undef VIS_SEL
2539#endif
2540
2541/*
2542 * Set up default mappings.
2543 */
2544 void
2545init_mappings(void)
2546{
2547#if defined(MSWIN) || defined(MACOS_X)
2548 int i;
2549
2550# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2551# ifdef VIMDLL
2552 if (!gui.starting)
2553# endif
2554 {
K.Takataeeec2542021-06-02 13:28:16 +02002555 for (i = 0; i < (int)ARRAY_LENGTH(cinitmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002556 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2557 }
2558# endif
2559# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
K.Takataeeec2542021-06-02 13:28:16 +02002560 for (i = 0; i < (int)ARRAY_LENGTH(initmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002561 add_map(initmappings[i].arg, initmappings[i].mode);
2562# endif
2563#endif
2564}
2565
2566#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2567 || defined(PROTO)
2568/*
2569 * Add a mapping "map" for mode "mode".
2570 * Need to put string in allocated memory, because do_map() will modify it.
2571 */
2572 void
2573add_map(char_u *map, int mode)
2574{
2575 char_u *s;
2576 char_u *cpo_save = p_cpo;
2577
Bram Moolenaare5a2dc82021-01-03 19:52:05 +01002578 p_cpo = empty_option; // Allow <> notation
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002579 s = vim_strsave(map);
2580 if (s != NULL)
2581 {
2582 (void)do_map(0, s, mode, FALSE);
2583 vim_free(s);
2584 }
2585 p_cpo = cpo_save;
2586}
2587#endif
2588
Bram Moolenaare677df82019-09-02 22:31:11 +02002589#if defined(FEAT_LANGMAP) || defined(PROTO)
2590/*
2591 * Any character has an equivalent 'langmap' character. This is used for
2592 * keyboards that have a special language mode that sends characters above
2593 * 128 (although other characters can be translated too). The "to" field is a
2594 * Vim command character. This avoids having to switch the keyboard back to
2595 * ASCII mode when leaving Insert mode.
2596 *
2597 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2598 * commands.
2599 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2600 * same as langmap_mapchar[] for characters >= 256.
2601 *
2602 * Use growarray for 'langmap' chars >= 256
2603 */
2604typedef struct
2605{
2606 int from;
2607 int to;
2608} langmap_entry_T;
2609
2610static garray_T langmap_mapga;
2611
2612/*
2613 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2614 * field. If not found insert a new entry at the appropriate location.
2615 */
2616 static void
2617langmap_set_entry(int from, int to)
2618{
2619 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2620 int a = 0;
2621 int b = langmap_mapga.ga_len;
2622
2623 // Do a binary search for an existing entry.
2624 while (a != b)
2625 {
2626 int i = (a + b) / 2;
2627 int d = entries[i].from - from;
2628
2629 if (d == 0)
2630 {
2631 entries[i].to = to;
2632 return;
2633 }
2634 if (d < 0)
2635 a = i + 1;
2636 else
2637 b = i;
2638 }
2639
2640 if (ga_grow(&langmap_mapga, 1) != OK)
2641 return; // out of memory
2642
2643 // insert new entry at position "a"
2644 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2645 mch_memmove(entries + 1, entries,
2646 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2647 ++langmap_mapga.ga_len;
2648 entries[0].from = from;
2649 entries[0].to = to;
2650}
2651
2652/*
2653 * Apply 'langmap' to multi-byte character "c" and return the result.
2654 */
2655 int
2656langmap_adjust_mb(int c)
2657{
2658 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2659 int a = 0;
2660 int b = langmap_mapga.ga_len;
2661
2662 while (a != b)
2663 {
2664 int i = (a + b) / 2;
2665 int d = entries[i].from - c;
2666
2667 if (d == 0)
2668 return entries[i].to; // found matching entry
2669 if (d < 0)
2670 a = i + 1;
2671 else
2672 b = i;
2673 }
2674 return c; // no entry found, return "c" unmodified
2675}
2676
2677 void
2678langmap_init(void)
2679{
2680 int i;
2681
2682 for (i = 0; i < 256; i++)
2683 langmap_mapchar[i] = i; // we init with a one-to-one map
2684 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
2685}
2686
2687/*
2688 * Called when langmap option is set; the language map can be
2689 * changed at any time!
2690 */
2691 void
2692langmap_set(void)
2693{
2694 char_u *p;
2695 char_u *p2;
2696 int from, to;
2697
2698 ga_clear(&langmap_mapga); // clear the previous map first
2699 langmap_init(); // back to one-to-one map
2700
2701 for (p = p_langmap; p[0] != NUL; )
2702 {
2703 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2704 MB_PTR_ADV(p2))
2705 {
2706 if (p2[0] == '\\' && p2[1] != NUL)
2707 ++p2;
2708 }
2709 if (p2[0] == ';')
2710 ++p2; // abcd;ABCD form, p2 points to A
2711 else
2712 p2 = NULL; // aAbBcCdD form, p2 is NULL
2713 while (p[0])
2714 {
2715 if (p[0] == ',')
2716 {
2717 ++p;
2718 break;
2719 }
2720 if (p[0] == '\\' && p[1] != NUL)
2721 ++p;
2722 from = (*mb_ptr2char)(p);
2723 to = NUL;
2724 if (p2 == NULL)
2725 {
2726 MB_PTR_ADV(p);
2727 if (p[0] != ',')
2728 {
2729 if (p[0] == '\\')
2730 ++p;
2731 to = (*mb_ptr2char)(p);
2732 }
2733 }
2734 else
2735 {
2736 if (p2[0] != ',')
2737 {
2738 if (p2[0] == '\\')
2739 ++p2;
2740 to = (*mb_ptr2char)(p2);
2741 }
2742 }
2743 if (to == NUL)
2744 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002745 semsg(_(e_langmap_matching_character_missing_for_str),
Bram Moolenaare677df82019-09-02 22:31:11 +02002746 transchar(from));
2747 return;
2748 }
2749
2750 if (from >= 256)
2751 langmap_set_entry(from, to);
2752 else
2753 langmap_mapchar[from & 255] = to;
2754
2755 // Advance to next pair
2756 MB_PTR_ADV(p);
2757 if (p2 != NULL)
2758 {
2759 MB_PTR_ADV(p2);
2760 if (*p == ';')
2761 {
2762 p = p2;
2763 if (p[0] != NUL)
2764 {
2765 if (p[0] != ',')
2766 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002767 semsg(_(e_langmap_extra_characters_after_semicolon_str), p);
Bram Moolenaare677df82019-09-02 22:31:11 +02002768 return;
2769 }
2770 ++p;
2771 }
2772 break;
2773 }
2774 }
2775 }
2776 }
2777}
2778#endif
2779
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002780 static void
2781do_exmap(exarg_T *eap, int isabbrev)
2782{
2783 int mode;
2784 char_u *cmdp;
2785
2786 cmdp = eap->cmd;
2787 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2788
2789 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2790 eap->arg, mode, isabbrev))
2791 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002792 case 1: emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002793 break;
Bram Moolenaare29a27f2021-07-20 21:07:36 +02002794 case 2: emsg((isabbrev ? _(e_no_such_abbreviation)
2795 : _(e_no_such_mapping)));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002796 break;
2797 }
2798}
2799
2800/*
2801 * ":abbreviate" and friends.
2802 */
2803 void
2804ex_abbreviate(exarg_T *eap)
2805{
2806 do_exmap(eap, TRUE); // almost the same as mapping
2807}
2808
2809/*
2810 * ":map" and friends.
2811 */
2812 void
2813ex_map(exarg_T *eap)
2814{
2815 // If we are sourcing .exrc or .vimrc in current directory we
2816 // print the mappings for security reasons.
2817 if (secure)
2818 {
2819 secure = 2;
2820 msg_outtrans(eap->cmd);
2821 msg_putchar('\n');
2822 }
2823 do_exmap(eap, FALSE);
2824}
2825
2826/*
2827 * ":unmap" and friends.
2828 */
2829 void
2830ex_unmap(exarg_T *eap)
2831{
2832 do_exmap(eap, FALSE);
2833}
2834
2835/*
2836 * ":mapclear" and friends.
2837 */
2838 void
2839ex_mapclear(exarg_T *eap)
2840{
2841 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2842}
2843
2844/*
2845 * ":abclear" and friends.
2846 */
2847 void
2848ex_abclear(exarg_T *eap)
2849{
2850 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2851}