1 /* vi:set ts=8 sts=4 sw=4 noet:
3 * VIM - Vi IMproved by Bram Moolenaar
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.
11 * map.c: Code for mappings and abbreviations.
17 * List used for abbreviations.
19 static mapblock_T *first_abbr = NULL; // first entry in abbrlist
22 * Each mapping is put in one of the 256 hash lists, to speed up finding it.
24 static mapblock_T *(maphash[256]);
25 static int maphash_valid = FALSE;
27 // When non-zero then no mappings can be added or removed. Prevents mappings
28 // to change while listing them.
29 static int map_locked = 0;
32 * Make a hash value for a mapping.
33 * "mode" is the lower 4 bits of the State for the mapping.
34 * "c1" is the first character of the "lhs".
35 * Returns a value between 0 and 255, index in maphash.
36 * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
38 #define MAP_HASH(mode, c1) (((mode) & (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING | MODE_TERMINAL)) ? (c1) : ((c1) ^ 0x80))
41 * Get the start of the hashed map list for "state" and first character "c".
44 get_maphash_list(int state, int c)
46 return maphash[MAP_HASH(state, c)];
50 * Get the buffer-local hashed map list for "state" and first character "c".
53 get_buf_maphash_list(int state, int c)
55 return curbuf->b_maphash[MAP_HASH(state, c)];
59 is_maphash_valid(void)
65 * Initialize maphash[] for first use.
68 validate_maphash(void)
78 * Delete one entry from the abbrlist or maphash[].
79 * "mpp" is a pointer to the m_next field of the PREVIOUS entry!
82 map_free(mapblock_T **mpp)
89 vim_free(mp->m_orig_str);
92 reset_last_used_map(mp);
98 * Return characters to represent the map mode in an allocated string.
99 * Returns NULL when out of memory.
102 map_mode_to_chars(int mode)
106 ga_init2(&mapmode, 1, 7);
108 if ((mode & (MODE_INSERT | MODE_CMDLINE)) == (MODE_INSERT | MODE_CMDLINE))
109 ga_append(&mapmode, '!'); // :map!
110 else if (mode & MODE_INSERT)
111 ga_append(&mapmode, 'i'); // :imap
112 else if (mode & MODE_LANGMAP)
113 ga_append(&mapmode, 'l'); // :lmap
114 else if (mode & MODE_CMDLINE)
115 ga_append(&mapmode, 'c'); // :cmap
117 & (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING))
118 == (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING))
119 ga_append(&mapmode, ' '); // :map
122 if (mode & MODE_NORMAL)
123 ga_append(&mapmode, 'n'); // :nmap
124 if (mode & MODE_OP_PENDING)
125 ga_append(&mapmode, 'o'); // :omap
126 if (mode & MODE_TERMINAL)
127 ga_append(&mapmode, 't'); // :tmap
128 if ((mode & (MODE_VISUAL | MODE_SELECT)) == (MODE_VISUAL | MODE_SELECT))
129 ga_append(&mapmode, 'v'); // :vmap
132 if (mode & MODE_VISUAL)
133 ga_append(&mapmode, 'x'); // :xmap
134 if (mode & MODE_SELECT)
135 ga_append(&mapmode, 's'); // :smap
139 ga_append(&mapmode, NUL);
140 return (char_u *)mapmode.ga_data;
144 * Output a line for one mapping.
149 int local) // TRUE for buffer-local map
154 if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
157 // Prevent mappings to be cleared while at the more prompt.
158 // Must jump to "theend" instead of returning.
161 if (msg_didout || msg_silent != 0)
164 if (got_int) // 'q' typed at MORE prompt
168 mapchars = map_mode_to_chars(mp->m_mode);
169 if (mapchars != NULL)
171 msg_puts((char *)mapchars);
172 len = (int)STRLEN(mapchars);
179 // Display the LHS. Get length of what we write.
180 len = msg_outtrans_special(mp->m_keys, TRUE, 0);
183 msg_putchar(' '); // pad with blanks
187 if (mp->m_noremap == REMAP_NONE)
188 msg_puts_attr("*", HL_ATTR(HLF_8));
189 else if (mp->m_noremap == REMAP_SCRIPT)
190 msg_puts_attr("&", HL_ATTR(HLF_8));
199 // Use FALSE below if we only want things like <Up> to show up as such on
200 // the rhs, and not M-x etc, TRUE gets both -- webb
201 if (*mp->m_str == NUL)
202 msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
204 msg_outtrans_special(mp->m_str, FALSE, 0);
207 last_set_msg(mp->m_script_ctx);
210 out_flush(); // show one line at a time
218 mapblock_T **map_table,
219 mapblock_T **abbr_table,
230 scid_T sid, // -1 to use current_sctx
236 mapblock_T *mp = ALLOC_CLEAR_ONE(mapblock_T);
241 // If CTRL-C has been mapped, don't always use it for Interrupting.
244 if (map_table == curbuf->b_maphash)
245 curbuf->b_mapped_ctrl_c |= mode;
247 mapped_ctrl_c |= mode;
250 mp->m_keys = vim_strsave(keys);
251 mp->m_str = vim_strsave(rhs);
252 mp->m_orig_str = vim_strsave(orig_rhs);
253 if (mp->m_keys == NULL || mp->m_str == NULL)
255 vim_free(mp->m_keys);
257 vim_free(mp->m_orig_str);
261 mp->m_keylen = (int)STRLEN(mp->m_keys);
262 mp->m_noremap = noremap;
263 mp->m_nowait = nowait;
264 mp->m_silent = silent;
266 mp->m_simplified = simplified;
271 mp->m_script_ctx.sc_sid = sid;
272 mp->m_script_ctx.sc_lnum = lnum;
273 mp->m_script_ctx.sc_version = scriptversion;
277 mp->m_script_ctx = current_sctx;
278 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
282 // add the new entry in front of the abbrlist or maphash[] list
285 mp->m_next = *abbr_table;
290 int n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
292 mp->m_next = map_table[n];
299 * List mappings. When "haskey" is FALSE all mappings, otherwise mappings that
300 * match "keys[keys_len]".
312 // Prevent mappings to be cleared while at the more prompt.
315 if (p_verbose > 0 && keyround == 1)
317 if (seenModifyOtherKeys)
318 msg_puts(_("Seen modifyOtherKeys: true\n"));
320 if (modify_otherkeys_state != MOKS_INITIAL)
322 char *name = _("Unknown");
323 switch (modify_otherkeys_state)
325 case MOKS_INITIAL: break;
326 case MOKS_OFF: name = _("Off"); break;
327 case MOKS_ENABLED: name = _("On"); break;
328 case MOKS_DISABLED: name = _("Disabled"); break;
329 case MOKS_AFTER_T_TE: name = _("Cleared"); break;
333 vim_snprintf(buf, sizeof(buf),
334 _("modifyOtherKeys detected: %s\n"), name);
338 if (kitty_protocol_state != KKPS_INITIAL)
340 char *name = _("Unknown");
341 switch (kitty_protocol_state)
343 case KKPS_INITIAL: break;
344 case KKPS_OFF: name = _("Off"); break;
345 case KKPS_ENABLED: name = _("On"); break;
346 case KKPS_DISABLED: name = _("Disabled"); break;
347 case KKPS_AFTER_T_TE: name = _("Cleared"); break;
351 vim_snprintf(buf, sizeof(buf),
352 _("Kitty keyboard protocol: %s\n"), name);
357 // need to loop over all global hash lists
358 for (int hash = 0; hash < 256 && !got_int; ++hash)
364 if (hash != 0) // there is only one abbreviation list
366 mp = curbuf->b_first_abbr;
369 mp = curbuf->b_maphash[hash];
370 for ( ; mp != NULL && !got_int; mp = mp->m_next)
372 // check entries with the same mode
373 if (!mp->m_simplified && (mp->m_mode & mode) != 0)
375 if (!haskey) // show all entries
382 int n = mp->m_keylen;
383 if (STRNCMP(mp->m_keys, keys,
384 (size_t)(n < keys_len ? n : keys_len)) == 0)
398 * map[!] : show all key mappings
399 * map[!] {lhs} : show key mapping for {lhs}
400 * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs}
401 * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs}
402 * unmap[!] {lhs} : remove key mapping for {lhs}
403 * abbr : show all abbreviations
404 * abbr {lhs} : show abbreviations for {lhs}
405 * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs}
406 * noreabbr {lhs} {rhs} : same, but no remapping for {rhs}
407 * unabbr {lhs} : remove abbreviation for {lhs}
409 * maptype: MAPTYPE_MAP for :map
410 * MAPTYPE_UNMAP for :unmap
411 * MAPTYPE_NOREMAP for noremap
413 * arg is pointer to any arguments. Note: arg cannot be a read-only string,
414 * it will be modified.
416 * for :map mode is MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING
417 * for :map! mode is MODE_INSERT | MODE_CMDLINE
418 * for :cmap mode is MODE_CMDLINE
419 * for :imap mode is MODE_INSERT
420 * for :lmap mode is MODE_LANGMAP
421 * for :nmap mode is MODE_NORMAL
422 * for :vmap mode is MODE_VISUAL | MODE_SELECT
423 * for :xmap mode is MODE_VISUAL
424 * for :smap mode is MODE_SELECT
425 * for :omap mode is MODE_OP_PENDING
426 * for :tmap mode is MODE_TERMINAL
428 * for :abbr mode is MODE_INSERT | MODE_CMDLINE
429 * for :iabbr mode is MODE_INSERT
430 * for :cabbr mode is MODE_CMDLINE
432 * Return 0 for success
433 * 1 for invalid arguments
436 * 5 for entry not unique
443 int abbrev) // not a mapping but an abbreviation
446 mapblock_T *mp, **mpp;
450 int len = 0; // init for GCC
455 char_u *keys_buf = NULL;
456 char_u *alt_keys_buf = NULL;
457 char_u *arg_buf = NULL;
460 mapblock_T **abbr_table;
461 mapblock_T **map_table;
469 int did_simplify = FALSE;
475 abbr_table = &first_abbr;
477 // For ":noremap" don't remap, otherwise do remap.
478 if (maptype == MAPTYPE_NOREMAP)
479 noremap = REMAP_NONE;
483 // Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
487 // Check for "<buffer>": mapping local to buffer.
488 if (STRNCMP(keys, "<buffer>", 8) == 0)
490 keys = skipwhite(keys + 8);
491 map_table = curbuf->b_maphash;
492 abbr_table = &curbuf->b_first_abbr;
496 // Check for "<nowait>": don't wait for more characters.
497 if (STRNCMP(keys, "<nowait>", 8) == 0)
499 keys = skipwhite(keys + 8);
504 // Check for "<silent>": don't echo commands.
505 if (STRNCMP(keys, "<silent>", 8) == 0)
507 keys = skipwhite(keys + 8);
512 // Check for "<special>": accept special keys in <>
513 if (STRNCMP(keys, "<special>", 9) == 0)
515 keys = skipwhite(keys + 9);
521 // Check for "<script>": remap script-local mappings only
522 if (STRNCMP(keys, "<script>", 8) == 0)
524 keys = skipwhite(keys + 8);
525 noremap = REMAP_SCRIPT;
529 // Check for "<expr>": {rhs} is an expression.
530 if (STRNCMP(keys, "<expr>", 6) == 0)
532 keys = skipwhite(keys + 6);
537 // Check for "<unique>": don't overwrite an existing mapping.
538 if (STRNCMP(keys, "<unique>", 8) == 0)
540 keys = skipwhite(keys + 8);
549 // Find end of keys and skip CTRL-Vs (and backslashes) in it.
550 // Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
551 // with :unmap white space is included in the keys, no argument possible.
553 do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
554 while (*p && (maptype == MAPTYPE_UNMAP || !VIM_ISWHITE(*p)))
556 if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
558 ++p; // skip CTRL-V or backslash
566 hasarg = (*rhs != NUL);
567 haskey = (*keys != NUL);
568 do_print = !haskey || (maptype != MAPTYPE_UNMAP && !hasarg);
570 // check for :unmap without argument
571 if (maptype == MAPTYPE_UNMAP && !haskey)
577 // If mapping has been given as ^V<C_UP> say, then replace the term codes
578 // with the appropriate two bytes. If it is a shifted special key, unshift
579 // it too, giving another two bytes.
580 // replace_termcodes() may move the result to allocated memory, which
581 // needs to be freed later (*keys_buf and *arg_buf).
582 // replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
583 // If something like <C-H> is simplified to 0x08 then mark it as simplified
584 // and also add an entry with a modifier, which will work when using a key
589 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
592 flags |= REPTERM_SPECIAL;
593 new_keys = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
595 (void)replace_termcodes(keys, &alt_keys_buf,
596 flags | REPTERM_NO_SIMPLIFY, NULL);
602 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
605 rhs = replace_termcodes(rhs, &arg_buf,
606 REPTERM_DO_LT | (special ? REPTERM_SPECIAL : 0), NULL);
610 * The following is done twice if we have two versions of keys:
611 * "alt_keys_buf" is not NULL.
613 for (keyround = 1; keyround <= 2; ++keyround)
616 int did_local = FALSE;
617 int keyround1_simplified = keyround == 1 && did_simplify;
622 if (alt_keys_buf == NULL)
626 else if (alt_keys_buf != NULL && do_print)
627 // when printing always use the not-simplified map
630 // check arguments and translate function keys
633 len = (int)STRLEN(keys);
634 if (len > MAXMAPLEN) // maximum length of MAXMAPLEN chars
640 if (abbrev && maptype != MAPTYPE_UNMAP)
642 // If an abbreviation ends in a keyword character, the
643 // rest must be all keyword-char or all non-keyword-char.
644 // Otherwise we won't be able to find the start of it in a
645 // vi-compatible way.
651 first = vim_iswordp(keys);
653 p = keys + (*mb_ptr2len)(keys);
655 while (p < keys + len)
657 ++n; // nr of (multi-byte) chars
658 last = vim_iswordp(p); // type of last char
659 if (same == -1 && last != first)
660 same = n - 1; // count of same char type
661 p += (*mb_ptr2len)(p);
663 if (last && n > 2 && same >= 0 && same < n - 1)
669 else if (vim_iswordc(keys[len - 1]))
670 // ends in keyword char
671 for (n = 0; n < len - 2; ++n)
672 if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
677 // An abbreviation cannot contain white space.
678 for (n = 0; n < len; ++n)
679 if (VIM_ISWHITE(keys[n]))
687 if (haskey && hasarg && abbrev) // if we will add an abbreviation
688 no_abbr = FALSE; // reset flag that indicates there are
694 // Check if a new local mapping wasn't already defined globally.
695 if (unique && map_table == curbuf->b_maphash
696 && haskey && hasarg && maptype != MAPTYPE_UNMAP)
698 // need to loop over all global hash lists
699 for (int hash = 0; hash < 256 && !got_int; ++hash)
703 if (hash != 0) // there is only one abbreviation list
709 for ( ; mp != NULL && !got_int; mp = mp->m_next)
711 // check entries with the same mode
712 if ((mp->m_mode & mode) != 0
713 && mp->m_keylen == len
714 && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
718 _(e_global_abbreviation_already_exists_for_str),
721 semsg(_(e_global_mapping_already_exists_for_str),
730 // When listing global mappings, also list buffer-local ones here.
731 if (map_table != curbuf->b_maphash && !hasarg
732 && maptype != MAPTYPE_UNMAP)
733 list_mappings(keyround, abbrev, haskey, keys, len,
736 // Find an entry in the maphash[] list that matches.
737 // For :unmap we may loop two times: once to try to unmap an entry with
738 // a matching 'from' part, a second time, if the first fails, to unmap
739 // an entry with a matching 'to' part. This was done to allow
740 // ":ab foo bar" to be unmapped by typing ":unab foo", where "foo" will
741 // be replaced by "bar" because of the abbreviation.
742 for (round = 0; (round == 0 || maptype == MAPTYPE_UNMAP) && round <= 1
743 && !did_it && !got_int; ++round)
745 // need to loop over all hash lists
746 for (int hash = 0; hash < 256 && !got_int; ++hash)
750 if (hash > 0) // there is only one abbreviation list
755 mpp = &(map_table[hash]);
756 for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
759 if ((mp->m_mode & mode) == 0)
761 // skip entries with wrong mode
765 if (!haskey) // show all entries
767 if (!mp->m_simplified)
769 showmap(mp, map_table != maphash);
773 else // do we have a match?
775 if (round) // second round: Try unmap "rhs" string
777 n = (int)STRLEN(mp->m_str);
785 if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
787 if (maptype == MAPTYPE_UNMAP)
790 // Only accept a full match. For abbreviations
791 // we ignore trailing space when matching with
792 // the "lhs", since an abbreviation can't have
794 if (n != len && (!abbrev || round || n > len
795 || *skipwhite(keys + n) != NUL))
800 // In keyround for simplified keys, don't unmap
801 // a mapping without m_simplified flag.
802 if (keyround1_simplified && !mp->m_simplified)
804 // We reset the indicated mode bits. If nothing
805 // is left the entry is deleted below.
807 did_it = TRUE; // remember we did something
809 else if (!hasarg) // show matching entry
811 if (!mp->m_simplified)
813 showmap(mp, map_table != maphash);
817 else if (n != len) // new entry is ambiguous
826 _(e_abbreviation_already_exists_for_str),
829 semsg(_(e_mapping_already_exists_for_str),
836 // new rhs for existing entry
837 mp->m_mode &= ~mode; // remove mode bits
838 if (mp->m_mode == 0 && !did_it) // reuse entry
840 char_u *newstr = vim_strsave(rhs);
844 retval = 4; // no mem
849 vim_free(mp->m_orig_str);
850 mp->m_orig_str = vim_strsave(orig_rhs);
851 mp->m_noremap = noremap;
852 mp->m_nowait = nowait;
853 mp->m_silent = silent;
855 mp->m_simplified = keyround1_simplified;
858 mp->m_script_ctx = current_sctx;
859 mp->m_script_ctx.sc_lnum += SOURCING_LNUM;
864 if (mp->m_mode == 0) // entry can be deleted
867 continue; // continue with *mpp
870 // May need to put this entry into another hash
872 int new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
873 if (!abbrev && new_hash != hash)
876 mp->m_next = map_table[new_hash];
877 map_table[new_hash] = mp;
879 continue; // continue with *mpp
888 if (maptype == MAPTYPE_UNMAP)
893 if (!keyround1_simplified)
894 retval = 2; // no match
896 else if (*keys == Ctrl_C)
898 // If CTRL-C has been unmapped, reuse it for Interrupting.
899 if (map_table == curbuf->b_maphash)
900 curbuf->b_mapped_ctrl_c &= ~mode;
902 mapped_ctrl_c &= ~mode;
907 if (!haskey || !hasarg)
910 if (!did_it && !did_local)
913 msg(_("No abbreviation found"));
915 msg(_("No mapping found"));
917 goto theend; // listing finished
921 continue; // have added the new entry already
923 // Get here when adding a new entry to the maphash[] list or abbrlist.
924 if (map_add(map_table, abbr_table, keys, rhs, orig_rhs,
925 noremap, nowait, silent, mode, abbrev,
927 expr, /* sid */ -1, /* scriptversion */ 0, /* lnum */ 0,
929 keyround1_simplified) == FAIL)
931 retval = 4; // no mem
938 vim_free(alt_keys_buf);
944 * Get the mapping mode from the command name.
947 get_map_mode(char_u **cmdp, int forceit)
956 mode = MODE_INSERT; // :imap
957 else if (modec == 'l')
958 mode = MODE_LANGMAP; // :lmap
959 else if (modec == 'c')
960 mode = MODE_CMDLINE; // :cmap
961 else if (modec == 'n' && *p != 'o') // avoid :noremap
962 mode = MODE_NORMAL; // :nmap
963 else if (modec == 'v')
964 mode = MODE_VISUAL | MODE_SELECT; // :vmap
965 else if (modec == 'x')
966 mode = MODE_VISUAL; // :xmap
967 else if (modec == 's')
968 mode = MODE_SELECT; // :smap
969 else if (modec == 'o')
970 mode = MODE_OP_PENDING; // :omap
971 else if (modec == 't')
972 mode = MODE_TERMINAL; // :tmap
977 mode = MODE_INSERT | MODE_CMDLINE; // :map !
979 mode = MODE_VISUAL | MODE_SELECT | MODE_NORMAL | MODE_OP_PENDING;
988 * Clear all mappings (":mapclear") or abbreviations (":abclear").
989 * "abbr" should be FALSE for mappings, TRUE for abbreviations.
1001 local = (STRCMP(arg, "<buffer>") == 0);
1002 if (!local && *arg != NUL)
1004 emsg(_(e_invalid_argument));
1008 mode = get_map_mode(&cmdp, forceit);
1009 map_clear_mode(curbuf, mode, local, abbr);
1013 * If "map_locked" is set then give an error and return TRUE.
1014 * Otherwise return FALSE.
1021 emsg(_(e_cannot_change_mappings_while_listing));
1028 * Clear all mappings in "mode".
1032 buf_T *buf, // buffer for local mappings
1033 int mode, // mode in which to delete
1034 int local, // TRUE for buffer-local mappings
1035 int abbr) // TRUE for abbreviations
1037 mapblock_T *mp, **mpp;
1041 if (is_map_locked())
1046 for (hash = 0; hash < 256; ++hash)
1050 if (hash > 0) // there is only one abbrlist
1053 mpp = &buf->b_first_abbr;
1060 mpp = &buf->b_maphash[hash];
1062 mpp = &maphash[hash];
1064 while (*mpp != NULL)
1067 if (mp->m_mode & mode)
1069 mp->m_mode &= ~mode;
1070 if (mp->m_mode == 0) // entry can be deleted
1075 // May need to put this entry into another hash list.
1076 new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
1077 if (!abbr && new_hash != hash)
1082 mp->m_next = buf->b_maphash[new_hash];
1083 buf->b_maphash[new_hash] = mp;
1087 mp->m_next = maphash[new_hash];
1088 maphash[new_hash] = mp;
1090 continue; // continue with *mpp
1093 mpp = &(mp->m_next);
1098 #if defined(FEAT_EVAL) || defined(PROTO)
1100 mode_str2flags(char_u *modechars)
1104 if (vim_strchr(modechars, 'n') != NULL)
1105 mode |= MODE_NORMAL;
1106 if (vim_strchr(modechars, 'v') != NULL)
1107 mode |= MODE_VISUAL | MODE_SELECT;
1108 if (vim_strchr(modechars, 'x') != NULL)
1109 mode |= MODE_VISUAL;
1110 if (vim_strchr(modechars, 's') != NULL)
1111 mode |= MODE_SELECT;
1112 if (vim_strchr(modechars, 'o') != NULL)
1113 mode |= MODE_OP_PENDING;
1114 if (vim_strchr(modechars, 'i') != NULL)
1115 mode |= MODE_INSERT;
1116 if (vim_strchr(modechars, 'l') != NULL)
1117 mode |= MODE_LANGMAP;
1118 if (vim_strchr(modechars, 'c') != NULL)
1119 mode |= MODE_CMDLINE;
1125 * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
1126 * Recognize termcap codes in "str".
1127 * Also checks mappings local to the current buffer.
1130 map_to_exists(char_u *str, char_u *modechars, int abbr)
1136 rhs = replace_termcodes(str, &buf, REPTERM_DO_LT, NULL);
1138 retval = map_to_exists_mode(rhs, mode_str2flags(modechars), abbr);
1146 * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
1147 * Also checks mappings local to the current buffer.
1150 map_to_exists_mode(char_u *rhs, int mode, int abbr)
1154 int exp_buffer = FALSE;
1158 // Do it twice: once for global maps and once for local maps.
1161 for (hash = 0; hash < 256; ++hash)
1165 if (hash > 0) // there is only one abbr list
1168 mp = curbuf->b_first_abbr;
1172 else if (exp_buffer)
1173 mp = curbuf->b_maphash[hash];
1176 for (; mp; mp = mp->m_next)
1178 if ((mp->m_mode & mode)
1179 && strstr((char *)mp->m_str, (char *)rhs) != NULL)
1192 * Used below when expanding mapping/abbreviation names.
1194 static int expand_mapmodes = 0;
1195 static int expand_isabbrev = 0;
1196 static int expand_buffer = FALSE;
1199 * Translate an internal mapping/abbreviation representation into the
1200 * corresponding external one recognized by :map/:abbrev commands.
1201 * Respects the current B/k/< settings of 'cpoption'.
1203 * This function is called when expanding mappings/abbreviations on the
1206 * It uses a growarray to build the translation string since the latter can be
1207 * wider than the original description. The caller has to free the string
1210 * Returns NULL when there is a problem.
1213 translate_mapping(char_u *str)
1223 ga.ga_growsize = 40;
1225 cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL);
1226 cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL);
1231 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1234 if (str[1] == KS_MODIFIER)
1240 if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1247 c = TO_SPECIAL(str[1], str[2]);
1248 if (c == K_ZERO) // display <Nul> as ^@
1252 if (IS_SPECIAL(c) || modifiers) // special key
1259 ga_concat(&ga, get_special_key_name(c, modifiers));
1260 continue; // for (str)
1263 if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
1264 || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash))
1265 ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
1269 ga_append(&ga, NUL);
1270 return (char_u *)(ga.ga_data);
1274 * Work out what to complete when doing command line completion of mapping
1275 * or abbreviation names.
1278 set_context_in_map_cmd(
1282 int forceit, // TRUE if '!' given
1283 int isabbrev, // TRUE if abbreviation
1284 int isunmap, // TRUE if unmap/unabbrev command
1287 if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
1288 xp->xp_context = EXPAND_NOTHING;
1292 expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
1295 expand_mapmodes = MODE_INSERT | MODE_CMDLINE;
1297 expand_mapmodes += MODE_VISUAL | MODE_SELECT | MODE_NORMAL
1300 expand_isabbrev = isabbrev;
1301 xp->xp_context = EXPAND_MAPPINGS;
1302 expand_buffer = FALSE;
1305 if (STRNCMP(arg, "<buffer>", 8) == 0)
1307 expand_buffer = TRUE;
1308 arg = skipwhite(arg + 8);
1311 if (STRNCMP(arg, "<unique>", 8) == 0)
1313 arg = skipwhite(arg + 8);
1316 if (STRNCMP(arg, "<nowait>", 8) == 0)
1318 arg = skipwhite(arg + 8);
1321 if (STRNCMP(arg, "<silent>", 8) == 0)
1323 arg = skipwhite(arg + 8);
1326 if (STRNCMP(arg, "<special>", 9) == 0)
1328 arg = skipwhite(arg + 9);
1332 if (STRNCMP(arg, "<script>", 8) == 0)
1334 arg = skipwhite(arg + 8);
1337 if (STRNCMP(arg, "<expr>", 6) == 0)
1339 arg = skipwhite(arg + 6);
1345 xp->xp_pattern = arg;
1352 * Find all mapping/abbreviation names that match regexp "regmatch"'.
1353 * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
1354 * Return OK if matches found, FAIL otherwise.
1359 regmatch_T *regmatch,
1372 fuzmatch_str_T *fuzmatch;
1374 fuzzy = cmdline_fuzzy_complete(pat);
1378 *numMatches = 0; // return values in case of FAIL
1382 ga_init2(&ga, sizeof(char *), 3);
1384 ga_init2(&ga, sizeof(fuzmatch_str_T), 3);
1386 // First search in map modifier arguments
1387 for (i = 0; i < 7; ++i)
1390 p = (char_u *)"<silent>";
1392 p = (char_u *)"<unique>";
1395 p = (char_u *)"<script>";
1397 p = (char_u *)"<expr>";
1399 else if (i == 4 && !expand_buffer)
1400 p = (char_u *)"<buffer>";
1402 p = (char_u *)"<nowait>";
1404 p = (char_u *)"<special>";
1409 match = vim_regexec(regmatch, p, (colnr_T)0);
1412 score = fuzzy_match_str(p, pat);
1413 match = (score != 0);
1419 if (ga_grow(&ga, 1) == FAIL)
1424 fuzmatch = &((fuzmatch_str_T *)ga.ga_data)[ga.ga_len];
1425 fuzmatch->idx = ga.ga_len;
1426 fuzmatch->str = vim_strsave(p);
1427 fuzmatch->score = score;
1430 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strsave(p);
1434 for (hash = 0; hash < 256; ++hash)
1436 if (expand_isabbrev)
1438 if (hash > 0) // only one abbrev list
1439 break; // for (hash)
1442 else if (expand_buffer)
1443 mp = curbuf->b_maphash[hash];
1446 for (; mp; mp = mp->m_next)
1448 if (mp->m_simplified || !(mp->m_mode & expand_mapmodes))
1451 p = translate_mapping(mp->m_keys);
1456 match = vim_regexec(regmatch, p, (colnr_T)0);
1459 score = fuzzy_match_str(p, pat);
1460 match = (score != 0);
1469 if (ga_grow(&ga, 1) == FAIL)
1477 fuzmatch = &((fuzmatch_str_T *)ga.ga_data)[ga.ga_len];
1478 fuzmatch->idx = ga.ga_len;
1480 fuzmatch->score = score;
1483 ((char_u **)ga.ga_data)[ga.ga_len] = p;
1494 *matches = ga.ga_data;
1495 *numMatches = ga.ga_len;
1499 if (fuzzymatches_to_strmatches(ga.ga_data, matches, ga.ga_len,
1502 *numMatches = ga.ga_len;
1505 count = *numMatches;
1513 // Fuzzy matching already sorts the matches
1515 sort_strings(*matches, count);
1517 // Remove multiple entries
1520 ptr3 = ptr1 + count;
1524 if (STRCMP(*ptr1, *ptr2))
1534 *numMatches = count;
1535 return (count == 0 ? FAIL : OK);
1539 * Check for an abbreviation.
1540 * Cursor is at ptr[col].
1541 * When inserting, mincol is where insert started.
1542 * For the command line, mincol is what is to be skipped over.
1543 * "c" is the character typed before check_abbr was called. It may have
1544 * ABBR_OFF added to avoid prepending a CTRL-V to it.
1546 * Historic vi practice: The last character of an abbreviation must be an id
1547 * character ([a-zA-Z0-9_]). The characters in front of it must be all id
1548 * characters or all non-id characters. This allows for abbr. "#i" to
1551 * Vim addition: Allow for abbreviations that end in a non-keyword character.
1552 * Then there must be white space before the abbr.
1554 * return TRUE if there is an abbreviation, FALSE if not
1564 int scol; // starting column of the abbr.
1567 char_u tb[MB_MAXBYTES + 4];
1570 int clen = 0; // length in characters
1574 if (typebuf.tb_no_abbr_cnt) // abbrev. are not recursive
1577 // no remapping implies no abbreviation, except for CTRL-]
1578 if (noremap_keys() && c != Ctrl_RSB)
1581 // Check for word before the cursor: If it ends in a keyword char all
1582 // chars before it must be keyword chars or non-keyword chars, but not
1583 // white space. If it ends in a non-keyword char we accept any characters
1584 // before it except white space.
1585 if (col == 0) // cannot be an abbr.
1592 p = mb_prevptr(ptr, ptr + col);
1593 if (!vim_iswordp(p))
1594 vim_abbr = TRUE; // Vim added abbr.
1597 vim_abbr = FALSE; // vi compatible abbr.
1599 is_id = vim_iswordp(mb_prevptr(ptr, p));
1602 while (p > ptr + mincol)
1604 p = mb_prevptr(ptr, p);
1605 if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
1607 p += (*mb_ptr2len)(p);
1612 scol = (int)(p - ptr);
1616 if (!vim_iswordc(ptr[col - 1]))
1617 vim_abbr = TRUE; // Vim added abbr.
1620 vim_abbr = FALSE; // vi compatible abbr.
1622 is_id = vim_iswordc(ptr[col - 2]);
1624 for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
1625 && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
1631 if (scol < col) // there is a word in front of the cursor
1635 mp = curbuf->b_first_abbr;
1642 for ( ; mp; mp->m_next == NULL
1643 ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
1645 int qlen = mp->m_keylen;
1646 char_u *q = mp->m_keys;
1649 if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
1651 char_u *qe = vim_strsave(mp->m_keys);
1653 // might have CSI escaped mp->m_keys
1657 vim_unescape_csi(q);
1658 qlen = (int)STRLEN(q);
1662 // find entries with right mode and keys
1663 match = (mp->m_mode & State)
1665 && !STRNCMP(q, ptr, (size_t)len);
1666 if (q != mp->m_keys)
1680 // Insert the rest of the abbreviation in typebuf.tb_buf[].
1681 // This goes from end to start.
1683 // Characters 0x000 - 0x100: normal chars, may need CTRL-V,
1684 // except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
1685 // Characters where IS_SPECIAL() == TRUE: key codes, need
1686 // K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
1688 // Character CTRL-] is treated specially - it completes the
1689 // abbreviation, but is not inserted into the input stream.
1693 // special key code, split up
1694 if (IS_SPECIAL(c) || c == K_SPECIAL)
1696 tb[j++] = K_SPECIAL;
1697 tb[j++] = K_SECOND(c);
1698 tb[j++] = K_THIRD(c);
1702 if (c < ABBR_OFF && (c < ' ' || c > '~'))
1703 tb[j++] = Ctrl_V; // special char needs CTRL-V
1709 // if ABBR_OFF has been added, remove it here
1712 newlen = (*mb_char2bytes)(c, tb + j);
1713 tb[j + newlen] = NUL;
1714 // Need to escape K_SPECIAL.
1715 escaped = vim_strsave_escape_csi(tb + j);
1716 if (escaped != NULL)
1718 newlen = (int)STRLEN(escaped);
1719 mch_memmove(tb + j, escaped, newlen);
1728 // insert the last typed char
1729 (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
1732 // copy values here, calling eval_map_expr() may make "mp" invalid!
1733 noremap = mp->m_noremap;
1734 silent = mp->m_silent;
1739 s = eval_map_expr(mp, c);
1745 // insert the to string
1746 (void)ins_typebuf(s, noremap, 0, TRUE, silent);
1747 // no abbrev. for these chars
1748 typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
1758 len = clen; // Delete characters instead of bytes
1759 while (len-- > 0) // delete the from string
1760 (void)ins_typebuf(tb, 1, 0, TRUE, silent);
1769 * Evaluate the RHS of a mapping or abbreviations and take care of escaping
1770 * special characters.
1771 * Careful: after this "mp" will be invalid if the mapping was deleted.
1776 int c) // NUL or typed character for abbreviation
1784 scid_T save_sctx_sid = current_sctx.sc_sid;
1785 int save_sctx_version = current_sctx.sc_version;
1787 // Remove escaping of CSI, because "str" is in a format to be used as
1789 expr = vim_strsave(mp->m_str);
1792 vim_unescape_csi(expr);
1794 // Forbid changing text or using ":normal" to avoid most of the bad side
1795 // effects. Also restore the cursor position.
1798 set_vim_var_char(c); // set v:char to the typed character
1799 save_cursor = curwin->w_cursor;
1800 save_msg_col = msg_col;
1801 save_msg_row = msg_row;
1802 if (mp->m_script_ctx.sc_version == SCRIPT_VERSION_VIM9)
1804 current_sctx.sc_sid = mp->m_script_ctx.sc_sid;
1805 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
1808 // Note: the evaluation may make "mp" invalid.
1809 p = eval_to_string(expr, FALSE, FALSE);
1813 curwin->w_cursor = save_cursor;
1814 msg_col = save_msg_col;
1815 msg_row = save_msg_row;
1816 current_sctx.sc_sid = save_sctx_sid;
1817 current_sctx.sc_version = save_sctx_version;
1823 // Escape CSI in the result to be able to use the string as typeahead.
1824 res = vim_strsave_escape_csi(p);
1832 * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
1833 * can be put in the typeahead buffer.
1834 * Returns NULL when out of memory.
1837 vim_strsave_escape_csi(char_u *p)
1842 // Need a buffer to hold up to three times as much. Four in case of an
1843 // illegal utf-8 byte:
1844 // 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER
1845 res = alloc(STRLEN(p) * 4 + 1);
1850 for (s = p; *s != NUL; )
1852 if ((s[0] == K_SPECIAL
1854 || (gui.in_use && s[0] == CSI)
1856 ) && s[1] != NUL && s[2] != NUL)
1858 // Copy special key unmodified.
1865 // Add character, possibly multi-byte to destination, escaping
1866 // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
1867 d = add_char2buf(PTR2CHAR(s), d);
1868 s += MB_CPTR2LEN(s);
1877 * Remove escaping from CSI and K_SPECIAL characters. Reverse of
1878 * vim_strsave_escape_csi(). Works in-place.
1881 vim_unescape_csi(char_u *p)
1883 char_u *s = p, *d = p;
1887 if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
1892 else if ((s[0] == K_SPECIAL || s[0] == CSI)
1893 && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
1905 * Write map commands for the current mappings to an .exrc file.
1906 * Return FAIL on error, OK otherwise.
1911 buf_T *buf) // buffer for local mappings or NULL
1919 int did_cpo = FALSE;
1924 // Do the loop twice: Once for mappings, once for abbreviations.
1925 // Then loop over all map hash lists.
1926 for (abbr = 0; abbr < 2; ++abbr)
1927 for (hash = 0; hash < 256; ++hash)
1931 if (hash > 0) // there is only one abbr list
1934 mp = buf->b_first_abbr;
1941 mp = buf->b_maphash[hash];
1946 for ( ; mp; mp = mp->m_next)
1948 // skip script-local mappings
1949 if (mp->m_noremap == REMAP_SCRIPT)
1952 // skip mappings that contain a <SNR> (script-local thing),
1953 // they probably don't work when loaded again
1954 for (p = mp->m_str; *p != NUL; ++p)
1955 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
1956 && p[2] == (int)KE_SNR)
1961 // It's possible to create a mapping and then ":unmap" certain
1962 // modes. We recreate this here by mapping the individual
1963 // modes, which requires up to three of them.
1973 case MODE_NORMAL | MODE_VISUAL | MODE_SELECT
1985 case MODE_OP_PENDING:
1988 case MODE_NORMAL | MODE_VISUAL:
1992 case MODE_NORMAL | MODE_SELECT:
1996 case MODE_NORMAL | MODE_OP_PENDING:
2000 case MODE_VISUAL | MODE_SELECT:
2003 case MODE_VISUAL | MODE_OP_PENDING:
2007 case MODE_SELECT | MODE_OP_PENDING:
2011 case MODE_NORMAL | MODE_VISUAL | MODE_SELECT:
2015 case MODE_NORMAL | MODE_VISUAL | MODE_OP_PENDING:
2020 case MODE_NORMAL | MODE_SELECT | MODE_OP_PENDING:
2025 case MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING:
2029 case MODE_CMDLINE | MODE_INSERT:
2046 iemsg(_(e_makemap_illegal_mode));
2049 do // do this twice if c2 is set, 3 times with c3
2051 // When outputting <> form, need to make sure that 'cpo'
2052 // is set to the Vim default.
2055 if (*mp->m_str == NUL) // will use <Nop>
2058 for (i = 0; i < 2; ++i)
2059 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
2060 if (*p == K_SPECIAL || *p == NL)
2064 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
2066 || fprintf(fd, "set cpo&vim") < 0
2071 if (c1 && putc(c1, fd) < 0)
2073 if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
2075 if (fputs(cmd, fd) < 0)
2077 if (buf != NULL && fputs(" <buffer>", fd) < 0)
2079 if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
2081 if (mp->m_silent && fputs(" <silent>", fd) < 0)
2084 if (mp->m_noremap == REMAP_SCRIPT
2085 && fputs("<script>", fd) < 0)
2087 if (mp->m_expr && fputs(" <expr>", fd) < 0)
2091 if ( putc(' ', fd) < 0
2092 || put_escstr(fd, mp->m_keys, 0) == FAIL
2093 || putc(' ', fd) < 0
2094 || put_escstr(fd, mp->m_str, 1) == FAIL
2100 } while (c1 != NUL);
2105 if (fprintf(fd, "let &cpo=s:cpo_save") < 0
2107 || fprintf(fd, "unlet s:cpo_save") < 0
2114 * write escape string to file
2115 * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
2117 * return FAIL for failure, OK otherwise
2120 put_escstr(FILE *fd, char_u *strstart, int what)
2122 char_u *str = strstart;
2127 if (*str == NUL && what == 1)
2129 if (fprintf(fd, "<Nop>") < 0)
2134 for ( ; *str != NUL; ++str)
2138 // Check for a multi-byte character, which may contain escaped
2139 // K_SPECIAL and CSI bytes
2140 p = mb_unescape(&str);
2144 if (fputc(*p++, fd) < 0)
2151 // Special key codes have to be translated to be able to make sense
2152 // when they are read back.
2153 if (c == K_SPECIAL && what != 2)
2156 if (str[1] == KS_MODIFIER)
2164 c = TO_SPECIAL(str[1], str[2]);
2167 if (IS_SPECIAL(c) || modifiers) // special key
2169 if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
2175 // A '\n' in a map command should be written as <NL>.
2176 // A '\n' in a set command should be written as \^V^J.
2181 if (fprintf(fd, "\\\026\n") < 0)
2186 if (fprintf(fd, "<NL>") < 0)
2192 // Some characters have to be escaped with CTRL-V to
2193 // prevent them from misinterpreted in DoOneCmd().
2194 // A space, Tab and '"' has to be escaped with a backslash to
2195 // prevent it to be misinterpreted in do_set().
2196 // A space has to be escaped with a CTRL-V when it's at the start of a
2198 // A '<' has to be escaped with a CTRL-V to prevent it being
2199 // interpreted as the start of a special key name.
2200 // A space in the lhs of a :map needs a CTRL-V.
2201 if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
2203 if (putc('\\', fd) < 0)
2206 else if (c < ' ' || c > '~' || c == '|'
2207 || (what == 0 && c == ' ')
2208 || (what == 1 && str == strstart && c == ' ')
2209 || (what != 2 && c == '<'))
2211 if (putc(Ctrl_V, fd) < 0)
2214 if (putc(c, fd) < 0)
2221 * Check all mappings for the presence of special key codes.
2222 * Used after ":set term=xxx".
2225 check_map_keycodes(void)
2234 ESTACK_CHECK_DECLARATION
2237 // avoids giving error messages
2238 estack_push(ETYPE_INTERNAL, (char_u *)"mappings", 0);
2241 // Do this once for each buffer, and then once for global
2242 // mappings/abbreviations with bp == NULL
2243 for (bp = firstbuf; ; bp = bp->b_next)
2245 // Do the loop twice: Once for mappings, once for abbreviations.
2246 // Then loop over all map hash lists.
2247 for (abbr = 0; abbr <= 1; ++abbr)
2248 for (hash = 0; hash < 256; ++hash)
2252 if (hash) // there is only one abbr list
2255 mp = bp->b_first_abbr;
2262 mp = bp->b_maphash[hash];
2266 for ( ; mp != NULL; mp = mp->m_next)
2268 for (i = 0; i <= 1; ++i) // do this twice
2271 p = mp->m_keys; // once for the "from" part
2273 p = mp->m_str; // and once for the "to" part
2276 if (*p == K_SPECIAL)
2279 if (*p < 128) // for "normal" tcap entries
2284 (void)add_termcap_entry(buf, FALSE);
2300 #if defined(FEAT_EVAL) || defined(PROTO)
2302 * Check the string "keys" against the lhs of all mappings.
2303 * Return pointer to rhs of mapping (mapblock->m_str).
2304 * NULL when no mapping found.
2310 int exact, // require exact match
2311 int ign_mod, // ignore preceding modifier
2312 int abbr, // do abbreviations
2313 mapblock_T **mp_ptr, // return: pointer to mapblock or NULL
2314 int *local_ptr) // return: buffer-local mapping or NULL
2324 len = (int)STRLEN(keys);
2325 for (local = 1; local >= 0; --local)
2326 // loop over all hash lists
2327 for (hash = 0; hash < 256; ++hash)
2331 if (hash > 0) // there is only one list.
2334 mp = curbuf->b_first_abbr;
2339 mp = curbuf->b_maphash[hash];
2342 for ( ; mp != NULL; mp = mp->m_next)
2344 // skip entries with wrong mode, wrong length and not matching
2346 if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
2348 if (len > mp->m_keylen)
2349 minlen = mp->m_keylen;
2353 if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
2357 if (len > mp->m_keylen - 3)
2358 minlen = mp->m_keylen - 3;
2360 if (STRNCMP(s, keys, minlen) == 0)
2364 if (local_ptr != NULL)
2376 * "hasmapto()" function
2379 f_hasmapto(typval_T *argvars, typval_T *rettv)
2383 char_u buf[NUMBUFLEN];
2387 && (check_for_string_arg(argvars, 0) == FAIL
2388 || check_for_opt_string_arg(argvars, 1) == FAIL
2389 || (argvars[1].v_type != VAR_UNKNOWN
2390 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2393 name = tv_get_string(&argvars[0]);
2394 if (argvars[1].v_type == VAR_UNKNOWN)
2395 mode = (char_u *)"nvo";
2398 mode = tv_get_string_buf(&argvars[1], buf);
2399 if (argvars[2].v_type != VAR_UNKNOWN)
2400 abbr = (int)tv_get_bool(&argvars[2]);
2403 if (map_to_exists(name, mode, abbr))
2404 rettv->vval.v_number = TRUE;
2406 rettv->vval.v_number = FALSE;
2410 * Fill in the empty dictionary with items as defined by maparg builtin.
2416 char_u *lhsrawalt, // may be NULL
2417 int buffer_local, // false if not buffer local mapping
2418 int abbr) // true if abbreviation
2420 char_u *lhs = str2special_save(mp->m_keys, TRUE, FALSE);
2421 char_u *mapmode = map_mode_to_chars(mp->m_mode);
2423 dict_add_string(dict, "lhs", lhs);
2425 dict_add_string(dict, "lhsraw", mp->m_keys);
2427 // Also add the value for the simplified entry.
2428 dict_add_string(dict, "lhsrawalt", lhsrawalt);
2429 dict_add_string(dict, "rhs", mp->m_orig_str);
2430 dict_add_number(dict, "noremap", mp->m_noremap ? 1L : 0L);
2431 dict_add_number(dict, "script", mp->m_noremap == REMAP_SCRIPT
2433 dict_add_number(dict, "expr", mp->m_expr ? 1L : 0L);
2434 dict_add_number(dict, "silent", mp->m_silent ? 1L : 0L);
2435 dict_add_number(dict, "sid", (long)mp->m_script_ctx.sc_sid);
2436 dict_add_number(dict, "scriptversion",
2437 (long)mp->m_script_ctx.sc_version);
2438 dict_add_number(dict, "lnum", (long)mp->m_script_ctx.sc_lnum);
2439 dict_add_number(dict, "buffer", (long)buffer_local);
2440 dict_add_number(dict, "nowait", mp->m_nowait ? 1L : 0L);
2441 dict_add_string(dict, "mode", mapmode);
2442 dict_add_number(dict, "abbr", abbr ? 1L : 0L);
2443 dict_add_number(dict, "mode_bits", mp->m_mode);
2449 get_maparg(typval_T *argvars, typval_T *rettv, int exact)
2452 char_u *keys_simplified;
2454 char_u buf[NUMBUFLEN];
2455 char_u *keys_buf = NULL;
2456 char_u *alt_keys_buf = NULL;
2457 int did_simplify = FALSE;
2461 int get_dict = FALSE;
2462 mapblock_T *mp = NULL;
2464 int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
2466 // return empty string for failure
2467 rettv->v_type = VAR_STRING;
2468 rettv->vval.v_string = NULL;
2470 keys = tv_get_string(&argvars[0]);
2474 if (argvars[1].v_type != VAR_UNKNOWN)
2476 which = tv_get_string_buf_chk(&argvars[1], buf);
2477 if (argvars[2].v_type != VAR_UNKNOWN)
2479 abbr = (int)tv_get_bool(&argvars[2]);
2480 if (argvars[3].v_type != VAR_UNKNOWN)
2481 get_dict = (int)tv_get_bool(&argvars[3]);
2485 which = (char_u *)"";
2489 mode = get_map_mode(&which, 0);
2491 keys_simplified = replace_termcodes(keys, &keys_buf, flags, &did_simplify);
2492 rhs = check_map(keys_simplified, mode, exact, FALSE, abbr,
2493 &mp, &buffer_local);
2496 // When the lhs is being simplified the not-simplified keys are
2497 // preferred for printing, like in do_map().
2498 (void)replace_termcodes(keys, &alt_keys_buf,
2499 flags | REPTERM_NO_SIMPLIFY, NULL);
2500 rhs = check_map(alt_keys_buf, mode, exact, FALSE, abbr, &mp,
2510 rettv->vval.v_string = vim_strsave((char_u *)"<Nop>");
2512 rettv->vval.v_string = str2special_save(rhs, FALSE, FALSE);
2516 else if (rettv_dict_alloc(rettv) == OK && rhs != NULL)
2517 mapblock2dict(mp, rettv->vval.v_dict,
2518 did_simplify ? keys_simplified : NULL,
2519 buffer_local, abbr);
2522 vim_free(alt_keys_buf);
2526 * "maplist()" function
2529 f_maplist(typval_T *argvars UNUSED, typval_T *rettv)
2538 const int flags = REPTERM_FROM_PART | REPTERM_DO_LT;
2541 if (in_vim9script() && check_for_opt_bool_arg(argvars, 0) == FAIL)
2543 if (argvars[0].v_type != VAR_UNKNOWN)
2544 abbr = tv_get_bool(&argvars[0]);
2546 if (rettv_list_alloc(rettv) == FAIL)
2551 // Do it twice: once for global maps and once for local maps.
2552 for (buffer_local = 0; buffer_local <= 1; ++buffer_local)
2554 for (hash = 0; hash < 256; ++hash)
2558 if (hash > 0) // there is only one abbr list
2561 mp = curbuf->b_first_abbr;
2565 else if (buffer_local)
2566 mp = curbuf->b_maphash[hash];
2569 for (; mp; mp = mp->m_next)
2571 if (mp->m_simplified)
2573 if ((d = dict_alloc()) == NULL)
2575 if (list_append_dict(rettv->vval.v_list, d) == FAIL)
2579 did_simplify = FALSE;
2581 lhs = str2special_save(mp->m_keys, TRUE, FALSE);
2582 (void)replace_termcodes(lhs, &keys_buf, flags, &did_simplify);
2585 mapblock2dict(mp, d,
2586 did_simplify ? keys_buf : NULL,
2587 buffer_local, abbr);
2595 * "maparg()" function
2598 f_maparg(typval_T *argvars, typval_T *rettv)
2601 && (check_for_string_arg(argvars, 0) == FAIL
2602 || check_for_opt_string_arg(argvars, 1) == FAIL
2603 || (argvars[1].v_type != VAR_UNKNOWN
2604 && (check_for_opt_bool_arg(argvars, 2) == FAIL
2605 || (argvars[2].v_type != VAR_UNKNOWN
2606 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
2609 get_maparg(argvars, rettv, TRUE);
2613 * "mapcheck()" function
2616 f_mapcheck(typval_T *argvars, typval_T *rettv)
2619 && (check_for_string_arg(argvars, 0) == FAIL
2620 || check_for_opt_string_arg(argvars, 1) == FAIL
2621 || (argvars[1].v_type != VAR_UNKNOWN
2622 && check_for_opt_bool_arg(argvars, 2) == FAIL)))
2625 get_maparg(argvars, rettv, FALSE);
2629 * Get the mapping mode from the mode string.
2630 * It may contain multiple characters, eg "nox", or "!", or ' '
2631 * Return 0 if there is an error.
2634 get_map_mode_string(char_u *mode_string, int abbr)
2636 char_u *p = mode_string;
2640 const int MASK_V = MODE_VISUAL | MODE_SELECT;
2641 const int MASK_MAP = MODE_VISUAL | MODE_SELECT | MODE_NORMAL
2643 const int MASK_BANG = MODE_INSERT | MODE_CMDLINE;
2646 p = (char_u *)" "; // compatibility
2647 while ((modec = *p++))
2651 case 'i': tmode = MODE_INSERT; break;
2652 case 'l': tmode = MODE_LANGMAP; break;
2653 case 'c': tmode = MODE_CMDLINE; break;
2654 case 'n': tmode = MODE_NORMAL; break;
2655 case 'x': tmode = MODE_VISUAL; break;
2656 case 's': tmode = MODE_SELECT; break;
2657 case 'o': tmode = MODE_OP_PENDING; break;
2658 case 't': tmode = MODE_TERMINAL; break;
2659 case 'v': tmode = MASK_V; break;
2660 case '!': tmode = MASK_BANG; break;
2661 case ' ': tmode = MASK_MAP; break;
2663 return 0; // error, unknown mode character
2667 if ((abbr && (mode & ~MASK_BANG) != 0)
2668 || (!abbr && (mode & (mode-1)) != 0 // more than one bit set
2670 // false if multiple bits set in mode and mode is fully
2671 // contained in one mask
2672 !(((mode & MASK_BANG) != 0 && (mode & ~MASK_BANG) == 0)
2673 || ((mode & MASK_MAP) != 0 && (mode & ~MASK_MAP) == 0)))))
2680 * "mapset()" function
2683 f_mapset(typval_T *argvars, typval_T *rettv UNUSED)
2687 char_u buf[NUMBUFLEN];
2695 char_u *arg_buf = NULL;
2703 mapblock_T **map_table = maphash;
2704 mapblock_T **abbr_table = &first_abbr;
2709 // If first arg is a dict, then that's the only arg permitted.
2710 dict_only = argvars[0].v_type == VAR_DICT;
2712 && (check_for_string_or_dict_arg(argvars, 0) == FAIL
2713 || (dict_only && check_for_unknown_arg(argvars, 1) == FAIL)
2715 && (check_for_string_arg(argvars, 0) == FAIL
2716 || check_for_bool_arg(argvars, 1) == FAIL
2717 || check_for_dict_arg(argvars, 2) == FAIL))))
2722 d = argvars[0].vval.v_dict;
2723 which = dict_get_string(d, "mode", FALSE);
2724 is_abbr = dict_get_bool(d, "abbr", -1);
2725 if (which == NULL || is_abbr < 0)
2727 emsg(_(e_entries_missing_in_mapset_dict_argument));
2733 which = tv_get_string_buf_chk(&argvars[0], buf);
2736 is_abbr = (int)tv_get_bool(&argvars[1]);
2738 if (check_for_dict_arg(argvars, 2) == FAIL)
2740 d = argvars[2].vval.v_dict;
2742 mode = get_map_mode_string(which, is_abbr);
2745 semsg(_(e_illegal_map_mode_string_str), which);
2750 // Get the values in the same order as above in get_maparg().
2751 lhs = dict_get_string(d, "lhs", FALSE);
2752 lhsraw = dict_get_string(d, "lhsraw", FALSE);
2753 lhsrawalt = dict_get_string(d, "lhsrawalt", FALSE);
2754 rhs = dict_get_string(d, "rhs", FALSE);
2755 if (lhs == NULL || lhsraw == NULL || rhs == NULL)
2757 emsg(_(e_entries_missing_in_mapset_dict_argument));
2761 if (STRICMP(rhs, "<nop>") == 0) // "<Nop>" means nothing
2764 rhs = replace_termcodes(rhs, &arg_buf,
2765 REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
2767 noremap = dict_get_number(d, "noremap") ? REMAP_NONE: 0;
2768 if (dict_get_number(d, "script") != 0)
2769 noremap = REMAP_SCRIPT;
2770 expr = dict_get_number(d, "expr") != 0;
2771 silent = dict_get_number(d, "silent") != 0;
2772 sid = dict_get_number(d, "sid");
2773 scriptversion = dict_get_number(d, "scriptversion");
2774 lnum = dict_get_number(d, "lnum");
2775 buffer = dict_get_number(d, "buffer");
2776 nowait = dict_get_number(d, "nowait") != 0;
2777 // mode from the dict is not used
2781 map_table = curbuf->b_maphash;
2782 abbr_table = &curbuf->b_first_abbr;
2785 // Delete any existing mapping for this lhs and mode.
2788 arg = alloc(STRLEN(lhs) + STRLEN("<buffer>") + 1);
2791 STRCPY(arg, "<buffer>");
2792 STRCPY(arg + 8, lhs);
2796 arg = vim_strsave(lhs);
2800 do_map(MAPTYPE_UNMAP, arg, mode, is_abbr);
2803 (void)map_add(map_table, abbr_table, lhsraw, rhs, orig_rhs, noremap,
2804 nowait, silent, mode, is_abbr, expr, sid, scriptversion, lnum, 0);
2805 if (lhsrawalt != NULL)
2806 (void)map_add(map_table, abbr_table, lhsrawalt, rhs, orig_rhs, noremap,
2807 nowait, silent, mode, is_abbr, expr, sid, scriptversion,
2814 #if defined(MSWIN) || defined(MACOS_X)
2816 # define VIS_SEL (MODE_VISUAL | MODE_SELECT) // abbreviation
2819 * Default mappings for some often used keys.
2827 # ifdef FEAT_GUI_MSWIN
2828 // Use the Windows (CUA) keybindings. (GUI)
2829 static struct initmap initmappings[] =
2831 // paste, copy and cut
2832 {(char_u *)"<S-Insert> \"*P", MODE_NORMAL},
2833 {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
2834 {(char_u *)"<S-Insert> <C-R><C-O>*", MODE_INSERT | MODE_CMDLINE},
2835 {(char_u *)"<C-Insert> \"*y", VIS_SEL},
2836 {(char_u *)"<S-Del> \"*d", VIS_SEL},
2837 {(char_u *)"<C-Del> \"*d", VIS_SEL},
2838 {(char_u *)"<C-X> \"*d", VIS_SEL},
2839 // Missing: CTRL-C (cancel) and CTRL-V (block selection)
2843 # if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
2844 // Use the Windows (CUA) keybindings. (Console)
2845 static struct initmap cinitmappings[] =
2847 {(char_u *)"\316w <C-Home>", MODE_NORMAL | VIS_SEL},
2848 {(char_u *)"\316w <C-Home>", MODE_INSERT | MODE_CMDLINE},
2849 {(char_u *)"\316u <C-End>", MODE_NORMAL | VIS_SEL},
2850 {(char_u *)"\316u <C-End>", MODE_INSERT | MODE_CMDLINE},
2852 // paste, copy and cut
2853 # ifdef FEAT_CLIPBOARD
2854 {(char_u *)"\316\324 \"*P", MODE_NORMAL}, // SHIFT-Insert is "*P
2855 {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, // SHIFT-Insert is "-d"*P
2856 {(char_u *)"\316\324 \022\017*", MODE_INSERT}, // SHIFT-Insert is ^R^O*
2857 {(char_u *)"\316\325 \"*y", VIS_SEL}, // CTRL-Insert is "*y
2858 {(char_u *)"\316\327 \"*d", VIS_SEL}, // SHIFT-Del is "*d
2859 {(char_u *)"\316\330 \"*d", VIS_SEL}, // CTRL-Del is "*d
2860 {(char_u *)"\030 \"*d", VIS_SEL}, // CTRL-X is "*d
2862 {(char_u *)"\316\324 P", MODE_NORMAL}, // SHIFT-Insert is P
2863 {(char_u *)"\316\324 \"-dP", VIS_SEL}, // SHIFT-Insert is "-dP
2864 {(char_u *)"\316\324 \022\017\"", MODE_INSERT}, // SHIFT-Insert is ^R^O"
2865 {(char_u *)"\316\325 y", VIS_SEL}, // CTRL-Insert is y
2866 {(char_u *)"\316\327 d", VIS_SEL}, // SHIFT-Del is d
2867 {(char_u *)"\316\330 d", VIS_SEL}, // CTRL-Del is d
2872 # if defined(MACOS_X)
2873 static struct initmap initmappings[] =
2875 // Use the Standard MacOS binding.
2876 // paste, copy and cut
2877 {(char_u *)"<D-v> \"*P", MODE_NORMAL},
2878 {(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
2879 {(char_u *)"<D-v> <C-R>*", MODE_INSERT | MODE_CMDLINE},
2880 {(char_u *)"<D-c> \"*y", VIS_SEL},
2881 {(char_u *)"<D-x> \"*d", VIS_SEL},
2882 {(char_u *)"<Backspace> \"-d", VIS_SEL},
2890 * Set up default mappings.
2895 #if defined(MSWIN) || defined(MACOS_X)
2898 # if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2903 for (i = 0; i < (int)ARRAY_LENGTH(cinitmappings); ++i)
2904 add_map(cinitmappings[i].arg, cinitmappings[i].mode, FALSE);
2907 # if defined(FEAT_GUI_MSWIN) || defined(MACOS_X)
2908 for (i = 0; i < (int)ARRAY_LENGTH(initmappings); ++i)
2909 add_map(initmappings[i].arg, initmappings[i].mode, FALSE);
2915 * Add a mapping "map" for mode "mode".
2916 * When "nore" is TRUE use MAPTYPE_NOREMAP.
2917 * Need to put string in allocated memory, because do_map() will modify it.
2920 add_map(char_u *map, int mode, int nore)
2923 char_u *cpo_save = p_cpo;
2925 p_cpo = empty_option; // Allow <> notation
2926 s = vim_strsave(map);
2929 (void)do_map(nore ? MAPTYPE_NOREMAP : MAPTYPE_MAP, s, mode, FALSE);
2935 #if defined(FEAT_LANGMAP) || defined(PROTO)
2937 * Any character has an equivalent 'langmap' character. This is used for
2938 * keyboards that have a special language mode that sends characters above
2939 * 128 (although other characters can be translated too). The "to" field is a
2940 * Vim command character. This avoids having to switch the keyboard back to
2941 * ASCII mode when leaving Insert mode.
2943 * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim
2945 * langmap_mapga.ga_data is a sorted table of langmap_entry_T. This does the
2946 * same as langmap_mapchar[] for characters >= 256.
2948 * Use growarray for 'langmap' chars >= 256
2956 static garray_T langmap_mapga;
2959 * Search for an entry in "langmap_mapga" for "from". If found set the "to"
2960 * field. If not found insert a new entry at the appropriate location.
2963 langmap_set_entry(int from, int to)
2965 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
2967 int b = langmap_mapga.ga_len;
2969 // Do a binary search for an existing entry.
2972 int i = (a + b) / 2;
2973 int d = entries[i].from - from;
2986 if (ga_grow(&langmap_mapga, 1) == FAIL)
2987 return; // out of memory
2989 // insert new entry at position "a"
2990 entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a;
2991 mch_memmove(entries + 1, entries,
2992 (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T));
2993 ++langmap_mapga.ga_len;
2994 entries[0].from = from;
2999 * Apply 'langmap' to multi-byte character "c" and return the result.
3002 langmap_adjust_mb(int c)
3004 langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data);
3006 int b = langmap_mapga.ga_len;
3010 int i = (a + b) / 2;
3011 int d = entries[i].from - c;
3014 return entries[i].to; // found matching entry
3020 return c; // no entry found, return "c" unmodified
3028 for (i = 0; i < 256; i++)
3029 langmap_mapchar[i] = i; // we init with a one-to-one map
3030 ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8);
3034 * Called when langmap option is set; the language map can be
3035 * changed at any time!
3038 did_set_langmap(optset_T *args UNUSED)
3044 ga_clear(&langmap_mapga); // clear the previous map first
3045 langmap_init(); // back to one-to-one map
3047 for (p = p_langmap; p[0] != NUL; )
3049 for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';';
3052 if (p2[0] == '\\' && p2[1] != NUL)
3056 ++p2; // abcd;ABCD form, p2 points to A
3058 p2 = NULL; // aAbBcCdD form, p2 is NULL
3066 if (p[0] == '\\' && p[1] != NUL)
3068 from = (*mb_ptr2char)(p);
3077 to = (*mb_ptr2char)(p);
3086 to = (*mb_ptr2char)(p2);
3091 // TODO: Need to use errbuf argument for this error message
3093 semsg(_(e_langmap_matching_character_missing_for_str),
3099 langmap_set_entry(from, to);
3101 langmap_mapchar[from & 255] = to;
3103 // Advance to next pair
3115 // TODO: Need to use errbuf argument for this error
3116 // message and return it.
3117 semsg(_(e_langmap_extra_characters_after_semicolon_str), p);
3133 do_exmap(exarg_T *eap, int isabbrev)
3139 mode = get_map_mode(&cmdp, eap->forceit || isabbrev);
3141 switch (do_map(*cmdp == 'n' ? MAPTYPE_NOREMAP
3142 : *cmdp == 'u' ? MAPTYPE_UNMAP : MAPTYPE_MAP,
3143 eap->arg, mode, isabbrev))
3145 case 1: emsg(_(e_invalid_argument));
3147 case 2: emsg((isabbrev ? _(e_no_such_abbreviation)
3148 : _(e_no_such_mapping)));
3154 * ":abbreviate" and friends.
3157 ex_abbreviate(exarg_T *eap)
3159 do_exmap(eap, TRUE); // almost the same as mapping
3163 * ":map" and friends.
3166 ex_map(exarg_T *eap)
3168 // If we are sourcing .exrc or .vimrc in current directory we
3169 // print the mappings for security reasons.
3173 msg_outtrans(eap->cmd);
3176 do_exmap(eap, FALSE);
3180 * ":unmap" and friends.
3183 ex_unmap(exarg_T *eap)
3185 do_exmap(eap, FALSE);
3189 * ":mapclear" and friends.
3192 ex_mapclear(exarg_T *eap)
3194 map_clear(eap->cmd, eap->arg, eap->forceit, FALSE);
3198 * ":abclear" and friends.
3201 ex_abclear(exarg_T *eap)
3203 map_clear(eap->cmd, eap->arg, TRUE, TRUE);