blob: 0257cb7041a035611f5f7777db442956e43824d6 [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 {
68 vim_memset(maphash, 0, sizeof(maphash));
69 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
207/*
208 * map[!] : show all key mappings
209 * map[!] {lhs} : show key mapping for {lhs}
210 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
211 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
212 * unmap[!] {lhs} : remove key mapping for {lhs}
213 * abbr : show all abbreviations
214 * abbr {lhs} : show abbreviations for {lhs}
215 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
216 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
217 * unabbr {lhs} : remove abbreviation for {lhs}
218 *
219 * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
220 *
221 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
222 * it will be modified.
223 *
224 * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
225 * for :map! mode is INSERT + CMDLINE
226 * for :cmap mode is CMDLINE
227 * for :imap mode is INSERT
228 * for :lmap mode is LANGMAP
229 * for :nmap mode is NORMAL
230 * for :vmap mode is VISUAL + SELECTMODE
231 * for :xmap mode is VISUAL
232 * for :smap mode is SELECTMODE
233 * for :omap mode is OP_PENDING
234 * for :tmap mode is TERMINAL
235 *
236 * for :abbr mode is INSERT + CMDLINE
237 * for :iabbr mode is INSERT
238 * for :cabbr mode is CMDLINE
239 *
240 * Return 0 for success
241 * 1 for invalid arguments
242 * 2 for no match
243 * 4 for out of mem
244 * 5 for entry not unique
245 */
246 int
247do_map(
248 int maptype,
249 char_u *arg,
250 int mode,
251 int abbrev) // not a mapping but an abbreviation
252{
253 char_u *keys;
254 mapblock_T *mp, **mpp;
255 char_u *rhs;
256 char_u *p;
257 int n;
258 int len = 0; // init for GCC
259 char_u *newstr;
260 int hasarg;
261 int haskey;
262 int did_it = FALSE;
263 int did_local = FALSE;
264 int round;
265 char_u *keys_buf = NULL;
266 char_u *arg_buf = NULL;
267 int retval = 0;
268 int do_backslash;
269 int hash;
270 int new_hash;
271 mapblock_T **abbr_table;
272 mapblock_T **map_table;
273 int unique = FALSE;
274 int nowait = FALSE;
275 int silent = FALSE;
276 int special = FALSE;
277#ifdef FEAT_EVAL
278 int expr = FALSE;
279#endif
280 int noremap;
281 char_u *orig_rhs;
282
283 keys = arg;
284 map_table = maphash;
285 abbr_table = &first_abbr;
286
287 // For ":noremap" don't remap, otherwise do remap.
288 if (maptype == 2)
289 noremap = REMAP_NONE;
290 else
291 noremap = REMAP_YES;
292
293 // Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
294 // any order.
295 for (;;)
296 {
297 // Check for "<buffer>": mapping local to buffer.
298 if (STRNCMP(keys, "<buffer>", 8) == 0)
299 {
300 keys = skipwhite(keys + 8);
301 map_table = curbuf->b_maphash;
302 abbr_table = &curbuf->b_first_abbr;
303 continue;
304 }
305
306 // Check for "<nowait>": don't wait for more characters.
307 if (STRNCMP(keys, "<nowait>", 8) == 0)
308 {
309 keys = skipwhite(keys + 8);
310 nowait = TRUE;
311 continue;
312 }
313
314 // Check for "<silent>": don't echo commands.
315 if (STRNCMP(keys, "<silent>", 8) == 0)
316 {
317 keys = skipwhite(keys + 8);
318 silent = TRUE;
319 continue;
320 }
321
322 // Check for "<special>": accept special keys in <>
323 if (STRNCMP(keys, "<special>", 9) == 0)
324 {
325 keys = skipwhite(keys + 9);
326 special = TRUE;
327 continue;
328 }
329
330#ifdef FEAT_EVAL
331 // Check for "<script>": remap script-local mappings only
332 if (STRNCMP(keys, "<script>", 8) == 0)
333 {
334 keys = skipwhite(keys + 8);
335 noremap = REMAP_SCRIPT;
336 continue;
337 }
338
339 // Check for "<expr>": {rhs} is an expression.
340 if (STRNCMP(keys, "<expr>", 6) == 0)
341 {
342 keys = skipwhite(keys + 6);
343 expr = TRUE;
344 continue;
345 }
346#endif
347 // Check for "<unique>": don't overwrite an existing mapping.
348 if (STRNCMP(keys, "<unique>", 8) == 0)
349 {
350 keys = skipwhite(keys + 8);
351 unique = TRUE;
352 continue;
353 }
354 break;
355 }
356
357 validate_maphash();
358
359 // Find end of keys and skip CTRL-Vs (and backslashes) in it.
360 // Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
361 // with :unmap white space is included in the keys, no argument possible.
362 p = keys;
363 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
364 while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
365 {
366 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
367 p[1] != NUL)
368 ++p; // skip CTRL-V or backslash
369 ++p;
370 }
371 if (*p != NUL)
372 *p++ = NUL;
373
374 p = skipwhite(p);
375 rhs = p;
376 hasarg = (*rhs != NUL);
377 haskey = (*keys != NUL);
378
379 // check for :unmap without argument
380 if (maptype == 1 && !haskey)
381 {
382 retval = 1;
383 goto theend;
384 }
385
386 // If mapping has been given as ^V<C_UP> say, then replace the term codes
387 // with the appropriate two bytes. If it is a shifted special key, unshift
388 // it too, giving another two bytes.
389 // replace_termcodes() may move the result to allocated memory, which
390 // needs to be freed later (*keys_buf and *arg_buf).
391 // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
392 if (haskey)
393 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special);
394 orig_rhs = rhs;
395 if (hasarg)
396 {
397 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
398 rhs = (char_u *)"";
399 else
400 rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special);
401 }
402
403 // check arguments and translate function keys
404 if (haskey)
405 {
406 len = (int)STRLEN(keys);
407 if (len > MAXMAPLEN) // maximum length of MAXMAPLEN chars
408 {
409 retval = 1;
410 goto theend;
411 }
412
413 if (abbrev && maptype != 1)
414 {
415 // If an abbreviation ends in a keyword character, the
416 // rest must be all keyword-char or all non-keyword-char.
417 // Otherwise we won't be able to find the start of it in a
418 // vi-compatible way.
419 if (has_mbyte)
420 {
421 int first, last;
422 int same = -1;
423
424 first = vim_iswordp(keys);
425 last = first;
426 p = keys + (*mb_ptr2len)(keys);
427 n = 1;
428 while (p < keys + len)
429 {
430 ++n; // nr of (multi-byte) chars
431 last = vim_iswordp(p); // type of last char
432 if (same == -1 && last != first)
433 same = n - 1; // count of same char type
434 p += (*mb_ptr2len)(p);
435 }
436 if (last && n > 2 && same >= 0 && same < n - 1)
437 {
438 retval = 1;
439 goto theend;
440 }
441 }
442 else if (vim_iswordc(keys[len - 1])) // ends in keyword char
443 for (n = 0; n < len - 2; ++n)
444 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
445 {
446 retval = 1;
447 goto theend;
448 }
449 // An abbreviation cannot contain white space.
450 for (n = 0; n < len; ++n)
451 if (VIM_ISWHITE(keys[n]))
452 {
453 retval = 1;
454 goto theend;
455 }
456 }
457 }
458
459 if (haskey && hasarg && abbrev) // if we will add an abbreviation
460 no_abbr = FALSE; // reset flag that indicates there are
461 // no abbreviations
462
463 if (!haskey || (maptype != 1 && !hasarg))
464 msg_start();
465
466 // Check if a new local mapping wasn't already defined globally.
467 if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
468 {
469 // need to loop over all global hash lists
470 for (hash = 0; hash < 256 && !got_int; ++hash)
471 {
472 if (abbrev)
473 {
474 if (hash != 0) // there is only one abbreviation list
475 break;
476 mp = first_abbr;
477 }
478 else
479 mp = maphash[hash];
480 for ( ; mp != NULL && !got_int; mp = mp->m_next)
481 {
482 // check entries with the same mode
483 if ((mp->m_mode & mode) != 0
484 && mp->m_keylen == len
485 && unique
486 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
487 {
488 if (abbrev)
489 semsg(_("E224: global abbreviation already exists for %s"),
490 mp->m_keys);
491 else
492 semsg(_("E225: global mapping already exists for %s"),
493 mp->m_keys);
494 retval = 5;
495 goto theend;
496 }
497 }
498 }
499 }
500
501 // When listing global mappings, also list buffer-local ones here.
502 if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
503 {
504 // need to loop over all global hash lists
505 for (hash = 0; hash < 256 && !got_int; ++hash)
506 {
507 if (abbrev)
508 {
509 if (hash != 0) // there is only one abbreviation list
510 break;
511 mp = curbuf->b_first_abbr;
512 }
513 else
514 mp = curbuf->b_maphash[hash];
515 for ( ; mp != NULL && !got_int; mp = mp->m_next)
516 {
517 // check entries with the same mode
518 if ((mp->m_mode & mode) != 0)
519 {
520 if (!haskey) // show all entries
521 {
522 showmap(mp, TRUE);
523 did_local = TRUE;
524 }
525 else
526 {
527 n = mp->m_keylen;
528 if (STRNCMP(mp->m_keys, keys,
529 (size_t)(n < len ? n : len)) == 0)
530 {
531 showmap(mp, TRUE);
532 did_local = TRUE;
533 }
534 }
535 }
536 }
537 }
538 }
539
540 // Find an entry in the maphash[] list that matches.
541 // For :unmap we may loop two times: once to try to unmap an entry with a
542 // matching 'from' part, a second time, if the first fails, to unmap an
543 // entry with a matching 'to' part. This was done to allow ":ab foo bar"
544 // to be unmapped by typing ":unab foo", where "foo" will be replaced by
545 // "bar" because of the abbreviation.
546 for (round = 0; (round == 0 || maptype == 1) && round <= 1
547 && !did_it && !got_int; ++round)
548 {
549 // need to loop over all hash lists
550 for (hash = 0; hash < 256 && !got_int; ++hash)
551 {
552 if (abbrev)
553 {
554 if (hash > 0) // there is only one abbreviation list
555 break;
556 mpp = abbr_table;
557 }
558 else
559 mpp = &(map_table[hash]);
560 for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
561 {
562
563 if (!(mp->m_mode & mode)) // skip entries with wrong mode
564 {
565 mpp = &(mp->m_next);
566 continue;
567 }
568 if (!haskey) // show all entries
569 {
570 showmap(mp, map_table != maphash);
571 did_it = TRUE;
572 }
573 else // do we have a match?
574 {
575 if (round) // second round: Try unmap "rhs" string
576 {
577 n = (int)STRLEN(mp->m_str);
578 p = mp->m_str;
579 }
580 else
581 {
582 n = mp->m_keylen;
583 p = mp->m_keys;
584 }
585 if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
586 {
587 if (maptype == 1) // delete entry
588 {
589 // Only accept a full match. For abbreviations we
590 // ignore trailing space when matching with the
591 // "lhs", since an abbreviation can't have
592 // trailing space.
593 if (n != len && (!abbrev || round || n > len
594 || *skipwhite(keys + n) != NUL))
595 {
596 mpp = &(mp->m_next);
597 continue;
598 }
599 // We reset the indicated mode bits. If nothing is
600 // left the entry is deleted below.
601 mp->m_mode &= ~mode;
602 did_it = TRUE; // remember we did something
603 }
604 else if (!hasarg) // show matching entry
605 {
606 showmap(mp, map_table != maphash);
607 did_it = TRUE;
608 }
609 else if (n != len) // new entry is ambiguous
610 {
611 mpp = &(mp->m_next);
612 continue;
613 }
614 else if (unique)
615 {
616 if (abbrev)
617 semsg(_("E226: abbreviation already exists for %s"),
618 p);
619 else
620 semsg(_("E227: mapping already exists for %s"), p);
621 retval = 5;
622 goto theend;
623 }
624 else // new rhs for existing entry
625 {
626 mp->m_mode &= ~mode; // remove mode bits
627 if (mp->m_mode == 0 && !did_it) // reuse entry
628 {
629 newstr = vim_strsave(rhs);
630 if (newstr == NULL)
631 {
632 retval = 4; // no mem
633 goto theend;
634 }
635 vim_free(mp->m_str);
636 mp->m_str = newstr;
637 vim_free(mp->m_orig_str);
638 mp->m_orig_str = vim_strsave(orig_rhs);
639 mp->m_noremap = noremap;
640 mp->m_nowait = nowait;
641 mp->m_silent = silent;
642 mp->m_mode = mode;
643#ifdef FEAT_EVAL
644 mp->m_expr = expr;
645 mp->m_script_ctx = current_sctx;
646 mp->m_script_ctx.sc_lnum += sourcing_lnum;
647#endif
648 did_it = TRUE;
649 }
650 }
651 if (mp->m_mode == 0) // entry can be deleted
652 {
653 map_free(mpp);
654 continue; // continue with *mpp
655 }
656
657 // May need to put this entry into another hash list.
658 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
659 if (!abbrev && new_hash != hash)
660 {
661 *mpp = mp->m_next;
662 mp->m_next = map_table[new_hash];
663 map_table[new_hash] = mp;
664
665 continue; // continue with *mpp
666 }
667 }
668 }
669 mpp = &(mp->m_next);
670 }
671 }
672 }
673
674 if (maptype == 1) // delete entry
675 {
676 if (!did_it)
677 retval = 2; // no match
678 else if (*keys == Ctrl_C)
679 {
680 // If CTRL-C has been unmapped, reuse it for Interrupting.
681 if (map_table == curbuf->b_maphash)
682 curbuf->b_mapped_ctrl_c &= ~mode;
683 else
684 mapped_ctrl_c &= ~mode;
685 }
686 goto theend;
687 }
688
689 if (!haskey || !hasarg) // print entries
690 {
691 if (!did_it && !did_local)
692 {
693 if (abbrev)
694 msg(_("No abbreviation found"));
695 else
696 msg(_("No mapping found"));
697 }
698 goto theend; // listing finished
699 }
700
701 if (did_it) // have added the new entry already
702 goto theend;
703
704 // Get here when adding a new entry to the maphash[] list or abbrlist.
705 mp = ALLOC_ONE(mapblock_T);
706 if (mp == NULL)
707 {
708 retval = 4; // no mem
709 goto theend;
710 }
711
712 // If CTRL-C has been mapped, don't always use it for Interrupting.
713 if (*keys == Ctrl_C)
714 {
715 if (map_table == curbuf->b_maphash)
716 curbuf->b_mapped_ctrl_c |= mode;
717 else
718 mapped_ctrl_c |= mode;
719 }
720
721 mp->m_keys = vim_strsave(keys);
722 mp->m_str = vim_strsave(rhs);
723 mp->m_orig_str = vim_strsave(orig_rhs);
724 if (mp->m_keys == NULL || mp->m_str == NULL)
725 {
726 vim_free(mp->m_keys);
727 vim_free(mp->m_str);
728 vim_free(mp->m_orig_str);
729 vim_free(mp);
730 retval = 4; // no mem
731 goto theend;
732 }
733 mp->m_keylen = (int)STRLEN(mp->m_keys);
734 mp->m_noremap = noremap;
735 mp->m_nowait = nowait;
736 mp->m_silent = silent;
737 mp->m_mode = mode;
738#ifdef FEAT_EVAL
739 mp->m_expr = expr;
740 mp->m_script_ctx = current_sctx;
741 mp->m_script_ctx.sc_lnum += sourcing_lnum;
742#endif
743
744 // add the new entry in front of the abbrlist or maphash[] list
745 if (abbrev)
746 {
747 mp->m_next = *abbr_table;
748 *abbr_table = mp;
749 }
750 else
751 {
752 n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
753 mp->m_next = map_table[n];
754 map_table[n] = mp;
755 }
756
757theend:
758 vim_free(keys_buf);
759 vim_free(arg_buf);
760 return retval;
761}
762
763/*
764 * Get the mapping mode from the command name.
765 */
766 static int
767get_map_mode(char_u **cmdp, int forceit)
768{
769 char_u *p;
770 int modec;
771 int mode;
772
773 p = *cmdp;
774 modec = *p++;
775 if (modec == 'i')
776 mode = INSERT; // :imap
777 else if (modec == 'l')
778 mode = LANGMAP; // :lmap
779 else if (modec == 'c')
780 mode = CMDLINE; // :cmap
781 else if (modec == 'n' && *p != 'o') // avoid :noremap
782 mode = NORMAL; // :nmap
783 else if (modec == 'v')
784 mode = VISUAL + SELECTMODE; // :vmap
785 else if (modec == 'x')
786 mode = VISUAL; // :xmap
787 else if (modec == 's')
788 mode = SELECTMODE; // :smap
789 else if (modec == 'o')
790 mode = OP_PENDING; // :omap
791 else if (modec == 't')
792 mode = TERMINAL; // :tmap
793 else
794 {
795 --p;
796 if (forceit)
797 mode = INSERT + CMDLINE; // :map !
798 else
799 mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;// :map
800 }
801
802 *cmdp = p;
803 return mode;
804}
805
806/*
807 * Clear all mappings or abbreviations.
808 * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
809 */
810 static void
811map_clear(
812 char_u *cmdp,
813 char_u *arg UNUSED,
814 int forceit,
815 int abbr)
816{
817 int mode;
818 int local;
819
820 local = (STRCMP(arg, "<buffer>") == 0);
821 if (!local && *arg != NUL)
822 {
823 emsg(_(e_invarg));
824 return;
825 }
826
827 mode = get_map_mode(&cmdp, forceit);
828 map_clear_int(curbuf, mode, local, abbr);
829}
830
831/*
832 * Clear all mappings in "mode".
833 */
834 void
835map_clear_int(
836 buf_T *buf, // buffer for local mappings
837 int mode, // mode in which to delete
838 int local, // TRUE for buffer-local mappings
839 int abbr) // TRUE for abbreviations
840{
841 mapblock_T *mp, **mpp;
842 int hash;
843 int new_hash;
844
845 validate_maphash();
846
847 for (hash = 0; hash < 256; ++hash)
848 {
849 if (abbr)
850 {
851 if (hash > 0) // there is only one abbrlist
852 break;
853 if (local)
854 mpp = &buf->b_first_abbr;
855 else
856 mpp = &first_abbr;
857 }
858 else
859 {
860 if (local)
861 mpp = &buf->b_maphash[hash];
862 else
863 mpp = &maphash[hash];
864 }
865 while (*mpp != NULL)
866 {
867 mp = *mpp;
868 if (mp->m_mode & mode)
869 {
870 mp->m_mode &= ~mode;
871 if (mp->m_mode == 0) // entry can be deleted
872 {
873 map_free(mpp);
874 continue;
875 }
876 // May need to put this entry into another hash list.
877 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
878 if (!abbr && new_hash != hash)
879 {
880 *mpp = mp->m_next;
881 if (local)
882 {
883 mp->m_next = buf->b_maphash[new_hash];
884 buf->b_maphash[new_hash] = mp;
885 }
886 else
887 {
888 mp->m_next = maphash[new_hash];
889 maphash[new_hash] = mp;
890 }
891 continue; // continue with *mpp
892 }
893 }
894 mpp = &(mp->m_next);
895 }
896 }
897}
898
899#if defined(FEAT_EVAL) || defined(PROTO)
900/*
901 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
902 * Recognize termcap codes in "str".
903 * Also checks mappings local to the current buffer.
904 */
905 int
906map_to_exists(char_u *str, char_u *modechars, int abbr)
907{
908 int mode = 0;
909 char_u *rhs;
910 char_u *buf;
911 int retval;
912
913 rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE);
914
915 if (vim_strchr(modechars, 'n') != NULL)
916 mode |= NORMAL;
917 if (vim_strchr(modechars, 'v') != NULL)
918 mode |= VISUAL + SELECTMODE;
919 if (vim_strchr(modechars, 'x') != NULL)
920 mode |= VISUAL;
921 if (vim_strchr(modechars, 's') != NULL)
922 mode |= SELECTMODE;
923 if (vim_strchr(modechars, 'o') != NULL)
924 mode |= OP_PENDING;
925 if (vim_strchr(modechars, 'i') != NULL)
926 mode |= INSERT;
927 if (vim_strchr(modechars, 'l') != NULL)
928 mode |= LANGMAP;
929 if (vim_strchr(modechars, 'c') != NULL)
930 mode |= CMDLINE;
931
932 retval = map_to_exists_mode(rhs, mode, abbr);
933 vim_free(buf);
934
935 return retval;
936}
937#endif
938
939/*
940 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
941 * Also checks mappings local to the current buffer.
942 */
943 int
944map_to_exists_mode(char_u *rhs, int mode, int abbr)
945{
946 mapblock_T *mp;
947 int hash;
948 int exp_buffer = FALSE;
949
950 validate_maphash();
951
952 // Do it twice: once for global maps and once for local maps.
953 for (;;)
954 {
955 for (hash = 0; hash < 256; ++hash)
956 {
957 if (abbr)
958 {
959 if (hash > 0) // there is only one abbr list
960 break;
961 if (exp_buffer)
962 mp = curbuf->b_first_abbr;
963 else
964 mp = first_abbr;
965 }
966 else if (exp_buffer)
967 mp = curbuf->b_maphash[hash];
968 else
969 mp = maphash[hash];
970 for (; mp; mp = mp->m_next)
971 {
972 if ((mp->m_mode & mode)
973 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
974 return TRUE;
975 }
976 }
977 if (exp_buffer)
978 break;
979 exp_buffer = TRUE;
980 }
981
982 return FALSE;
983}
984
Bram Moolenaarb66bab32019-08-01 14:28:24 +0200985/*
986 * Used below when expanding mapping/abbreviation names.
987 */
988static int expand_mapmodes = 0;
989static int expand_isabbrev = 0;
990static int expand_buffer = FALSE;
991
992/*
993 * Work out what to complete when doing command line completion of mapping
994 * or abbreviation names.
995 */
996 char_u *
997set_context_in_map_cmd(
998 expand_T *xp,
999 char_u *cmd,
1000 char_u *arg,
1001 int forceit, // TRUE if '!' given
1002 int isabbrev, // TRUE if abbreviation
1003 int isunmap, // TRUE if unmap/unabbrev command
1004 cmdidx_T cmdidx)
1005{
1006 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
1007 xp->xp_context = EXPAND_NOTHING;
1008 else
1009 {
1010 if (isunmap)
1011 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1012 else
1013 {
1014 expand_mapmodes = INSERT + CMDLINE;
1015 if (!isabbrev)
1016 expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
1017 }
1018 expand_isabbrev = isabbrev;
1019 xp->xp_context = EXPAND_MAPPINGS;
1020 expand_buffer = FALSE;
1021 for (;;)
1022 {
1023 if (STRNCMP(arg, "<buffer>", 8) == 0)
1024 {
1025 expand_buffer = TRUE;
1026 arg = skipwhite(arg + 8);
1027 continue;
1028 }
1029 if (STRNCMP(arg, "<unique>", 8) == 0)
1030 {
1031 arg = skipwhite(arg + 8);
1032 continue;
1033 }
1034 if (STRNCMP(arg, "<nowait>", 8) == 0)
1035 {
1036 arg = skipwhite(arg + 8);
1037 continue;
1038 }
1039 if (STRNCMP(arg, "<silent>", 8) == 0)
1040 {
1041 arg = skipwhite(arg + 8);
1042 continue;
1043 }
1044 if (STRNCMP(arg, "<special>", 9) == 0)
1045 {
1046 arg = skipwhite(arg + 9);
1047 continue;
1048 }
1049#ifdef FEAT_EVAL
1050 if (STRNCMP(arg, "<script>", 8) == 0)
1051 {
1052 arg = skipwhite(arg + 8);
1053 continue;
1054 }
1055 if (STRNCMP(arg, "<expr>", 6) == 0)
1056 {
1057 arg = skipwhite(arg + 6);
1058 continue;
1059 }
1060#endif
1061 break;
1062 }
1063 xp->xp_pattern = arg;
1064 }
1065
1066 return NULL;
1067}
1068
1069/*
1070 * Find all mapping/abbreviation names that match regexp "regmatch"'.
1071 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1072 * Return OK if matches found, FAIL otherwise.
1073 */
1074 int
1075ExpandMappings(
1076 regmatch_T *regmatch,
1077 int *num_file,
1078 char_u ***file)
1079{
1080 mapblock_T *mp;
1081 int hash;
1082 int count;
1083 int round;
1084 char_u *p;
1085 int i;
1086
1087 validate_maphash();
1088
1089 *num_file = 0; // return values in case of FAIL
1090 *file = NULL;
1091
1092 // round == 1: Count the matches.
1093 // round == 2: Build the array to keep the matches.
1094 for (round = 1; round <= 2; ++round)
1095 {
1096 count = 0;
1097
1098 for (i = 0; i < 7; ++i)
1099 {
1100 if (i == 0)
1101 p = (char_u *)"<silent>";
1102 else if (i == 1)
1103 p = (char_u *)"<unique>";
1104#ifdef FEAT_EVAL
1105 else if (i == 2)
1106 p = (char_u *)"<script>";
1107 else if (i == 3)
1108 p = (char_u *)"<expr>";
1109#endif
1110 else if (i == 4 && !expand_buffer)
1111 p = (char_u *)"<buffer>";
1112 else if (i == 5)
1113 p = (char_u *)"<nowait>";
1114 else if (i == 6)
1115 p = (char_u *)"<special>";
1116 else
1117 continue;
1118
1119 if (vim_regexec(regmatch, p, (colnr_T)0))
1120 {
1121 if (round == 1)
1122 ++count;
1123 else
1124 (*file)[count++] = vim_strsave(p);
1125 }
1126 }
1127
1128 for (hash = 0; hash < 256; ++hash)
1129 {
1130 if (expand_isabbrev)
1131 {
1132 if (hash > 0) // only one abbrev list
1133 break; // for (hash)
1134 mp = first_abbr;
1135 }
1136 else if (expand_buffer)
1137 mp = curbuf->b_maphash[hash];
1138 else
1139 mp = maphash[hash];
1140 for (; mp; mp = mp->m_next)
1141 {
1142 if (mp->m_mode & expand_mapmodes)
1143 {
1144 p = translate_mapping(mp->m_keys);
1145 if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
1146 {
1147 if (round == 1)
1148 ++count;
1149 else
1150 {
1151 (*file)[count++] = p;
1152 p = NULL;
1153 }
1154 }
1155 vim_free(p);
1156 }
1157 } // for (mp)
1158 } // for (hash)
1159
1160 if (count == 0) // no match found
1161 break; // for (round)
1162
1163 if (round == 1)
1164 {
1165 *file = ALLOC_MULT(char_u *, count);
1166 if (*file == NULL)
1167 return FAIL;
1168 }
1169 } // for (round)
1170
1171 if (count > 1)
1172 {
1173 char_u **ptr1;
1174 char_u **ptr2;
1175 char_u **ptr3;
1176
1177 // Sort the matches
1178 sort_strings(*file, count);
1179
1180 // Remove multiple entries
1181 ptr1 = *file;
1182 ptr2 = ptr1 + 1;
1183 ptr3 = ptr1 + count;
1184
1185 while (ptr2 < ptr3)
1186 {
1187 if (STRCMP(*ptr1, *ptr2))
1188 *++ptr1 = *ptr2++;
1189 else
1190 {
1191 vim_free(*ptr2++);
1192 count--;
1193 }
1194 }
1195 }
1196
1197 *num_file = count;
1198 return (count == 0 ? FAIL : OK);
1199}
Bram Moolenaarb66bab32019-08-01 14:28:24 +02001200
1201/*
1202 * Check for an abbreviation.
1203 * Cursor is at ptr[col].
1204 * When inserting, mincol is where insert started.
1205 * For the command line, mincol is what is to be skipped over.
1206 * "c" is the character typed before check_abbr was called. It may have
1207 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1208 *
1209 * Historic vi practice: The last character of an abbreviation must be an id
1210 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1211 * characters or all non-id characters. This allows for abbr. "#i" to
1212 * "#include".
1213 *
1214 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1215 * Then there must be white space before the abbr.
1216 *
1217 * return TRUE if there is an abbreviation, FALSE if not
1218 */
1219 int
1220check_abbr(
1221 int c,
1222 char_u *ptr,
1223 int col,
1224 int mincol)
1225{
1226 int len;
1227 int scol; // starting column of the abbr.
1228 int j;
1229 char_u *s;
1230 char_u tb[MB_MAXBYTES + 4];
1231 mapblock_T *mp;
1232 mapblock_T *mp2;
1233 int clen = 0; // length in characters
1234 int is_id = TRUE;
1235 int vim_abbr;
1236
1237 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1238 return FALSE;
1239
1240 // no remapping implies no abbreviation, except for CTRL-]
1241 if (noremap_keys() && c != Ctrl_RSB)
1242 return FALSE;
1243
1244 // Check for word before the cursor: If it ends in a keyword char all
1245 // chars before it must be keyword chars or non-keyword chars, but not
1246 // white space. If it ends in a non-keyword char we accept any characters
1247 // before it except white space.
1248 if (col == 0) // cannot be an abbr.
1249 return FALSE;
1250
1251 if (has_mbyte)
1252 {
1253 char_u *p;
1254
1255 p = mb_prevptr(ptr, ptr + col);
1256 if (!vim_iswordp(p))
1257 vim_abbr = TRUE; // Vim added abbr.
1258 else
1259 {
1260 vim_abbr = FALSE; // vi compatible abbr.
1261 if (p > ptr)
1262 is_id = vim_iswordp(mb_prevptr(ptr, p));
1263 }
1264 clen = 1;
1265 while (p > ptr + mincol)
1266 {
1267 p = mb_prevptr(ptr, p);
1268 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1269 {
1270 p += (*mb_ptr2len)(p);
1271 break;
1272 }
1273 ++clen;
1274 }
1275 scol = (int)(p - ptr);
1276 }
1277 else
1278 {
1279 if (!vim_iswordc(ptr[col - 1]))
1280 vim_abbr = TRUE; // Vim added abbr.
1281 else
1282 {
1283 vim_abbr = FALSE; // vi compatible abbr.
1284 if (col > 1)
1285 is_id = vim_iswordc(ptr[col - 2]);
1286 }
1287 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1288 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1289 ;
1290 }
1291
1292 if (scol < mincol)
1293 scol = mincol;
1294 if (scol < col) // there is a word in front of the cursor
1295 {
1296 ptr += scol;
1297 len = col - scol;
1298 mp = curbuf->b_first_abbr;
1299 mp2 = first_abbr;
1300 if (mp == NULL)
1301 {
1302 mp = mp2;
1303 mp2 = NULL;
1304 }
1305 for ( ; mp; mp->m_next == NULL
1306 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1307 {
1308 int qlen = mp->m_keylen;
1309 char_u *q = mp->m_keys;
1310 int match;
1311
1312 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1313 {
1314 char_u *qe = vim_strsave(mp->m_keys);
1315
1316 // might have CSI escaped mp->m_keys
1317 if (qe != NULL)
1318 {
1319 q = qe;
1320 vim_unescape_csi(q);
1321 qlen = (int)STRLEN(q);
1322 }
1323 }
1324
1325 // find entries with right mode and keys
1326 match = (mp->m_mode & State)
1327 && qlen == len
1328 && !STRNCMP(q, ptr, (size_t)len);
1329 if (q != mp->m_keys)
1330 vim_free(q);
1331 if (match)
1332 break;
1333 }
1334 if (mp != NULL)
1335 {
1336 // Found a match:
1337 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1338 // This goes from end to start.
1339 //
1340 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1341 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1342 // Characters where IS_SPECIAL() == TRUE: key codes, need
1343 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1344 //
1345 // Character CTRL-] is treated specially - it completes the
1346 // abbreviation, but is not inserted into the input stream.
1347 j = 0;
1348 if (c != Ctrl_RSB)
1349 {
1350 // special key code, split up
1351 if (IS_SPECIAL(c) || c == K_SPECIAL)
1352 {
1353 tb[j++] = K_SPECIAL;
1354 tb[j++] = K_SECOND(c);
1355 tb[j++] = K_THIRD(c);
1356 }
1357 else
1358 {
1359 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1360 tb[j++] = Ctrl_V; // special char needs CTRL-V
1361 if (has_mbyte)
1362 {
1363 // if ABBR_OFF has been added, remove it here
1364 if (c >= ABBR_OFF)
1365 c -= ABBR_OFF;
1366 j += (*mb_char2bytes)(c, tb + j);
1367 }
1368 else
1369 tb[j++] = c;
1370 }
1371 tb[j] = NUL;
1372 // insert the last typed char
1373 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1374 }
1375#ifdef FEAT_EVAL
1376 if (mp->m_expr)
1377 s = eval_map_expr(mp->m_str, c);
1378 else
1379#endif
1380 s = mp->m_str;
1381 if (s != NULL)
1382 {
1383 // insert the to string
1384 (void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
1385 // no abbrev. for these chars
1386 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1387#ifdef FEAT_EVAL
1388 if (mp->m_expr)
1389 vim_free(s);
1390#endif
1391 }
1392
1393 tb[0] = Ctrl_H;
1394 tb[1] = NUL;
1395 if (has_mbyte)
1396 len = clen; // Delete characters instead of bytes
1397 while (len-- > 0) // delete the from string
1398 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1399 return TRUE;
1400 }
1401 }
1402 return FALSE;
1403}
1404
1405#ifdef FEAT_EVAL
1406/*
1407 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1408 * special characters.
1409 */
1410 char_u *
1411eval_map_expr(
1412 char_u *str,
1413 int c) // NUL or typed character for abbreviation
1414{
1415 char_u *res;
1416 char_u *p;
1417 char_u *expr;
1418 pos_T save_cursor;
1419 int save_msg_col;
1420 int save_msg_row;
1421
1422 // Remove escaping of CSI, because "str" is in a format to be used as
1423 // typeahead.
1424 expr = vim_strsave(str);
1425 if (expr == NULL)
1426 return NULL;
1427 vim_unescape_csi(expr);
1428
1429 // Forbid changing text or using ":normal" to avoid most of the bad side
1430 // effects. Also restore the cursor position.
1431 ++textlock;
1432 ++ex_normal_lock;
1433 set_vim_var_char(c); // set v:char to the typed character
1434 save_cursor = curwin->w_cursor;
1435 save_msg_col = msg_col;
1436 save_msg_row = msg_row;
1437 p = eval_to_string(expr, NULL, FALSE);
1438 --textlock;
1439 --ex_normal_lock;
1440 curwin->w_cursor = save_cursor;
1441 msg_col = save_msg_col;
1442 msg_row = save_msg_row;
1443
1444 vim_free(expr);
1445
1446 if (p == NULL)
1447 return NULL;
1448 // Escape CSI in the result to be able to use the string as typeahead.
1449 res = vim_strsave_escape_csi(p);
1450 vim_free(p);
1451
1452 return res;
1453}
1454#endif
1455
1456/*
1457 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1458 * can be put in the typeahead buffer.
1459 * Returns NULL when out of memory.
1460 */
1461 char_u *
1462vim_strsave_escape_csi(
1463 char_u *p)
1464{
1465 char_u *res;
1466 char_u *s, *d;
1467
1468 // Need a buffer to hold up to three times as much. Four in case of an
1469 // illegal utf-8 byte:
1470 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1471 res = alloc(STRLEN(p) * 4 + 1);
1472 if (res != NULL)
1473 {
1474 d = res;
1475 for (s = p; *s != NUL; )
1476 {
1477 if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
1478 {
1479 // Copy special key unmodified.
1480 *d++ = *s++;
1481 *d++ = *s++;
1482 *d++ = *s++;
1483 }
1484 else
1485 {
1486 // Add character, possibly multi-byte to destination, escaping
1487 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1488 d = add_char2buf(PTR2CHAR(s), d);
1489 s += MB_CPTR2LEN(s);
1490 }
1491 }
1492 *d = NUL;
1493 }
1494 return res;
1495}
1496
1497/*
1498 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1499 * vim_strsave_escape_csi(). Works in-place.
1500 */
1501 void
1502vim_unescape_csi(char_u *p)
1503{
1504 char_u *s = p, *d = p;
1505
1506 while (*s != NUL)
1507 {
1508 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1509 {
1510 *d++ = K_SPECIAL;
1511 s += 3;
1512 }
1513 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1514 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1515 {
1516 *d++ = CSI;
1517 s += 3;
1518 }
1519 else
1520 *d++ = *s++;
1521 }
1522 *d = NUL;
1523}
1524
1525/*
1526 * Write map commands for the current mappings to an .exrc file.
1527 * Return FAIL on error, OK otherwise.
1528 */
1529 int
1530makemap(
1531 FILE *fd,
1532 buf_T *buf) // buffer for local mappings or NULL
1533{
1534 mapblock_T *mp;
1535 char_u c1, c2, c3;
1536 char_u *p;
1537 char *cmd;
1538 int abbr;
1539 int hash;
1540 int did_cpo = FALSE;
1541 int i;
1542
1543 validate_maphash();
1544
1545 // Do the loop twice: Once for mappings, once for abbreviations.
1546 // Then loop over all map hash lists.
1547 for (abbr = 0; abbr < 2; ++abbr)
1548 for (hash = 0; hash < 256; ++hash)
1549 {
1550 if (abbr)
1551 {
1552 if (hash > 0) // there is only one abbr list
1553 break;
1554 if (buf != NULL)
1555 mp = buf->b_first_abbr;
1556 else
1557 mp = first_abbr;
1558 }
1559 else
1560 {
1561 if (buf != NULL)
1562 mp = buf->b_maphash[hash];
1563 else
1564 mp = maphash[hash];
1565 }
1566
1567 for ( ; mp; mp = mp->m_next)
1568 {
1569 // skip script-local mappings
1570 if (mp->m_noremap == REMAP_SCRIPT)
1571 continue;
1572
1573 // skip mappings that contain a <SNR> (script-local thing),
1574 // they probably don't work when loaded again
1575 for (p = mp->m_str; *p != NUL; ++p)
1576 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1577 && p[2] == (int)KE_SNR)
1578 break;
1579 if (*p != NUL)
1580 continue;
1581
1582 // It's possible to create a mapping and then ":unmap" certain
1583 // modes. We recreate this here by mapping the individual
1584 // modes, which requires up to three of them.
1585 c1 = NUL;
1586 c2 = NUL;
1587 c3 = NUL;
1588 if (abbr)
1589 cmd = "abbr";
1590 else
1591 cmd = "map";
1592 switch (mp->m_mode)
1593 {
1594 case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
1595 break;
1596 case NORMAL:
1597 c1 = 'n';
1598 break;
1599 case VISUAL:
1600 c1 = 'x';
1601 break;
1602 case SELECTMODE:
1603 c1 = 's';
1604 break;
1605 case OP_PENDING:
1606 c1 = 'o';
1607 break;
1608 case NORMAL + VISUAL:
1609 c1 = 'n';
1610 c2 = 'x';
1611 break;
1612 case NORMAL + SELECTMODE:
1613 c1 = 'n';
1614 c2 = 's';
1615 break;
1616 case NORMAL + OP_PENDING:
1617 c1 = 'n';
1618 c2 = 'o';
1619 break;
1620 case VISUAL + SELECTMODE:
1621 c1 = 'v';
1622 break;
1623 case VISUAL + OP_PENDING:
1624 c1 = 'x';
1625 c2 = 'o';
1626 break;
1627 case SELECTMODE + OP_PENDING:
1628 c1 = 's';
1629 c2 = 'o';
1630 break;
1631 case NORMAL + VISUAL + SELECTMODE:
1632 c1 = 'n';
1633 c2 = 'v';
1634 break;
1635 case NORMAL + VISUAL + OP_PENDING:
1636 c1 = 'n';
1637 c2 = 'x';
1638 c3 = 'o';
1639 break;
1640 case NORMAL + SELECTMODE + OP_PENDING:
1641 c1 = 'n';
1642 c2 = 's';
1643 c3 = 'o';
1644 break;
1645 case VISUAL + SELECTMODE + OP_PENDING:
1646 c1 = 'v';
1647 c2 = 'o';
1648 break;
1649 case CMDLINE + INSERT:
1650 if (!abbr)
1651 cmd = "map!";
1652 break;
1653 case CMDLINE:
1654 c1 = 'c';
1655 break;
1656 case INSERT:
1657 c1 = 'i';
1658 break;
1659 case LANGMAP:
1660 c1 = 'l';
1661 break;
1662 case TERMINAL:
1663 c1 = 't';
1664 break;
1665 default:
1666 iemsg(_("E228: makemap: Illegal mode"));
1667 return FAIL;
1668 }
1669 do // do this twice if c2 is set, 3 times with c3
1670 {
1671 // When outputting <> form, need to make sure that 'cpo'
1672 // is set to the Vim default.
1673 if (!did_cpo)
1674 {
1675 if (*mp->m_str == NUL) // will use <Nop>
1676 did_cpo = TRUE;
1677 else
1678 for (i = 0; i < 2; ++i)
1679 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
1680 if (*p == K_SPECIAL || *p == NL)
1681 did_cpo = TRUE;
1682 if (did_cpo)
1683 {
1684 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
1685 || put_eol(fd) < 0
1686 || fprintf(fd, "set cpo&vim") < 0
1687 || put_eol(fd) < 0)
1688 return FAIL;
1689 }
1690 }
1691 if (c1 && putc(c1, fd) < 0)
1692 return FAIL;
1693 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
1694 return FAIL;
1695 if (fputs(cmd, fd) < 0)
1696 return FAIL;
1697 if (buf != NULL && fputs(" <buffer>", fd) < 0)
1698 return FAIL;
1699 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
1700 return FAIL;
1701 if (mp->m_silent && fputs(" <silent>", fd) < 0)
1702 return FAIL;
1703#ifdef FEAT_EVAL
1704 if (mp->m_noremap == REMAP_SCRIPT
1705 && fputs("<script>", fd) < 0)
1706 return FAIL;
1707 if (mp->m_expr && fputs(" <expr>", fd) < 0)
1708 return FAIL;
1709#endif
1710
1711 if ( putc(' ', fd) < 0
1712 || put_escstr(fd, mp->m_keys, 0) == FAIL
1713 || putc(' ', fd) < 0
1714 || put_escstr(fd, mp->m_str, 1) == FAIL
1715 || put_eol(fd) < 0)
1716 return FAIL;
1717 c1 = c2;
1718 c2 = c3;
1719 c3 = NUL;
1720 } while (c1 != NUL);
1721 }
1722 }
1723
1724 if (did_cpo)
1725 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
1726 || put_eol(fd) < 0
1727 || fprintf(fd, "unlet s:cpo_save") < 0
1728 || put_eol(fd) < 0)
1729 return FAIL;
1730 return OK;
1731}
1732
1733/*
1734 * write escape string to file
1735 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
1736 *
1737 * return FAIL for failure, OK otherwise
1738 */
1739 int
1740put_escstr(FILE *fd, char_u *strstart, int what)
1741{
1742 char_u *str = strstart;
1743 int c;
1744 int modifiers;
1745
1746 // :map xx <Nop>
1747 if (*str == NUL && what == 1)
1748 {
1749 if (fprintf(fd, "<Nop>") < 0)
1750 return FAIL;
1751 return OK;
1752 }
1753
1754 for ( ; *str != NUL; ++str)
1755 {
1756 char_u *p;
1757
1758 // Check for a multi-byte character, which may contain escaped
1759 // K_SPECIAL and CSI bytes
1760 p = mb_unescape(&str);
1761 if (p != NULL)
1762 {
1763 while (*p != NUL)
1764 if (fputc(*p++, fd) < 0)
1765 return FAIL;
1766 --str;
1767 continue;
1768 }
1769
1770 c = *str;
1771 // Special key codes have to be translated to be able to make sense
1772 // when they are read back.
1773 if (c == K_SPECIAL && what != 2)
1774 {
1775 modifiers = 0x0;
1776 if (str[1] == KS_MODIFIER)
1777 {
1778 modifiers = str[2];
1779 str += 3;
1780 c = *str;
1781 }
1782 if (c == K_SPECIAL)
1783 {
1784 c = TO_SPECIAL(str[1], str[2]);
1785 str += 2;
1786 }
1787 if (IS_SPECIAL(c) || modifiers) // special key
1788 {
1789 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
1790 return FAIL;
1791 continue;
1792 }
1793 }
1794
1795 // A '\n' in a map command should be written as <NL>.
1796 // A '\n' in a set command should be written as \^V^J.
1797 if (c == NL)
1798 {
1799 if (what == 2)
1800 {
1801 if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
1802 return FAIL;
1803 }
1804 else
1805 {
1806 if (fprintf(fd, "<NL>") < 0)
1807 return FAIL;
1808 }
1809 continue;
1810 }
1811
1812 // Some characters have to be escaped with CTRL-V to
1813 // prevent them from misinterpreted in DoOneCmd().
1814 // A space, Tab and '"' has to be escaped with a backslash to
1815 // prevent it to be misinterpreted in do_set().
1816 // A space has to be escaped with a CTRL-V when it's at the start of a
1817 // ":map" rhs.
1818 // A '<' has to be escaped with a CTRL-V to prevent it being
1819 // interpreted as the start of a special key name.
1820 // A space in the lhs of a :map needs a CTRL-V.
1821 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
1822 {
1823 if (putc('\\', fd) < 0)
1824 return FAIL;
1825 }
1826 else if (c < ' ' || c > '~' || c == '|'
1827 || (what == 0 && c == ' ')
1828 || (what == 1 && str == strstart && c == ' ')
1829 || (what != 2 && c == '<'))
1830 {
1831 if (putc(Ctrl_V, fd) < 0)
1832 return FAIL;
1833 }
1834 if (putc(c, fd) < 0)
1835 return FAIL;
1836 }
1837 return OK;
1838}
1839
1840/*
1841 * Check all mappings for the presence of special key codes.
1842 * Used after ":set term=xxx".
1843 */
1844 void
1845check_map_keycodes(void)
1846{
1847 mapblock_T *mp;
1848 char_u *p;
1849 int i;
1850 char_u buf[3];
1851 char_u *save_name;
1852 int abbr;
1853 int hash;
1854 buf_T *bp;
1855
1856 validate_maphash();
1857 save_name = sourcing_name;
1858 sourcing_name = (char_u *)"mappings"; // avoids giving error messages
1859
1860 // This this once for each buffer, and then once for global
1861 // mappings/abbreviations with bp == NULL
1862 for (bp = firstbuf; ; bp = bp->b_next)
1863 {
1864 // Do the loop twice: Once for mappings, once for abbreviations.
1865 // Then loop over all map hash lists.
1866 for (abbr = 0; abbr <= 1; ++abbr)
1867 for (hash = 0; hash < 256; ++hash)
1868 {
1869 if (abbr)
1870 {
1871 if (hash) // there is only one abbr list
1872 break;
1873 if (bp != NULL)
1874 mp = bp->b_first_abbr;
1875 else
1876 mp = first_abbr;
1877 }
1878 else
1879 {
1880 if (bp != NULL)
1881 mp = bp->b_maphash[hash];
1882 else
1883 mp = maphash[hash];
1884 }
1885 for ( ; mp != NULL; mp = mp->m_next)
1886 {
1887 for (i = 0; i <= 1; ++i) // do this twice
1888 {
1889 if (i == 0)
1890 p = mp->m_keys; // once for the "from" part
1891 else
1892 p = mp->m_str; // and once for the "to" part
1893 while (*p)
1894 {
1895 if (*p == K_SPECIAL)
1896 {
1897 ++p;
1898 if (*p < 128) // for "normal" tcap entries
1899 {
1900 buf[0] = p[0];
1901 buf[1] = p[1];
1902 buf[2] = NUL;
1903 (void)add_termcap_entry(buf, FALSE);
1904 }
1905 ++p;
1906 }
1907 ++p;
1908 }
1909 }
1910 }
1911 }
1912 if (bp == NULL)
1913 break;
1914 }
1915 sourcing_name = save_name;
1916}
1917
1918#if defined(FEAT_EVAL) || defined(PROTO)
1919/*
1920 * Check the string "keys" against the lhs of all mappings.
1921 * Return pointer to rhs of mapping (mapblock->m_str).
1922 * NULL when no mapping found.
1923 */
1924 char_u *
1925check_map(
1926 char_u *keys,
1927 int mode,
1928 int exact, // require exact match
1929 int ign_mod, // ignore preceding modifier
1930 int abbr, // do abbreviations
1931 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
1932 int *local_ptr) // return: buffer-local mapping or NULL
1933{
1934 int hash;
1935 int len, minlen;
1936 mapblock_T *mp;
1937 char_u *s;
1938 int local;
1939
1940 validate_maphash();
1941
1942 len = (int)STRLEN(keys);
1943 for (local = 1; local >= 0; --local)
1944 // loop over all hash lists
1945 for (hash = 0; hash < 256; ++hash)
1946 {
1947 if (abbr)
1948 {
1949 if (hash > 0) // there is only one list.
1950 break;
1951 if (local)
1952 mp = curbuf->b_first_abbr;
1953 else
1954 mp = first_abbr;
1955 }
1956 else if (local)
1957 mp = curbuf->b_maphash[hash];
1958 else
1959 mp = maphash[hash];
1960 for ( ; mp != NULL; mp = mp->m_next)
1961 {
1962 // skip entries with wrong mode, wrong length and not matching
1963 // ones
1964 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
1965 {
1966 if (len > mp->m_keylen)
1967 minlen = mp->m_keylen;
1968 else
1969 minlen = len;
1970 s = mp->m_keys;
1971 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
1972 && s[2] != NUL)
1973 {
1974 s += 3;
1975 if (len > mp->m_keylen - 3)
1976 minlen = mp->m_keylen - 3;
1977 }
1978 if (STRNCMP(s, keys, minlen) == 0)
1979 {
1980 if (mp_ptr != NULL)
1981 *mp_ptr = mp;
1982 if (local_ptr != NULL)
1983 *local_ptr = local;
1984 return mp->m_str;
1985 }
1986 }
1987 }
1988 }
1989
1990 return NULL;
1991}
1992
1993 void
1994get_maparg(typval_T *argvars, typval_T *rettv, int exact)
1995{
1996 char_u *keys;
1997 char_u *which;
1998 char_u buf[NUMBUFLEN];
1999 char_u *keys_buf = NULL;
2000 char_u *rhs;
2001 int mode;
2002 int abbr = FALSE;
2003 int get_dict = FALSE;
2004 mapblock_T *mp;
2005 int buffer_local;
2006
2007 // return empty string for failure
2008 rettv->v_type = VAR_STRING;
2009 rettv->vval.v_string = NULL;
2010
2011 keys = tv_get_string(&argvars[0]);
2012 if (*keys == NUL)
2013 return;
2014
2015 if (argvars[1].v_type != VAR_UNKNOWN)
2016 {
2017 which = tv_get_string_buf_chk(&argvars[1], buf);
2018 if (argvars[2].v_type != VAR_UNKNOWN)
2019 {
2020 abbr = (int)tv_get_number(&argvars[2]);
2021 if (argvars[3].v_type != VAR_UNKNOWN)
2022 get_dict = (int)tv_get_number(&argvars[3]);
2023 }
2024 }
2025 else
2026 which = (char_u *)"";
2027 if (which == NULL)
2028 return;
2029
2030 mode = get_map_mode(&which, 0);
2031
2032 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
2033 rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local);
2034 vim_free(keys_buf);
2035
2036 if (!get_dict)
2037 {
2038 // Return a string.
2039 if (rhs != NULL)
2040 {
2041 if (*rhs == NUL)
2042 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2043 else
2044 rettv->vval.v_string = str2special_save(rhs, FALSE);
2045 }
2046
2047 }
2048 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
2049 {
2050 // Return a dictionary.
2051 char_u *lhs = str2special_save(mp->m_keys, TRUE);
2052 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2053 dict_T *dict = rettv->vval.v_dict;
2054
2055 dict_add_string(dict, "lhs", lhs);
2056 dict_add_string(dict, "rhs", mp->m_orig_str);
2057 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
2058 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2059 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2060 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
2061 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2062 dict_add_number(dict, "buffer", (long)buffer_local);
2063 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2064 dict_add_string(dict, "mode", mapmode);
2065
2066 vim_free(lhs);
2067 vim_free(mapmode);
2068 }
2069}
2070#endif
2071
2072#if defined(MSWIN) || defined(MACOS_X)
2073
2074# define VIS_SEL (VISUAL+SELECTMODE) // abbreviation
2075
2076/*
2077 * Default mappings for some often used keys.
2078 */
2079struct initmap
2080{
2081 char_u *arg;
2082 int mode;
2083};
2084
2085# ifdef FEAT_GUI_MSWIN
2086// Use the Windows (CUA) keybindings. (GUI)
2087static struct initmap initmappings[] =
2088{
2089 // paste, copy and cut
2090 {(char_u *)"<S-Insert> \"*P", NORMAL},
2091 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2092 {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
2093 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2094 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2095 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2096 {(char_u *)"<C-X> \"*d", VIS_SEL},
2097 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2098};
2099# endif
2100
2101# if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2102// Use the Windows (CUA) keybindings. (Console)
2103static struct initmap cinitmappings[] =
2104{
2105 {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
2106 {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
2107 {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
2108 {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
2109
2110 // paste, copy and cut
2111# ifdef FEAT_CLIPBOARD
2112 {(char_u *)"\316\324 \"*P", NORMAL}, // SHIFT-Insert is "*P
2113 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2114 {(char_u *)"\316\324 \022\017*", INSERT}, // SHIFT-Insert is ^R^O*
2115 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2116 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2117 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2118 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2119# else
2120 {(char_u *)"\316\324 P", NORMAL}, // SHIFT-Insert is P
2121 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2122 {(char_u *)"\316\324 \022\017\"", INSERT}, // SHIFT-Insert is ^R^O"
2123 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2124 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2125 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2126# endif
2127};
2128# endif
2129
2130# if defined(MACOS_X)
2131static struct initmap initmappings[] =
2132{
2133 // Use the Standard MacOS binding.
2134 // paste, copy and cut
2135 {(char_u *)"<D-v> \"*P", NORMAL},
2136 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2137 {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
2138 {(char_u *)"<D-c> \"*y", VIS_SEL},
2139 {(char_u *)"<D-x> \"*d", VIS_SEL},
2140 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2141};
2142# endif
2143
2144# undef VIS_SEL
2145#endif
2146
2147/*
2148 * Set up default mappings.
2149 */
2150 void
2151init_mappings(void)
2152{
2153#if defined(MSWIN) || defined(MACOS_X)
2154 int i;
2155
2156# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2157# ifdef VIMDLL
2158 if (!gui.starting)
2159# endif
2160 {
2161 for (i = 0;
2162 i < (int)(sizeof(cinitmappings) / sizeof(struct initmap)); ++i)
2163 add_map(cinitmappings[i].arg, cinitmappings[i].mode);
2164 }
2165# endif
2166# if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
2167 for (i = 0; i < (int)(sizeof(initmappings) / sizeof(struct initmap)); ++i)
2168 add_map(initmappings[i].arg, initmappings[i].mode);
2169# endif
2170#endif
2171}
2172
2173#if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
2174 || defined(PROTO)
2175/*
2176 * Add a mapping "map" for mode "mode".
2177 * Need to put string in allocated memory, because do_map() will modify it.
2178 */
2179 void
2180add_map(char_u *map, int mode)
2181{
2182 char_u *s;
2183 char_u *cpo_save = p_cpo;
2184
2185 p_cpo = (char_u *)""; // Allow <> notation
2186 s = vim_strsave(map);
2187 if (s != NULL)
2188 {
2189 (void)do_map(0, s, mode, FALSE);
2190 vim_free(s);
2191 }
2192 p_cpo = cpo_save;
2193}
2194#endif
2195
2196 static void
2197do_exmap(exarg_T *eap, int isabbrev)
2198{
2199 int mode;
2200 char_u *cmdp;
2201
2202 cmdp = eap->cmd;
2203 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
2204
2205 switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'),
2206 eap->arg, mode, isabbrev))
2207 {
2208 case 1: emsg(_(e_invarg));
2209 break;
2210 case 2: emsg((isabbrev ? _(e_noabbr) : _(e_nomap)));
2211 break;
2212 }
2213}
2214
2215/*
2216 * ":abbreviate" and friends.
2217 */
2218 void
2219ex_abbreviate(exarg_T *eap)
2220{
2221 do_exmap(eap, TRUE); // almost the same as mapping
2222}
2223
2224/*
2225 * ":map" and friends.
2226 */
2227 void
2228ex_map(exarg_T *eap)
2229{
2230 // If we are sourcing .exrc or .vimrc in current directory we
2231 // print the mappings for security reasons.
2232 if (secure)
2233 {
2234 secure = 2;
2235 msg_outtrans(eap->cmd);
2236 msg_putchar('\n');
2237 }
2238 do_exmap(eap, FALSE);
2239}
2240
2241/*
2242 * ":unmap" and friends.
2243 */
2244 void
2245ex_unmap(exarg_T *eap)
2246{
2247 do_exmap(eap, FALSE);
2248}
2249
2250/*
2251 * ":mapclear" and friends.
2252 */
2253 void
2254ex_mapclear(exarg_T *eap)
2255{
2256 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
2257}
2258
2259/*
2260 * ":abclear" and friends.
2261 */
2262 void
2263ex_abclear(exarg_T *eap)
2264{
2265 map_clear(eap->cmd, eap->arg, TRUE, TRUE);
2266}