blob: 181aa654b6ff0410f2843674cb0316b4ede38b5e [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;
87 vim_free(mp);
88}
89
90/*
91 * Return characters to represent the map mode in an allocated string.
92 * Returns NULL when out of memory.
93 */
94 static char_u *
95map_mode_to_chars(int mode)
96{
97 garray_T mapmode;
98
99 ga_init2(&mapmode, 1, 7);
100
101 if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
102 ga_append(&mapmode, '!'); // :map!
103 else if (mode & INSERT)
104 ga_append(&mapmode, 'i'); // :imap
105 else if (mode & LANGMAP)
106 ga_append(&mapmode, 'l'); // :lmap
107 else if (mode & CMDLINE)
108 ga_append(&mapmode, 'c'); // :cmap
109 else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
110 == NORMAL + VISUAL + SELECTMODE + OP_PENDING)
111 ga_append(&mapmode, ' '); // :map
112 else
113 {
114 if (mode & NORMAL)
115 ga_append(&mapmode, 'n'); // :nmap
116 if (mode & OP_PENDING)
117 ga_append(&mapmode, 'o'); // :omap
118 if (mode & TERMINAL)
119 ga_append(&mapmode, 't'); // :tmap
120 if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
121 ga_append(&mapmode, 'v'); // :vmap
122 else
123 {
124 if (mode & VISUAL)
125 ga_append(&mapmode, 'x'); // :xmap
126 if (mode & SELECTMODE)
127 ga_append(&mapmode, 's'); // :smap
128 }
129 }
130
131 ga_append(&mapmode, NUL);
132 return (char_u *)mapmode.ga_data;
133}
134
135 static void
136showmap(
137 mapblock_T *mp,
138 int local) // TRUE for buffer-local map
139{
140 int len = 1;
141 char_u *mapchars;
142
143 if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
144 return;
145
146 if (msg_didout || msg_silent != 0)
147 {
148 msg_putchar('\n');
149 if (got_int) // 'q' typed at MORE prompt
150 return;
151 }
152
153 mapchars = map_mode_to_chars(mp->m_mode);
154 if (mapchars != NULL)
155 {
156 msg_puts((char *)mapchars);
157 len = (int)STRLEN(mapchars);
158 vim_free(mapchars);
159 }
160
161 while (++len <= 3)
162 msg_putchar(' ');
163
164 // Display the LHS. Get length of what we write.
165 len = msg_outtrans_special(mp->m_keys, TRUE, 0);
166 do
167 {
168 msg_putchar(' '); // padd with blanks
169 ++len;
170 } while (len < 12);
171
172 if (mp->m_noremap == REMAP_NONE)
173 msg_puts_attr("*", HL_ATTR(HLF_8));
174 else if (mp->m_noremap == REMAP_SCRIPT)
175 msg_puts_attr("&", HL_ATTR(HLF_8));
176 else
177 msg_putchar(' ');
178
179 if (local)
180 msg_putchar('@');
181 else
182 msg_putchar(' ');
183
184 // Use FALSE below if we only want things like <Up> to show up as such on
185 // the rhs, and not M-x etc, TRUE gets both -- webb
186 if (*mp->m_str == NUL)
187 msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
188 else
189 {
190 // Remove escaping of CSI, because "m_str" is in a format to be used
191 // as typeahead.
192 char_u *s = vim_strsave(mp->m_str);
193 if (s != NULL)
194 {
195 vim_unescape_csi(s);
196 msg_outtrans_special(s, FALSE, 0);
197 vim_free(s);
198 }
199 }
200#ifdef FEAT_EVAL
201 if (p_verbose > 0)
202 last_set_msg(mp->m_script_ctx);
203#endif
204 out_flush(); // show one line at a time
205}
206
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200207 static int
208map_add(
209 mapblock_T **map_table,
210 mapblock_T **abbr_table,
211 char_u *keys,
212 char_u *rhs,
213 char_u *orig_rhs,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200214 int noremap,
215 int nowait,
216 int silent,
217 int mode,
218 int is_abbr,
219#ifdef FEAT_EVAL
Bram Moolenaar5a80f8a2020-05-22 13:38:18 +0200220 int expr,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200221 scid_T sid, // -1 to use current_sctx
222 linenr_T lnum,
223#endif
224 int simplified)
225{
226 mapblock_T *mp = ALLOC_ONE(mapblock_T);
227
228 if (mp == NULL)
229 return FAIL;
230
231 // If CTRL-C has been mapped, don't always use it for Interrupting.
232 if (*keys == Ctrl_C)
233 {
234 if (map_table == curbuf->b_maphash)
235 curbuf->b_mapped_ctrl_c |= mode;
236 else
237 mapped_ctrl_c |= mode;
238 }
239
240 mp->m_keys = vim_strsave(keys);
241 mp->m_str = vim_strsave(rhs);
242 mp->m_orig_str = vim_strsave(orig_rhs);
243 if (mp->m_keys == NULL || mp->m_str == NULL)
244 {
245 vim_free(mp->m_keys);
246 vim_free(mp->m_str);
247 vim_free(mp->m_orig_str);
248 vim_free(mp);
249 return FAIL;
250 }
251 mp->m_keylen = (int)STRLEN(mp->m_keys);
252 mp->m_noremap = noremap;
253 mp->m_nowait = nowait;
254 mp->m_silent = silent;
255 mp->m_mode = mode;
256 mp->m_simplified = simplified;
257#ifdef FEAT_EVAL
258 mp->m_expr = expr;
259 if (sid >= 0)
260 {
261 mp->m_script_ctx.sc_sid = sid;
262 mp->m_script_ctx.sc_lnum = lnum;
Bram Moolenaar19db9e62022-01-11 11:58:19 +0000263 mp->m_script_ctx.sc_version = in_vim9script() ? SCRIPT_VERSION_VIM9 : 0;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200264 }
265 else
266 {
267 mp->m_script_ctx = current_sctx;
268 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
269 }
270#endif
271
272 // add the new entry in front of the abbrlist or maphash[] list
273 if (is_abbr)
274 {
275 mp->m_next = *abbr_table;
276 *abbr_table = mp;
277 }
278 else
279 {
280 int n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
281
282 mp->m_next = map_table[n];
283 map_table[n] = mp;
284 }
285 return OK;
286}
287
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200288/*
289 * map[!] : show all key mappings
290 * map[!] {lhs} : show key mapping for {lhs}
291 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
292 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
293 * unmap[!] {lhs} : remove key mapping for {lhs}
294 * abbr : show all abbreviations
295 * abbr {lhs} : show abbreviations for {lhs}
296 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
297 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
298 * unabbr {lhs} : remove abbreviation for {lhs}
299 *
300 * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
301 *
302 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
303 * it will be modified.
304 *
305 * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
306 * for :map! mode is INSERT + CMDLINE
307 * for :cmap mode is CMDLINE
308 * for :imap mode is INSERT
309 * for :lmap mode is LANGMAP
310 * for :nmap mode is NORMAL
311 * for :vmap mode is VISUAL + SELECTMODE
312 * for :xmap mode is VISUAL
313 * for :smap mode is SELECTMODE
314 * for :omap mode is OP_PENDING
315 * for :tmap mode is TERMINAL
316 *
317 * for :abbr mode is INSERT + CMDLINE
318 * for :iabbr mode is INSERT
319 * for :cabbr mode is CMDLINE
320 *
321 * Return 0 for success
322 * 1 for invalid arguments
323 * 2 for no match
324 * 4 for out of mem
325 * 5 for entry not unique
326 */
327 int
328do_map(
329 int maptype,
330 char_u *arg,
331 int mode,
332 int abbrev) // not a mapping but an abbreviation
333{
334 char_u *keys;
335 mapblock_T *mp, **mpp;
336 char_u *rhs;
337 char_u *p;
338 int n;
339 int len = 0; // init for GCC
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200340 int hasarg;
341 int haskey;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200342 int do_print;
343 int keyround;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200344 char_u *keys_buf = NULL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200345 char_u *alt_keys_buf = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200346 char_u *arg_buf = NULL;
347 int retval = 0;
348 int do_backslash;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200349 mapblock_T **abbr_table;
350 mapblock_T **map_table;
351 int unique = FALSE;
352 int nowait = FALSE;
353 int silent = FALSE;
354 int special = FALSE;
355#ifdef FEAT_EVAL
356 int expr = FALSE;
357#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200358 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200359 int noremap;
360 char_u *orig_rhs;
361
362 keys = arg;
363 map_table = maphash;
364 abbr_table = &first_abbr;
365
366 // For ":noremap" don't remap, otherwise do remap.
367 if (maptype == 2)
368 noremap = REMAP_NONE;
369 else
370 noremap = REMAP_YES;
371
372 // Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
373 // any order.
374 for (;;)
375 {
376 // Check for "<buffer>": mapping local to buffer.
377 if (STRNCMP(keys, "<buffer>", 8) == 0)
378 {
379 keys = skipwhite(keys + 8);
380 map_table = curbuf->b_maphash;
381 abbr_table = &curbuf->b_first_abbr;
382 continue;
383 }
384
385 // Check for "<nowait>": don't wait for more characters.
386 if (STRNCMP(keys, "<nowait>", 8) == 0)
387 {
388 keys = skipwhite(keys + 8);
389 nowait = TRUE;
390 continue;
391 }
392
393 // Check for "<silent>": don't echo commands.
394 if (STRNCMP(keys, "<silent>", 8) == 0)
395 {
396 keys = skipwhite(keys + 8);
397 silent = TRUE;
398 continue;
399 }
400
401 // Check for "<special>": accept special keys in <>
402 if (STRNCMP(keys, "<special>", 9) == 0)
403 {
404 keys = skipwhite(keys + 9);
405 special = TRUE;
406 continue;
407 }
408
409#ifdef FEAT_EVAL
410 // Check for "<script>": remap script-local mappings only
411 if (STRNCMP(keys, "<script>", 8) == 0)
412 {
413 keys = skipwhite(keys + 8);
414 noremap = REMAP_SCRIPT;
415 continue;
416 }
417
418 // Check for "<expr>": {rhs} is an expression.
419 if (STRNCMP(keys, "<expr>", 6) == 0)
420 {
421 keys = skipwhite(keys + 6);
422 expr = TRUE;
423 continue;
424 }
425#endif
426 // Check for "<unique>": don't overwrite an existing mapping.
427 if (STRNCMP(keys, "<unique>", 8) == 0)
428 {
429 keys = skipwhite(keys + 8);
430 unique = TRUE;
431 continue;
432 }
433 break;
434 }
435
436 validate_maphash();
437
438 // Find end of keys and skip CTRL-Vs (and backslashes) in it.
439 // Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
440 // with :unmap white space is included in the keys, no argument possible.
441 p = keys;
442 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
443 while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
444 {
445 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
446 p[1] != NUL)
447 ++p; // skip CTRL-V or backslash
448 ++p;
449 }
450 if (*p != NUL)
451 *p++ = NUL;
452
453 p = skipwhite(p);
454 rhs = p;
455 hasarg = (*rhs != NUL);
456 haskey = (*keys != NUL);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200457 do_print = !haskey || (maptype != 1 && !hasarg);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200458
459 // check for :unmap without argument
460 if (maptype == 1 && !haskey)
461 {
462 retval = 1;
463 goto theend;
464 }
465
466 // If mapping has been given as ^V<C_UP> say, then replace the term codes
467 // with the appropriate two bytes. If it is a shifted special key, unshift
468 // it too, giving another two bytes.
469 // replace_termcodes() may move the result to allocated memory, which
470 // needs to be freed later (*keys_buf and *arg_buf).
471 // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
Bram Moolenaar459fd782019-10-13 16:43:39 +0200472 // If something like <C-H> is simplified to 0x08 then mark it as simplified
473 // and also add a n entry with a modifier, which will work when
474 // modifyOtherKeys is working.
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200475 if (haskey)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200476 {
477 char_u *new_keys;
478 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
479
480 if (special)
481 flags |= REPTERM_SPECIAL;
482 new_keys = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
483 if (did_simplify)
484 (void)replace_termcodes(keys, &alt_keys_buf,
485 flags | REPTERM_NO_SIMPLIFY, NULL);
486 keys = new_keys;
487 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200488 orig_rhs = rhs;
489 if (hasarg)
490 {
491 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
492 rhs = (char_u *)"";
493 else
Bram Moolenaar459fd782019-10-13 16:43:39 +0200494 rhs = replace_termcodes(rhs, &arg_buf,
495 REPTERM_DO_LT | (special ? REPTERM_SPECIAL : 0), NULL);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200496 }
497
Bram Moolenaar459fd782019-10-13 16:43:39 +0200498 /*
499 * The following is done twice if we have two versions of keys:
500 * "alt_keys_buf" is not NULL.
501 */
502 for (keyround = 1; keyround <= 2; ++keyround)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200503 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200504 int did_it = FALSE;
505 int did_local = FALSE;
506 int round;
507 int hash;
508 int new_hash;
509
510 if (keyround == 2)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200511 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200512 if (alt_keys_buf == NULL)
513 break;
514 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200515 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200516 else if (alt_keys_buf != NULL && do_print)
517 // when printing always use the not-simplified map
518 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200519
Bram Moolenaar459fd782019-10-13 16:43:39 +0200520 // check arguments and translate function keys
521 if (haskey)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200522 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200523 len = (int)STRLEN(keys);
524 if (len > MAXMAPLEN) // maximum length of MAXMAPLEN chars
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200525 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200526 retval = 1;
527 goto theend;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200528 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200529
530 if (abbrev && maptype != 1)
531 {
532 // If an abbreviation ends in a keyword character, the
533 // rest must be all keyword-char or all non-keyword-char.
534 // Otherwise we won't be able to find the start of it in a
535 // vi-compatible way.
536 if (has_mbyte)
537 {
538 int first, last;
539 int same = -1;
540
541 first = vim_iswordp(keys);
542 last = first;
543 p = keys + (*mb_ptr2len)(keys);
544 n = 1;
545 while (p < keys + len)
546 {
547 ++n; // nr of (multi-byte) chars
548 last = vim_iswordp(p); // type of last char
549 if (same == -1 && last != first)
550 same = n - 1; // count of same char type
551 p += (*mb_ptr2len)(p);
552 }
553 if (last && n > 2 && same >= 0 && same < n - 1)
554 {
555 retval = 1;
556 goto theend;
557 }
558 }
559 else if (vim_iswordc(keys[len - 1]))
560 // ends in keyword char
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200561 for (n = 0; n < len - 2; ++n)
562 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
563 {
564 retval = 1;
565 goto theend;
566 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200567 // An abbreviation cannot contain white space.
568 for (n = 0; n < len; ++n)
569 if (VIM_ISWHITE(keys[n]))
570 {
571 retval = 1;
572 goto theend;
573 }
574 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200575 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200576
Bram Moolenaar459fd782019-10-13 16:43:39 +0200577 if (haskey && hasarg && abbrev) // if we will add an abbreviation
578 no_abbr = FALSE; // reset flag that indicates there are
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200579 // no abbreviations
580
Bram Moolenaar459fd782019-10-13 16:43:39 +0200581 if (do_print)
582 msg_start();
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200583
Bram Moolenaar459fd782019-10-13 16:43:39 +0200584 // Check if a new local mapping wasn't already defined globally.
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200585 if (unique && map_table == curbuf->b_maphash
586 && haskey && hasarg && maptype != 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200587 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200588 // need to loop over all global hash lists
589 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200590 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200591 if (abbrev)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200592 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200593 if (hash != 0) // there is only one abbreviation list
594 break;
595 mp = first_abbr;
596 }
597 else
598 mp = maphash[hash];
599 for ( ; mp != NULL && !got_int; mp = mp->m_next)
600 {
601 // check entries with the same mode
602 if ((mp->m_mode & mode) != 0
603 && mp->m_keylen == len
Bram Moolenaar459fd782019-10-13 16:43:39 +0200604 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
605 {
606 if (abbrev)
Bram Moolenaar6d057012021-12-31 18:49:43 +0000607 semsg(
608 _(e_global_abbreviation_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200609 mp->m_keys);
610 else
Bram Moolenaar6d057012021-12-31 18:49:43 +0000611 semsg(_(e_global_mapping_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200612 mp->m_keys);
613 retval = 5;
614 goto theend;
615 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200616 }
617 }
618 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200619
Bram Moolenaar459fd782019-10-13 16:43:39 +0200620 // When listing global mappings, also list buffer-local ones here.
621 if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200622 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200623 // need to loop over all global hash lists
624 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200625 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200626 if (abbrev)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200627 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200628 if (hash != 0) // there is only one abbreviation list
629 break;
630 mp = curbuf->b_first_abbr;
631 }
632 else
633 mp = curbuf->b_maphash[hash];
634 for ( ; mp != NULL && !got_int; mp = mp->m_next)
635 {
636 // check entries with the same mode
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200637 if (!mp->m_simplified && (mp->m_mode & mode) != 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200638 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200639 if (!haskey) // show all entries
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200640 {
641 showmap(mp, TRUE);
642 did_local = TRUE;
643 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200644 else
645 {
646 n = mp->m_keylen;
647 if (STRNCMP(mp->m_keys, keys,
648 (size_t)(n < len ? n : len)) == 0)
649 {
650 showmap(mp, TRUE);
651 did_local = TRUE;
652 }
653 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200654 }
655 }
656 }
657 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200658
Bram Moolenaar459fd782019-10-13 16:43:39 +0200659 // Find an entry in the maphash[] list that matches.
660 // For :unmap we may loop two times: once to try to unmap an entry with
661 // a matching 'from' part, a second time, if the first fails, to unmap
zeertzjqa3f83fe2021-11-22 12:47:39 +0000662 // an entry with a matching 'to' part. This was done to allow
663 // ":ab foo bar" to be unmapped by typing ":unab foo", where "foo" will
664 // be replaced by "bar" because of the abbreviation.
Bram Moolenaar459fd782019-10-13 16:43:39 +0200665 for (round = 0; (round == 0 || maptype == 1) && round <= 1
666 && !did_it && !got_int; ++round)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200667 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200668 // need to loop over all hash lists
669 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200670 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200671 if (abbrev)
672 {
673 if (hash > 0) // there is only one abbreviation list
674 break;
675 mpp = abbr_table;
676 }
677 else
678 mpp = &(map_table[hash]);
679 for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
680 {
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200681
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200682 if ((mp->m_mode & mode) == 0)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200683 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200684 // skip entries with wrong mode
Bram Moolenaar459fd782019-10-13 16:43:39 +0200685 mpp = &(mp->m_next);
686 continue;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200687 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200688 if (!haskey) // show all entries
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200689 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200690 if (!mp->m_simplified)
691 {
692 showmap(mp, map_table != maphash);
693 did_it = TRUE;
694 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200695 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200696 else // do we have a match?
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200697 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200698 if (round) // second round: Try unmap "rhs" string
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200699 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200700 n = (int)STRLEN(mp->m_str);
701 p = mp->m_str;
702 }
703 else
704 {
705 n = mp->m_keylen;
706 p = mp->m_keys;
707 }
708 if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
709 {
710 if (maptype == 1)
711 {
712 // Delete entry.
713 // Only accept a full match. For abbreviations
714 // we ignore trailing space when matching with
715 // the "lhs", since an abbreviation can't have
716 // trailing space.
717 if (n != len && (!abbrev || round || n > len
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200718 || *skipwhite(keys + n) != NUL))
Bram Moolenaar459fd782019-10-13 16:43:39 +0200719 {
720 mpp = &(mp->m_next);
721 continue;
722 }
723 // We reset the indicated mode bits. If nothing
724 // is left the entry is deleted below.
725 mp->m_mode &= ~mode;
726 did_it = TRUE; // remember we did something
727 }
728 else if (!hasarg) // show matching entry
729 {
Bram Moolenaarfafb4b12019-10-16 18:34:57 +0200730 if (!mp->m_simplified)
731 {
732 showmap(mp, map_table != maphash);
733 did_it = TRUE;
734 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200735 }
736 else if (n != len) // new entry is ambiguous
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200737 {
738 mpp = &(mp->m_next);
739 continue;
740 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200741 else if (unique)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200742 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200743 if (abbrev)
Bram Moolenaar6d057012021-12-31 18:49:43 +0000744 semsg(
745 _(e_abbreviation_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200746 p);
747 else
Bram Moolenaar6d057012021-12-31 18:49:43 +0000748 semsg(_(e_mapping_already_exists_for_str),
Bram Moolenaar459fd782019-10-13 16:43:39 +0200749 p);
750 retval = 5;
751 goto theend;
752 }
753 else
754 {
755 // new rhs for existing entry
756 mp->m_mode &= ~mode; // remove mode bits
757 if (mp->m_mode == 0 && !did_it) // reuse entry
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200758 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200759 char_u *newstr = vim_strsave(rhs);
760
761 if (newstr == NULL)
762 {
763 retval = 4; // no mem
764 goto theend;
765 }
766 vim_free(mp->m_str);
767 mp->m_str = newstr;
768 vim_free(mp->m_orig_str);
769 mp->m_orig_str = vim_strsave(orig_rhs);
770 mp->m_noremap = noremap;
771 mp->m_nowait = nowait;
772 mp->m_silent = silent;
773 mp->m_mode = mode;
774 mp->m_simplified =
775 did_simplify && keyround == 1;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200776#ifdef FEAT_EVAL
Bram Moolenaar459fd782019-10-13 16:43:39 +0200777 mp->m_expr = expr;
778 mp->m_script_ctx = current_sctx;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +0100779 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200780#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200781 did_it = TRUE;
782 }
783 }
784 if (mp->m_mode == 0) // entry can be deleted
785 {
786 map_free(mpp);
787 continue; // continue with *mpp
788 }
789
790 // May need to put this entry into another hash
791 // list.
792 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
793 if (!abbrev && new_hash != hash)
794 {
795 *mpp = mp->m_next;
796 mp->m_next = map_table[new_hash];
797 map_table[new_hash] = mp;
798
799 continue; // continue with *mpp
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200800 }
801 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200802 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200803 mpp = &(mp->m_next);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200804 }
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 if (maptype == 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200809 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200810 // delete entry
811 if (!did_it)
812 retval = 2; // no match
813 else if (*keys == Ctrl_C)
814 {
815 // If CTRL-C has been unmapped, reuse it for Interrupting.
816 if (map_table == curbuf->b_maphash)
817 curbuf->b_mapped_ctrl_c &= ~mode;
818 else
819 mapped_ctrl_c &= ~mode;
820 }
821 continue;
822 }
823
824 if (!haskey || !hasarg)
825 {
826 // print entries
827 if (!did_it && !did_local)
828 {
829 if (abbrev)
830 msg(_("No abbreviation found"));
831 else
832 msg(_("No mapping found"));
833 }
834 goto theend; // listing finished
835 }
836
837 if (did_it)
838 continue; // have added the new entry already
839
840 // Get here when adding a new entry to the maphash[] list or abbrlist.
Bram Moolenaar5a80f8a2020-05-22 13:38:18 +0200841 if (map_add(map_table, abbr_table, keys, rhs, orig_rhs,
842 noremap, nowait, silent, mode, abbrev,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200843#ifdef FEAT_EVAL
Bram Moolenaar5a80f8a2020-05-22 13:38:18 +0200844 expr, /* sid */ -1, /* lnum */ 0,
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200845#endif
846 did_simplify && keyround == 1) == FAIL)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200847 {
848 retval = 4; // no mem
849 goto theend;
850 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200851 }
852
853theend:
854 vim_free(keys_buf);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200855 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200856 vim_free(arg_buf);
857 return retval;
858}
859
860/*
861 * Get the mapping mode from the command name.
862 */
863 static int
864get_map_mode(char_u **cmdp, int forceit)
865{
866 char_u *p;
867 int modec;
868 int mode;
869
870 p = *cmdp;
871 modec = *p++;
872 if (modec == 'i')
873 mode = INSERT; // :imap
874 else if (modec == 'l')
875 mode = LANGMAP; // :lmap
876 else if (modec == 'c')
877 mode = CMDLINE; // :cmap
878 else if (modec == 'n' && *p != 'o') // avoid :noremap
879 mode = NORMAL; // :nmap
880 else if (modec == 'v')
881 mode = VISUAL + SELECTMODE; // :vmap
882 else if (modec == 'x')
883 mode = VISUAL; // :xmap
884 else if (modec == 's')
885 mode = SELECTMODE; // :smap
886 else if (modec == 'o')
887 mode = OP_PENDING; // :omap
888 else if (modec == 't')
889 mode = TERMINAL; // :tmap
890 else
891 {
892 --p;
893 if (forceit)
894 mode = INSERT + CMDLINE; // :map !
895 else
896 mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;// :map
897 }
898
899 *cmdp = p;
900 return mode;
901}
902
903/*
904 * Clear all mappings or abbreviations.
905 * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
906 */
907 static void
908map_clear(
909 char_u *cmdp,
910 char_u *arg UNUSED,
911 int forceit,
912 int abbr)
913{
914 int mode;
915 int local;
916
917 local = (STRCMP(arg, "<buffer>") == 0);
918 if (!local && *arg != NUL)
919 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000920 emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200921 return;
922 }
923
924 mode = get_map_mode(&cmdp, forceit);
925 map_clear_int(curbuf, mode, local, abbr);
926}
927
928/*
929 * Clear all mappings in "mode".
930 */
931 void
932map_clear_int(
933 buf_T *buf, // buffer for local mappings
934 int mode, // mode in which to delete
935 int local, // TRUE for buffer-local mappings
936 int abbr) // TRUE for abbreviations
937{
938 mapblock_T *mp, **mpp;
939 int hash;
940 int new_hash;
941
942 validate_maphash();
943
944 for (hash = 0; hash < 256; ++hash)
945 {
946 if (abbr)
947 {
948 if (hash > 0) // there is only one abbrlist
949 break;
950 if (local)
951 mpp = &buf->b_first_abbr;
952 else
953 mpp = &first_abbr;
954 }
955 else
956 {
957 if (local)
958 mpp = &buf->b_maphash[hash];
959 else
960 mpp = &maphash[hash];
961 }
962 while (*mpp != NULL)
963 {
964 mp = *mpp;
965 if (mp->m_mode & mode)
966 {
967 mp->m_mode &= ~mode;
968 if (mp->m_mode == 0) // entry can be deleted
969 {
970 map_free(mpp);
971 continue;
972 }
973 // May need to put this entry into another hash list.
974 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
975 if (!abbr && new_hash != hash)
976 {
977 *mpp = mp->m_next;
978 if (local)
979 {
980 mp->m_next = buf->b_maphash[new_hash];
981 buf->b_maphash[new_hash] = mp;
982 }
983 else
984 {
985 mp->m_next = maphash[new_hash];
986 maphash[new_hash] = mp;
987 }
988 continue; // continue with *mpp
989 }
990 }
991 mpp = &(mp->m_next);
992 }
993 }
994}
995
996#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200997 int
Bram Moolenaar581ba392019-09-03 22:08:33 +0200998mode_str2flags(char_u *modechars)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200999{
1000 int mode = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001001
1002 if (vim_strchr(modechars, 'n') != NULL)
1003 mode |= NORMAL;
1004 if (vim_strchr(modechars, 'v') != NULL)
1005 mode |= VISUAL + SELECTMODE;
1006 if (vim_strchr(modechars, 'x') != NULL)
1007 mode |= VISUAL;
1008 if (vim_strchr(modechars, 's') != NULL)
1009 mode |= SELECTMODE;
1010 if (vim_strchr(modechars, 'o') != NULL)
1011 mode |= OP_PENDING;
1012 if (vim_strchr(modechars, 'i') != NULL)
1013 mode |= INSERT;
1014 if (vim_strchr(modechars, 'l') != NULL)
1015 mode |= LANGMAP;
1016 if (vim_strchr(modechars, 'c') != NULL)
1017 mode |= CMDLINE;
1018
Bram Moolenaar581ba392019-09-03 22:08:33 +02001019 return mode;
1020}
1021
1022/*
1023 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
1024 * Recognize termcap codes in "str".
1025 * Also checks mappings local to the current buffer.
1026 */
1027 int
1028map_to_exists(char_u *str, char_u *modechars, int abbr)
1029{
1030 char_u *rhs;
1031 char_u *buf;
1032 int retval;
1033
Bram Moolenaar459fd782019-10-13 16:43:39 +02001034 rhs = replace_termcodes(str, &buf, REPTERM_DO_LT, NULL);
Bram Moolenaar581ba392019-09-03 22:08:33 +02001035
1036 retval = map_to_exists_mode(rhs, mode_str2flags(modechars), abbr);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001037 vim_free(buf);
1038
1039 return retval;
1040}
1041#endif
1042
1043/*
1044 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
1045 * Also checks mappings local to the current buffer.
1046 */
1047 int
1048map_to_exists_mode(char_u *rhs, int mode, int abbr)
1049{
1050 mapblock_T *mp;
1051 int hash;
1052 int exp_buffer = FALSE;
1053
1054 validate_maphash();
1055
1056 // Do it twice: once for global maps and once for local maps.
1057 for (;;)
1058 {
1059 for (hash = 0; hash < 256; ++hash)
1060 {
1061 if (abbr)
1062 {
1063 if (hash > 0) // there is only one abbr list
1064 break;
1065 if (exp_buffer)
1066 mp = curbuf->b_first_abbr;
1067 else
1068 mp = first_abbr;
1069 }
1070 else if (exp_buffer)
1071 mp = curbuf->b_maphash[hash];
1072 else
1073 mp = maphash[hash];
1074 for (; mp; mp = mp->m_next)
1075 {
1076 if ((mp->m_mode & mode)
1077 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
1078 return TRUE;
1079 }
1080 }
1081 if (exp_buffer)
1082 break;
1083 exp_buffer = TRUE;
1084 }
1085
1086 return FALSE;
1087}
1088
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001089/*
1090 * Used below when expanding mapping/abbreviation names.
1091 */
1092static int expand_mapmodes = 0;
1093static int expand_isabbrev = 0;
1094static int expand_buffer = FALSE;
1095
1096/*
Bram Moolenaar7f51bbe2020-01-24 20:21:19 +01001097 * Translate an internal mapping/abbreviation representation into the
1098 * corresponding external one recognized by :map/:abbrev commands.
1099 * Respects the current B/k/< settings of 'cpoption'.
1100 *
1101 * This function is called when expanding mappings/abbreviations on the
1102 * command-line.
1103 *
1104 * It uses a growarray to build the translation string since the latter can be
1105 * wider than the original description. The caller has to free the string
1106 * afterwards.
1107 *
1108 * Returns NULL when there is a problem.
1109 */
1110 static char_u *
1111translate_mapping(char_u *str)
1112{
1113 garray_T ga;
1114 int c;
1115 int modifiers;
1116 int cpo_bslash;
1117 int cpo_special;
1118
1119 ga_init(&ga);
1120 ga.ga_itemsize = 1;
1121 ga.ga_growsize = 40;
1122
1123 cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL);
1124 cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL);
1125
1126 for (; *str; ++str)
1127 {
1128 c = *str;
1129 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1130 {
1131 modifiers = 0;
1132 if (str[1] == KS_MODIFIER)
1133 {
1134 str++;
1135 modifiers = *++str;
1136 c = *++str;
1137 }
1138 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1139 {
1140 if (cpo_special)
1141 {
1142 ga_clear(&ga);
1143 return NULL;
1144 }
1145 c = TO_SPECIAL(str[1], str[2]);
1146 if (c == K_ZERO) // display <Nul> as ^@
1147 c = NUL;
1148 str += 2;
1149 }
1150 if (IS_SPECIAL(c) || modifiers) // special key
1151 {
1152 if (cpo_special)
1153 {
1154 ga_clear(&ga);
1155 return NULL;
1156 }
1157 ga_concat(&ga, get_special_key_name(c, modifiers));
1158 continue; // for (str)
1159 }
1160 }
1161 if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
1162 || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash))
1163 ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
1164 if (c)
1165 ga_append(&ga, c);
1166 }
1167 ga_append(&ga, NUL);
1168 return (char_u *)(ga.ga_data);
1169}
1170
1171/*
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001172 * Work out what to complete when doing command line completion of mapping
1173 * or abbreviation names.
1174 */
1175 char_u *
1176set_context_in_map_cmd(
1177 expand_T *xp,
1178 char_u *cmd,
1179 char_u *arg,
1180 int forceit, // TRUE if '!' given
1181 int isabbrev, // TRUE if abbreviation
1182 int isunmap, // TRUE if unmap/unabbrev command
1183 cmdidx_T cmdidx)
1184{
1185 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
1186 xp->xp_context = EXPAND_NOTHING;
1187 else
1188 {
1189 if (isunmap)
1190 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1191 else
1192 {
1193 expand_mapmodes = INSERT + CMDLINE;
1194 if (!isabbrev)
1195 expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
1196 }
1197 expand_isabbrev = isabbrev;
1198 xp->xp_context = EXPAND_MAPPINGS;
1199 expand_buffer = FALSE;
1200 for (;;)
1201 {
1202 if (STRNCMP(arg, "<buffer>", 8) == 0)
1203 {
1204 expand_buffer = TRUE;
1205 arg = skipwhite(arg + 8);
1206 continue;
1207 }
1208 if (STRNCMP(arg, "<unique>", 8) == 0)
1209 {
1210 arg = skipwhite(arg + 8);
1211 continue;
1212 }
1213 if (STRNCMP(arg, "<nowait>", 8) == 0)
1214 {
1215 arg = skipwhite(arg + 8);
1216 continue;
1217 }
1218 if (STRNCMP(arg, "<silent>", 8) == 0)
1219 {
1220 arg = skipwhite(arg + 8);
1221 continue;
1222 }
1223 if (STRNCMP(arg, "<special>", 9) == 0)
1224 {
1225 arg = skipwhite(arg + 9);
1226 continue;
1227 }
1228#ifdef FEAT_EVAL
1229 if (STRNCMP(arg, "<script>", 8) == 0)
1230 {
1231 arg = skipwhite(arg + 8);
1232 continue;
1233 }
1234 if (STRNCMP(arg, "<expr>", 6) == 0)
1235 {
1236 arg = skipwhite(arg + 6);
1237 continue;
1238 }
1239#endif
1240 break;
1241 }
1242 xp->xp_pattern = arg;
1243 }
1244
1245 return NULL;
1246}
1247
1248/*
1249 * Find all mapping/abbreviation names that match regexp "regmatch"'.
1250 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1251 * Return OK if matches found, FAIL otherwise.
1252 */
1253 int
1254ExpandMappings(
1255 regmatch_T *regmatch,
1256 int *num_file,
1257 char_u ***file)
1258{
1259 mapblock_T *mp;
1260 int hash;
1261 int count;
1262 int round;
1263 char_u *p;
1264 int i;
1265
1266 validate_maphash();
1267
1268 *num_file = 0; // return values in case of FAIL
1269 *file = NULL;
1270
1271 // round == 1: Count the matches.
1272 // round == 2: Build the array to keep the matches.
1273 for (round = 1; round <= 2; ++round)
1274 {
1275 count = 0;
1276
1277 for (i = 0; i < 7; ++i)
1278 {
1279 if (i == 0)
1280 p = (char_u *)"<silent>";
1281 else if (i == 1)
1282 p = (char_u *)"<unique>";
1283#ifdef FEAT_EVAL
1284 else if (i == 2)
1285 p = (char_u *)"<script>";
1286 else if (i == 3)
1287 p = (char_u *)"<expr>";
1288#endif
1289 else if (i == 4 && !expand_buffer)
1290 p = (char_u *)"<buffer>";
1291 else if (i == 5)
1292 p = (char_u *)"<nowait>";
1293 else if (i == 6)
1294 p = (char_u *)"<special>";
1295 else
1296 continue;
1297
1298 if (vim_regexec(regmatch, p, (colnr_T)0))
1299 {
1300 if (round == 1)
1301 ++count;
1302 else
1303 (*file)[count++] = vim_strsave(p);
1304 }
1305 }
1306
1307 for (hash = 0; hash < 256; ++hash)
1308 {
1309 if (expand_isabbrev)
1310 {
1311 if (hash > 0) // only one abbrev list
1312 break; // for (hash)
1313 mp = first_abbr;
1314 }
1315 else if (expand_buffer)
1316 mp = curbuf->b_maphash[hash];
1317 else
1318 mp = maphash[hash];
1319 for (; mp; mp = mp->m_next)
1320 {
1321 if (mp->m_mode & expand_mapmodes)
1322 {
1323 p = translate_mapping(mp->m_keys);
1324 if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
1325 {
1326 if (round == 1)
1327 ++count;
1328 else
1329 {
1330 (*file)[count++] = p;
1331 p = NULL;
1332 }
1333 }
1334 vim_free(p);
1335 }
1336 } // for (mp)
1337 } // for (hash)
1338
1339 if (count == 0) // no match found
1340 break; // for (round)
1341
1342 if (round == 1)
1343 {
1344 *file = ALLOC_MULT(char_u *, count);
1345 if (*file == NULL)
1346 return FAIL;
1347 }
1348 } // for (round)
1349
1350 if (count > 1)
1351 {
1352 char_u **ptr1;
1353 char_u **ptr2;
1354 char_u **ptr3;
1355
1356 // Sort the matches
1357 sort_strings(*file, count);
1358
1359 // Remove multiple entries
1360 ptr1 = *file;
1361 ptr2 = ptr1 + 1;
1362 ptr3 = ptr1 + count;
1363
1364 while (ptr2 < ptr3)
1365 {
1366 if (STRCMP(*ptr1, *ptr2))
1367 *++ptr1 = *ptr2++;
1368 else
1369 {
1370 vim_free(*ptr2++);
1371 count--;
1372 }
1373 }
1374 }
1375
1376 *num_file = count;
1377 return (count == 0 ? FAIL : OK);
1378}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001379
1380/*
1381 * Check for an abbreviation.
1382 * Cursor is at ptr[col].
1383 * When inserting, mincol is where insert started.
1384 * For the command line, mincol is what is to be skipped over.
1385 * "c" is the character typed before check_abbr was called. It may have
1386 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1387 *
1388 * Historic vi practice: The last character of an abbreviation must be an id
1389 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1390 * characters or all non-id characters. This allows for abbr. "#i" to
1391 * "#include".
1392 *
1393 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1394 * Then there must be white space before the abbr.
1395 *
1396 * return TRUE if there is an abbreviation, FALSE if not
1397 */
1398 int
1399check_abbr(
1400 int c,
1401 char_u *ptr,
1402 int col,
1403 int mincol)
1404{
1405 int len;
1406 int scol; // starting column of the abbr.
1407 int j;
1408 char_u *s;
1409 char_u tb[MB_MAXBYTES + 4];
1410 mapblock_T *mp;
1411 mapblock_T *mp2;
1412 int clen = 0; // length in characters
1413 int is_id = TRUE;
1414 int vim_abbr;
1415
1416 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1417 return FALSE;
1418
1419 // no remapping implies no abbreviation, except for CTRL-]
1420 if (noremap_keys() && c != Ctrl_RSB)
1421 return FALSE;
1422
1423 // Check for word before the cursor: If it ends in a keyword char all
1424 // chars before it must be keyword chars or non-keyword chars, but not
1425 // white space. If it ends in a non-keyword char we accept any characters
1426 // before it except white space.
1427 if (col == 0) // cannot be an abbr.
1428 return FALSE;
1429
1430 if (has_mbyte)
1431 {
1432 char_u *p;
1433
1434 p = mb_prevptr(ptr, ptr + col);
1435 if (!vim_iswordp(p))
1436 vim_abbr = TRUE; // Vim added abbr.
1437 else
1438 {
1439 vim_abbr = FALSE; // vi compatible abbr.
1440 if (p > ptr)
1441 is_id = vim_iswordp(mb_prevptr(ptr, p));
1442 }
1443 clen = 1;
1444 while (p > ptr + mincol)
1445 {
1446 p = mb_prevptr(ptr, p);
1447 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1448 {
1449 p += (*mb_ptr2len)(p);
1450 break;
1451 }
1452 ++clen;
1453 }
1454 scol = (int)(p - ptr);
1455 }
1456 else
1457 {
1458 if (!vim_iswordc(ptr[col - 1]))
1459 vim_abbr = TRUE; // Vim added abbr.
1460 else
1461 {
1462 vim_abbr = FALSE; // vi compatible abbr.
1463 if (col > 1)
1464 is_id = vim_iswordc(ptr[col - 2]);
1465 }
1466 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1467 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1468 ;
1469 }
1470
1471 if (scol < mincol)
1472 scol = mincol;
1473 if (scol < col) // there is a word in front of the cursor
1474 {
1475 ptr += scol;
1476 len = col - scol;
1477 mp = curbuf->b_first_abbr;
1478 mp2 = first_abbr;
1479 if (mp == NULL)
1480 {
1481 mp = mp2;
1482 mp2 = NULL;
1483 }
1484 for ( ; mp; mp->m_next == NULL
1485 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1486 {
1487 int qlen = mp->m_keylen;
1488 char_u *q = mp->m_keys;
1489 int match;
1490
1491 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1492 {
1493 char_u *qe = vim_strsave(mp->m_keys);
1494
1495 // might have CSI escaped mp->m_keys
1496 if (qe != NULL)
1497 {
1498 q = qe;
1499 vim_unescape_csi(q);
1500 qlen = (int)STRLEN(q);
1501 }
1502 }
1503
1504 // find entries with right mode and keys
1505 match = (mp->m_mode & State)
1506 && qlen == len
1507 && !STRNCMP(q, ptr, (size_t)len);
1508 if (q != mp->m_keys)
1509 vim_free(q);
1510 if (match)
1511 break;
1512 }
1513 if (mp != NULL)
1514 {
1515 // Found a match:
1516 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1517 // This goes from end to start.
1518 //
1519 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1520 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1521 // Characters where IS_SPECIAL() == TRUE: key codes, need
1522 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1523 //
1524 // Character CTRL-] is treated specially - it completes the
1525 // abbreviation, but is not inserted into the input stream.
1526 j = 0;
1527 if (c != Ctrl_RSB)
1528 {
1529 // special key code, split up
1530 if (IS_SPECIAL(c) || c == K_SPECIAL)
1531 {
1532 tb[j++] = K_SPECIAL;
1533 tb[j++] = K_SECOND(c);
1534 tb[j++] = K_THIRD(c);
1535 }
1536 else
1537 {
1538 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1539 tb[j++] = Ctrl_V; // special char needs CTRL-V
1540 if (has_mbyte)
1541 {
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001542 int newlen;
1543 char_u *escaped;
1544
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001545 // if ABBR_OFF has been added, remove it here
1546 if (c >= ABBR_OFF)
1547 c -= ABBR_OFF;
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001548 newlen = (*mb_char2bytes)(c, tb + j);
1549 tb[j + newlen] = NUL;
1550 // Need to escape K_SPECIAL.
1551 escaped = vim_strsave_escape_csi(tb + j);
1552 if (escaped != NULL)
1553 {
Bram Moolenaar551c1ae2021-05-03 18:57:05 +02001554 newlen = (int)STRLEN(escaped);
Bram Moolenaar4934ed32021-04-30 19:43:11 +02001555 mch_memmove(tb + j, escaped, newlen);
1556 j += newlen;
1557 vim_free(escaped);
1558 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001559 }
1560 else
1561 tb[j++] = c;
1562 }
1563 tb[j] = NUL;
1564 // insert the last typed char
1565 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1566 }
1567#ifdef FEAT_EVAL
1568 if (mp->m_expr)
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001569 s = eval_map_expr(mp, c);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001570 else
1571#endif
1572 s = mp->m_str;
1573 if (s != NULL)
1574 {
1575 // insert the to string
1576 (void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
1577 // no abbrev. for these chars
1578 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1579#ifdef FEAT_EVAL
1580 if (mp->m_expr)
1581 vim_free(s);
1582#endif
1583 }
1584
1585 tb[0] = Ctrl_H;
1586 tb[1] = NUL;
1587 if (has_mbyte)
1588 len = clen; // Delete characters instead of bytes
1589 while (len-- > 0) // delete the from string
1590 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1591 return TRUE;
1592 }
1593 }
1594 return FALSE;
1595}
1596
1597#ifdef FEAT_EVAL
1598/*
1599 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1600 * special characters.
1601 */
1602 char_u *
1603eval_map_expr(
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001604 mapblock_T *mp,
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001605 int c) // NUL or typed character for abbreviation
1606{
1607 char_u *res;
1608 char_u *p;
1609 char_u *expr;
1610 pos_T save_cursor;
1611 int save_msg_col;
1612 int save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001613 scid_T save_sctx_sid = current_sctx.sc_sid;
1614 int save_sctx_version = current_sctx.sc_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001615
1616 // Remove escaping of CSI, because "str" is in a format to be used as
1617 // typeahead.
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001618 expr = vim_strsave(mp->m_str);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001619 if (expr == NULL)
1620 return NULL;
1621 vim_unescape_csi(expr);
1622
1623 // Forbid changing text or using ":normal" to avoid most of the bad side
1624 // effects. Also restore the cursor position.
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001625 ++textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001626 ++ex_normal_lock;
1627 set_vim_var_char(c); // set v:char to the typed character
1628 save_cursor = curwin->w_cursor;
1629 save_msg_col = msg_col;
1630 save_msg_row = msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001631 if (mp->m_script_ctx.sc_version == SCRIPT_VERSION_VIM9)
1632 {
1633 current_sctx.sc_sid = mp->m_script_ctx.sc_sid;
1634 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
1635 }
1636
1637 // Note: the evaluation may make "mp" invalid.
Bram Moolenaarb171fb12020-06-24 20:34:03 +02001638 p = eval_to_string(expr, FALSE);
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001639
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001640 --textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001641 --ex_normal_lock;
1642 curwin->w_cursor = save_cursor;
1643 msg_col = save_msg_col;
1644 msg_row = save_msg_row;
Bram Moolenaar19db9e62022-01-11 11:58:19 +00001645 current_sctx.sc_sid = save_sctx_sid;
1646 current_sctx.sc_version = save_sctx_version;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001647
1648 vim_free(expr);
1649
1650 if (p == NULL)
1651 return NULL;
1652 // Escape CSI in the result to be able to use the string as typeahead.
1653 res = vim_strsave_escape_csi(p);
1654 vim_free(p);
1655
1656 return res;
1657}
1658#endif
1659
1660/*
1661 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1662 * can be put in the typeahead buffer.
1663 * Returns NULL when out of memory.
1664 */
1665 char_u *
Bram Moolenaar957cf672020-11-12 14:21:06 +01001666vim_strsave_escape_csi(char_u *p)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001667{
1668 char_u *res;
1669 char_u *s, *d;
1670
1671 // Need a buffer to hold up to three times as much. Four in case of an
1672 // illegal utf-8 byte:
1673 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1674 res = alloc(STRLEN(p) * 4 + 1);
1675 if (res != NULL)
1676 {
1677 d = res;
1678 for (s = p; *s != NUL; )
1679 {
1680 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1681 {
1682 // Copy special key unmodified.
1683 *d++ = *s++;
1684 *d++ = *s++;
1685 *d++ = *s++;
1686 }
1687 else
1688 {
1689 // Add character, possibly multi-byte to destination, escaping
1690 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1691 d = add_char2buf(PTR2CHAR(s), d);
1692 s += MB_CPTR2LEN(s);
1693 }
1694 }
1695 *d = NUL;
1696 }
1697 return res;
1698}
1699
1700/*
1701 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1702 * vim_strsave_escape_csi(). Works in-place.
1703 */
1704 void
1705vim_unescape_csi(char_u *p)
1706{
1707 char_u *s = p, *d = p;
1708
1709 while (*s != NUL)
1710 {
1711 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1712 {
1713 *d++ = K_SPECIAL;
1714 s += 3;
1715 }
1716 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1717 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1718 {
1719 *d++ = CSI;
1720 s += 3;
1721 }
1722 else
1723 *d++ = *s++;
1724 }
1725 *d = NUL;
1726}
1727
1728/*
1729 * Write map commands for the current mappings to an .exrc file.
1730 * Return FAIL on error, OK otherwise.
1731 */
1732 int
1733makemap(
1734 FILE *fd,
1735 buf_T *buf) // buffer for local mappings or NULL
1736{
1737 mapblock_T *mp;
1738 char_u c1, c2, c3;
1739 char_u *p;
1740 char *cmd;
1741 int abbr;
1742 int hash;
1743 int did_cpo = FALSE;
1744 int i;
1745
1746 validate_maphash();
1747
1748 // Do the loop twice: Once for mappings, once for abbreviations.
1749 // Then loop over all map hash lists.
1750 for (abbr = 0; abbr < 2; ++abbr)
1751 for (hash = 0; hash < 256; ++hash)
1752 {
1753 if (abbr)
1754 {
1755 if (hash > 0) // there is only one abbr list
1756 break;
1757 if (buf != NULL)
1758 mp = buf->b_first_abbr;
1759 else
1760 mp = first_abbr;
1761 }
1762 else
1763 {
1764 if (buf != NULL)
1765 mp = buf->b_maphash[hash];
1766 else
1767 mp = maphash[hash];
1768 }
1769
1770 for ( ; mp; mp = mp->m_next)
1771 {
1772 // skip script-local mappings
1773 if (mp->m_noremap == REMAP_SCRIPT)
1774 continue;
1775
1776 // skip mappings that contain a <SNR> (script-local thing),
1777 // they probably don't work when loaded again
1778 for (p = mp->m_str; *p != NUL; ++p)
1779 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1780 && p[2] == (int)KE_SNR)
1781 break;
1782 if (*p != NUL)
1783 continue;
1784
1785 // It's possible to create a mapping and then ":unmap" certain
1786 // modes. We recreate this here by mapping the individual
1787 // modes, which requires up to three of them.
1788 c1 = NUL;
1789 c2 = NUL;
1790 c3 = NUL;
1791 if (abbr)
1792 cmd = "abbr";
1793 else
1794 cmd = "map";
1795 switch (mp->m_mode)
1796 {
1797 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1798 break;
1799 case NORMAL:
1800 c1 = 'n';
1801 break;
1802 case VISUAL:
1803 c1 = 'x';
1804 break;
1805 case SELECTMODE:
1806 c1 = 's';
1807 break;
1808 case OP_PENDING:
1809 c1 = 'o';
1810 break;
1811 case NORMAL + VISUAL:
1812 c1 = 'n';
1813 c2 = 'x';
1814 break;
1815 case NORMAL + SELECTMODE:
1816 c1 = 'n';
1817 c2 = 's';
1818 break;
1819 case NORMAL + OP_PENDING:
1820 c1 = 'n';
1821 c2 = 'o';
1822 break;
1823 case VISUAL + SELECTMODE:
1824 c1 = 'v';
1825 break;
1826 case VISUAL + OP_PENDING:
1827 c1 = 'x';
1828 c2 = 'o';
1829 break;
1830 case SELECTMODE + OP_PENDING:
1831 c1 = 's';
1832 c2 = 'o';
1833 break;
1834 case NORMAL + VISUAL + SELECTMODE:
1835 c1 = 'n';
1836 c2 = 'v';
1837 break;
1838 case NORMAL + VISUAL + OP_PENDING:
1839 c1 = 'n';
1840 c2 = 'x';
1841 c3 = 'o';
1842 break;
1843 case NORMAL + SELECTMODE + OP_PENDING:
1844 c1 = 'n';
1845 c2 = 's';
1846 c3 = 'o';
1847 break;
1848 case VISUAL + SELECTMODE + OP_PENDING:
1849 c1 = 'v';
1850 c2 = 'o';
1851 break;
1852 case CMDLINE + INSERT:
1853 if (!abbr)
1854 cmd = "map!";
1855 break;
1856 case CMDLINE:
1857 c1 = 'c';
1858 break;
1859 case INSERT:
1860 c1 = 'i';
1861 break;
1862 case LANGMAP:
1863 c1 = 'l';
1864 break;
1865 case TERMINAL:
1866 c1 = 't';
1867 break;
1868 default:
Bram Moolenaar6d057012021-12-31 18:49:43 +00001869 iemsg(_(e_makemap_illegal_mode));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001870 return FAIL;
1871 }
1872 do // do this twice if c2 is set, 3 times with c3
1873 {
1874 // When outputting <> form, need to make sure that 'cpo'
1875 // is set to the Vim default.
1876 if (!did_cpo)
1877 {
1878 if (*mp->m_str == NUL) // will use <Nop>
1879 did_cpo = TRUE;
1880 else
1881 for (i = 0; i < 2; ++i)
1882 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1883 if (*p == K_SPECIAL || *p == NL)
1884 did_cpo = TRUE;
1885 if (did_cpo)
1886 {
1887 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1888 || put_eol(fd) < 0
1889 || fprintf(fd, "set cpo&vim") < 0
1890 || put_eol(fd) < 0)
1891 return FAIL;
1892 }
1893 }
1894 if (c1 && putc(c1, fd) < 0)
1895 return FAIL;
1896 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1897 return FAIL;
1898 if (fputs(cmd, fd) < 0)
1899 return FAIL;
1900 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1901 return FAIL;
1902 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1903 return FAIL;
1904 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1905 return FAIL;
1906#ifdef FEAT_EVAL
1907 if (mp->m_noremap == REMAP_SCRIPT
1908 && fputs("<script>", fd) < 0)
1909 return FAIL;
1910 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1911 return FAIL;
1912#endif
1913
1914 if ( putc(' ', fd) < 0
1915 || put_escstr(fd, mp->m_keys, 0) == FAIL
1916 || putc(' ', fd) < 0
1917 || put_escstr(fd, mp->m_str, 1) == FAIL
1918 || put_eol(fd) < 0)
1919 return FAIL;
1920 c1 = c2;
1921 c2 = c3;
1922 c3 = NUL;
1923 } while (c1 != NUL);
1924 }
1925 }
1926
1927 if (did_cpo)
1928 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
1929 || put_eol(fd) < 0
1930 || fprintf(fd, "unlet s:cpo_save") < 0
1931 || put_eol(fd) < 0)
1932 return FAIL;
1933 return OK;
1934}
1935
1936/*
1937 * write escape string to file
1938 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
1939 *
1940 * return FAIL for failure, OK otherwise
1941 */
1942 int
1943put_escstr(FILE *fd, char_u *strstart, int what)
1944{
1945 char_u *str = strstart;
1946 int c;
1947 int modifiers;
1948
1949 // :map xx <Nop>
1950 if (*str == NUL && what == 1)
1951 {
1952 if (fprintf(fd, "<Nop>") < 0)
1953 return FAIL;
1954 return OK;
1955 }
1956
1957 for ( ; *str != NUL; ++str)
1958 {
1959 char_u *p;
1960
1961 // Check for a multi-byte character, which may contain escaped
1962 // K_SPECIAL and CSI bytes
1963 p = mb_unescape(&str);
1964 if (p != NULL)
1965 {
1966 while (*p != NUL)
1967 if (fputc(*p++, fd) < 0)
1968 return FAIL;
1969 --str;
1970 continue;
1971 }
1972
1973 c = *str;
1974 // Special key codes have to be translated to be able to make sense
1975 // when they are read back.
1976 if (c == K_SPECIAL && what != 2)
1977 {
Bram Moolenaar02c037a2020-08-30 19:26:45 +02001978 modifiers = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001979 if (str[1] == KS_MODIFIER)
1980 {
1981 modifiers = str[2];
1982 str += 3;
1983 c = *str;
1984 }
1985 if (c == K_SPECIAL)
1986 {
1987 c = TO_SPECIAL(str[1], str[2]);
1988 str += 2;
1989 }
1990 if (IS_SPECIAL(c) || modifiers) // special key
1991 {
1992 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
1993 return FAIL;
1994 continue;
1995 }
1996 }
1997
1998 // A '\n' in a map command should be written as <NL>.
1999 // A '\n' in a set command should be written as \^V^J.
2000 if (c == NL)
2001 {
2002 if (what == 2)
2003 {
2004 if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
2005 return FAIL;
2006 }
2007 else
2008 {
2009 if (fprintf(fd, "<NL>") < 0)
2010 return FAIL;
2011 }
2012 continue;
2013 }
2014
2015 // Some characters have to be escaped with CTRL-V to
2016 // prevent them from misinterpreted in DoOneCmd().
2017 // A space, Tab and '"' has to be escaped with a backslash to
2018 // prevent it to be misinterpreted in do_set().
2019 // A space has to be escaped with a CTRL-V when it's at the start of a
2020 // ":map" rhs.
2021 // A '<' has to be escaped with a CTRL-V to prevent it being
2022 // interpreted as the start of a special key name.
2023 // A space in the lhs of a :map needs a CTRL-V.
2024 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2025 {
2026 if (putc('\\', fd) < 0)
2027 return FAIL;
2028 }
2029 else if (c < ' ' || c > '~' || c == '|'
2030 || (what == 0 && c == ' ')
2031 || (what == 1 && str == strstart && c == ' ')
2032 || (what != 2 && c == '<'))
2033 {
2034 if (putc(Ctrl_V, fd) < 0)
2035 return FAIL;
2036 }
2037 if (putc(c, fd) < 0)
2038 return FAIL;
2039 }
2040 return OK;
2041}
2042
2043/*
2044 * Check all mappings for the presence of special key codes.
2045 * Used after ":set term=xxx".
2046 */
2047 void
2048check_map_keycodes(void)
2049{
2050 mapblock_T *mp;
2051 char_u *p;
2052 int i;
2053 char_u buf[3];
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002054 int abbr;
2055 int hash;
2056 buf_T *bp;
Bram Moolenaare31ee862020-01-07 20:59:34 +01002057 ESTACK_CHECK_DECLARATION
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002058
2059 validate_maphash();
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002060 // avoids giving error messages
2061 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
Bram Moolenaare31ee862020-01-07 20:59:34 +01002062 ESTACK_CHECK_SETUP
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002063
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002064 // Do this once for each buffer, and then once for global
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002065 // mappings/abbreviations with bp == NULL
2066 for (bp = firstbuf; ; bp = bp->b_next)
2067 {
2068 // Do the loop twice: Once for mappings, once for abbreviations.
2069 // Then loop over all map hash lists.
2070 for (abbr = 0; abbr <= 1; ++abbr)
2071 for (hash = 0; hash < 256; ++hash)
2072 {
2073 if (abbr)
2074 {
2075 if (hash) // there is only one abbr list
2076 break;
2077 if (bp != NULL)
2078 mp = bp->b_first_abbr;
2079 else
2080 mp = first_abbr;
2081 }
2082 else
2083 {
2084 if (bp != NULL)
2085 mp = bp->b_maphash[hash];
2086 else
2087 mp = maphash[hash];
2088 }
2089 for ( ; mp != NULL; mp = mp->m_next)
2090 {
2091 for (i = 0; i <= 1; ++i) // do this twice
2092 {
2093 if (i == 0)
2094 p = mp->m_keys; // once for the "from" part
2095 else
2096 p = mp->m_str; // and once for the "to" part
2097 while (*p)
2098 {
2099 if (*p == K_SPECIAL)
2100 {
2101 ++p;
2102 if (*p < 128) // for "normal" tcap entries
2103 {
2104 buf[0] = p[0];
2105 buf[1] = p[1];
2106 buf[2] = NUL;
2107 (void)add_termcap_entry(buf, FALSE);
2108 }
2109 ++p;
2110 }
2111 ++p;
2112 }
2113 }
2114 }
2115 }
2116 if (bp == NULL)
2117 break;
2118 }
Bram Moolenaare31ee862020-01-07 20:59:34 +01002119 ESTACK_CHECK_NOW
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002120 estack_pop();
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002121}
2122
2123#if defined(FEAT_EVAL) || defined(PROTO)
2124/*
2125 * Check the string "keys" against the lhs of all mappings.
2126 * Return pointer to rhs of mapping (mapblock->m_str).
2127 * NULL when no mapping found.
2128 */
2129 char_u *
2130check_map(
2131 char_u *keys,
2132 int mode,
2133 int exact, // require exact match
2134 int ign_mod, // ignore preceding modifier
2135 int abbr, // do abbreviations
2136 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2137 int *local_ptr) // return: buffer-local mapping or NULL
2138{
2139 int hash;
2140 int len, minlen;
2141 mapblock_T *mp;
2142 char_u *s;
2143 int local;
2144
2145 validate_maphash();
2146
2147 len = (int)STRLEN(keys);
2148 for (local = 1; local >= 0; --local)
2149 // loop over all hash lists
2150 for (hash = 0; hash < 256; ++hash)
2151 {
2152 if (abbr)
2153 {
2154 if (hash > 0) // there is only one list.
2155 break;
2156 if (local)
2157 mp = curbuf->b_first_abbr;
2158 else
2159 mp = first_abbr;
2160 }
2161 else if (local)
2162 mp = curbuf->b_maphash[hash];
2163 else
2164 mp = maphash[hash];
2165 for ( ; mp != NULL; mp = mp->m_next)
2166 {
2167 // skip entries with wrong mode, wrong length and not matching
2168 // ones
2169 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2170 {
2171 if (len > mp->m_keylen)
2172 minlen = mp->m_keylen;
2173 else
2174 minlen = len;
2175 s = mp->m_keys;
2176 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2177 && s[2] != NUL)
2178 {
2179 s += 3;
2180 if (len > mp->m_keylen - 3)
2181 minlen = mp->m_keylen - 3;
2182 }
2183 if (STRNCMP(s, keys, minlen) == 0)
2184 {
2185 if (mp_ptr != NULL)
2186 *mp_ptr = mp;
2187 if (local_ptr != NULL)
2188 *local_ptr = local;
2189 return mp->m_str;
2190 }
2191 }
2192 }
2193 }
2194
2195 return NULL;
2196}
2197
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002198 static void
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002199get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2200{
2201 char_u *keys;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002202 char_u *keys_simplified;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002203 char_u *which;
2204 char_u buf[NUMBUFLEN];
2205 char_u *keys_buf = NULL;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002206 char_u *alt_keys_buf = NULL;
2207 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002208 char_u *rhs;
2209 int mode;
2210 int abbr = FALSE;
2211 int get_dict = FALSE;
2212 mapblock_T *mp;
Bram Moolenaara55ba062020-05-27 21:29:04 +02002213 mapblock_T *mp_simplified = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002214 int buffer_local;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002215 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002216
2217 // return empty string for failure
2218 rettv->v_type = VAR_STRING;
2219 rettv->vval.v_string = NULL;
2220
2221 keys = tv_get_string(&argvars[0]);
2222 if (*keys == NUL)
2223 return;
2224
2225 if (argvars[1].v_type != VAR_UNKNOWN)
2226 {
2227 which = tv_get_string_buf_chk(&argvars[1], buf);
2228 if (argvars[2].v_type != VAR_UNKNOWN)
2229 {
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002230 abbr = (int)tv_get_bool(&argvars[2]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002231 if (argvars[3].v_type != VAR_UNKNOWN)
Bram Moolenaar04d594b2020-09-02 22:25:35 +02002232 get_dict = (int)tv_get_bool(&argvars[3]);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002233 }
2234 }
2235 else
2236 which = (char_u *)"";
2237 if (which == NULL)
2238 return;
2239
2240 mode = get_map_mode(&which, 0);
2241
Bram Moolenaar9c652532020-05-24 13:10:18 +02002242 keys_simplified = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
2243 rhs = check_map(keys_simplified, mode, exact, FALSE, abbr,
2244 &mp, &buffer_local);
2245 if (did_simplify)
2246 {
2247 // When the lhs is being simplified the not-simplified keys are
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002248 // preferred for printing, like in do_map().
Bram Moolenaar9c652532020-05-24 13:10:18 +02002249 // The "rhs" and "buffer_local" values are not expected to change.
2250 mp_simplified = mp;
2251 (void)replace_termcodes(keys, &alt_keys_buf,
2252 flags | REPTERM_NO_SIMPLIFY, NULL);
2253 rhs = check_map(alt_keys_buf, mode, exact, FALSE, abbr, &mp,
2254 &buffer_local);
2255 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002256
2257 if (!get_dict)
2258 {
2259 // Return a string.
2260 if (rhs != NULL)
2261 {
2262 if (*rhs == NUL)
2263 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2264 else
2265 rettv->vval.v_string = str2special_save(rhs, FALSE);
2266 }
2267
2268 }
2269 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2270 {
2271 // Return a dictionary.
2272 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2273 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2274 dict_T *dict = rettv->vval.v_dict;
2275
2276 dict_add_string(dict, "lhs", lhs);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002277 vim_free(lhs);
2278 dict_add_string(dict, "lhsraw", mp->m_keys);
2279 if (did_simplify)
2280 // Also add the value for the simplified entry.
2281 dict_add_string(dict, "lhsrawalt", mp_simplified->m_keys);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002282 dict_add_string(dict, "rhs", mp->m_orig_str);
2283 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
Bram Moolenaar2da0f0c2020-04-01 19:22:12 +02002284 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2285 ? 1L : 0L);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002286 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2287 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2288 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
2289 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2290 dict_add_number(dict, "buffer", (long)buffer_local);
2291 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2292 dict_add_string(dict, "mode", mapmode);
2293
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002294 vim_free(mapmode);
2295 }
Bram Moolenaar9c652532020-05-24 13:10:18 +02002296
2297 vim_free(keys_buf);
2298 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002299}
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002300
2301/*
Yegappan Lakshmanan4a155042021-07-30 21:32:45 +02002302 * "maparg()" function
2303 */
2304 void
2305f_maparg(typval_T *argvars, typval_T *rettv)
2306{
2307 if (in_vim9script()
2308 && (check_for_string_arg(argvars, 0) == FAIL
2309 || check_for_opt_string_arg(argvars, 1) == FAIL
2310 || (argvars[1].v_type != VAR_UNKNOWN
2311 && (check_for_opt_bool_arg(argvars, 2) == FAIL
2312 || (argvars[2].v_type != VAR_UNKNOWN
2313 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
2314 return;
2315
2316 get_maparg(argvars, rettv, TRUE);
2317}
2318
2319/*
2320 * "mapcheck()" function
2321 */
2322 void
2323f_mapcheck(typval_T *argvars, typval_T *rettv)
2324{
2325 if (in_vim9script()
2326 && (check_for_string_arg(argvars, 0) == FAIL
2327 || check_for_opt_string_arg(argvars, 1) == FAIL
2328 || (argvars[1].v_type != VAR_UNKNOWN
2329 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2330 return;
2331
2332 get_maparg(argvars, rettv, FALSE);
2333}
2334
2335/*
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002336 * "mapset()" function
2337 */
2338 void
2339f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2340{
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002341 char_u *keys_buf = NULL;
2342 char_u *which;
2343 int mode;
2344 char_u buf[NUMBUFLEN];
2345 int is_abbr;
2346 dict_T *d;
2347 char_u *lhs;
Bram Moolenaar9c652532020-05-24 13:10:18 +02002348 char_u *lhsraw;
2349 char_u *lhsrawalt;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002350 char_u *rhs;
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002351 char_u *orig_rhs;
2352 char_u *arg_buf = NULL;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002353 int noremap;
2354 int expr;
2355 int silent;
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002356 int buffer;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002357 scid_T sid;
2358 linenr_T lnum;
2359 mapblock_T **map_table = maphash;
2360 mapblock_T **abbr_table = &first_abbr;
2361 int nowait;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002362 char_u *arg;
2363
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002364 if (in_vim9script()
2365 && (check_for_string_arg(argvars, 0) == FAIL
2366 || check_for_bool_arg(argvars, 1) == FAIL
2367 || check_for_dict_arg(argvars, 2) == FAIL))
2368 return;
2369
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002370 which = tv_get_string_buf_chk(&argvars[0], buf);
Bram Moolenaar1b912982020-09-29 21:45:41 +02002371 if (which == NULL)
2372 return;
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002373 mode = get_map_mode(&which, 0);
Bram Moolenaar74273e62020-10-01 21:37:21 +02002374 is_abbr = (int)tv_get_bool(&argvars[1]);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002375
2376 if (argvars[2].v_type != VAR_DICT)
2377 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002378 emsg(_(e_key_not_present_in_dictionary));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002379 return;
2380 }
2381 d = argvars[2].vval.v_dict;
2382
2383 // Get the values in the same order as above in get_maparg().
2384 lhs = dict_get_string(d, (char_u *)"lhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002385 lhsraw = dict_get_string(d, (char_u *)"lhsraw", FALSE);
2386 lhsrawalt = dict_get_string(d, (char_u *)"lhsrawalt", FALSE);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002387 rhs = dict_get_string(d, (char_u *)"rhs", FALSE);
Bram Moolenaar9c652532020-05-24 13:10:18 +02002388 if (lhs == NULL || lhsraw == NULL || rhs == NULL)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002389 {
Bram Moolenaarb09feaa2022-01-02 20:20:45 +00002390 emsg(_(e_entries_missing_in_mapset_dict_argument));
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002391 return;
2392 }
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002393 orig_rhs = rhs;
2394 rhs = replace_termcodes(rhs, &arg_buf,
2395 REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002396
2397 noremap = dict_get_number(d, (char_u *)"noremap") ? REMAP_NONE: 0;
2398 if (dict_get_number(d, (char_u *)"script") != 0)
2399 noremap = REMAP_SCRIPT;
2400 expr = dict_get_number(d, (char_u *)"expr") != 0;
2401 silent = dict_get_number(d, (char_u *)"silent") != 0;
2402 sid = dict_get_number(d, (char_u *)"sid");
2403 lnum = dict_get_number(d, (char_u *)"lnum");
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002404 buffer = dict_get_number(d, (char_u *)"buffer");
2405 nowait = dict_get_number(d, (char_u *)"nowait") != 0;
2406 // mode from the dict is not used
2407
2408 if (buffer)
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002409 {
2410 map_table = curbuf->b_maphash;
2411 abbr_table = &curbuf->b_first_abbr;
2412 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002413
2414 // Delete any existing mapping for this lhs and mode.
Bram Moolenaar7ba1e4d2021-04-24 13:12:38 +02002415 if (buffer)
2416 {
2417 arg = alloc(STRLEN(lhs) + STRLEN("<buffer>") + 1);
2418 if (arg == NULL)
2419 return;
2420 STRCPY(arg, "<buffer>");
2421 STRCPY(arg + 8, lhs);
2422 }
2423 else
2424 {
2425 arg = vim_strsave(lhs);
2426 if (arg == NULL)
2427 return;
2428 }
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002429 do_map(1, arg, mode, is_abbr);
2430 vim_free(arg);
2431
Bram Moolenaar9c652532020-05-24 13:10:18 +02002432 (void)map_add(map_table, abbr_table, lhsraw, rhs, orig_rhs, noremap,
2433 nowait, silent, mode, is_abbr, expr, sid, lnum, 0);
2434 if (lhsrawalt != NULL)
2435 (void)map_add(map_table, abbr_table, lhsrawalt, rhs, orig_rhs, noremap,
2436 nowait, silent, mode, is_abbr, expr, sid, lnum, 1);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002437 vim_free(keys_buf);
Bram Moolenaarc94c1462020-05-22 20:01:06 +02002438 vim_free(arg_buf);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002439}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002440#endif
2441
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002442
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002443#if defined(MSWIN) || defined(MACOS_X)
2444
2445# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2446
2447/*
2448 * Default mappings for some often used keys.
2449 */
2450struct initmap
2451{
2452 char_u *arg;
2453 int mode;
2454};
2455
2456# ifdef FEAT_GUI_MSWIN
2457// Use the Windows (CUA) keybindings. (GUI)
2458static struct initmap initmappings[] =
2459{
2460 // paste, copy and cut
2461 {(char_u *)"<S-Insert> \"*P", NORMAL},
2462 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2463 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2464 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2465 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2466 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2467 {(char_u *)"<C-X> \"*d", VIS_SEL},
2468 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2469};
2470# endif
2471
2472# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2473// Use the Windows (CUA) keybindings. (Console)
2474static struct initmap cinitmappings[] =
2475{
2476 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2477 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2478 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2479 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2480
2481 // paste, copy and cut
2482# ifdef FEAT_CLIPBOARD
2483 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2484 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2485 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2486 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2487 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2488 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2489 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2490# else
2491 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2492 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2493 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2494 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2495 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2496 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2497# endif
2498};
2499# endif
2500
2501# if defined(MACOS_X)
2502static struct initmap initmappings[] =
2503{
2504 // Use the Standard MacOS binding.
2505 // paste, copy and cut
2506 {(char_u *)"<D-v> \"*P", NORMAL},
2507 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2508 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2509 {(char_u *)"<D-c> \"*y", VIS_SEL},
2510 {(char_u *)"<D-x> \"*d", VIS_SEL},
2511 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2512};
2513# endif
2514
2515# undef VIS_SEL
2516#endif
2517
2518/*
2519 * Set up default mappings.
2520 */
2521 void
2522init_mappings(void)
2523{
2524#if defined(MSWIN) || defined(MACOS_X)
2525 int i;
2526
2527# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2528# ifdef VIMDLL
2529 if (!gui.starting)
2530# endif
2531 {
K.Takataeeec2542021-06-02 13:28:16 +02002532 for (i = 0; i < (int)ARRAY_LENGTH(cinitmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002533 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2534 }
2535# endif
2536# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
K.Takataeeec2542021-06-02 13:28:16 +02002537 for (i = 0; i < (int)ARRAY_LENGTH(initmappings); ++i)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002538 add_map(initmappings[i].arg, initmappings[i].mode);
2539# endif
2540#endif
2541}
2542
2543#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2544 || defined(PROTO)
2545/*
2546 * Add a mapping "map" for mode "mode".
2547 * Need to put string in allocated memory, because do_map() will modify it.
2548 */
2549 void
2550add_map(char_u *map, int mode)
2551{
2552 char_u *s;
2553 char_u *cpo_save = p_cpo;
2554
Bram Moolenaare5a2dc82021-01-03 19:52:05 +01002555 p_cpo = empty_option; // Allow <> notation
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002556 s = vim_strsave(map);
2557 if (s != NULL)
2558 {
2559 (void)do_map(0, s, mode, FALSE);
2560 vim_free(s);
2561 }
2562 p_cpo = cpo_save;
2563}
2564#endif
2565
Bram Moolenaare677df82019-09-02 22:31:11 +02002566#if defined(FEAT_LANGMAP) || defined(PROTO)
2567/*
2568 * Any character has an equivalent 'langmap' character. This is used for
2569 * keyboards that have a special language mode that sends characters above
2570 * 128 (although other characters can be translated too). The "to" field is a
2571 * Vim command character. This avoids having to switch the keyboard back to
2572 * ASCII mode when leaving Insert mode.
2573 *
2574 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2575 * commands.
2576 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2577 * same as langmap_mapchar[] for characters >= 256.
2578 *
2579 * Use growarray for 'langmap' chars >= 256
2580 */
2581typedef struct
2582{
2583 int from;
2584 int to;
2585} langmap_entry_T;
2586
2587static garray_T langmap_mapga;
2588
2589/*
2590 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2591 * field. If not found insert a new entry at the appropriate location.
2592 */
2593 static void
2594langmap_set_entry(int from, int to)
2595{
2596 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2597 int a = 0;
2598 int b = langmap_mapga.ga_len;
2599
2600 // Do a binary search for an existing entry.
2601 while (a != b)
2602 {
2603 int i = (a + b) / 2;
2604 int d = entries[i].from - from;
2605
2606 if (d == 0)
2607 {
2608 entries[i].to = to;
2609 return;
2610 }
2611 if (d < 0)
2612 a = i + 1;
2613 else
2614 b = i;
2615 }
2616
2617 if (ga_grow(&langmap_mapga, 1) != OK)
2618 return; // out of memory
2619
2620 // insert new entry at position "a"
2621 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2622 mch_memmove(entries + 1, entries,
2623 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2624 ++langmap_mapga.ga_len;
2625 entries[0].from = from;
2626 entries[0].to = to;
2627}
2628
2629/*
2630 * Apply 'langmap' to multi-byte character "c" and return the result.
2631 */
2632 int
2633langmap_adjust_mb(int c)
2634{
2635 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2636 int a = 0;
2637 int b = langmap_mapga.ga_len;
2638
2639 while (a != b)
2640 {
2641 int i = (a + b) / 2;
2642 int d = entries[i].from - c;
2643
2644 if (d == 0)
2645 return entries[i].to; // found matching entry
2646 if (d < 0)
2647 a = i + 1;
2648 else
2649 b = i;
2650 }
2651 return c; // no entry found, return "c" unmodified
2652}
2653
2654 void
2655langmap_init(void)
2656{
2657 int i;
2658
2659 for (i = 0; i < 256; i++)
2660 langmap_mapchar[i] = i; // we init with a one-to-one map
2661 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
2662}
2663
2664/*
2665 * Called when langmap option is set; the language map can be
2666 * changed at any time!
2667 */
2668 void
2669langmap_set(void)
2670{
2671 char_u *p;
2672 char_u *p2;
2673 int from, to;
2674
2675 ga_clear(&langmap_mapga); // clear the previous map first
2676 langmap_init(); // back to one-to-one map
2677
2678 for (p = p_langmap; p[0] != NUL; )
2679 {
2680 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2681 MB_PTR_ADV(p2))
2682 {
2683 if (p2[0] == '\\' && p2[1] != NUL)
2684 ++p2;
2685 }
2686 if (p2[0] == ';')
2687 ++p2; // abcd;ABCD form, p2 points to A
2688 else
2689 p2 = NULL; // aAbBcCdD form, p2 is NULL
2690 while (p[0])
2691 {
2692 if (p[0] == ',')
2693 {
2694 ++p;
2695 break;
2696 }
2697 if (p[0] == '\\' && p[1] != NUL)
2698 ++p;
2699 from = (*mb_ptr2char)(p);
2700 to = NUL;
2701 if (p2 == NULL)
2702 {
2703 MB_PTR_ADV(p);
2704 if (p[0] != ',')
2705 {
2706 if (p[0] == '\\')
2707 ++p;
2708 to = (*mb_ptr2char)(p);
2709 }
2710 }
2711 else
2712 {
2713 if (p2[0] != ',')
2714 {
2715 if (p2[0] == '\\')
2716 ++p2;
2717 to = (*mb_ptr2char)(p2);
2718 }
2719 }
2720 if (to == NUL)
2721 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002722 semsg(_(e_langmap_matching_character_missing_for_str),
Bram Moolenaare677df82019-09-02 22:31:11 +02002723 transchar(from));
2724 return;
2725 }
2726
2727 if (from >= 256)
2728 langmap_set_entry(from, to);
2729 else
2730 langmap_mapchar[from & 255] = to;
2731
2732 // Advance to next pair
2733 MB_PTR_ADV(p);
2734 if (p2 != NULL)
2735 {
2736 MB_PTR_ADV(p2);
2737 if (*p == ';')
2738 {
2739 p = p2;
2740 if (p[0] != NUL)
2741 {
2742 if (p[0] != ',')
2743 {
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002744 semsg(_(e_langmap_extra_characters_after_semicolon_str), p);
Bram Moolenaare677df82019-09-02 22:31:11 +02002745 return;
2746 }
2747 ++p;
2748 }
2749 break;
2750 }
2751 }
2752 }
2753 }
2754}
2755#endif
2756
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002757 static void
2758do_exmap(exarg_T *eap, int isabbrev)
2759{
2760 int mode;
2761 char_u *cmdp;
2762
2763 cmdp = eap->cmd;
2764 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2765
2766 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2767 eap->arg, mode, isabbrev))
2768 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002769 case 1: emsg(_(e_invalid_argument));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002770 break;
Bram Moolenaare29a27f2021-07-20 21:07:36 +02002771 case 2: emsg((isabbrev ? _(e_no_such_abbreviation)
2772 : _(e_no_such_mapping)));
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002773 break;
2774 }
2775}
2776
2777/*
2778 * ":abbreviate" and friends.
2779 */
2780 void
2781ex_abbreviate(exarg_T *eap)
2782{
2783 do_exmap(eap, TRUE); // almost the same as mapping
2784}
2785
2786/*
2787 * ":map" and friends.
2788 */
2789 void
2790ex_map(exarg_T *eap)
2791{
2792 // If we are sourcing .exrc or .vimrc in current directory we
2793 // print the mappings for security reasons.
2794 if (secure)
2795 {
2796 secure = 2;
2797 msg_outtrans(eap->cmd);
2798 msg_putchar('\n');
2799 }
2800 do_exmap(eap, FALSE);
2801}
2802
2803/*
2804 * ":unmap" and friends.
2805 */
2806 void
2807ex_unmap(exarg_T *eap)
2808{
2809 do_exmap(eap, FALSE);
2810}
2811
2812/*
2813 * ":mapclear" and friends.
2814 */
2815 void
2816ex_mapclear(exarg_T *eap)
2817{
2818 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2819}
2820
2821/*
2822 * ":abclear" and friends.
2823 */
2824 void
2825ex_abclear(exarg_T *eap)
2826{
2827 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2828}