blob: 34a956e0be0bd5dbd94f47f1969c2492704c4340 [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/*
11 * map.c: functions for maps and abbreviations
12 */
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,
214 int expr,
215 int noremap,
216 int nowait,
217 int silent,
218 int mode,
219 int is_abbr,
220#ifdef FEAT_EVAL
221 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;
263 }
264 else
265 {
266 mp->m_script_ctx = current_sctx;
267 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
268 }
269#endif
270
271 // add the new entry in front of the abbrlist or maphash[] list
272 if (is_abbr)
273 {
274 mp->m_next = *abbr_table;
275 *abbr_table = mp;
276 }
277 else
278 {
279 int n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
280
281 mp->m_next = map_table[n];
282 map_table[n] = mp;
283 }
284 return OK;
285}
286
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200287/*
288 * map[!] : show all key mappings
289 * map[!] {lhs} : show key mapping for {lhs}
290 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
291 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
292 * unmap[!] {lhs} : remove key mapping for {lhs}
293 * abbr : show all abbreviations
294 * abbr {lhs} : show abbreviations for {lhs}
295 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
296 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
297 * unabbr {lhs} : remove abbreviation for {lhs}
298 *
299 * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
300 *
301 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
302 * it will be modified.
303 *
304 * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
305 * for :map! mode is INSERT + CMDLINE
306 * for :cmap mode is CMDLINE
307 * for :imap mode is INSERT
308 * for :lmap mode is LANGMAP
309 * for :nmap mode is NORMAL
310 * for :vmap mode is VISUAL + SELECTMODE
311 * for :xmap mode is VISUAL
312 * for :smap mode is SELECTMODE
313 * for :omap mode is OP_PENDING
314 * for :tmap mode is TERMINAL
315 *
316 * for :abbr mode is INSERT + CMDLINE
317 * for :iabbr mode is INSERT
318 * for :cabbr mode is CMDLINE
319 *
320 * Return 0 for success
321 * 1 for invalid arguments
322 * 2 for no match
323 * 4 for out of mem
324 * 5 for entry not unique
325 */
326 int
327do_map(
328 int maptype,
329 char_u *arg,
330 int mode,
331 int abbrev) // not a mapping but an abbreviation
332{
333 char_u *keys;
334 mapblock_T *mp, **mpp;
335 char_u *rhs;
336 char_u *p;
337 int n;
338 int len = 0; // init for GCC
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200339 int hasarg;
340 int haskey;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200341 int do_print;
342 int keyround;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200343 char_u *keys_buf = NULL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200344 char_u *alt_keys_buf = NULL;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200345 char_u *arg_buf = NULL;
346 int retval = 0;
347 int do_backslash;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200348 mapblock_T **abbr_table;
349 mapblock_T **map_table;
350 int unique = FALSE;
351 int nowait = FALSE;
352 int silent = FALSE;
353 int special = FALSE;
354#ifdef FEAT_EVAL
355 int expr = FALSE;
356#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200357 int did_simplify = FALSE;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200358 int noremap;
359 char_u *orig_rhs;
360
361 keys = arg;
362 map_table = maphash;
363 abbr_table = &first_abbr;
364
365 // For ":noremap" don't remap, otherwise do remap.
366 if (maptype == 2)
367 noremap = REMAP_NONE;
368 else
369 noremap = REMAP_YES;
370
371 // Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
372 // any order.
373 for (;;)
374 {
375 // Check for "<buffer>": mapping local to buffer.
376 if (STRNCMP(keys, "<buffer>", 8) == 0)
377 {
378 keys = skipwhite(keys + 8);
379 map_table = curbuf->b_maphash;
380 abbr_table = &curbuf->b_first_abbr;
381 continue;
382 }
383
384 // Check for "<nowait>": don't wait for more characters.
385 if (STRNCMP(keys, "<nowait>", 8) == 0)
386 {
387 keys = skipwhite(keys + 8);
388 nowait = TRUE;
389 continue;
390 }
391
392 // Check for "<silent>": don't echo commands.
393 if (STRNCMP(keys, "<silent>", 8) == 0)
394 {
395 keys = skipwhite(keys + 8);
396 silent = TRUE;
397 continue;
398 }
399
400 // Check for "<special>": accept special keys in <>
401 if (STRNCMP(keys, "<special>", 9) == 0)
402 {
403 keys = skipwhite(keys + 9);
404 special = TRUE;
405 continue;
406 }
407
408#ifdef FEAT_EVAL
409 // Check for "<script>": remap script-local mappings only
410 if (STRNCMP(keys, "<script>", 8) == 0)
411 {
412 keys = skipwhite(keys + 8);
413 noremap = REMAP_SCRIPT;
414 continue;
415 }
416
417 // Check for "<expr>": {rhs} is an expression.
418 if (STRNCMP(keys, "<expr>", 6) == 0)
419 {
420 keys = skipwhite(keys + 6);
421 expr = TRUE;
422 continue;
423 }
424#endif
425 // Check for "<unique>": don't overwrite an existing mapping.
426 if (STRNCMP(keys, "<unique>", 8) == 0)
427 {
428 keys = skipwhite(keys + 8);
429 unique = TRUE;
430 continue;
431 }
432 break;
433 }
434
435 validate_maphash();
436
437 // Find end of keys and skip CTRL-Vs (and backslashes) in it.
438 // Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
439 // with :unmap white space is included in the keys, no argument possible.
440 p = keys;
441 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
442 while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
443 {
444 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
445 p[1] != NUL)
446 ++p; // skip CTRL-V or backslash
447 ++p;
448 }
449 if (*p != NUL)
450 *p++ = NUL;
451
452 p = skipwhite(p);
453 rhs = p;
454 hasarg = (*rhs != NUL);
455 haskey = (*keys != NUL);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200456 do_print = !haskey || (maptype != 1 && !hasarg);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200457
458 // check for :unmap without argument
459 if (maptype == 1 && !haskey)
460 {
461 retval = 1;
462 goto theend;
463 }
464
465 // If mapping has been given as ^V<C_UP> say, then replace the term codes
466 // with the appropriate two bytes. If it is a shifted special key, unshift
467 // it too, giving another two bytes.
468 // replace_termcodes() may move the result to allocated memory, which
469 // needs to be freed later (*keys_buf and *arg_buf).
470 // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
Bram Moolenaar459fd782019-10-13 16:43:39 +0200471 // If something like <C-H> is simplified to 0x08 then mark it as simplified
472 // and also add a n entry with a modifier, which will work when
473 // modifyOtherKeys is working.
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200474 if (haskey)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200475 {
476 char_u *new_keys;
477 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
478
479 if (special)
480 flags |= REPTERM_SPECIAL;
481 new_keys = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
482 if (did_simplify)
483 (void)replace_termcodes(keys, &alt_keys_buf,
484 flags | REPTERM_NO_SIMPLIFY, NULL);
485 keys = new_keys;
486 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200487 orig_rhs = rhs;
488 if (hasarg)
489 {
490 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
491 rhs = (char_u *)"";
492 else
Bram Moolenaar459fd782019-10-13 16:43:39 +0200493 rhs = replace_termcodes(rhs, &arg_buf,
494 REPTERM_DO_LT | (special ? REPTERM_SPECIAL : 0), NULL);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200495 }
496
Bram Moolenaar459fd782019-10-13 16:43:39 +0200497 /*
498 * The following is done twice if we have two versions of keys:
499 * "alt_keys_buf" is not NULL.
500 */
501 for (keyround = 1; keyround <= 2; ++keyround)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200502 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200503 int did_it = FALSE;
504 int did_local = FALSE;
505 int round;
506 int hash;
507 int new_hash;
508
509 if (keyround == 2)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200510 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200511 if (alt_keys_buf == NULL)
512 break;
513 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200514 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200515 else if (alt_keys_buf != NULL && do_print)
516 // when printing always use the not-simplified map
517 keys = alt_keys_buf;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200518
Bram Moolenaar459fd782019-10-13 16:43:39 +0200519 // check arguments and translate function keys
520 if (haskey)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200521 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200522 len = (int)STRLEN(keys);
523 if (len > MAXMAPLEN) // maximum length of MAXMAPLEN chars
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200524 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200525 retval = 1;
526 goto theend;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200527 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200528
529 if (abbrev && maptype != 1)
530 {
531 // If an abbreviation ends in a keyword character, the
532 // rest must be all keyword-char or all non-keyword-char.
533 // Otherwise we won't be able to find the start of it in a
534 // vi-compatible way.
535 if (has_mbyte)
536 {
537 int first, last;
538 int same = -1;
539
540 first = vim_iswordp(keys);
541 last = first;
542 p = keys + (*mb_ptr2len)(keys);
543 n = 1;
544 while (p < keys + len)
545 {
546 ++n; // nr of (multi-byte) chars
547 last = vim_iswordp(p); // type of last char
548 if (same == -1 && last != first)
549 same = n - 1; // count of same char type
550 p += (*mb_ptr2len)(p);
551 }
552 if (last && n > 2 && same >= 0 && same < n - 1)
553 {
554 retval = 1;
555 goto theend;
556 }
557 }
558 else if (vim_iswordc(keys[len - 1]))
559 // ends in keyword char
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200560 for (n = 0; n < len - 2; ++n)
561 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
562 {
563 retval = 1;
564 goto theend;
565 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200566 // An abbreviation cannot contain white space.
567 for (n = 0; n < len; ++n)
568 if (VIM_ISWHITE(keys[n]))
569 {
570 retval = 1;
571 goto theend;
572 }
573 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200574 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200575
Bram Moolenaar459fd782019-10-13 16:43:39 +0200576 if (haskey && hasarg && abbrev) // if we will add an abbreviation
577 no_abbr = FALSE; // reset flag that indicates there are
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200578 // no abbreviations
579
Bram Moolenaar459fd782019-10-13 16:43:39 +0200580 if (do_print)
581 msg_start();
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200582
Bram Moolenaar459fd782019-10-13 16:43:39 +0200583 // Check if a new local mapping wasn't already defined globally.
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200584 if (unique && map_table == curbuf->b_maphash
585 && haskey && hasarg && maptype != 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200586 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200587 // need to loop over all global hash lists
588 for (hash = 0; hash < 256 && !got_int; ++hash)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200589 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200590 if (abbrev)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200591 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200592 if (hash != 0) // there is only one abbreviation list
593 break;
594 mp = first_abbr;
595 }
596 else
597 mp = maphash[hash];
598 for ( ; mp != NULL && !got_int; mp = mp->m_next)
599 {
600 // check entries with the same mode
601 if ((mp->m_mode & mode) != 0
602 && mp->m_keylen == len
Bram Moolenaar459fd782019-10-13 16:43:39 +0200603 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
604 {
605 if (abbrev)
606 semsg(_(
607 "E224: global abbreviation already exists for %s"),
608 mp->m_keys);
609 else
610 semsg(_(
611 "E225: global mapping already exists for %s"),
612 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
662 // an entry with a matching 'to' part. This was done to allow ":ab foo
663 // bar" to be unmapped by typing ":unab foo", where "foo" will be
664 // replaced by "bar" because of the abbreviation.
665 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)
744 semsg(_(
745 "E226: abbreviation already exists for %s"),
746 p);
747 else
748 semsg(_(
749 "E227: mapping already exists for %s"),
750 p);
751 retval = 5;
752 goto theend;
753 }
754 else
755 {
756 // new rhs for existing entry
757 mp->m_mode &= ~mode; // remove mode bits
758 if (mp->m_mode == 0 && !did_it) // reuse entry
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200759 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200760 char_u *newstr = vim_strsave(rhs);
761
762 if (newstr == NULL)
763 {
764 retval = 4; // no mem
765 goto theend;
766 }
767 vim_free(mp->m_str);
768 mp->m_str = newstr;
769 vim_free(mp->m_orig_str);
770 mp->m_orig_str = vim_strsave(orig_rhs);
771 mp->m_noremap = noremap;
772 mp->m_nowait = nowait;
773 mp->m_silent = silent;
774 mp->m_mode = mode;
775 mp->m_simplified =
776 did_simplify && keyround == 1;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200777#ifdef FEAT_EVAL
Bram Moolenaar459fd782019-10-13 16:43:39 +0200778 mp->m_expr = expr;
779 mp->m_script_ctx = current_sctx;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +0100780 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200781#endif
Bram Moolenaar459fd782019-10-13 16:43:39 +0200782 did_it = TRUE;
783 }
784 }
785 if (mp->m_mode == 0) // entry can be deleted
786 {
787 map_free(mpp);
788 continue; // continue with *mpp
789 }
790
791 // May need to put this entry into another hash
792 // list.
793 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
794 if (!abbrev && new_hash != hash)
795 {
796 *mpp = mp->m_next;
797 mp->m_next = map_table[new_hash];
798 map_table[new_hash] = mp;
799
800 continue; // continue with *mpp
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200801 }
802 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200803 }
Bram Moolenaar459fd782019-10-13 16:43:39 +0200804 mpp = &(mp->m_next);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200805 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200806 }
807 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200808
Bram Moolenaar459fd782019-10-13 16:43:39 +0200809 if (maptype == 1)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200810 {
Bram Moolenaar459fd782019-10-13 16:43:39 +0200811 // delete entry
812 if (!did_it)
813 retval = 2; // no match
814 else if (*keys == Ctrl_C)
815 {
816 // If CTRL-C has been unmapped, reuse it for Interrupting.
817 if (map_table == curbuf->b_maphash)
818 curbuf->b_mapped_ctrl_c &= ~mode;
819 else
820 mapped_ctrl_c &= ~mode;
821 }
822 continue;
823 }
824
825 if (!haskey || !hasarg)
826 {
827 // print entries
828 if (!did_it && !did_local)
829 {
830 if (abbrev)
831 msg(_("No abbreviation found"));
832 else
833 msg(_("No mapping found"));
834 }
835 goto theend; // listing finished
836 }
837
838 if (did_it)
839 continue; // have added the new entry already
840
841 // Get here when adding a new entry to the maphash[] list or abbrlist.
Bram Moolenaar4c9243f2020-05-22 13:10:44 +0200842 if (map_add(map_table, abbr_table, keys, rhs, orig_rhs, expr,
843 noremap, nowait, silent, mode,
844 abbrev,
845#ifdef FEAT_EVAL
846 /* sid */ -1, /* lnum */ 0,
847#endif
848 did_simplify && keyround == 1) == FAIL)
Bram Moolenaar459fd782019-10-13 16:43:39 +0200849 {
850 retval = 4; // no mem
851 goto theend;
852 }
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200853 }
854
855theend:
856 vim_free(keys_buf);
Bram Moolenaar459fd782019-10-13 16:43:39 +0200857 vim_free(alt_keys_buf);
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200858 vim_free(arg_buf);
859 return retval;
860}
861
862/*
863 * Get the mapping mode from the command name.
864 */
865 static int
866get_map_mode(char_u **cmdp, int forceit)
867{
868 char_u *p;
869 int modec;
870 int mode;
871
872 p = *cmdp;
873 modec = *p++;
874 if (modec == 'i')
875 mode = INSERT; // :imap
876 else if (modec == 'l')
877 mode = LANGMAP; // :lmap
878 else if (modec == 'c')
879 mode = CMDLINE; // :cmap
880 else if (modec == 'n' && *p != 'o') // avoid :noremap
881 mode = NORMAL; // :nmap
882 else if (modec == 'v')
883 mode = VISUAL + SELECTMODE; // :vmap
884 else if (modec == 'x')
885 mode = VISUAL; // :xmap
886 else if (modec == 's')
887 mode = SELECTMODE; // :smap
888 else if (modec == 'o')
889 mode = OP_PENDING; // :omap
890 else if (modec == 't')
891 mode = TERMINAL; // :tmap
892 else
893 {
894 --p;
895 if (forceit)
896 mode = INSERT + CMDLINE; // :map !
897 else
898 mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;// :map
899 }
900
901 *cmdp = p;
902 return mode;
903}
904
905/*
906 * Clear all mappings or abbreviations.
907 * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
908 */
909 static void
910map_clear(
911 char_u *cmdp,
912 char_u *arg UNUSED,
913 int forceit,
914 int abbr)
915{
916 int mode;
917 int local;
918
919 local = (STRCMP(arg, "<buffer>") == 0);
920 if (!local && *arg != NUL)
921 {
922 emsg(_(e_invarg));
923 return;
924 }
925
926 mode = get_map_mode(&cmdp, forceit);
927 map_clear_int(curbuf, mode, local, abbr);
928}
929
930/*
931 * Clear all mappings in "mode".
932 */
933 void
934map_clear_int(
935 buf_T *buf, // buffer for local mappings
936 int mode, // mode in which to delete
937 int local, // TRUE for buffer-local mappings
938 int abbr) // TRUE for abbreviations
939{
940 mapblock_T *mp, **mpp;
941 int hash;
942 int new_hash;
943
944 validate_maphash();
945
946 for (hash = 0; hash < 256; ++hash)
947 {
948 if (abbr)
949 {
950 if (hash > 0) // there is only one abbrlist
951 break;
952 if (local)
953 mpp = &buf->b_first_abbr;
954 else
955 mpp = &first_abbr;
956 }
957 else
958 {
959 if (local)
960 mpp = &buf->b_maphash[hash];
961 else
962 mpp = &maphash[hash];
963 }
964 while (*mpp != NULL)
965 {
966 mp = *mpp;
967 if (mp->m_mode & mode)
968 {
969 mp->m_mode &= ~mode;
970 if (mp->m_mode == 0) // entry can be deleted
971 {
972 map_free(mpp);
973 continue;
974 }
975 // May need to put this entry into another hash list.
976 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
977 if (!abbr && new_hash != hash)
978 {
979 *mpp = mp->m_next;
980 if (local)
981 {
982 mp->m_next = buf->b_maphash[new_hash];
983 buf->b_maphash[new_hash] = mp;
984 }
985 else
986 {
987 mp->m_next = maphash[new_hash];
988 maphash[new_hash] = mp;
989 }
990 continue; // continue with *mpp
991 }
992 }
993 mpp = &(mp->m_next);
994 }
995 }
996}
997
998#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200999 int
Bram Moolenaar581ba392019-09-03 22:08:33 +02001000mode_str2flags(char_u *modechars)
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001001{
1002 int mode = 0;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001003
1004 if (vim_strchr(modechars, 'n') != NULL)
1005 mode |= NORMAL;
1006 if (vim_strchr(modechars, 'v') != NULL)
1007 mode |= VISUAL + SELECTMODE;
1008 if (vim_strchr(modechars, 'x') != NULL)
1009 mode |= VISUAL;
1010 if (vim_strchr(modechars, 's') != NULL)
1011 mode |= SELECTMODE;
1012 if (vim_strchr(modechars, 'o') != NULL)
1013 mode |= OP_PENDING;
1014 if (vim_strchr(modechars, 'i') != NULL)
1015 mode |= INSERT;
1016 if (vim_strchr(modechars, 'l') != NULL)
1017 mode |= LANGMAP;
1018 if (vim_strchr(modechars, 'c') != NULL)
1019 mode |= CMDLINE;
1020
Bram Moolenaar581ba392019-09-03 22:08:33 +02001021 return mode;
1022}
1023
1024/*
1025 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
1026 * Recognize termcap codes in "str".
1027 * Also checks mappings local to the current buffer.
1028 */
1029 int
1030map_to_exists(char_u *str, char_u *modechars, int abbr)
1031{
1032 char_u *rhs;
1033 char_u *buf;
1034 int retval;
1035
Bram Moolenaar459fd782019-10-13 16:43:39 +02001036 rhs = replace_termcodes(str, &buf, REPTERM_DO_LT, NULL);
Bram Moolenaar581ba392019-09-03 22:08:33 +02001037
1038 retval = map_to_exists_mode(rhs, mode_str2flags(modechars), abbr);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001039 vim_free(buf);
1040
1041 return retval;
1042}
1043#endif
1044
1045/*
1046 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
1047 * Also checks mappings local to the current buffer.
1048 */
1049 int
1050map_to_exists_mode(char_u *rhs, int mode, int abbr)
1051{
1052 mapblock_T *mp;
1053 int hash;
1054 int exp_buffer = FALSE;
1055
1056 validate_maphash();
1057
1058 // Do it twice: once for global maps and once for local maps.
1059 for (;;)
1060 {
1061 for (hash = 0; hash < 256; ++hash)
1062 {
1063 if (abbr)
1064 {
1065 if (hash > 0) // there is only one abbr list
1066 break;
1067 if (exp_buffer)
1068 mp = curbuf->b_first_abbr;
1069 else
1070 mp = first_abbr;
1071 }
1072 else if (exp_buffer)
1073 mp = curbuf->b_maphash[hash];
1074 else
1075 mp = maphash[hash];
1076 for (; mp; mp = mp->m_next)
1077 {
1078 if ((mp->m_mode & mode)
1079 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
1080 return TRUE;
1081 }
1082 }
1083 if (exp_buffer)
1084 break;
1085 exp_buffer = TRUE;
1086 }
1087
1088 return FALSE;
1089}
1090
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001091/*
1092 * Used below when expanding mapping/abbreviation names.
1093 */
1094static int expand_mapmodes = 0;
1095static int expand_isabbrev = 0;
1096static int expand_buffer = FALSE;
1097
1098/*
Bram Moolenaar7f51bbe2020-01-24 20:21:19 +01001099 * Translate an internal mapping/abbreviation representation into the
1100 * corresponding external one recognized by :map/:abbrev commands.
1101 * Respects the current B/k/< settings of 'cpoption'.
1102 *
1103 * This function is called when expanding mappings/abbreviations on the
1104 * command-line.
1105 *
1106 * It uses a growarray to build the translation string since the latter can be
1107 * wider than the original description. The caller has to free the string
1108 * afterwards.
1109 *
1110 * Returns NULL when there is a problem.
1111 */
1112 static char_u *
1113translate_mapping(char_u *str)
1114{
1115 garray_T ga;
1116 int c;
1117 int modifiers;
1118 int cpo_bslash;
1119 int cpo_special;
1120
1121 ga_init(&ga);
1122 ga.ga_itemsize = 1;
1123 ga.ga_growsize = 40;
1124
1125 cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL);
1126 cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL);
1127
1128 for (; *str; ++str)
1129 {
1130 c = *str;
1131 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1132 {
1133 modifiers = 0;
1134 if (str[1] == KS_MODIFIER)
1135 {
1136 str++;
1137 modifiers = *++str;
1138 c = *++str;
1139 }
1140 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1141 {
1142 if (cpo_special)
1143 {
1144 ga_clear(&ga);
1145 return NULL;
1146 }
1147 c = TO_SPECIAL(str[1], str[2]);
1148 if (c == K_ZERO) // display <Nul> as ^@
1149 c = NUL;
1150 str += 2;
1151 }
1152 if (IS_SPECIAL(c) || modifiers) // special key
1153 {
1154 if (cpo_special)
1155 {
1156 ga_clear(&ga);
1157 return NULL;
1158 }
1159 ga_concat(&ga, get_special_key_name(c, modifiers));
1160 continue; // for (str)
1161 }
1162 }
1163 if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
1164 || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash))
1165 ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
1166 if (c)
1167 ga_append(&ga, c);
1168 }
1169 ga_append(&ga, NUL);
1170 return (char_u *)(ga.ga_data);
1171}
1172
1173/*
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001174 * Work out what to complete when doing command line completion of mapping
1175 * or abbreviation names.
1176 */
1177 char_u *
1178set_context_in_map_cmd(
1179 expand_T *xp,
1180 char_u *cmd,
1181 char_u *arg,
1182 int forceit, // TRUE if '!' given
1183 int isabbrev, // TRUE if abbreviation
1184 int isunmap, // TRUE if unmap/unabbrev command
1185 cmdidx_T cmdidx)
1186{
1187 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
1188 xp->xp_context = EXPAND_NOTHING;
1189 else
1190 {
1191 if (isunmap)
1192 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1193 else
1194 {
1195 expand_mapmodes = INSERT + CMDLINE;
1196 if (!isabbrev)
1197 expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
1198 }
1199 expand_isabbrev = isabbrev;
1200 xp->xp_context = EXPAND_MAPPINGS;
1201 expand_buffer = FALSE;
1202 for (;;)
1203 {
1204 if (STRNCMP(arg, "<buffer>", 8) == 0)
1205 {
1206 expand_buffer = TRUE;
1207 arg = skipwhite(arg + 8);
1208 continue;
1209 }
1210 if (STRNCMP(arg, "<unique>", 8) == 0)
1211 {
1212 arg = skipwhite(arg + 8);
1213 continue;
1214 }
1215 if (STRNCMP(arg, "<nowait>", 8) == 0)
1216 {
1217 arg = skipwhite(arg + 8);
1218 continue;
1219 }
1220 if (STRNCMP(arg, "<silent>", 8) == 0)
1221 {
1222 arg = skipwhite(arg + 8);
1223 continue;
1224 }
1225 if (STRNCMP(arg, "<special>", 9) == 0)
1226 {
1227 arg = skipwhite(arg + 9);
1228 continue;
1229 }
1230#ifdef FEAT_EVAL
1231 if (STRNCMP(arg, "<script>", 8) == 0)
1232 {
1233 arg = skipwhite(arg + 8);
1234 continue;
1235 }
1236 if (STRNCMP(arg, "<expr>", 6) == 0)
1237 {
1238 arg = skipwhite(arg + 6);
1239 continue;
1240 }
1241#endif
1242 break;
1243 }
1244 xp->xp_pattern = arg;
1245 }
1246
1247 return NULL;
1248}
1249
1250/*
1251 * Find all mapping/abbreviation names that match regexp "regmatch"'.
1252 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1253 * Return OK if matches found, FAIL otherwise.
1254 */
1255 int
1256ExpandMappings(
1257 regmatch_T *regmatch,
1258 int *num_file,
1259 char_u ***file)
1260{
1261 mapblock_T *mp;
1262 int hash;
1263 int count;
1264 int round;
1265 char_u *p;
1266 int i;
1267
1268 validate_maphash();
1269
1270 *num_file = 0; // return values in case of FAIL
1271 *file = NULL;
1272
1273 // round == 1: Count the matches.
1274 // round == 2: Build the array to keep the matches.
1275 for (round = 1; round <= 2; ++round)
1276 {
1277 count = 0;
1278
1279 for (i = 0; i < 7; ++i)
1280 {
1281 if (i == 0)
1282 p = (char_u *)"<silent>";
1283 else if (i == 1)
1284 p = (char_u *)"<unique>";
1285#ifdef FEAT_EVAL
1286 else if (i == 2)
1287 p = (char_u *)"<script>";
1288 else if (i == 3)
1289 p = (char_u *)"<expr>";
1290#endif
1291 else if (i == 4 && !expand_buffer)
1292 p = (char_u *)"<buffer>";
1293 else if (i == 5)
1294 p = (char_u *)"<nowait>";
1295 else if (i == 6)
1296 p = (char_u *)"<special>";
1297 else
1298 continue;
1299
1300 if (vim_regexec(regmatch, p, (colnr_T)0))
1301 {
1302 if (round == 1)
1303 ++count;
1304 else
1305 (*file)[count++] = vim_strsave(p);
1306 }
1307 }
1308
1309 for (hash = 0; hash < 256; ++hash)
1310 {
1311 if (expand_isabbrev)
1312 {
1313 if (hash > 0) // only one abbrev list
1314 break; // for (hash)
1315 mp = first_abbr;
1316 }
1317 else if (expand_buffer)
1318 mp = curbuf->b_maphash[hash];
1319 else
1320 mp = maphash[hash];
1321 for (; mp; mp = mp->m_next)
1322 {
1323 if (mp->m_mode & expand_mapmodes)
1324 {
1325 p = translate_mapping(mp->m_keys);
1326 if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
1327 {
1328 if (round == 1)
1329 ++count;
1330 else
1331 {
1332 (*file)[count++] = p;
1333 p = NULL;
1334 }
1335 }
1336 vim_free(p);
1337 }
1338 } // for (mp)
1339 } // for (hash)
1340
1341 if (count == 0) // no match found
1342 break; // for (round)
1343
1344 if (round == 1)
1345 {
1346 *file = ALLOC_MULT(char_u *, count);
1347 if (*file == NULL)
1348 return FAIL;
1349 }
1350 } // for (round)
1351
1352 if (count > 1)
1353 {
1354 char_u **ptr1;
1355 char_u **ptr2;
1356 char_u **ptr3;
1357
1358 // Sort the matches
1359 sort_strings(*file, count);
1360
1361 // Remove multiple entries
1362 ptr1 = *file;
1363 ptr2 = ptr1 + 1;
1364 ptr3 = ptr1 + count;
1365
1366 while (ptr2 < ptr3)
1367 {
1368 if (STRCMP(*ptr1, *ptr2))
1369 *++ptr1 = *ptr2++;
1370 else
1371 {
1372 vim_free(*ptr2++);
1373 count--;
1374 }
1375 }
1376 }
1377
1378 *num_file = count;
1379 return (count == 0 ? FAIL : OK);
1380}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001381
1382/*
1383 * Check for an abbreviation.
1384 * Cursor is at ptr[col].
1385 * When inserting, mincol is where insert started.
1386 * For the command line, mincol is what is to be skipped over.
1387 * "c" is the character typed before check_abbr was called. It may have
1388 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1389 *
1390 * Historic vi practice: The last character of an abbreviation must be an id
1391 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1392 * characters or all non-id characters. This allows for abbr. "#i" to
1393 * "#include".
1394 *
1395 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1396 * Then there must be white space before the abbr.
1397 *
1398 * return TRUE if there is an abbreviation, FALSE if not
1399 */
1400 int
1401check_abbr(
1402 int c,
1403 char_u *ptr,
1404 int col,
1405 int mincol)
1406{
1407 int len;
1408 int scol; // starting column of the abbr.
1409 int j;
1410 char_u *s;
1411 char_u tb[MB_MAXBYTES + 4];
1412 mapblock_T *mp;
1413 mapblock_T *mp2;
1414 int clen = 0; // length in characters
1415 int is_id = TRUE;
1416 int vim_abbr;
1417
1418 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1419 return FALSE;
1420
1421 // no remapping implies no abbreviation, except for CTRL-]
1422 if (noremap_keys() && c != Ctrl_RSB)
1423 return FALSE;
1424
1425 // Check for word before the cursor: If it ends in a keyword char all
1426 // chars before it must be keyword chars or non-keyword chars, but not
1427 // white space. If it ends in a non-keyword char we accept any characters
1428 // before it except white space.
1429 if (col == 0) // cannot be an abbr.
1430 return FALSE;
1431
1432 if (has_mbyte)
1433 {
1434 char_u *p;
1435
1436 p = mb_prevptr(ptr, ptr + col);
1437 if (!vim_iswordp(p))
1438 vim_abbr = TRUE; // Vim added abbr.
1439 else
1440 {
1441 vim_abbr = FALSE; // vi compatible abbr.
1442 if (p > ptr)
1443 is_id = vim_iswordp(mb_prevptr(ptr, p));
1444 }
1445 clen = 1;
1446 while (p > ptr + mincol)
1447 {
1448 p = mb_prevptr(ptr, p);
1449 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1450 {
1451 p += (*mb_ptr2len)(p);
1452 break;
1453 }
1454 ++clen;
1455 }
1456 scol = (int)(p - ptr);
1457 }
1458 else
1459 {
1460 if (!vim_iswordc(ptr[col - 1]))
1461 vim_abbr = TRUE; // Vim added abbr.
1462 else
1463 {
1464 vim_abbr = FALSE; // vi compatible abbr.
1465 if (col > 1)
1466 is_id = vim_iswordc(ptr[col - 2]);
1467 }
1468 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1469 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1470 ;
1471 }
1472
1473 if (scol < mincol)
1474 scol = mincol;
1475 if (scol < col) // there is a word in front of the cursor
1476 {
1477 ptr += scol;
1478 len = col - scol;
1479 mp = curbuf->b_first_abbr;
1480 mp2 = first_abbr;
1481 if (mp == NULL)
1482 {
1483 mp = mp2;
1484 mp2 = NULL;
1485 }
1486 for ( ; mp; mp->m_next == NULL
1487 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1488 {
1489 int qlen = mp->m_keylen;
1490 char_u *q = mp->m_keys;
1491 int match;
1492
1493 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1494 {
1495 char_u *qe = vim_strsave(mp->m_keys);
1496
1497 // might have CSI escaped mp->m_keys
1498 if (qe != NULL)
1499 {
1500 q = qe;
1501 vim_unescape_csi(q);
1502 qlen = (int)STRLEN(q);
1503 }
1504 }
1505
1506 // find entries with right mode and keys
1507 match = (mp->m_mode & State)
1508 && qlen == len
1509 && !STRNCMP(q, ptr, (size_t)len);
1510 if (q != mp->m_keys)
1511 vim_free(q);
1512 if (match)
1513 break;
1514 }
1515 if (mp != NULL)
1516 {
1517 // Found a match:
1518 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1519 // This goes from end to start.
1520 //
1521 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1522 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1523 // Characters where IS_SPECIAL() == TRUE: key codes, need
1524 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1525 //
1526 // Character CTRL-] is treated specially - it completes the
1527 // abbreviation, but is not inserted into the input stream.
1528 j = 0;
1529 if (c != Ctrl_RSB)
1530 {
1531 // special key code, split up
1532 if (IS_SPECIAL(c) || c == K_SPECIAL)
1533 {
1534 tb[j++] = K_SPECIAL;
1535 tb[j++] = K_SECOND(c);
1536 tb[j++] = K_THIRD(c);
1537 }
1538 else
1539 {
1540 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1541 tb[j++] = Ctrl_V; // special char needs CTRL-V
1542 if (has_mbyte)
1543 {
1544 // if ABBR_OFF has been added, remove it here
1545 if (c >= ABBR_OFF)
1546 c -= ABBR_OFF;
1547 j += (*mb_char2bytes)(c, tb + j);
1548 }
1549 else
1550 tb[j++] = c;
1551 }
1552 tb[j] = NUL;
1553 // insert the last typed char
1554 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1555 }
1556#ifdef FEAT_EVAL
1557 if (mp->m_expr)
1558 s = eval_map_expr(mp->m_str, c);
1559 else
1560#endif
1561 s = mp->m_str;
1562 if (s != NULL)
1563 {
1564 // insert the to string
1565 (void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
1566 // no abbrev. for these chars
1567 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1568#ifdef FEAT_EVAL
1569 if (mp->m_expr)
1570 vim_free(s);
1571#endif
1572 }
1573
1574 tb[0] = Ctrl_H;
1575 tb[1] = NUL;
1576 if (has_mbyte)
1577 len = clen; // Delete characters instead of bytes
1578 while (len-- > 0) // delete the from string
1579 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1580 return TRUE;
1581 }
1582 }
1583 return FALSE;
1584}
1585
1586#ifdef FEAT_EVAL
1587/*
1588 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1589 * special characters.
1590 */
1591 char_u *
1592eval_map_expr(
1593 char_u *str,
1594 int c) // NUL or typed character for abbreviation
1595{
1596 char_u *res;
1597 char_u *p;
1598 char_u *expr;
1599 pos_T save_cursor;
1600 int save_msg_col;
1601 int save_msg_row;
1602
1603 // Remove escaping of CSI, because "str" is in a format to be used as
1604 // typeahead.
1605 expr = vim_strsave(str);
1606 if (expr == NULL)
1607 return NULL;
1608 vim_unescape_csi(expr);
1609
1610 // Forbid changing text or using ":normal" to avoid most of the bad side
1611 // effects. Also restore the cursor position.
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001612 ++textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001613 ++ex_normal_lock;
1614 set_vim_var_char(c); // set v:char to the typed character
1615 save_cursor = curwin->w_cursor;
1616 save_msg_col = msg_col;
1617 save_msg_row = msg_row;
1618 p = eval_to_string(expr, NULL, FALSE);
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001619 --textwinlock;
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001620 --ex_normal_lock;
1621 curwin->w_cursor = save_cursor;
1622 msg_col = save_msg_col;
1623 msg_row = save_msg_row;
1624
1625 vim_free(expr);
1626
1627 if (p == NULL)
1628 return NULL;
1629 // Escape CSI in the result to be able to use the string as typeahead.
1630 res = vim_strsave_escape_csi(p);
1631 vim_free(p);
1632
1633 return res;
1634}
1635#endif
1636
1637/*
1638 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1639 * can be put in the typeahead buffer.
1640 * Returns NULL when out of memory.
1641 */
1642 char_u *
1643vim_strsave_escape_csi(
1644 char_u *p)
1645{
1646 char_u *res;
1647 char_u *s, *d;
1648
1649 // Need a buffer to hold up to three times as much. Four in case of an
1650 // illegal utf-8 byte:
1651 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1652 res = alloc(STRLEN(p) * 4 + 1);
1653 if (res != NULL)
1654 {
1655 d = res;
1656 for (s = p; *s != NUL; )
1657 {
1658 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1659 {
1660 // Copy special key unmodified.
1661 *d++ = *s++;
1662 *d++ = *s++;
1663 *d++ = *s++;
1664 }
1665 else
1666 {
1667 // Add character, possibly multi-byte to destination, escaping
1668 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1669 d = add_char2buf(PTR2CHAR(s), d);
1670 s += MB_CPTR2LEN(s);
1671 }
1672 }
1673 *d = NUL;
1674 }
1675 return res;
1676}
1677
1678/*
1679 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1680 * vim_strsave_escape_csi(). Works in-place.
1681 */
1682 void
1683vim_unescape_csi(char_u *p)
1684{
1685 char_u *s = p, *d = p;
1686
1687 while (*s != NUL)
1688 {
1689 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1690 {
1691 *d++ = K_SPECIAL;
1692 s += 3;
1693 }
1694 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1695 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1696 {
1697 *d++ = CSI;
1698 s += 3;
1699 }
1700 else
1701 *d++ = *s++;
1702 }
1703 *d = NUL;
1704}
1705
1706/*
1707 * Write map commands for the current mappings to an .exrc file.
1708 * Return FAIL on error, OK otherwise.
1709 */
1710 int
1711makemap(
1712 FILE *fd,
1713 buf_T *buf) // buffer for local mappings or NULL
1714{
1715 mapblock_T *mp;
1716 char_u c1, c2, c3;
1717 char_u *p;
1718 char *cmd;
1719 int abbr;
1720 int hash;
1721 int did_cpo = FALSE;
1722 int i;
1723
1724 validate_maphash();
1725
1726 // Do the loop twice: Once for mappings, once for abbreviations.
1727 // Then loop over all map hash lists.
1728 for (abbr = 0; abbr < 2; ++abbr)
1729 for (hash = 0; hash < 256; ++hash)
1730 {
1731 if (abbr)
1732 {
1733 if (hash > 0) // there is only one abbr list
1734 break;
1735 if (buf != NULL)
1736 mp = buf->b_first_abbr;
1737 else
1738 mp = first_abbr;
1739 }
1740 else
1741 {
1742 if (buf != NULL)
1743 mp = buf->b_maphash[hash];
1744 else
1745 mp = maphash[hash];
1746 }
1747
1748 for ( ; mp; mp = mp->m_next)
1749 {
1750 // skip script-local mappings
1751 if (mp->m_noremap == REMAP_SCRIPT)
1752 continue;
1753
1754 // skip mappings that contain a <SNR> (script-local thing),
1755 // they probably don't work when loaded again
1756 for (p = mp->m_str; *p != NUL; ++p)
1757 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1758 && p[2] == (int)KE_SNR)
1759 break;
1760 if (*p != NUL)
1761 continue;
1762
1763 // It's possible to create a mapping and then ":unmap" certain
1764 // modes. We recreate this here by mapping the individual
1765 // modes, which requires up to three of them.
1766 c1 = NUL;
1767 c2 = NUL;
1768 c3 = NUL;
1769 if (abbr)
1770 cmd = "abbr";
1771 else
1772 cmd = "map";
1773 switch (mp->m_mode)
1774 {
1775 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1776 break;
1777 case NORMAL:
1778 c1 = 'n';
1779 break;
1780 case VISUAL:
1781 c1 = 'x';
1782 break;
1783 case SELECTMODE:
1784 c1 = 's';
1785 break;
1786 case OP_PENDING:
1787 c1 = 'o';
1788 break;
1789 case NORMAL + VISUAL:
1790 c1 = 'n';
1791 c2 = 'x';
1792 break;
1793 case NORMAL + SELECTMODE:
1794 c1 = 'n';
1795 c2 = 's';
1796 break;
1797 case NORMAL + OP_PENDING:
1798 c1 = 'n';
1799 c2 = 'o';
1800 break;
1801 case VISUAL + SELECTMODE:
1802 c1 = 'v';
1803 break;
1804 case VISUAL + OP_PENDING:
1805 c1 = 'x';
1806 c2 = 'o';
1807 break;
1808 case SELECTMODE + OP_PENDING:
1809 c1 = 's';
1810 c2 = 'o';
1811 break;
1812 case NORMAL + VISUAL + SELECTMODE:
1813 c1 = 'n';
1814 c2 = 'v';
1815 break;
1816 case NORMAL + VISUAL + OP_PENDING:
1817 c1 = 'n';
1818 c2 = 'x';
1819 c3 = 'o';
1820 break;
1821 case NORMAL + SELECTMODE + OP_PENDING:
1822 c1 = 'n';
1823 c2 = 's';
1824 c3 = 'o';
1825 break;
1826 case VISUAL + SELECTMODE + OP_PENDING:
1827 c1 = 'v';
1828 c2 = 'o';
1829 break;
1830 case CMDLINE + INSERT:
1831 if (!abbr)
1832 cmd = "map!";
1833 break;
1834 case CMDLINE:
1835 c1 = 'c';
1836 break;
1837 case INSERT:
1838 c1 = 'i';
1839 break;
1840 case LANGMAP:
1841 c1 = 'l';
1842 break;
1843 case TERMINAL:
1844 c1 = 't';
1845 break;
1846 default:
1847 iemsg(_("E228: makemap: Illegal mode"));
1848 return FAIL;
1849 }
1850 do // do this twice if c2 is set, 3 times with c3
1851 {
1852 // When outputting <> form, need to make sure that 'cpo'
1853 // is set to the Vim default.
1854 if (!did_cpo)
1855 {
1856 if (*mp->m_str == NUL) // will use <Nop>
1857 did_cpo = TRUE;
1858 else
1859 for (i = 0; i < 2; ++i)
1860 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1861 if (*p == K_SPECIAL || *p == NL)
1862 did_cpo = TRUE;
1863 if (did_cpo)
1864 {
1865 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1866 || put_eol(fd) < 0
1867 || fprintf(fd, "set cpo&vim") < 0
1868 || put_eol(fd) < 0)
1869 return FAIL;
1870 }
1871 }
1872 if (c1 && putc(c1, fd) < 0)
1873 return FAIL;
1874 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1875 return FAIL;
1876 if (fputs(cmd, fd) < 0)
1877 return FAIL;
1878 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1879 return FAIL;
1880 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1881 return FAIL;
1882 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1883 return FAIL;
1884#ifdef FEAT_EVAL
1885 if (mp->m_noremap == REMAP_SCRIPT
1886 && fputs("<script>", fd) < 0)
1887 return FAIL;
1888 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1889 return FAIL;
1890#endif
1891
1892 if ( putc(' ', fd) < 0
1893 || put_escstr(fd, mp->m_keys, 0) == FAIL
1894 || putc(' ', fd) < 0
1895 || put_escstr(fd, mp->m_str, 1) == FAIL
1896 || put_eol(fd) < 0)
1897 return FAIL;
1898 c1 = c2;
1899 c2 = c3;
1900 c3 = NUL;
1901 } while (c1 != NUL);
1902 }
1903 }
1904
1905 if (did_cpo)
1906 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
1907 || put_eol(fd) < 0
1908 || fprintf(fd, "unlet s:cpo_save") < 0
1909 || put_eol(fd) < 0)
1910 return FAIL;
1911 return OK;
1912}
1913
1914/*
1915 * write escape string to file
1916 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
1917 *
1918 * return FAIL for failure, OK otherwise
1919 */
1920 int
1921put_escstr(FILE *fd, char_u *strstart, int what)
1922{
1923 char_u *str = strstart;
1924 int c;
1925 int modifiers;
1926
1927 // :map xx <Nop>
1928 if (*str == NUL && what == 1)
1929 {
1930 if (fprintf(fd, "<Nop>") < 0)
1931 return FAIL;
1932 return OK;
1933 }
1934
1935 for ( ; *str != NUL; ++str)
1936 {
1937 char_u *p;
1938
1939 // Check for a multi-byte character, which may contain escaped
1940 // K_SPECIAL and CSI bytes
1941 p = mb_unescape(&str);
1942 if (p != NULL)
1943 {
1944 while (*p != NUL)
1945 if (fputc(*p++, fd) < 0)
1946 return FAIL;
1947 --str;
1948 continue;
1949 }
1950
1951 c = *str;
1952 // Special key codes have to be translated to be able to make sense
1953 // when they are read back.
1954 if (c == K_SPECIAL && what != 2)
1955 {
1956 modifiers = 0x0;
1957 if (str[1] == KS_MODIFIER)
1958 {
1959 modifiers = str[2];
1960 str += 3;
1961 c = *str;
1962 }
1963 if (c == K_SPECIAL)
1964 {
1965 c = TO_SPECIAL(str[1], str[2]);
1966 str += 2;
1967 }
1968 if (IS_SPECIAL(c) || modifiers) // special key
1969 {
1970 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
1971 return FAIL;
1972 continue;
1973 }
1974 }
1975
1976 // A '\n' in a map command should be written as <NL>.
1977 // A '\n' in a set command should be written as \^V^J.
1978 if (c == NL)
1979 {
1980 if (what == 2)
1981 {
1982 if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
1983 return FAIL;
1984 }
1985 else
1986 {
1987 if (fprintf(fd, "<NL>") < 0)
1988 return FAIL;
1989 }
1990 continue;
1991 }
1992
1993 // Some characters have to be escaped with CTRL-V to
1994 // prevent them from misinterpreted in DoOneCmd().
1995 // A space, Tab and '"' has to be escaped with a backslash to
1996 // prevent it to be misinterpreted in do_set().
1997 // A space has to be escaped with a CTRL-V when it's at the start of a
1998 // ":map" rhs.
1999 // A '<' has to be escaped with a CTRL-V to prevent it being
2000 // interpreted as the start of a special key name.
2001 // A space in the lhs of a :map needs a CTRL-V.
2002 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2003 {
2004 if (putc('\\', fd) < 0)
2005 return FAIL;
2006 }
2007 else if (c < ' ' || c > '~' || c == '|'
2008 || (what == 0 && c == ' ')
2009 || (what == 1 && str == strstart && c == ' ')
2010 || (what != 2 && c == '<'))
2011 {
2012 if (putc(Ctrl_V, fd) < 0)
2013 return FAIL;
2014 }
2015 if (putc(c, fd) < 0)
2016 return FAIL;
2017 }
2018 return OK;
2019}
2020
2021/*
2022 * Check all mappings for the presence of special key codes.
2023 * Used after ":set term=xxx".
2024 */
2025 void
2026check_map_keycodes(void)
2027{
2028 mapblock_T *mp;
2029 char_u *p;
2030 int i;
2031 char_u buf[3];
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002032 int abbr;
2033 int hash;
2034 buf_T *bp;
Bram Moolenaare31ee862020-01-07 20:59:34 +01002035 ESTACK_CHECK_DECLARATION
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002036
2037 validate_maphash();
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002038 // avoids giving error messages
2039 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
Bram Moolenaare31ee862020-01-07 20:59:34 +01002040 ESTACK_CHECK_SETUP
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002041
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002042 // Do this once for each buffer, and then once for global
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002043 // mappings/abbreviations with bp == NULL
2044 for (bp = firstbuf; ; bp = bp->b_next)
2045 {
2046 // Do the loop twice: Once for mappings, once for abbreviations.
2047 // Then loop over all map hash lists.
2048 for (abbr = 0; abbr <= 1; ++abbr)
2049 for (hash = 0; hash < 256; ++hash)
2050 {
2051 if (abbr)
2052 {
2053 if (hash) // there is only one abbr list
2054 break;
2055 if (bp != NULL)
2056 mp = bp->b_first_abbr;
2057 else
2058 mp = first_abbr;
2059 }
2060 else
2061 {
2062 if (bp != NULL)
2063 mp = bp->b_maphash[hash];
2064 else
2065 mp = maphash[hash];
2066 }
2067 for ( ; mp != NULL; mp = mp->m_next)
2068 {
2069 for (i = 0; i <= 1; ++i) // do this twice
2070 {
2071 if (i == 0)
2072 p = mp->m_keys; // once for the "from" part
2073 else
2074 p = mp->m_str; // and once for the "to" part
2075 while (*p)
2076 {
2077 if (*p == K_SPECIAL)
2078 {
2079 ++p;
2080 if (*p < 128) // for "normal" tcap entries
2081 {
2082 buf[0] = p[0];
2083 buf[1] = p[1];
2084 buf[2] = NUL;
2085 (void)add_termcap_entry(buf, FALSE);
2086 }
2087 ++p;
2088 }
2089 ++p;
2090 }
2091 }
2092 }
2093 }
2094 if (bp == NULL)
2095 break;
2096 }
Bram Moolenaare31ee862020-01-07 20:59:34 +01002097 ESTACK_CHECK_NOW
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002098 estack_pop();
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002099}
2100
2101#if defined(FEAT_EVAL) || defined(PROTO)
2102/*
2103 * Check the string "keys" against the lhs of all mappings.
2104 * Return pointer to rhs of mapping (mapblock->m_str).
2105 * NULL when no mapping found.
2106 */
2107 char_u *
2108check_map(
2109 char_u *keys,
2110 int mode,
2111 int exact, // require exact match
2112 int ign_mod, // ignore preceding modifier
2113 int abbr, // do abbreviations
2114 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2115 int *local_ptr) // return: buffer-local mapping or NULL
2116{
2117 int hash;
2118 int len, minlen;
2119 mapblock_T *mp;
2120 char_u *s;
2121 int local;
2122
2123 validate_maphash();
2124
2125 len = (int)STRLEN(keys);
2126 for (local = 1; local >= 0; --local)
2127 // loop over all hash lists
2128 for (hash = 0; hash < 256; ++hash)
2129 {
2130 if (abbr)
2131 {
2132 if (hash > 0) // there is only one list.
2133 break;
2134 if (local)
2135 mp = curbuf->b_first_abbr;
2136 else
2137 mp = first_abbr;
2138 }
2139 else if (local)
2140 mp = curbuf->b_maphash[hash];
2141 else
2142 mp = maphash[hash];
2143 for ( ; mp != NULL; mp = mp->m_next)
2144 {
2145 // skip entries with wrong mode, wrong length and not matching
2146 // ones
2147 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2148 {
2149 if (len > mp->m_keylen)
2150 minlen = mp->m_keylen;
2151 else
2152 minlen = len;
2153 s = mp->m_keys;
2154 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2155 && s[2] != NUL)
2156 {
2157 s += 3;
2158 if (len > mp->m_keylen - 3)
2159 minlen = mp->m_keylen - 3;
2160 }
2161 if (STRNCMP(s, keys, minlen) == 0)
2162 {
2163 if (mp_ptr != NULL)
2164 *mp_ptr = mp;
2165 if (local_ptr != NULL)
2166 *local_ptr = local;
2167 return mp->m_str;
2168 }
2169 }
2170 }
2171 }
2172
2173 return NULL;
2174}
2175
2176 void
2177get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2178{
2179 char_u *keys;
2180 char_u *which;
2181 char_u buf[NUMBUFLEN];
2182 char_u *keys_buf = NULL;
2183 char_u *rhs;
2184 int mode;
2185 int abbr = FALSE;
2186 int get_dict = FALSE;
2187 mapblock_T *mp;
2188 int buffer_local;
2189
2190 // return empty string for failure
2191 rettv->v_type = VAR_STRING;
2192 rettv->vval.v_string = NULL;
2193
2194 keys = tv_get_string(&argvars[0]);
2195 if (*keys == NUL)
2196 return;
2197
2198 if (argvars[1].v_type != VAR_UNKNOWN)
2199 {
2200 which = tv_get_string_buf_chk(&argvars[1], buf);
2201 if (argvars[2].v_type != VAR_UNKNOWN)
2202 {
2203 abbr = (int)tv_get_number(&argvars[2]);
2204 if (argvars[3].v_type != VAR_UNKNOWN)
2205 get_dict = (int)tv_get_number(&argvars[3]);
2206 }
2207 }
2208 else
2209 which = (char_u *)"";
2210 if (which == NULL)
2211 return;
2212
2213 mode = get_map_mode(&which, 0);
2214
Bram Moolenaar459fd782019-10-13 16:43:39 +02002215 keys = replace_termcodes(keys, &keys_buf,
2216 REPTERM_FROM_PART | REPTERM_DO_LT, NULL);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002217 rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local);
2218 vim_free(keys_buf);
2219
2220 if (!get_dict)
2221 {
2222 // Return a string.
2223 if (rhs != NULL)
2224 {
2225 if (*rhs == NUL)
2226 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2227 else
2228 rettv->vval.v_string = str2special_save(rhs, FALSE);
2229 }
2230
2231 }
2232 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2233 {
2234 // Return a dictionary.
2235 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2236 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2237 dict_T *dict = rettv->vval.v_dict;
2238
2239 dict_add_string(dict, "lhs", lhs);
2240 dict_add_string(dict, "rhs", mp->m_orig_str);
2241 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
Bram Moolenaar2da0f0c2020-04-01 19:22:12 +02002242 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2243 ? 1L : 0L);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002244 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2245 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2246 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
2247 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2248 dict_add_number(dict, "buffer", (long)buffer_local);
2249 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2250 dict_add_string(dict, "mode", mapmode);
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002251 dict_add_number(dict, "simplified", mp->m_simplified);
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002252
2253 vim_free(lhs);
2254 vim_free(mapmode);
2255 }
2256}
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002257
2258/*
2259 * "mapset()" function
2260 */
2261 void
2262f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2263{
2264 char_u *keys;
2265 char_u *keys_buf = NULL;
2266 char_u *which;
2267 int mode;
2268 char_u buf[NUMBUFLEN];
2269 int is_abbr;
2270 dict_T *d;
2271 char_u *lhs;
2272 char_u *rhs;
2273 int noremap;
2274 int expr;
2275 int silent;
2276 scid_T sid;
2277 linenr_T lnum;
2278 mapblock_T **map_table = maphash;
2279 mapblock_T **abbr_table = &first_abbr;
2280 int nowait;
2281 int simplified;
2282 char_u *arg;
2283
2284 which = tv_get_string_buf_chk(&argvars[0], buf);
2285 mode = get_map_mode(&which, 0);
2286 is_abbr = (int)tv_get_number(&argvars[1]);
2287
2288 if (argvars[2].v_type != VAR_DICT)
2289 {
2290 emsg(_(e_dictkey));
2291 return;
2292 }
2293 d = argvars[2].vval.v_dict;
2294
2295 // Get the values in the same order as above in get_maparg().
2296 lhs = dict_get_string(d, (char_u *)"lhs", FALSE);
2297 if (lhs == NULL)
2298 {
2299 emsg(_("E99: lhs entry missing in mapset() dict argument"));
2300 return;
2301 }
2302 rhs = dict_get_string(d, (char_u *)"rhs", FALSE);
2303 if (rhs == NULL)
2304 {
2305 emsg(_("E99: rhs entry missing in mapset() dict argument"));
2306 return;
2307 }
2308
2309 noremap = dict_get_number(d, (char_u *)"noremap") ? REMAP_NONE: 0;
2310 if (dict_get_number(d, (char_u *)"script") != 0)
2311 noremap = REMAP_SCRIPT;
2312 expr = dict_get_number(d, (char_u *)"expr") != 0;
2313 silent = dict_get_number(d, (char_u *)"silent") != 0;
2314 sid = dict_get_number(d, (char_u *)"sid");
2315 lnum = dict_get_number(d, (char_u *)"lnum");
2316 if (dict_get_number(d, (char_u *)"buffer"))
2317 {
2318 map_table = curbuf->b_maphash;
2319 abbr_table = &curbuf->b_first_abbr;
2320 }
2321 nowait = dict_get_number(d, (char_u *)"nowait") != 0;
2322 // mode from the dict is not used
2323 simplified = dict_get_number(d, (char_u *)"simplified") != 0;
2324
2325 // Delete any existing mapping for this lhs and mode.
2326 arg = vim_strsave(lhs);
2327 if (arg == NULL)
2328 return;
2329 do_map(1, arg, mode, is_abbr);
2330 vim_free(arg);
2331
2332 keys = replace_termcodes(lhs, &keys_buf,
2333 REPTERM_FROM_PART | REPTERM_DO_LT, NULL);
2334 (void)map_add(map_table, abbr_table, keys, rhs, rhs, expr,
2335 noremap, nowait, silent, mode, is_abbr, sid, lnum, simplified);
2336 vim_free(keys_buf);
2337}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002338#endif
2339
Bram Moolenaar4c9243f2020-05-22 13:10:44 +02002340
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002341#if defined(MSWIN) || defined(MACOS_X)
2342
2343# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2344
2345/*
2346 * Default mappings for some often used keys.
2347 */
2348struct initmap
2349{
2350 char_u *arg;
2351 int mode;
2352};
2353
2354# ifdef FEAT_GUI_MSWIN
2355// Use the Windows (CUA) keybindings. (GUI)
2356static struct initmap initmappings[] =
2357{
2358 // paste, copy and cut
2359 {(char_u *)"<S-Insert> \"*P", NORMAL},
2360 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2361 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2362 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2363 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2364 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2365 {(char_u *)"<C-X> \"*d", VIS_SEL},
2366 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2367};
2368# endif
2369
2370# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2371// Use the Windows (CUA) keybindings. (Console)
2372static struct initmap cinitmappings[] =
2373{
2374 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2375 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2376 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2377 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2378
2379 // paste, copy and cut
2380# ifdef FEAT_CLIPBOARD
2381 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2382 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2383 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2384 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2385 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2386 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2387 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2388# else
2389 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2390 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2391 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2392 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2393 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2394 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2395# endif
2396};
2397# endif
2398
2399# if defined(MACOS_X)
2400static struct initmap initmappings[] =
2401{
2402 // Use the Standard MacOS binding.
2403 // paste, copy and cut
2404 {(char_u *)"<D-v> \"*P", NORMAL},
2405 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2406 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2407 {(char_u *)"<D-c> \"*y", VIS_SEL},
2408 {(char_u *)"<D-x> \"*d", VIS_SEL},
2409 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2410};
2411# endif
2412
2413# undef VIS_SEL
2414#endif
2415
2416/*
2417 * Set up default mappings.
2418 */
2419 void
2420init_mappings(void)
2421{
2422#if defined(MSWIN) || defined(MACOS_X)
2423 int i;
2424
2425# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2426# ifdef VIMDLL
2427 if (!gui.starting)
2428# endif
2429 {
2430 for (i = 0;
2431 i < (int)(sizeof(cinitmappings) / sizeof(struct initmap)); ++i)
2432 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2433 }
2434# endif
2435# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
2436 for (i = 0; i < (int)(sizeof(initmappings) / sizeof(struct initmap)); ++i)
2437 add_map(initmappings[i].arg, initmappings[i].mode);
2438# endif
2439#endif
2440}
2441
2442#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2443 || defined(PROTO)
2444/*
2445 * Add a mapping "map" for mode "mode".
2446 * Need to put string in allocated memory, because do_map() will modify it.
2447 */
2448 void
2449add_map(char_u *map, int mode)
2450{
2451 char_u *s;
2452 char_u *cpo_save = p_cpo;
2453
2454 p_cpo = (char_u *)""; // Allow <> notation
2455 s = vim_strsave(map);
2456 if (s != NULL)
2457 {
2458 (void)do_map(0, s, mode, FALSE);
2459 vim_free(s);
2460 }
2461 p_cpo = cpo_save;
2462}
2463#endif
2464
Bram Moolenaare677df82019-09-02 22:31:11 +02002465#if defined(FEAT_LANGMAP) || defined(PROTO)
2466/*
2467 * Any character has an equivalent 'langmap' character. This is used for
2468 * keyboards that have a special language mode that sends characters above
2469 * 128 (although other characters can be translated too). The "to" field is a
2470 * Vim command character. This avoids having to switch the keyboard back to
2471 * ASCII mode when leaving Insert mode.
2472 *
2473 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2474 * commands.
2475 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2476 * same as langmap_mapchar[] for characters >= 256.
2477 *
2478 * Use growarray for 'langmap' chars >= 256
2479 */
2480typedef struct
2481{
2482 int from;
2483 int to;
2484} langmap_entry_T;
2485
2486static garray_T langmap_mapga;
2487
2488/*
2489 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2490 * field. If not found insert a new entry at the appropriate location.
2491 */
2492 static void
2493langmap_set_entry(int from, int to)
2494{
2495 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2496 int a = 0;
2497 int b = langmap_mapga.ga_len;
2498
2499 // Do a binary search for an existing entry.
2500 while (a != b)
2501 {
2502 int i = (a + b) / 2;
2503 int d = entries[i].from - from;
2504
2505 if (d == 0)
2506 {
2507 entries[i].to = to;
2508 return;
2509 }
2510 if (d < 0)
2511 a = i + 1;
2512 else
2513 b = i;
2514 }
2515
2516 if (ga_grow(&langmap_mapga, 1) != OK)
2517 return; // out of memory
2518
2519 // insert new entry at position "a"
2520 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2521 mch_memmove(entries + 1, entries,
2522 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2523 ++langmap_mapga.ga_len;
2524 entries[0].from = from;
2525 entries[0].to = to;
2526}
2527
2528/*
2529 * Apply 'langmap' to multi-byte character "c" and return the result.
2530 */
2531 int
2532langmap_adjust_mb(int c)
2533{
2534 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2535 int a = 0;
2536 int b = langmap_mapga.ga_len;
2537
2538 while (a != b)
2539 {
2540 int i = (a + b) / 2;
2541 int d = entries[i].from - c;
2542
2543 if (d == 0)
2544 return entries[i].to; // found matching entry
2545 if (d < 0)
2546 a = i + 1;
2547 else
2548 b = i;
2549 }
2550 return c; // no entry found, return "c" unmodified
2551}
2552
2553 void
2554langmap_init(void)
2555{
2556 int i;
2557
2558 for (i = 0; i < 256; i++)
2559 langmap_mapchar[i] = i; // we init with a one-to-one map
2560 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
2561}
2562
2563/*
2564 * Called when langmap option is set; the language map can be
2565 * changed at any time!
2566 */
2567 void
2568langmap_set(void)
2569{
2570 char_u *p;
2571 char_u *p2;
2572 int from, to;
2573
2574 ga_clear(&langmap_mapga); // clear the previous map first
2575 langmap_init(); // back to one-to-one map
2576
2577 for (p = p_langmap; p[0] != NUL; )
2578 {
2579 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
2580 MB_PTR_ADV(p2))
2581 {
2582 if (p2[0] == '\\' && p2[1] != NUL)
2583 ++p2;
2584 }
2585 if (p2[0] == ';')
2586 ++p2; // abcd;ABCD form, p2 points to A
2587 else
2588 p2 = NULL; // aAbBcCdD form, p2 is NULL
2589 while (p[0])
2590 {
2591 if (p[0] == ',')
2592 {
2593 ++p;
2594 break;
2595 }
2596 if (p[0] == '\\' && p[1] != NUL)
2597 ++p;
2598 from = (*mb_ptr2char)(p);
2599 to = NUL;
2600 if (p2 == NULL)
2601 {
2602 MB_PTR_ADV(p);
2603 if (p[0] != ',')
2604 {
2605 if (p[0] == '\\')
2606 ++p;
2607 to = (*mb_ptr2char)(p);
2608 }
2609 }
2610 else
2611 {
2612 if (p2[0] != ',')
2613 {
2614 if (p2[0] == '\\')
2615 ++p2;
2616 to = (*mb_ptr2char)(p2);
2617 }
2618 }
2619 if (to == NUL)
2620 {
2621 semsg(_("E357: 'langmap': Matching character missing for %s"),
2622 transchar(from));
2623 return;
2624 }
2625
2626 if (from >= 256)
2627 langmap_set_entry(from, to);
2628 else
2629 langmap_mapchar[from & 255] = to;
2630
2631 // Advance to next pair
2632 MB_PTR_ADV(p);
2633 if (p2 != NULL)
2634 {
2635 MB_PTR_ADV(p2);
2636 if (*p == ';')
2637 {
2638 p = p2;
2639 if (p[0] != NUL)
2640 {
2641 if (p[0] != ',')
2642 {
2643 semsg(_("E358: 'langmap': Extra characters after semicolon: %s"), p);
2644 return;
2645 }
2646 ++p;
2647 }
2648 break;
2649 }
2650 }
2651 }
2652 }
2653}
2654#endif
2655
Bram Moolenaarb66bab32019-08-01 14:28:24 +02002656 static void
2657do_exmap(exarg_T *eap, int isabbrev)
2658{
2659 int mode;
2660 char_u *cmdp;
2661
2662 cmdp = eap->cmd;
2663 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2664
2665 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2666 eap->arg, mode, isabbrev))
2667 {
2668 case 1: emsg(_(e_invarg));
2669 break;
2670 case 2: emsg((isabbrev ? _(e_noabbr) : _(e_nomap)));
2671 break;
2672 }
2673}
2674
2675/*
2676 * ":abbreviate" and friends.
2677 */
2678 void
2679ex_abbreviate(exarg_T *eap)
2680{
2681 do_exmap(eap, TRUE); // almost the same as mapping
2682}
2683
2684/*
2685 * ":map" and friends.
2686 */
2687 void
2688ex_map(exarg_T *eap)
2689{
2690 // If we are sourcing .exrc or .vimrc in current directory we
2691 // print the mappings for security reasons.
2692 if (secure)
2693 {
2694 secure = 2;
2695 msg_outtrans(eap->cmd);
2696 msg_putchar('\n');
2697 }
2698 do_exmap(eap, FALSE);
2699}
2700
2701/*
2702 * ":unmap" and friends.
2703 */
2704 void
2705ex_unmap(exarg_T *eap)
2706{
2707 do_exmap(eap, FALSE);
2708}
2709
2710/*
2711 * ":mapclear" and friends.
2712 */
2713 void
2714ex_mapclear(exarg_T *eap)
2715{
2716 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2717}
2718
2719/*
2720 * ":abclear" and friends.
2721 */
2722 void
2723ex_abclear(exarg_T *eap)
2724{
2725 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2726}