robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// mapping.c: Code for mappings and abbreviations. 2 3#include <assert.h> 4#include <lauxlib.h> 5#include <limits.h> 6#include <stdbool.h> 7#include <stdint.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11 12#include "klib/kvec.h" 13#include "nvim/api/keysets_defs.h" 14#include "nvim/api/private/converter.h" 15#include "nvim/api/private/defs.h" 16#include "nvim/api/private/dispatch.h" 17#include "nvim/api/private/helpers.h" 18#include "nvim/ascii_defs.h" 19#include "nvim/buffer_defs.h" 20#include "nvim/charset.h" 21#include "nvim/cmdexpand.h" 22#include "nvim/cmdexpand_defs.h" 23#include "nvim/errors.h" 24#include "nvim/eval.h" 25#include "nvim/eval/typval.h" 26#include "nvim/eval/typval_defs.h" 27#include "nvim/eval/userfunc.h" 28#include "nvim/eval/vars.h" 29#include "nvim/ex_cmds.h" 30#include "nvim/ex_cmds_defs.h" 31#include "nvim/ex_session.h" 32#include "nvim/fuzzy.h" 33#include "nvim/garray.h" 34#include "nvim/garray_defs.h" 35#include "nvim/gettext_defs.h" 36#include "nvim/globals.h" 37#include "nvim/highlight_defs.h" 38#include "nvim/input.h" 39#include "nvim/input_defs.h" 40#include "nvim/keycodes.h" 41#include "nvim/lua/executor.h" 42#include "nvim/macros_defs.h" 43#include "nvim/mapping.h" 44#include "nvim/mapping_defs.h" 45#include "nvim/mbyte.h" 46#include "nvim/mbyte_defs.h" 47#include "nvim/memory.h" 48#include "nvim/memory_defs.h" 49#include "nvim/message.h" 50#include "nvim/option.h" 51#include "nvim/option_defs.h" 52#include "nvim/option_vars.h" 53#include "nvim/pos_defs.h" 54#include "nvim/regexp.h" 55#include "nvim/regexp_defs.h" 56#include "nvim/runtime.h" 57#include "nvim/state_defs.h" 58#include "nvim/strings.h" 59#include "nvim/types_defs.h" 60#include "nvim/ui.h" 61#include "nvim/ui_defs.h" 62#include "nvim/vim_defs.h" 63 64/// Global abbreviations (first entry in the linkedlist). 65static mapblock_T * first_abbr = NULL ; 66 67/// Global mappings. 68/// Each mapping is put in one of the MAX_MAPHASH hash lists, to speed up finding it. 69static mapblock_T * (maphash [MAX_MAPHASH ])= {0 }; 70 71// Make a hash value for a mapping. 72// "mode" is the lower 4 bits of the State for the mapping. 73// "c1" is the first character of the "lhs". 74// Returns a value between 0 and 255, index in maphash. 75// Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode. 76#define MAP_HASH (mode , \ 77c1 ) (((mode) & \ 78 (MODE_NORMAL | MODE_VISUAL | MODE_SELECT | \ 79 MODE_OP_PENDING | MODE_TERMINAL)) ? (c1) : ((c1) ^ 0x80)) 80 81/// All possible |:map-arguments| usable in a |:map| command. 82/// 83/// The <special> argument has no effect on mappings and is excluded from this 84/// struct declaration. |:noremap| is included, since it behaves like a map 85/// argument when used in a mapping. 86/// 87/// @see mapblock_T 88struct map_arguments { 89bool buffer ; 90bool expr ; 91bool noremap ; 92bool nowait ; 93bool script ; 94bool silent ; 95bool unique ; 96bool replace_keycodes ; 97 98/// The {lhs} of the mapping. 99/// 100/// vim limits this to MAXMAPLEN characters, allowing us to use a static 101/// buffer. Setting lhs_len to a value larger than MAXMAPLEN can signal 102/// that {lhs} was too long and truncated. 103char lhs [MAXMAPLEN + 1 ]; 104size_t lhs_len ; 105 106/// Unsimplifed {lhs} of the mapping. If no simplification has been done then alt_lhs_len is 0. 107char alt_lhs [MAXMAPLEN + 1 ]; 108size_t alt_lhs_len ; 109 110char * rhs ;///< The {rhs} of the mapping. 111size_t rhs_len ; 112LuaRef rhs_lua ;///< lua function as {rhs} 113bool rhs_is_noop ;///< True when the {rhs} should be <Nop>. 114 115char * orig_rhs ;///< The original text of the {rhs}. 116size_t orig_rhs_len ; 117char * desc ;///< map description 118}; 119typedef struct map_arguments MapArguments ; 120#define MAP_ARGUMENTS_INIT { false, false, false, false, false, false, false, false, \ 121 { 0 }, 0, { 0 }, 0, NULL, 0, LUA_NOREF, false, NULL, 0, NULL } 122 123#include "mapping.c.generated.h" 124 125static const char e_global_abbreviation_already_exists_for_str [] 126= N_ ("E224: Global abbreviation already exists for %s" ); 127static const char e_global_mapping_already_exists_for_str [] 128= N_ ("E225: Global mapping already exists for %s" ); 129static const char e_abbreviation_already_exists_for_str [] 130= N_ ("E226: Abbreviation already exists for %s" ); 131static const char e_mapping_already_exists_for_str [] 132= N_ ("E227: Mapping already exists for %s" ); 133static const char e_entries_missing_in_mapset_dict_argument [] 134= N_ ("E460: Entries missing in mapset() dict argument" ); 135static const char e_illegal_map_mode_string_str [] 136= N_ ("E1276: Illegal map mode string: '%s'" ); 137 138/// Get the start of the hashed map list for "state" and first character "c". 139mapblock_T * get_maphash_list (int state ,int c ) 140{ 141return maphash [MAP_HASH (state ,c )]; 142} 143 144/// Get the buffer-local hashed map list for "state" and first character "c". 145mapblock_T * get_buf_maphash_list (int state ,int c ) 146{ 147return curbuf -> b_maphash [MAP_HASH (state ,c )]; 148} 149 150/// Finds the Lua mapping whose `m_str` embeds `id`. 151static mapblock_T * map_luaid_scan (mapblock_T * const * mappings ,size_t size ,int id ) 152{ 153for (size_t i = 0 ;i < size ;i ++ ) { 154for (mapblock_T * mp = mappings [i ];mp != NULL ;mp = mp -> m_next ) { 155// Find `id` in "<K_LUA><id><CR>". 156if (mp -> m_luaref != LUA_NOREF && atoi (mp -> m_str + 3 )== id ) { 157return mp ; 158 } 159 } 160 } 161return NULL ; 162} 163 164/// Resolves a Lua-mapping id to its callback. 165/// 166/// @return Lua callback, or LUA_NOREF if the mapping no longer exists. 167LuaRef map_luaid_get (int n ) 168{ 169mapblock_T * mp = map_luaid_scan (maphash ,MAX_MAPHASH ,n ); 170mp = mp != NULL ?mp :map_luaid_scan (& first_abbr ,1 ,n ); 171FOR_ALL_BUFFERS (fb ) { 172mp = mp != NULL ?mp :map_luaid_scan (fb -> b_maphash ,MAX_MAPHASH ,n ); 173mp = mp != NULL ?mp :map_luaid_scan (& fb -> b_first_abbr ,1 ,n ); 174 } 175return mp != NULL ?mp -> m_luaref :LUA_NOREF ; 176} 177 178/// Delete one entry from the abbrlist or maphash[]. 179/// "mpp" is a pointer to the m_next field of the PREVIOUS entry! 180static void mapblock_free (mapblock_T ** mpp ) 181{ 182mapblock_T * mp = * mpp ; 183xfree (mp -> m_keys ); 184if (mp -> m_alt != NULL ) { 185mp -> m_alt -> m_alt = NULL ; 186 }else { 187NLUA_CLEAR_REF (mp -> m_luaref ); 188xfree (mp -> m_str ); 189xfree (mp -> m_orig_str ); 190xfree (mp -> m_desc ); 191 } 192* mpp = mp -> m_next ; 193xfree (mp ); 194} 195 196/// put characters to represent the map mode in a string buffer 197/// 198/// @param[out] buf must be at least 7 bytes (including NUL) 199void map_mode_to_chars (int mode ,char * buf ) 200FUNC_ATTR_NONNULL_ALL 201{ 202char * p = buf ; 203if ((mode & (MODE_INSERT |MODE_CMDLINE ))== (MODE_INSERT |MODE_CMDLINE )) { 204* p ++ = '!' ;// :map! 205 }else if (mode & MODE_INSERT ) { 206* p ++ = 'i' ;// :imap 207 }else if (mode & MODE_LANGMAP ) { 208* p ++ = 'l' ;// :lmap 209 }else if (mode & MODE_CMDLINE ) { 210* p ++ = 'c' ;// :cmap 211 }else if ((mode & (MODE_NORMAL |MODE_VISUAL |MODE_SELECT |MODE_OP_PENDING )) 212== (MODE_NORMAL |MODE_VISUAL |MODE_SELECT |MODE_OP_PENDING )) { 213* p ++ = ' ' ;// :map 214 }else { 215if (mode & MODE_NORMAL ) { 216* p ++ = 'n' ;// :nmap 217 } 218if (mode & MODE_OP_PENDING ) { 219* p ++ = 'o' ;// :omap 220 } 221if (mode & MODE_TERMINAL ) { 222* p ++ = 't' ;// :tmap 223 } 224if ((mode & (MODE_VISUAL |MODE_SELECT ))== (MODE_VISUAL |MODE_SELECT )) { 225* p ++ = 'v' ;// :vmap 226 }else { 227if (mode & MODE_VISUAL ) { 228* p ++ = 'x' ;// :xmap 229 } 230if (mode & MODE_SELECT ) { 231* p ++ = 's' ;// :smap 232 } 233 } 234 } 235 236* p = NUL ; 237} 238 239/// @param local true for buffer-local map 240static void showmap (mapblock_T * mp ,bool local ) 241{ 242if (message_filtered (mp -> m_keys )&& message_filtered (mp -> m_str ) 243&& (mp -> m_desc == NULL || message_filtered (mp -> m_desc ))) { 244return ; 245 } 246 247if (msg_col > 0 || msg_silent != 0 ) { 248msg_putchar ('\n' ); 249if (got_int ) {// 'q' typed at MORE prompt 250return ; 251 } 252 } 253 254char mapchars [7 ]; 255map_mode_to_chars (mp -> m_mode ,mapchars ); 256msg_puts (mapchars ); 257size_t len = strlen (mapchars ); 258 259while (++ len <=3 ) { 260msg_putchar (' ' ); 261 } 262 263// Display the LHS. Get length of what we write. 264len = (size_t )msg_outtrans_special (mp -> m_keys , true,0 ); 265do { 266msg_putchar (' ' );// pad with blanks 267len ++ ; 268 }while (len < 12 ); 269 270if (mp -> m_noremap == REMAP_NONE ) { 271msg_puts_hl ("*" ,HLF_8 , false); 272 }else if (mp -> m_noremap == REMAP_SCRIPT ) { 273msg_puts_hl ("&" ,HLF_8 , false); 274 }else { 275msg_putchar (' ' ); 276 } 277 278if (local ) { 279msg_putchar ('@' ); 280 }else { 281msg_putchar (' ' ); 282 } 283 284// Use false below if we only want things like <Up> to show up as such on 285// the rhs, and not M-x etc, true gets both -- webb 286if (mp -> m_luaref != LUA_NOREF ) { 287char * str = nlua_funcref_str (mp -> m_luaref ,NULL , true); 288msg_puts_hl (str ,HLF_8 , false); 289xfree (str ); 290 }else if (mp -> m_str [0 ]== NUL ) { 291msg_puts_hl ("<Nop>" ,HLF_8 , false); 292 }else { 293msg_outtrans_special (mp -> m_str , false,0 ); 294 } 295 296if (mp -> m_desc != NULL ) { 297msg_puts ("\n " );// Shift line to same level as rhs. 298msg_puts (mp -> m_desc ); 299 } 300if (p_verbose > 0 ) { 301last_set_msg (mp -> m_script_ctx ); 302 } 303msg_clr_eos (); 304} 305 306/// Replace termcodes in the given LHS and RHS and store the results into the 307/// `lhs` and `rhs` of the given @ref MapArguments struct. 308/// 309/// `rhs` and `orig_rhs` will both point to new allocated buffers. `orig_rhs` 310/// will hold a copy of the given `orig_rhs`. 311/// 312/// The `*_len` variables will be set appropriately. If the length of 313/// the final `lhs` exceeds `MAXMAPLEN`, `lhs_len` will be set equal to the 314/// original larger length and `lhs` will be truncated. 315/// 316/// If RHS should be <Nop>, `rhs` will be an empty string, `rhs_len` will be 317/// zero, and `rhs_is_noop` will be set to true. 318/// 319/// Any memory allocated by @ref replace_termcodes is freed before this function 320/// returns. 321/// 322/// @param[in] orig_lhs Original mapping LHS, with characters to replace. 323/// @param[in] orig_lhs_len `strlen` of orig_lhs. 324/// @param[in] orig_rhs Original mapping RHS, with characters to replace. 325/// @param[in] rhs_lua Lua reference for Lua mappings. 326/// @param[in] orig_rhs_len `strlen` of orig_rhs. 327/// @param[in] cpo_val See param docs for @ref replace_termcodes. 328/// @param[out] mapargs MapArguments struct holding the replaced strings. 329static bool set_maparg_lhs_rhs (const char * const orig_lhs ,const size_t orig_lhs_len , 330const char * const orig_rhs ,const size_t orig_rhs_len , 331const LuaRef rhs_lua ,const char * const cpo_val , 332MapArguments * const mapargs ) 333{ 334mapargs -> rhs_lua = rhs_lua ; 335char lhs_buf [128 ]; 336 337// If mapping has been given as ^V<C_UP> say, then replace the term codes 338// with the appropriate two bytes. If it is a shifted special key, unshift 339// it too, giving another two bytes. 340// 341// replace_termcodes() may move the result to allocated memory, which 342// needs to be freed later (*lhs_buf and *rhs_buf). 343// replace_termcodes() also removes CTRL-Vs and sometimes backslashes. 344// If something like <C-H> is simplified to 0x08 then mark it as simplified 345// and also add en entry with a modifier. 346bool did_simplify = false; 347const int flags = REPTERM_FROM_PART |REPTERM_DO_LT ; 348char * bufarg = lhs_buf ; 349char * replaced = replace_termcodes (orig_lhs ,orig_lhs_len ,& bufarg ,0 , 350flags ,& did_simplify ,cpo_val ); 351if (replaced == NULL ) { 352return false; 353 } 354mapargs -> lhs_len = strlen (replaced ); 355xstrlcpy (mapargs -> lhs ,replaced ,sizeof (mapargs -> lhs )); 356if (did_simplify ) { 357replaced = replace_termcodes (orig_lhs ,orig_lhs_len ,& bufarg ,0 , 358flags |REPTERM_NO_SIMPLIFY ,NULL ,cpo_val ); 359if (replaced == NULL ) { 360return false; 361 } 362mapargs -> alt_lhs_len = strlen (replaced ); 363xstrlcpy (mapargs -> alt_lhs ,replaced ,sizeof (mapargs -> alt_lhs )); 364 }else { 365mapargs -> alt_lhs_len = 0 ; 366 } 367 368set_maparg_rhs (orig_rhs ,orig_rhs_len ,rhs_lua ,0 ,cpo_val ,mapargs ); 369 370return true; 371} 372 373/// @see set_maparg_lhs_rhs 374static void set_maparg_rhs (const char * const orig_rhs ,const size_t orig_rhs_len , 375const LuaRef rhs_lua ,const scid_T sid ,const char * const cpo_val , 376MapArguments * const mapargs ) 377{ 378mapargs -> rhs_lua = rhs_lua ; 379 380if (rhs_lua == LUA_NOREF ) { 381mapargs -> orig_rhs_len = orig_rhs_len ; 382mapargs -> orig_rhs = xcalloc (mapargs -> orig_rhs_len + 1 ,sizeof (char )); 383xmemcpyz (mapargs -> orig_rhs ,orig_rhs ,mapargs -> orig_rhs_len ); 384if (STRICMP (orig_rhs ,"<nop>" )== 0 ) {// "<Nop>" means nothing 385mapargs -> rhs = xcalloc (1 ,sizeof (char ));// single NUL-char 386mapargs -> rhs_len = 0 ; 387mapargs -> rhs_is_noop = true; 388 }else { 389char * rhs_buf = NULL ; 390char * replaced = replace_termcodes (orig_rhs ,orig_rhs_len ,& rhs_buf ,sid , 391REPTERM_DO_LT ,NULL ,cpo_val ); 392mapargs -> rhs_len = strlen (replaced ); 393// NB: replace_termcodes may produce an empty string even if orig_rhs is non-empty 394// (e.g. a single ^V, see :h map-empty-rhs) 395mapargs -> rhs_is_noop = orig_rhs_len != 0 && mapargs -> rhs_len == 0 ; 396mapargs -> rhs = replaced ; 397 } 398 }else { 399char tmp_buf [64 ]; 400// orig_rhs is not used for Lua mappings, but still needs to be a string. 401mapargs -> orig_rhs = xcalloc (1 ,sizeof (char )); 402mapargs -> orig_rhs_len = 0 ; 403// Stores "<K_LUA><lua-mapping-id><CR>" in map_str. 404static int map_luaid = 0 ; 405mapargs -> rhs_len = (size_t )vim_snprintf (S_LEN (tmp_buf ),"%c%c%c%d\r" ,K_SPECIAL , 406KS_EXTRA ,KE_LUA ,++ map_luaid ); 407mapargs -> rhs = xstrdup (tmp_buf ); 408 } 409} 410 411/// Parse a string of |:map-arguments| into a @ref MapArguments struct. 412/// 413/// Termcodes, backslashes, CTRL-V's, etc. inside the extracted {lhs} and 414/// {rhs} are replaced by @ref set_maparg_lhs_rhs. 415/// 416/// rhs and orig_rhs in the returned mapargs will be set to null or a pointer 417/// to allocated memory and should be freed even on error. 418/// 419/// @param[in] strargs String of map args, e.g. "<buffer> <expr><silent>". 420/// May contain leading or trailing whitespace. 421/// @param[in] is_unmap True, if strargs should be parsed like an |:unmap| 422/// command. |:unmap| commands interpret *all* text to the 423/// right of the last map argument as the {lhs} of the 424/// mapping, i.e. a literal ' ' character is treated like 425/// a "<space>", rather than separating the {lhs} from the 426/// {rhs}. 427/// @param[out] mapargs MapArguments struct holding all extracted argument 428/// values. 429/// @return 0 on success, 1 if invalid arguments are detected. 430static int str_to_mapargs (const char * strargs ,bool is_unmap ,MapArguments * mapargs ) 431{ 432const char * to_parse = strargs ; 433to_parse = skipwhite (to_parse ); 434CLEAR_POINTER (mapargs ); 435 436// Accept <buffer>, <nowait>, <silent>, <expr>, <script>, and <unique> in 437// any order. 438while (true) { 439if (strncmp (to_parse ,"<buffer>" ,8 )== 0 ) { 440to_parse = skipwhite (to_parse + 8 ); 441mapargs -> buffer = true; 442continue ; 443 } 444 445if (strncmp (to_parse ,"<nowait>" ,8 )== 0 ) { 446to_parse = skipwhite (to_parse + 8 ); 447mapargs -> nowait = true; 448continue ; 449 } 450 451if (strncmp (to_parse ,"<silent>" ,8 )== 0 ) { 452to_parse = skipwhite (to_parse + 8 ); 453mapargs -> silent = true; 454continue ; 455 } 456 457// Ignore obsolete "<special>" modifier. 458if (strncmp (to_parse ,"<special>" ,9 )== 0 ) { 459to_parse = skipwhite (to_parse + 9 ); 460continue ; 461 } 462 463if (strncmp (to_parse ,"<script>" ,8 )== 0 ) { 464to_parse = skipwhite (to_parse + 8 ); 465mapargs -> script = true; 466continue ; 467 } 468 469if (strncmp (to_parse ,"<expr>" ,6 )== 0 ) { 470to_parse = skipwhite (to_parse + 6 ); 471mapargs -> expr = true; 472continue ; 473 } 474 475if (strncmp (to_parse ,"<unique>" ,8 )== 0 ) { 476to_parse = skipwhite (to_parse + 8 ); 477mapargs -> unique = true; 478continue ; 479 } 480break ; 481 } 482 483// Find the next whitespace character, call that the end of {lhs}. 484// 485// If a character (e.g. whitespace) is immediately preceded by a CTRL-V, 486// "scan past" that character, i.e. don't "terminate" LHS with that character 487// if it's whitespace. 488// 489// Treat backslash like CTRL-V when 'cpoptions' does not contain 'B'. 490// 491// With :unmap, literal white space is included in the {lhs}; there is no 492// separate {rhs}. 493const char * lhs_end = to_parse ; 494bool do_backslash = (vim_strchr (p_cpo ,kCpoBslash )== NULL ); 495while (* lhs_end && (is_unmap || !ascii_iswhite (* lhs_end ))) { 496if ((lhs_end [0 ]== Ctrl_V || (do_backslash && lhs_end [0 ]== '\\' )) 497&& lhs_end [1 ]!= NUL ) { 498lhs_end ++ ;// skip CTRL-V or backslash 499 } 500lhs_end ++ ; 501 } 502 503// {lhs_end} is a pointer to the "terminating whitespace" after {lhs}. 504// Use that to initialize {rhs_start}. 505const char * rhs_start = skipwhite (lhs_end ); 506 507// Given {lhs} might be larger than MAXMAPLEN before replace_termcodes 508// (e.g. "<Space>" is longer than ' '), so first copy into a buffer. 509size_t orig_lhs_len = (size_t )(lhs_end - to_parse ); 510if (orig_lhs_len >=256 ) { 511return 1 ; 512 } 513char lhs_to_replace [256 ]; 514xmemcpyz (lhs_to_replace ,to_parse ,orig_lhs_len ); 515 516size_t orig_rhs_len = strlen (rhs_start ); 517if (!set_maparg_lhs_rhs (lhs_to_replace ,orig_lhs_len , 518rhs_start ,orig_rhs_len ,LUA_NOREF , 519p_cpo ,mapargs )) { 520return 1 ; 521 } 522 523if (mapargs -> lhs_len > MAXMAPLEN ) { 524return 1 ; 525 } 526return 0 ; 527} 528 529/// @param args "rhs", "rhs_lua", "orig_rhs", "expr", "silent", "nowait", 530/// "replace_keycodes" and "desc" fields are used. 531/// @param sid 0 to use current_sctx 532static mapblock_T * map_add (buf_T * buf ,mapblock_T ** map_table ,mapblock_T ** abbr_table , 533const char * keys ,MapArguments * args ,int noremap ,int mode , 534bool is_abbr ,scid_T sid ,linenr_T lnum ,bool simplified ) 535FUNC_ATTR_NONNULL_RET 536{ 537mapblock_T * mp = xcalloc (1 ,sizeof (mapblock_T )); 538 539// If CTRL-C has been mapped, don't always use it for Interrupting. 540if (* keys == Ctrl_C ) { 541if (map_table == buf -> b_maphash ) { 542buf -> b_mapped_ctrl_c |=mode ; 543 }else { 544mapped_ctrl_c |=mode ; 545 } 546 } 547 548mp -> m_keys = xstrdup (keys ); 549mp -> m_str = args -> rhs ; 550mp -> m_orig_str = args -> orig_rhs ; 551mp -> m_luaref = args -> rhs_lua ; 552mp -> m_keylen = (int )strlen (mp -> m_keys ); 553mp -> m_noremap = noremap ; 554mp -> m_nowait = args -> nowait ; 555mp -> m_silent = args -> silent ; 556mp -> m_mode = mode ; 557mp -> m_simplified = simplified ; 558mp -> m_expr = args -> expr ; 559mp -> m_replace_keycodes = args -> replace_keycodes ; 560if (sid != 0 ) { 561mp -> m_script_ctx .sc_sid = sid ; 562mp -> m_script_ctx .sc_lnum = lnum ; 563 }else { 564mp -> m_script_ctx = current_sctx ; 565mp -> m_script_ctx .sc_lnum += SOURCING_LNUM ; 566nlua_set_sctx (& mp -> m_script_ctx ); 567 } 568mp -> m_desc = args -> desc ; 569 570// add the new entry in front of the abbrlist or maphash[] list 571if (is_abbr ) { 572mp -> m_next = * abbr_table ; 573* abbr_table = mp ; 574 }else { 575const int n = MAP_HASH (mp -> m_mode , (uint8_t )mp -> m_keys [0 ]); 576mp -> m_next = map_table [n ]; 577map_table [n ]= mp ; 578 } 579return mp ; 580} 581 582/// Sets or removes a mapping or abbreviation in buffer `buf`. 583/// 584/// @param maptype @see do_map 585/// @param args Fully parsed and "preprocessed" arguments for the 586/// (un)map/abbrev command. Termcodes should have already been 587/// replaced; whitespace, `<` and `>` signs, etc. in {lhs} and 588/// {rhs} are assumed to be literal components of the mapping. 589/// @param mode @see do_map 590/// @param is_abbrev @see do_map 591/// @param buf Target Buffer 592static int buf_do_map (int maptype ,MapArguments * args ,int mode ,bool is_abbrev ,buf_T * buf ) 593{ 594int retval = 0 ; 595 596// If <buffer> was given, we'll be searching through the buffer's 597// mappings/abbreviations, not the globals. 598mapblock_T ** map_table = args -> buffer ?buf -> b_maphash :maphash ; 599mapblock_T ** abbr_table = args -> buffer ?& buf -> b_first_abbr :& first_abbr ; 600mapblock_T * mp_result [2 ]= {NULL ,NULL }; 601 602bool unmap_lhs_only = false; 603if (maptype == MAPTYPE_UNMAP_LHS ) { 604unmap_lhs_only = true; 605maptype = MAPTYPE_UNMAP ; 606 } 607 608// For ":noremap" don't remap, otherwise do remap. 609int noremap = args -> script ?REMAP_SCRIPT 610 :maptype == MAPTYPE_NOREMAP ?REMAP_NONE :REMAP_YES ; 611 612const bool has_lhs = (args -> lhs [0 ]!= NUL ); 613const bool has_rhs = args -> rhs_lua != LUA_NOREF || (args -> rhs [0 ]!= NUL )|| args -> rhs_is_noop ; 614const bool do_print = !has_lhs || (maptype != MAPTYPE_UNMAP && !has_rhs ); 615if (do_print ) { 616msg_ext_set_kind ("list_cmd" ); 617 } 618 619// check for :unmap without argument 620if (maptype == MAPTYPE_UNMAP && !has_lhs ) { 621retval = 1 ; 622 gototheend ; 623 } 624 625const char * lhs = (char * )& args -> lhs ; 626const bool did_simplify = args -> alt_lhs_len != 0 ; 627 628// The following is done twice if we have two versions of keys 629for (int keyround = 1 ;keyround <=2 ;keyround ++ ) { 630bool did_it = false; 631bool did_local = false; 632bool keyround1_simplified = keyround == 1 && did_simplify ; 633int len = (int )args -> lhs_len ; 634 635if (keyround == 2 ) { 636if (!did_simplify ) { 637break ; 638 } 639lhs = (char * )& args -> alt_lhs ; 640len = (int )args -> alt_lhs_len ; 641 }else if (did_simplify && do_print ) { 642// when printing always use the not-simplified map 643lhs = (char * )& args -> alt_lhs ; 644len = (int )args -> alt_lhs_len ; 645 } 646 647// check arguments and translate function keys 648if (has_lhs ) { 649if (len > MAXMAPLEN ) { 650retval = 1 ; 651 gototheend ; 652 } 653 654if (is_abbrev && maptype != MAPTYPE_UNMAP ) { 655// If an abbreviation ends in a keyword character, the 656// rest must be all keyword-char or all non-keyword-char. 657// Otherwise we won't be able to find the start of it in a 658// vi-compatible way. 659int same = -1 ; 660 661char keys_unescaped [MAXMAPLEN + 1 ]; 662xmemcpyz (keys_unescaped ,lhs , (size_t )len ); 663size_t keys_unescaped_len = vim_unescape_ks (keys_unescaped ); 664const char * p = keys_unescaped ; 665 666const int first = vim_iswordp (p ); 667int last = first ; 668MB_PTR_ADV (p ); 669int n = 1 ; 670while (p < keys_unescaped + keys_unescaped_len ) { 671n ++ ;// nr of (multi-byte) chars 672last = vim_iswordp (p );// type of last char 673if (same == -1 && last != first ) { 674same = n - 1 ;// count of same char type 675 } 676MB_PTR_ADV (p ); 677 } 678if (last && n > 2 && same >=0 && same < n - 1 ) { 679retval = 1 ; 680 gototheend ; 681 } 682 683// An abbreviation cannot contain white space. 684for (n = 0 ;n < len ;n ++ ) { 685if (ascii_iswhite (lhs [n ])) { 686retval = 1 ; 687 gototheend ; 688 } 689 }// for 690 } 691 } 692 693if (has_lhs && has_rhs && is_abbrev ) {// if we will add an abbreviation, 694no_abbr = false;// reset flag that indicates there are no abbreviations 695 } 696 697if (do_print ) { 698msg_start (); 699 } 700 701// Check if a new local mapping wasn't already defined globally. 702if (args -> unique && map_table == buf -> b_maphash && has_lhs && has_rhs 703&& maptype != MAPTYPE_UNMAP ) { 704// need to loop over all global hash lists 705for (int hash = 0 ;hash < 256 && !got_int ;hash ++ ) { 706mapblock_T * mp ; 707if (is_abbrev ) { 708if (hash != 0 ) {// there is only one abbreviation list 709break ; 710 } 711mp = first_abbr ; 712 }else { 713mp = maphash [hash ]; 714 } 715for (;mp != NULL && !got_int ;mp = mp -> m_next ) { 716// check entries with the same mode 717if ((mp -> m_mode & mode )!= 0 718&& mp -> m_keylen == len 719&& strncmp (mp -> m_keys ,lhs , (size_t )len )== 0 ) { 720retval = 6 ; 721 gototheend ; 722 } 723 } 724 } 725 } 726 727// When listing global mappings, also list buffer-local ones here. 728if (map_table != buf -> b_maphash && !has_rhs && maptype != MAPTYPE_UNMAP ) { 729// need to loop over all global hash lists 730for (int hash = 0 ;hash < 256 && !got_int ;hash ++ ) { 731mapblock_T * mp ; 732if (is_abbrev ) { 733if (hash != 0 ) {// there is only one abbreviation list 734break ; 735 } 736mp = buf -> b_first_abbr ; 737 }else { 738mp = buf -> b_maphash [hash ]; 739 } 740for (;mp != NULL && !got_int ;mp = mp -> m_next ) { 741// check entries with the same mode 742if (!mp -> m_simplified && (mp -> m_mode & mode )!= 0 ) { 743if (!has_lhs ) {// show all entries 744showmap (mp , true); 745did_local = true; 746 }else { 747int n = mp -> m_keylen ; 748if (strncmp (mp -> m_keys ,lhs , (size_t )(n < len ?n :len ))== 0 ) { 749showmap (mp , true); 750did_local = true; 751 } 752 } 753 } 754 } 755 } 756 } 757 758// Find an entry in the maphash[] list that matches. 759// For :unmap we may loop two times: once to try to unmap an entry with a 760// matching 'from' part, a second time, if the first fails, to unmap an 761// entry with a matching 'to' part. This was done to allow ":ab foo bar" 762// to be unmapped by typing ":unab foo", where "foo" will be replaced by 763// "bar" because of the abbreviation. 764const int num_rounds = maptype == MAPTYPE_UNMAP && !unmap_lhs_only ?2 :1 ; 765for (int round = 0 ;round < num_rounds && !did_it && !got_int ;round ++ ) { 766int hash_start ,hash_end ; 767if ((round == 0 && has_lhs )|| is_abbrev ) { 768// just use one hash 769hash_start = is_abbrev ?0 :MAP_HASH (mode , (uint8_t )lhs [0 ]); 770hash_end = hash_start + 1 ; 771 }else { 772// need to loop over all hash lists 773hash_start = 0 ; 774hash_end = 256 ; 775 } 776for (int hash = hash_start ;hash < hash_end && !got_int ;hash ++ ) { 777mapblock_T ** mpp = is_abbrev ?abbr_table :& (map_table [hash ]); 778for (mapblock_T * mp = * mpp ;mp != NULL && !got_int ;mp = * mpp ) { 779if ((mp -> m_mode & mode )== 0 ) { 780// skip entries with wrong mode 781mpp = & (mp -> m_next ); 782continue ; 783 } 784if (!has_lhs ) {// show all entries 785if (!mp -> m_simplified ) { 786showmap (mp ,map_table != maphash ); 787did_it = true; 788 } 789 }else {// do we have a match? 790int n ; 791const char * p ; 792if (round ) {// second round: Try unmap "rhs" string 793n = (int )strlen (mp -> m_str ); 794p = mp -> m_str ; 795 }else { 796n = mp -> m_keylen ; 797p = mp -> m_keys ; 798 } 799if (strncmp (p ,lhs , (size_t )(n < len ?n :len ))== 0 ) { 800if (maptype == MAPTYPE_UNMAP ) { 801// Delete entry. 802// Only accept a full match. For abbreviations 803// we ignore trailing space when matching with 804// the "lhs", since an abbreviation can't have 805// trailing space. 806if (n != len && (!is_abbrev || round || n > len || * skipwhite (lhs + n )!= NUL )) { 807mpp = & (mp -> m_next ); 808continue ; 809 } 810// In keyround for simplified keys, don't unmap 811// a mapping without m_simplified flag. 812if (keyround1_simplified && !mp -> m_simplified ) { 813break ; 814 } 815// We reset the indicated mode bits. If nothing 816// is left the entry is deleted below. 817mp -> m_mode &= ~mode ; 818did_it = true;// remember we did something 819 }else if (!has_rhs ) {// show matching entry 820if (!mp -> m_simplified ) { 821showmap (mp ,map_table != maphash ); 822did_it = true; 823 } 824 }else if (n != len ) {// new entry is ambiguous 825mpp = & (mp -> m_next ); 826continue ; 827 }else if (keyround1_simplified && !mp -> m_simplified ) { 828// In keyround for simplified keys, don't replace 829// a mapping without m_simplified flag. 830did_it = true; 831break ; 832 }else if (args -> unique ) { 833retval = 5 ; 834 gototheend ; 835 }else { 836// new rhs for existing entry 837mp -> m_mode &= ~mode ;// remove mode bits 838if (mp -> m_mode == 0 && !did_it ) {// reuse entry 839if (mp -> m_alt != NULL ) { 840mp -> m_alt = mp -> m_alt -> m_alt = NULL ; 841 }else { 842NLUA_CLEAR_REF (mp -> m_luaref ); 843xfree (mp -> m_str ); 844xfree (mp -> m_orig_str ); 845xfree (mp -> m_desc ); 846 } 847mp -> m_str = args -> rhs ; 848mp -> m_orig_str = args -> orig_rhs ; 849mp -> m_luaref = args -> rhs_lua ; 850mp -> m_noremap = noremap ; 851mp -> m_nowait = args -> nowait ; 852mp -> m_silent = args -> silent ; 853mp -> m_mode = mode ; 854mp -> m_simplified = keyround1_simplified ; 855mp -> m_expr = args -> expr ; 856mp -> m_replace_keycodes = args -> replace_keycodes ; 857mp -> m_script_ctx = current_sctx ; 858mp -> m_script_ctx .sc_lnum += SOURCING_LNUM ; 859nlua_set_sctx (& mp -> m_script_ctx ); 860mp -> m_desc = args -> desc ; 861mp_result [keyround - 1 ]= mp ; 862did_it = true; 863 } 864 } 865if (mp -> m_mode == 0 ) {// entry can be deleted 866mapblock_free (mpp ); 867continue ;// continue with *mpp 868 } 869 870// May need to put this entry into another hash list. 871int new_hash = MAP_HASH (mp -> m_mode , (uint8_t )mp -> m_keys [0 ]); 872if (!is_abbrev && new_hash != hash ) { 873* mpp = mp -> m_next ; 874mp -> m_next = map_table [new_hash ]; 875map_table [new_hash ]= mp ; 876 877continue ;// continue with *mpp 878 } 879 } 880 } 881mpp = & (mp -> m_next ); 882 } 883 } 884 } 885 886if (maptype == MAPTYPE_UNMAP ) { 887// delete entry 888if (!did_it ) { 889if (!keyround1_simplified ) { 890retval = 2 ;// no match 891 } 892 }else if (* lhs == Ctrl_C ) { 893// If CTRL-C has been unmapped, reuse it for Interrupting. 894if (map_table == buf -> b_maphash ) { 895buf -> b_mapped_ctrl_c &= ~mode ; 896 }else { 897mapped_ctrl_c &= ~mode ; 898 } 899 } 900continue ; 901 } 902 903if (!has_lhs || !has_rhs ) { 904// print entries 905if (!did_it && !did_local ) { 906if (is_abbrev ) { 907msg (_ ("No abbreviation found" ),0 ); 908 }else { 909msg (_ ("No mapping found" ),0 ); 910 } 911 } 912 gototheend ;// listing finished 913 } 914 915if (did_it ) { 916continue ;// have added the new entry already 917 } 918 919// Get here when adding a new entry to the maphash[] list or abbrlist. 920mp_result [keyround - 1 ]= map_add (buf ,map_table ,abbr_table ,lhs , 921args ,noremap ,mode ,is_abbrev , 9220 ,// sid 9230 ,// lnum 924keyround1_simplified ); 925 } 926 927if (mp_result [0 ]!= NULL && mp_result [1 ]!= NULL ) { 928mp_result [0 ]-> m_alt = mp_result [1 ]; 929mp_result [1 ]-> m_alt = mp_result [0 ]; 930 } 931 932theend : 933if (mp_result [0 ]!= NULL || mp_result [1 ]!= NULL ) { 934args -> rhs = NULL ; 935args -> orig_rhs = NULL ; 936args -> rhs_lua = LUA_NOREF ; 937args -> desc = NULL ; 938 } 939return retval ; 940} 941 942/// Set or remove a mapping or an abbreviation in the current buffer, OR 943/// display (matching) mappings/abbreviations. 944/// 945/// ```vim 946/// map[!] " show all key mappings 947/// map[!] {lhs} " show key mapping for {lhs} 948/// map[!] {lhs} {rhs} " set key mapping for {lhs} to {rhs} 949/// noremap[!] {lhs} {rhs} " same, but no remapping for {rhs} 950/// unmap[!] {lhs} " remove key mapping for {lhs} 951/// abbr " show all abbreviations 952/// abbr {lhs} " show abbreviations for {lhs} 953/// abbr {lhs} {rhs} " set abbreviation for {lhs} to {rhs} 954/// noreabbr {lhs} {rhs} " same, but no remapping for {rhs} 955/// unabbr {lhs} " remove abbreviation for {lhs} 956/// 957/// for :map mode is MODE_NORMAL | MODE_VISUAL | MODE_SELECT | MODE_OP_PENDING 958/// for :map! mode is MODE_INSERT | MODE_CMDLINE 959/// for :cmap mode is MODE_CMDLINE 960/// for :imap mode is MODE_INSERT 961/// for :lmap mode is MODE_LANGMAP 962/// for :nmap mode is MODE_NORMAL 963/// for :vmap mode is MODE_VISUAL | MODE_SELECT 964/// for :xmap mode is MODE_VISUAL 965/// for :smap mode is MODE_SELECT 966/// for :omap mode is MODE_OP_PENDING 967/// for :tmap mode is MODE_TERMINAL 968/// 969/// for :abbr mode is MODE_INSERT | MODE_CMDLINE 970/// for :iabbr mode is MODE_INSERT 971/// for :cabbr mode is MODE_CMDLINE 972/// ``` 973/// 974/// @param maptype MAPTYPE_MAP for |:map| or |:abbr| 975/// MAPTYPE_UNMAP for |:unmap| or |:unabbr| 976/// MAPTYPE_NOREMAP for |:noremap| or |:noreabbr| 977/// MAPTYPE_UNMAP_LHS is like MAPTYPE_UNMAP, but doesn't try to match 978/// with {rhs} if there is no match with {lhs}. 979/// @param arg C-string containing the arguments of the map/abbrev 980/// command, i.e. everything except the initial `:[X][nore]map`. 981/// - Cannot be a read-only string; it will be modified. 982/// @param mode Bitflags representing the mode in which to set the mapping. 983/// See @ref get_map_mode. 984/// @param is_abbrev True if setting an abbreviation, false otherwise. 985/// 986/// @return 0 on success. On failure, will return one of the following: 987/// - 1 for invalid arguments 988/// - 2 for no match 989/// - 4 for out of mem (deprecated, WON'T HAPPEN) 990/// - 5 for entry not unique 991/// - 6 for buflocal unique entry conflicts with global entry 992/// 993int do_map (int maptype ,char * arg ,int mode ,bool is_abbrev ) 994{ 995MapArguments parsed_args ; 996int result = str_to_mapargs (arg ,maptype == MAPTYPE_UNMAP ,& parsed_args ); 997switch (result ) { 998case 0 : 999break ; 1000case 1 : 1001// invalid arguments 1002 gotofree_and_return ; 1003default : 1004assert (false&& "Unknown return code from str_to_mapargs!" ); 1005result = -1 ; 1006 gotofree_and_return ; 1007 }// switch 1008 1009result = buf_do_map (maptype ,& parsed_args ,mode ,is_abbrev ,curbuf ); 1010 1011free_and_return : 1012xfree (parsed_args .rhs ); 1013xfree (parsed_args .orig_rhs ); 1014return result ; 1015} 1016 1017/// Get the mapping mode from the command name. 1018static int get_map_mode (char ** cmdp ,bool forceit ) 1019{ 1020int mode ; 1021 1022char * p = * cmdp ; 1023int modec = (uint8_t )(* p ++ ); 1024if (modec == 'i' ) { 1025mode = MODE_INSERT ;// :imap 1026 }else if (modec == 'l' ) { 1027mode = MODE_LANGMAP ;// :lmap 1028 }else if (modec == 'c' ) { 1029mode = MODE_CMDLINE ;// :cmap 1030 }else if (modec == 'n' && * p != 'o' ) {// avoid :noremap 1031mode = MODE_NORMAL ;// :nmap 1032 }else if (modec == 'v' ) { 1033mode = MODE_VISUAL |MODE_SELECT ;// :vmap 1034 }else if (modec == 'x' ) { 1035mode = MODE_VISUAL ;// :xmap 1036 }else if (modec == 's' ) { 1037mode = MODE_SELECT ;// :smap 1038 }else if (modec == 'o' ) { 1039mode = MODE_OP_PENDING ;// :omap 1040 }else if (modec == 't' ) { 1041mode = MODE_TERMINAL ;// :tmap 1042 }else { 1043p -- ; 1044if (forceit ) { 1045mode = MODE_INSERT |MODE_CMDLINE ;// :map ! 1046 }else { 1047mode = MODE_VISUAL |MODE_SELECT |MODE_NORMAL |MODE_OP_PENDING ;// :map 1048 } 1049 } 1050 1051* cmdp = p ; 1052return mode ; 1053} 1054 1055/// Clear all mappings (":mapclear") or abbreviations (":abclear"). 1056/// "abbr" should be false for mappings, true for abbreviations. 1057/// This function used to be called map_clear(). 1058static void do_mapclear (char * cmdp ,char * arg ,int forceit ,int abbr ) 1059{ 1060bool local = strcmp (arg ,"<buffer>" )== 0 ; 1061if (!local && * arg != NUL ) { 1062emsg (_ (e_invarg )); 1063return ; 1064 } 1065 1066int mode = get_map_mode (& cmdp ,forceit ); 1067map_clear_mode (curbuf ,mode ,local ,abbr ); 1068} 1069 1070/// Clear all mappings in "mode". 1071/// 1072/// @param buf, buffer for local mappings 1073/// @param mode mode in which to delete 1074/// @param local true for buffer-local mappings 1075/// @param abbr true for abbreviations 1076void map_clear_mode (buf_T * buf ,int mode ,bool local ,bool abbr ) 1077{ 1078for (int hash = 0 ;hash < 256 ;hash ++ ) { 1079mapblock_T ** mpp ; 1080if (abbr ) { 1081if (hash > 0 ) {// there is only one abbrlist 1082break ; 1083 } 1084if (local ) { 1085mpp = & buf -> b_first_abbr ; 1086 }else { 1087mpp = & first_abbr ; 1088 } 1089 }else { 1090if (local ) { 1091mpp = & buf -> b_maphash [hash ]; 1092 }else { 1093mpp = & maphash [hash ]; 1094 } 1095 } 1096while (* mpp != NULL ) { 1097mapblock_T * mp = * mpp ; 1098if (mp -> m_mode & mode ) { 1099mp -> m_mode &= ~mode ; 1100if (mp -> m_mode == 0 ) {// entry can be deleted 1101mapblock_free (mpp ); 1102continue ; 1103 } 1104// May need to put this entry into another hash list. 1105int new_hash = MAP_HASH (mp -> m_mode , (uint8_t )mp -> m_keys [0 ]); 1106if (!abbr && new_hash != hash ) { 1107* mpp = mp -> m_next ; 1108if (local ) { 1109mp -> m_next = buf -> b_maphash [new_hash ]; 1110buf -> b_maphash [new_hash ]= mp ; 1111 }else { 1112mp -> m_next = maphash [new_hash ]; 1113maphash [new_hash ]= mp ; 1114 } 1115continue ;// continue with *mpp 1116 } 1117 } 1118mpp = & (mp -> m_next ); 1119 } 1120 } 1121} 1122 1123/// Check if a map exists that has given string in the rhs 1124/// 1125/// Also checks mappings local to the current buffer. 1126/// 1127/// @param[in] str String which mapping must have in the rhs. Termcap codes 1128/// are recognized in this argument. 1129/// @param[in] modechars Mode(s) in which mappings are checked. 1130/// @param[in] abbr true if checking abbreviations in place of mappings. 1131/// 1132/// @return true if there is at least one mapping with given parameters. 1133bool map_to_exists (const char * const str ,const char * const modechars ,const bool abbr ) 1134FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 1135{ 1136int mode = 0 ; 1137 1138char * buf = NULL ; 1139const char * const rhs = replace_termcodes (str ,strlen (str ),& buf ,0 , 1140REPTERM_DO_LT ,NULL ,p_cpo ); 1141 1142#define MAPMODE (mode ,modechars ,chr ,modeflags ) \ 1143 do { \ 1144 if (strchr(modechars, chr) != NULL) { \ 1145 (mode) |= (modeflags); \ 1146 } \ 1147 } while (0) 1148MAPMODE (mode ,modechars ,'n' ,MODE_NORMAL ); 1149MAPMODE (mode ,modechars ,'v' ,MODE_VISUAL |MODE_SELECT ); 1150MAPMODE (mode ,modechars ,'x' ,MODE_VISUAL ); 1151MAPMODE (mode ,modechars ,'s' ,MODE_SELECT ); 1152MAPMODE (mode ,modechars ,'o' ,MODE_OP_PENDING ); 1153MAPMODE (mode ,modechars ,'i' ,MODE_INSERT ); 1154MAPMODE (mode ,modechars ,'l' ,MODE_LANGMAP ); 1155MAPMODE (mode ,modechars ,'c' ,MODE_CMDLINE ); 1156#undef MAPMODE 1157 1158bool retval = map_to_exists_mode (rhs ,mode ,abbr ); 1159xfree (buf ); 1160 1161return retval ; 1162} 1163 1164/// Check if a map exists that has given string in the rhs 1165/// 1166/// Also checks mappings local to the current buffer. 1167/// 1168/// @param[in] rhs String which mapping must have in the rhs. Termcap codes 1169/// are recognized in this argument. 1170/// @param[in] mode Mode(s) in which mappings are checked. 1171/// @param[in] abbr true if checking abbreviations in place of mappings. 1172/// 1173/// @return true if there is at least one mapping with given parameters. 1174bool map_to_exists_mode (const char * const rhs ,const int mode ,const bool abbr ) 1175{ 1176bool exp_buffer = false; 1177 1178// Do it twice: once for global maps and once for local maps. 1179while (true) { 1180for (int hash = 0 ;hash < 256 ;hash ++ ) { 1181mapblock_T * mp ; 1182if (abbr ) { 1183if (hash > 0 ) {// There is only one abbr list. 1184break ; 1185 } 1186if (exp_buffer ) { 1187mp = curbuf -> b_first_abbr ; 1188 }else { 1189mp = first_abbr ; 1190 } 1191 }else if (exp_buffer ) { 1192mp = curbuf -> b_maphash [hash ]; 1193 }else { 1194mp = maphash [hash ]; 1195 } 1196for (;mp ;mp = mp -> m_next ) { 1197if ((mp -> m_mode & mode )&& strstr (mp -> m_str ,rhs )!= NULL ) { 1198return true; 1199 } 1200 } 1201 } 1202if (exp_buffer ) { 1203break ; 1204 } 1205exp_buffer = true; 1206 } 1207 1208return false; 1209} 1210 1211/// Used below when expanding mapping/abbreviation names. 1212static int expand_mapmodes = 0 ; 1213static bool expand_isabbrev = false; 1214static bool expand_buffer = false; 1215 1216/// Translate an internal mapping/abbreviation representation into the 1217/// corresponding external one recognized by :map/:abbrev commands. 1218/// 1219/// This function is called when expanding mappings/abbreviations on the 1220/// command-line. 1221/// 1222/// It uses a growarray to build the translation string since the latter can be 1223/// wider than the original description. The caller has to free the string 1224/// afterwards. 1225/// 1226/// @param[in] cpo_val See param docs for @ref replace_termcodes. 1227/// 1228/// @return NULL when there is a problem. 1229static char * translate_mapping (const char * const str_in ,const char * const cpo_val ) 1230{ 1231const uint8_t * str = (const uint8_t * )str_in ; 1232garray_T ga ; 1233ga_init (& ga ,1 ,40 ); 1234 1235const bool cpo_bslash = (vim_strchr (cpo_val ,kCpoBslash )!= NULL ); 1236 1237for (;* str ;str ++ ) { 1238int c = * str ; 1239if (c == K_SPECIAL && str [1 ]!= NUL && str [2 ]!= NUL ) { 1240int modifiers = 0 ; 1241if (str [1 ]== KS_MODIFIER ) { 1242str ++ ; 1243modifiers = *++ str ; 1244c = *++ str ; 1245 } 1246 1247if (c == K_SPECIAL && str [1 ]!= NUL && str [2 ]!= NUL ) { 1248c = TO_SPECIAL (str [1 ],str [2 ]); 1249if (c == K_ZERO ) { 1250// display <Nul> as ^@ 1251c = NUL ; 1252 } 1253str += 2 ; 1254 } 1255if (IS_SPECIAL (c )|| modifiers ) {// special key 1256ga_concat (& ga ,get_special_key_name (c ,modifiers )); 1257continue ;// for (str) 1258 } 1259 } 1260 1261if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V 1262|| c == '<' || (c == '\\' && !cpo_bslash )) { 1263ga_append (& ga ,cpo_bslash ?Ctrl_V :'\\' ); 1264 } 1265 1266if (c ) { 1267ga_append (& ga , (uint8_t )c ); 1268 } 1269 } 1270ga_append (& ga ,NUL ); 1271return (char * )ga .ga_data ; 1272} 1273 1274/// Work out what to complete when doing command line completion of mapping 1275/// or abbreviation names. 1276/// 1277/// @param forceit true if '!' given 1278/// @param isabbrev true if abbreviation 1279/// @param isunmap true if unmap/unabbrev command 1280char * set_context_in_map_cmd (expand_T * xp ,char * cmd ,char * arg ,bool forceit ,bool isabbrev , 1281bool isunmap ,cmdidx_T cmdidx ) 1282{ 1283if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap ) { 1284xp -> xp_context = EXPAND_NOTHING ; 1285 }else { 1286if (isunmap ) { 1287expand_mapmodes = get_map_mode (& cmd ,forceit || isabbrev ); 1288 }else { 1289expand_mapmodes = MODE_INSERT |MODE_CMDLINE ; 1290if (!isabbrev ) { 1291expand_mapmodes |=MODE_VISUAL |MODE_SELECT |MODE_NORMAL |MODE_OP_PENDING ; 1292 } 1293 } 1294expand_isabbrev = isabbrev ; 1295xp -> xp_context = EXPAND_MAPPINGS ; 1296expand_buffer = false; 1297while (true) { 1298if (strncmp (arg ,"<buffer>" ,8 )== 0 ) { 1299expand_buffer = true; 1300arg = skipwhite (arg + 8 ); 1301continue ; 1302 } 1303if (strncmp (arg ,"<unique>" ,8 )== 0 ) { 1304arg = skipwhite (arg + 8 ); 1305continue ; 1306 } 1307if (strncmp (arg ,"<nowait>" ,8 )== 0 ) { 1308arg = skipwhite (arg + 8 ); 1309continue ; 1310 } 1311if (strncmp (arg ,"<silent>" ,8 )== 0 ) { 1312arg = skipwhite (arg + 8 ); 1313continue ; 1314 } 1315if (strncmp (arg ,"<special>" ,9 )== 0 ) { 1316arg = skipwhite (arg + 9 ); 1317continue ; 1318 } 1319if (strncmp (arg ,"<script>" ,8 )== 0 ) { 1320arg = skipwhite (arg + 8 ); 1321continue ; 1322 } 1323if (strncmp (arg ,"<expr>" ,6 )== 0 ) { 1324arg = skipwhite (arg + 6 ); 1325continue ; 1326 } 1327break ; 1328 } 1329xp -> xp_pattern = arg ; 1330 } 1331 1332return NULL ; 1333} 1334 1335/// Find all mapping/abbreviation names that match regexp "regmatch". 1336/// For command line expansion of ":[un]map" and ":[un]abbrev" in all modes. 1337/// @return OK if matches found, FAIL otherwise. 1338int ExpandMappings (char * pat ,regmatch_T * regmatch ,int * numMatches ,char *** matches ) 1339{ 1340const bool fuzzy = cmdline_fuzzy_complete (pat ); 1341 1342* numMatches = 0 ;// return values in case of FAIL 1343* matches = NULL ; 1344 1345garray_T ga ; 1346if (!fuzzy ) { 1347ga_init (& ga ,sizeof (char * ),3 ); 1348 }else { 1349ga_init (& ga ,sizeof (fuzmatch_str_T ),3 ); 1350 } 1351 1352// First search in map modifier arguments 1353for (int i = 0 ;i < 7 ;i ++ ) { 1354char * p ; 1355if (i == 0 ) { 1356p = "<silent>" ; 1357 }else if (i == 1 ) { 1358p = "<unique>" ; 1359 }else if (i == 2 ) { 1360p = "<script>" ; 1361 }else if (i == 3 ) { 1362p = "<expr>" ; 1363 }else if (i == 4 && !expand_buffer ) { 1364p = "<buffer>" ; 1365 }else if (i == 5 ) { 1366p = "<nowait>" ; 1367 }else if (i == 6 ) { 1368p = "<special>" ; 1369 }else { 1370continue ; 1371 } 1372 1373bool match ; 1374int score = 0 ; 1375if (!fuzzy ) { 1376match = vim_regexec (regmatch ,p ,0 ); 1377 }else { 1378score = fuzzy_match_str (p ,pat ); 1379match = (score != FUZZY_SCORE_NONE ); 1380 } 1381 1382if (!match ) { 1383continue ; 1384 } 1385 1386if (fuzzy ) { 1387GA_APPEND (fuzmatch_str_T ,& ga , ((fuzmatch_str_T ){ 1388 .idx = ga .ga_len , 1389 .str = xstrdup (p ), 1390 .score = score , 1391 })); 1392 }else { 1393GA_APPEND (char * ,& ga ,xstrdup (p )); 1394 } 1395 } 1396 1397for (int hash = 0 ;hash < 256 ;hash ++ ) { 1398mapblock_T * mp ; 1399if (expand_isabbrev ) { 1400if (hash > 0 ) {// only one abbrev list 1401break ;// for (hash) 1402 } 1403mp = first_abbr ; 1404 }else if (expand_buffer ) { 1405mp = curbuf -> b_maphash [hash ]; 1406 }else { 1407mp = maphash [hash ]; 1408 } 1409for (;mp ;mp = mp -> m_next ) { 1410if (mp -> m_simplified || !(mp -> m_mode & expand_mapmodes )) { 1411continue ; 1412 } 1413 1414char * p = translate_mapping (mp -> m_keys ,p_cpo ); 1415if (p == NULL ) { 1416continue ; 1417 } 1418 1419bool match ; 1420int score = 0 ; 1421if (!fuzzy ) { 1422match = vim_regexec (regmatch ,p ,0 ); 1423 }else { 1424score = fuzzy_match_str (p ,pat ); 1425match = (score != FUZZY_SCORE_NONE ); 1426 } 1427 1428if (!match ) { 1429xfree (p ); 1430continue ; 1431 } 1432 1433if (fuzzy ) { 1434GA_APPEND (fuzmatch_str_T ,& ga , ((fuzmatch_str_T ){ 1435 .idx = ga .ga_len , 1436 .str = p , 1437 .score = score , 1438 })); 1439 }else { 1440GA_APPEND (char * ,& ga ,p ); 1441 } 1442 }// for (mp) 1443 }// for (hash) 1444 1445if (ga .ga_len == 0 ) { 1446return FAIL ; 1447 } 1448 1449if (!fuzzy ) { 1450* matches = ga .ga_data ; 1451* numMatches = ga .ga_len ; 1452 }else { 1453fuzzymatches_to_strmatches (ga .ga_data ,matches ,ga .ga_len , false); 1454* numMatches = ga .ga_len ; 1455 } 1456 1457int count = * numMatches ; 1458if (count > 1 ) { 1459// Sort the matches 1460// Fuzzy matching already sorts the matches 1461if (!fuzzy ) { 1462sort_strings (* matches ,count ); 1463 } 1464 1465// Remove multiple entries 1466char ** ptr1 = * matches ; 1467char ** ptr2 = ptr1 + 1 ; 1468char ** ptr3 = ptr1 + count ; 1469 1470while (ptr2 < ptr3 ) { 1471if (strcmp (* ptr1 ,* ptr2 )!= 0 ) { 1472*++ ptr1 = * ptr2 ++ ; 1473 }else { 1474xfree (* ptr2 ++ ); 1475count -- ; 1476 } 1477 } 1478 } 1479 1480* numMatches = count ; 1481return count == 0 ?FAIL :OK ; 1482} 1483 1484// Check for an abbreviation. 1485// Cursor is at ptr[col]. 1486// When inserting, mincol is where insert started. 1487// For the command line, mincol is what is to be skipped over. 1488// "c" is the character typed before check_abbr was called. It may have 1489// ABBR_OFF added to avoid prepending a CTRL-V to it. 1490// 1491// Historic vi practice: The last character of an abbreviation must be an id 1492// character ([a-zA-Z0-9_]). The characters in front of it must be all id 1493// characters or all non-id characters. This allows for abbr. "#i" to 1494// "#include". 1495// 1496// Vim addition: Allow for abbreviations that end in a non-keyword character. 1497// Then there must be white space before the abbr. 1498// 1499// Return true if there is an abbreviation, false if not. 1500bool check_abbr (int c ,char * ptr ,int col ,int mincol ) 1501{ 1502uint8_t tb [MB_MAXBYTES + 4 ]; 1503int clen = 0 ;// length in characters 1504 1505if (typebuf .tb_no_abbr_cnt ) {// abbrev. are not recursive 1506return false; 1507 } 1508 1509// no remapping implies no abbreviation, except for CTRL-] 1510if (noremap_keys ()&& c != Ctrl_RSB ) { 1511return false; 1512 } 1513 1514// Check for word before the cursor: If it ends in a keyword char all 1515// chars before it must be keyword chars or non-keyword chars, but not 1516// white space. If it ends in a non-keyword char we accept any characters 1517// before it except white space. 1518if (col == 0 ) {// cannot be an abbr. 1519return false; 1520 } 1521 1522int scol ;// starting column of the abbr. 1523 1524 { 1525bool is_id = true; 1526bool vim_abbr ; 1527char * p = mb_prevptr (ptr ,ptr + col ); 1528if (!vim_iswordp (p )) { 1529vim_abbr = true;// Vim added abbr. 1530 }else { 1531vim_abbr = false;// vi compatible abbr. 1532if (p > ptr ) { 1533is_id = vim_iswordp (mb_prevptr (ptr ,p )); 1534 } 1535 } 1536clen = 1 ; 1537while (p > ptr + mincol ) { 1538p = mb_prevptr (ptr ,p ); 1539if (ascii_isspace (* p )|| (!vim_abbr && is_id != vim_iswordp (p ))) { 1540p += utfc_ptr2len (p ); 1541break ; 1542 } 1543clen ++ ; 1544 } 1545scol = (int )(p - ptr ); 1546 } 1547 1548if (scol < mincol ) { 1549scol = mincol ; 1550 } 1551if (scol < col ) {// there is a word in front of the cursor 1552ptr += scol ; 1553int len = col - scol ; 1554mapblock_T * mp = curbuf -> b_first_abbr ; 1555mapblock_T * mp2 = first_abbr ; 1556if (mp == NULL ) { 1557mp = mp2 ; 1558mp2 = NULL ; 1559 } 1560for (;mp ; 1561mp -> m_next == NULL ? (mp = mp2 ,mp2 = NULL ) 1562 : (mp = mp -> m_next )) { 1563int qlen = mp -> m_keylen ; 1564char * q = mp -> m_keys ; 1565 1566if (strchr (mp -> m_keys ,K_SPECIAL )!= NULL ) { 1567// Might have K_SPECIAL escaped mp->m_keys. 1568q = xstrdup (mp -> m_keys ); 1569qlen = (int )vim_unescape_ks (q ); 1570 } 1571// find entries with right mode and keys 1572int match = (mp -> m_mode & State ) 1573&& qlen == len 1574&& strncmp (q ,ptr , (size_t )len )== 0 ; 1575if (q != mp -> m_keys ) { 1576xfree (q ); 1577 } 1578if (match ) { 1579break ; 1580 } 1581 } 1582if (mp != NULL ) { 1583// Found a match: 1584// Insert the rest of the abbreviation in typebuf.tb_buf[]. 1585// This goes from end to start. 1586// 1587// Characters 0x000 - 0x100: normal chars, may need CTRL-V, 1588// except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER 1589// Characters where IS_SPECIAL() == true: key codes, need 1590// K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V. 1591// 1592// Character CTRL-] is treated specially - it completes the 1593// abbreviation, but is not inserted into the input stream. 1594int j = 0 ; 1595if (c != Ctrl_RSB ) { 1596// special key code, split up 1597if (IS_SPECIAL (c )|| c == K_SPECIAL ) { 1598tb [j ++ ]= K_SPECIAL ; 1599tb [j ++ ]= (uint8_t )K_SECOND (c ); 1600tb [j ++ ]= (uint8_t )K_THIRD (c ); 1601 }else { 1602if (c < ABBR_OFF && (c < ' ' || c > '~' )) { 1603tb [j ++ ]= Ctrl_V ;// special char needs CTRL-V 1604 } 1605// if ABBR_OFF has been added, remove it here. 1606if (c >=ABBR_OFF ) { 1607c -= ABBR_OFF ; 1608 } 1609int newlen = utf_char2bytes (c , (char * )tb + j ); 1610tb [j + newlen ]= NUL ; 1611// Need to escape K_SPECIAL. 1612char * escaped = vim_strsave_escape_ks ((char * )tb + j ); 1613if (escaped != NULL ) { 1614newlen = (int )strlen (escaped ); 1615memmove (tb + j ,escaped , (size_t )newlen ); 1616j += newlen ; 1617xfree (escaped ); 1618 } 1619 } 1620tb [j ]= NUL ; 1621// insert the last typed char 1622ins_typebuf ((char * )tb ,1 ,0 , true,mp -> m_silent ); 1623 } 1624 1625// copy values here, calling eval_map_expr() may make "mp" invalid! 1626const int noremap = mp -> m_noremap ; 1627const bool silent = mp -> m_silent ; 1628const bool expr = mp -> m_expr ; 1629 1630char * s ; 1631if (expr ) { 1632s = eval_map_expr (mp ,c ); 1633 }else { 1634s = mp -> m_str ; 1635 } 1636if (s != NULL ) { 1637// insert the to string 1638ins_typebuf (s ,noremap ,0 , true,silent ); 1639// no abbrev. for these chars 1640typebuf .tb_no_abbr_cnt += (int )strlen (s )+ j + 1 ; 1641if (expr ) { 1642xfree (s ); 1643 } 1644 } 1645 1646tb [0 ]= Ctrl_H ; 1647tb [1 ]= NUL ; 1648len = clen ;// Delete characters instead of bytes 1649while (len -- > 0 ) {// delete the from string 1650ins_typebuf ((char * )tb ,1 ,0 , true,silent ); 1651 } 1652return true; 1653 } 1654 } 1655return false; 1656} 1657 1658/// Evaluate the RHS of a mapping or abbreviations and take care of escaping 1659/// special characters. 1660/// Careful: after this "mp" will be invalid if the mapping was deleted. 1661/// 1662/// @param c NUL or typed character for abbreviation 1663char * eval_map_expr (mapblock_T * mp ,int c ) 1664{ 1665char * p = NULL ; 1666char * expr = NULL ; 1667 1668// Remove escaping of K_SPECIAL, because "str" is in a format to be used as 1669// typeahead. 1670if (mp -> m_luaref == LUA_NOREF ) { 1671expr = xstrdup (mp -> m_str ); 1672vim_unescape_ks (expr ); 1673 } 1674 1675const bool replace_keycodes = mp -> m_replace_keycodes ; 1676 1677// Forbid changing text or using ":normal" to avoid most of the bad side 1678// effects. Also restore the cursor position. 1679expr_map_lock ++ ; 1680set_vim_var_char (c );// set v:char to the typed character 1681const pos_T save_cursor = curwin -> w_cursor ; 1682const int save_msg_col = msg_col ; 1683const int save_msg_row = msg_row ; 1684if (mp -> m_luaref != LUA_NOREF ) { 1685Error err = ERROR_INIT ; 1686Array args = ARRAY_DICT_INIT ; 1687Object ret = nlua_call_ref (mp -> m_luaref ,NULL ,args ,kRetObject ,NULL ,& err ); 1688if (ret .type == kObjectTypeString ) { 1689p = string_to_cstr (ret .data .string ); 1690 } 1691api_free_object (ret ); 1692if (ERROR_SET (& err )) { 1693semsg_multiline ("emsg" ,"E5108: %s" ,err .msg ); 1694api_clear_error (& err ); 1695 } 1696 }else { 1697p = eval_to_string (expr , false, false); 1698xfree (expr ); 1699 } 1700expr_map_lock -- ; 1701curwin -> w_cursor = save_cursor ; 1702msg_col = save_msg_col ; 1703msg_row = save_msg_row ; 1704 1705if (p == NULL ) { 1706return NULL ; 1707 } 1708 1709char * res = NULL ; 1710 1711if (replace_keycodes ) { 1712replace_termcodes (p ,strlen (p ),& res ,0 ,REPTERM_DO_LT ,NULL ,p_cpo ); 1713 }else { 1714// Escape K_SPECIAL in the result to be able to use the string as typeahead. 1715res = vim_strsave_escape_ks (p ); 1716 } 1717xfree (p ); 1718 1719return res ; 1720} 1721 1722/// Write map commands for the current mappings to an .exrc file. 1723/// Return FAIL on error, OK otherwise. 1724/// 1725/// @param buf buffer for local mappings or NULL 1726int makemap (FILE * fd ,buf_T * buf ) 1727{ 1728bool did_cpo = false; 1729 1730// Do the loop twice: Once for mappings, once for abbreviations. 1731// Then loop over all map hash lists. 1732for (int abbr = 0 ;abbr < 2 ;abbr ++ ) { 1733for (int hash = 0 ;hash < 256 ;hash ++ ) { 1734mapblock_T * mp ; 1735if (abbr ) { 1736if (hash > 0 ) {// there is only one abbr list 1737break ; 1738 } 1739if (buf != NULL ) { 1740mp = buf -> b_first_abbr ; 1741 }else { 1742mp = first_abbr ; 1743 } 1744 }else { 1745if (buf != NULL ) { 1746mp = buf -> b_maphash [hash ]; 1747 }else { 1748mp = maphash [hash ]; 1749 } 1750 } 1751 1752for (;mp ;mp = mp -> m_next ) { 1753// simplified map blocks are not created explicitly 1754if (mp -> m_simplified ) { 1755continue ; 1756 } 1757 1758// skip script-local mappings 1759if (mp -> m_noremap == REMAP_SCRIPT ) { 1760continue ; 1761 } 1762 1763// skip Lua mappings and mappings that contain a <SNR> (script-local thing), 1764// they probably don't work when loaded again 1765if (mp -> m_luaref != LUA_NOREF ) { 1766continue ; 1767 } 1768char * p ; 1769for (p = mp -> m_str ;* p != NUL ;p ++ ) { 1770if ((uint8_t )p [0 ]== K_SPECIAL && (uint8_t )p [1 ]== KS_EXTRA 1771&& p [2 ]== KE_SNR ) { 1772break ; 1773 } 1774 } 1775if (* p != NUL ) { 1776continue ; 1777 } 1778 1779// It's possible to create a mapping and then ":unmap" certain 1780// modes. We recreate this here by mapping the individual 1781// modes, which requires up to three of them. 1782char c1 = NUL ; 1783char c2 = NUL ; 1784char c3 = NUL ; 1785char * cmd = abbr ?"abbr" :"map" ; 1786switch (mp -> m_mode ) { 1787case MODE_NORMAL |MODE_VISUAL |MODE_SELECT |MODE_OP_PENDING : 1788break ; 1789case MODE_NORMAL : 1790c1 = 'n' ; 1791break ; 1792case MODE_VISUAL : 1793c1 = 'x' ; 1794break ; 1795case MODE_SELECT : 1796c1 = 's' ; 1797break ; 1798case MODE_OP_PENDING : 1799c1 = 'o' ; 1800break ; 1801case MODE_NORMAL |MODE_VISUAL : 1802c1 = 'n' ; 1803c2 = 'x' ; 1804break ; 1805case MODE_NORMAL |MODE_SELECT : 1806c1 = 'n' ; 1807c2 = 's' ; 1808break ; 1809case MODE_NORMAL |MODE_OP_PENDING : 1810c1 = 'n' ; 1811c2 = 'o' ; 1812break ; 1813case MODE_VISUAL |MODE_SELECT : 1814c1 = 'v' ; 1815break ; 1816case MODE_VISUAL |MODE_OP_PENDING : 1817c1 = 'x' ; 1818c2 = 'o' ; 1819break ; 1820case MODE_SELECT |MODE_OP_PENDING : 1821c1 = 's' ; 1822c2 = 'o' ; 1823break ; 1824case MODE_NORMAL |MODE_VISUAL |MODE_SELECT : 1825c1 = 'n' ; 1826c2 = 'v' ; 1827break ; 1828case MODE_NORMAL |MODE_VISUAL |MODE_OP_PENDING : 1829c1 = 'n' ; 1830c2 = 'x' ; 1831c3 = 'o' ; 1832break ; 1833case MODE_NORMAL |MODE_SELECT |MODE_OP_PENDING : 1834c1 = 'n' ; 1835c2 = 's' ; 1836c3 = 'o' ; 1837break ; 1838case MODE_VISUAL |MODE_SELECT |MODE_OP_PENDING : 1839c1 = 'v' ; 1840c2 = 'o' ; 1841break ; 1842case MODE_CMDLINE |MODE_INSERT : 1843if (!abbr ) { 1844cmd = "map!" ; 1845 } 1846break ; 1847case MODE_CMDLINE : 1848c1 = 'c' ; 1849break ; 1850case MODE_INSERT : 1851c1 = 'i' ; 1852break ; 1853case MODE_LANGMAP : 1854c1 = 'l' ; 1855break ; 1856case MODE_TERMINAL : 1857c1 = 't' ; 1858break ; 1859default : 1860iemsg (_ ("E228: makemap: Illegal mode" )); 1861return FAIL ; 1862 } 1863do {// do this twice if c2 is set, 3 times with c3 1864// When outputting <> form, need to make sure that 'cpo' 1865// is set to the Vim default. 1866if (!did_cpo ) { 1867if (* mp -> m_str == NUL ) {// Will use <Nop>. 1868did_cpo = true; 1869 }else { 1870const char specials []= { (char )(uint8_t )K_SPECIAL ,NL ,NUL }; 1871if (strpbrk (mp -> m_str ,specials )!= NULL || strpbrk (mp -> m_keys ,specials )!= NULL ) { 1872did_cpo = true; 1873 } 1874 } 1875if (did_cpo ) { 1876if (fprintf (fd ,"let s:cpo_save=&cpo" )< 0 1877|| put_eol (fd )< 0 1878|| fprintf (fd ,"set cpo&vim" )< 0 1879|| put_eol (fd )< 0 ) { 1880return FAIL ; 1881 } 1882 } 1883 } 1884if (c1 && putc (c1 ,fd )< 0 ) { 1885return FAIL ; 1886 } 1887if (mp -> m_noremap != REMAP_YES && fprintf (fd ,"nore" )< 0 ) { 1888return FAIL ; 1889 } 1890if (fputs (cmd ,fd )< 0 ) { 1891return FAIL ; 1892 } 1893if (buf != NULL && fputs (" <buffer>" ,fd )< 0 ) { 1894return FAIL ; 1895 } 1896if (mp -> m_nowait && fputs (" <nowait>" ,fd )< 0 ) { 1897return FAIL ; 1898 } 1899if (mp -> m_silent && fputs (" <silent>" ,fd )< 0 ) { 1900return FAIL ; 1901 } 1902if (mp -> m_expr && fputs (" <expr>" ,fd )< 0 ) { 1903return FAIL ; 1904 } 1905 1906if (putc (' ' ,fd )< 0 1907|| put_escstr (fd ,mp -> m_keys ,0 )== FAIL 1908|| putc (' ' ,fd )< 0 1909|| put_escstr (fd ,mp -> m_str ,1 )== FAIL 1910|| put_eol (fd )< 0 ) { 1911return FAIL ; 1912 } 1913c1 = c2 ; 1914c2 = c3 ; 1915c3 = NUL ; 1916 }while (c1 != NUL ); 1917 } 1918 } 1919 } 1920if (did_cpo ) { 1921if (fprintf (fd ,"let &cpo=s:cpo_save" )< 0 1922|| put_eol (fd )< 0 1923|| fprintf (fd ,"unlet s:cpo_save" )< 0 1924|| put_eol (fd )< 0 ) { 1925return FAIL ; 1926 } 1927 } 1928return OK ; 1929} 1930 1931// write escape string to file 1932// "what": 0 for :map lhs, 1 for :map rhs, 2 for :set 1933// 1934// return FAIL for failure, OK otherwise 1935int put_escstr (FILE * fd ,const char * strstart ,int what ) 1936{ 1937uint8_t * str = (uint8_t * )strstart ; 1938 1939// :map xx <Nop> 1940if (* str == NUL && what == 1 ) { 1941if (fprintf (fd ,"<Nop>" )< 0 ) { 1942return FAIL ; 1943 } 1944return OK ; 1945 } 1946 1947for (;* str != NUL ;str ++ ) { 1948// Check for a multi-byte character, which may contain escaped 1949// K_SPECIAL bytes. 1950const char * p = mb_unescape ((const char ** )& str ); 1951if (p != NULL ) { 1952while (* p != NUL ) { 1953if (fputc (* p ++ ,fd )< 0 ) { 1954return FAIL ; 1955 } 1956 } 1957str -- ; 1958continue ; 1959 } 1960 1961int c = * str ; 1962// Special key codes have to be translated to be able to make sense 1963// when they are read back. 1964if (c == K_SPECIAL && what != 2 ) { 1965int modifiers = 0 ; 1966if (str [1 ]== KS_MODIFIER ) { 1967modifiers = str [2 ]; 1968str += 3 ; 1969 1970// Modifiers can be applied too to multi-byte characters. 1971p = mb_unescape ((const char ** )& str ); 1972 1973if (p == NULL ) { 1974c = * str ; 1975 }else { 1976// retrieve codepoint (character number) from unescaped string 1977c = utf_ptr2char (p ); 1978str -- ; 1979 } 1980 } 1981if (c == K_SPECIAL ) { 1982c = TO_SPECIAL (str [1 ],str [2 ]); 1983str += 2 ; 1984 } 1985if (IS_SPECIAL (c )|| modifiers ) {// special key 1986if (fputs (get_special_key_name (c ,modifiers ),fd )< 0 ) { 1987return FAIL ; 1988 } 1989continue ; 1990 } 1991 } 1992 1993// A '\n' in a map command should be written as <NL>. 1994// A '\n' in a set command should be written as \^V^J. 1995if (c == NL ) { 1996if (what == 2 ) { 1997if (fprintf (fd ,"\\\026\n" )< 0 ) { 1998return FAIL ; 1999 } 2000 }else { 2001if (fprintf (fd ,"<NL>" )< 0 ) { 2002return FAIL ; 2003 } 2004 } 2005continue ; 2006 } 2007 2008// Some characters have to be escaped with CTRL-V to 2009// prevent them from misinterpreted in DoOneCmd(). 2010// A space, Tab and '"' has to be escaped with a backslash to 2011// prevent it to be misinterpreted in do_set(). 2012// A space has to be escaped with a CTRL-V when it's at the start of a 2013// ":map" rhs. 2014// A '<' has to be escaped with a CTRL-V to prevent it being 2015// interpreted as the start of a special key name. 2016// A space in the lhs of a :map needs a CTRL-V. 2017if (what == 2 && (ascii_iswhite (c )|| c == '"' || c == '\\' )) { 2018if (putc ('\\' ,fd )< 0 ) { 2019return FAIL ; 2020 } 2021 }else if (c < ' ' || c > '~' || c == '|' 2022|| (what == 0 && c == ' ' ) 2023|| (what == 1 && str == (uint8_t * )strstart && c == ' ' ) 2024|| (what != 2 && c == '<' )) { 2025if (putc (Ctrl_V ,fd )< 0 ) { 2026return FAIL ; 2027 } 2028 } 2029if (putc (c ,fd )< 0 ) { 2030return FAIL ; 2031 } 2032 } 2033return OK ; 2034} 2035 2036/// Check the string "keys" against the lhs of all mappings. 2037/// Return pointer to rhs of mapping (mapblock->m_str). 2038/// NULL when no mapping found. 2039/// 2040/// @param exact require exact match 2041/// @param ign_mod ignore preceding modifier 2042/// @param abbr do abbreviations 2043/// @param mp_ptr return: pointer to mapblock or NULL 2044/// @param local_ptr return: buffer-local mapping or NULL 2045char * check_map (char * keys ,int mode ,int exact ,int ign_mod ,int abbr ,mapblock_T ** mp_ptr , 2046int * local_ptr ,int * rhs_lua ) 2047{ 2048* rhs_lua = LUA_NOREF ; 2049 2050int len = (int )strlen (keys ); 2051for (int local = 1 ;local >=0 ;local -- ) { 2052// loop over all hash lists 2053for (int hash = 0 ;hash < 256 ;hash ++ ) { 2054mapblock_T * mp ; 2055if (abbr ) { 2056if (hash > 0 ) {// there is only one list. 2057break ; 2058 } 2059if (local ) { 2060mp = curbuf -> b_first_abbr ; 2061 }else { 2062mp = first_abbr ; 2063 } 2064 }else if (local ) { 2065mp = curbuf -> b_maphash [hash ]; 2066 }else { 2067mp = maphash [hash ]; 2068 } 2069for (;mp != NULL ;mp = mp -> m_next ) { 2070// skip entries with wrong mode, wrong length and not matching ones 2071if ((mp -> m_mode & mode )&& (!exact || mp -> m_keylen == len )) { 2072char * s = mp -> m_keys ; 2073int keylen = mp -> m_keylen ; 2074if (ign_mod && keylen >=3 2075&& (uint8_t )s [0 ]== K_SPECIAL && (uint8_t )s [1 ]== KS_MODIFIER ) { 2076s += 3 ; 2077keylen -= 3 ; 2078 } 2079int minlen = keylen < len ?keylen :len ; 2080if (strncmp (s ,keys , (size_t )minlen )== 0 ) { 2081if (mp_ptr != NULL ) { 2082* mp_ptr = mp ; 2083 } 2084if (local_ptr != NULL ) { 2085* local_ptr = local ; 2086 } 2087* rhs_lua = mp -> m_luaref ; 2088return mp -> m_luaref == LUA_NOREF ?mp -> m_str :NULL ; 2089 } 2090 } 2091 } 2092 } 2093 } 2094 2095return NULL ; 2096} 2097 2098/// "hasmapto()" function 2099void f_hasmapto (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2100{ 2101const char * mode ; 2102const char * const name = tv_get_string (& argvars [0 ]); 2103bool abbr = false; 2104char buf [NUMBUFLEN ]; 2105if (argvars [1 ].v_type == VAR_UNKNOWN ) { 2106mode = "nvo" ; 2107 }else { 2108mode = tv_get_string_buf (& argvars [1 ],buf ); 2109if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2110abbr = tv_get_bool (& argvars [2 ]); 2111 } 2112 } 2113 2114rettv -> vval .v_number = map_to_exists (name ,mode ,abbr ); 2115} 2116 2117/// Fill a Dict with all applicable maparg() like dictionaries 2118/// 2119/// @param mp The maphash that contains the mapping information 2120/// @param buffer_value The "buffer" value 2121/// @param abbr True if abbreviation 2122/// @param compatible True for compatible with old maparg() dict 2123/// 2124/// @return Dict. 2125static Dict mapblock_fill_dict (const mapblock_T * const mp ,const char * lhsrawalt , 2126const int buffer_value ,const bool abbr ,const bool compatible , 2127Arena * arena ) 2128FUNC_ATTR_NONNULL_ARG (1 ) 2129{ 2130Dict dict = arena_dict (arena ,20 ); 2131char * const lhs = str2special_arena (mp -> m_keys ,compatible ,compatible ?kFalse :kNone ,arena ); 2132char * mapmode = arena_alloc (arena ,7 , false); 2133map_mode_to_chars (mp -> m_mode ,mapmode ); 2134int noremap_value ; 2135 2136if (compatible ) { 2137// Keep old compatible behavior 2138// This is unable to determine whether a mapping is a <script> mapping 2139noremap_value = !!mp -> m_noremap ; 2140 }else { 2141// Distinguish between <script> mapping 2142// If it's not a <script> mapping, check if it's a noremap 2143noremap_value = mp -> m_noremap == REMAP_SCRIPT ?2 : !!mp -> m_noremap ; 2144 } 2145 2146if (mp -> m_luaref != LUA_NOREF ) { 2147PUT_C (dict ,"callback" ,LUAREF_OBJ (api_new_luaref (mp -> m_luaref ))); 2148 }else { 2149String rhs = cstr_as_string (compatible 2150 ?mp -> m_orig_str 2151 :str2special_arena (mp -> m_str , false,kNone ,arena )); 2152PUT_C (dict ,"rhs" ,STRING_OBJ (rhs )); 2153 } 2154if (mp -> m_desc != NULL ) { 2155PUT_C (dict ,"desc" ,CSTR_AS_OBJ (mp -> m_desc )); 2156 } 2157PUT_C (dict ,"lhs" ,CSTR_AS_OBJ (lhs )); 2158PUT_C (dict ,"lhsraw" ,CSTR_AS_OBJ (mp -> m_keys )); 2159if (lhsrawalt != NULL ) { 2160// Also add the value for the simplified entry. 2161PUT_C (dict ,"lhsrawalt" ,CSTR_AS_OBJ (lhsrawalt )); 2162 } 2163PUT_C (dict ,"noremap" ,INTEGER_OBJ (noremap_value )); 2164PUT_C (dict ,"script" ,INTEGER_OBJ (mp -> m_noremap == REMAP_SCRIPT ?1 :0 )); 2165PUT_C (dict ,"expr" ,INTEGER_OBJ (mp -> m_expr ?1 :0 )); 2166PUT_C (dict ,"silent" ,INTEGER_OBJ (mp -> m_silent ?1 :0 )); 2167PUT_C (dict ,"sid" ,INTEGER_OBJ (mp -> m_script_ctx .sc_sid )); 2168PUT_C (dict ,"scriptversion" ,INTEGER_OBJ (1 )); 2169PUT_C (dict ,"lnum" ,INTEGER_OBJ (mp -> m_script_ctx .sc_lnum )); 2170PUT_C (dict ,"buffer" ,INTEGER_OBJ (buffer_value )); 2171if (!compatible ) { 2172PUT_C (dict ,"buf" ,INTEGER_OBJ (buffer_value )); 2173 } 2174PUT_C (dict ,"nowait" ,INTEGER_OBJ (mp -> m_nowait ?1 :0 )); 2175PUT_C (dict ,"replace_keycodes" ,INTEGER_OBJ (mp -> m_replace_keycodes ?1 :0 )); 2176PUT_C (dict ,"mode" ,CSTR_AS_OBJ (mapmode )); 2177PUT_C (dict ,"abbr" ,INTEGER_OBJ (abbr ?1 :0 )); 2178PUT_C (dict ,"mode_bits" ,INTEGER_OBJ (mp -> m_mode )); 2179 2180return dict ; 2181} 2182 2183static void get_maparg (typval_T * argvars ,typval_T * rettv ,int exact ) 2184{ 2185// Return empty string for failure. 2186rettv -> v_type = VAR_STRING ; 2187rettv -> vval .v_string = NULL ; 2188 2189char * keys = (char * )tv_get_string (& argvars [0 ]); 2190if (* keys == NUL ) { 2191return ; 2192 } 2193 2194const char * which ; 2195char buf [NUMBUFLEN ]; 2196bool abbr = false; 2197bool get_dict = false; 2198 2199if (argvars [1 ].v_type != VAR_UNKNOWN ) { 2200which = tv_get_string_buf_chk (& argvars [1 ],buf ); 2201if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2202abbr = (bool )tv_get_bool (& argvars [2 ]); 2203if (argvars [3 ].v_type != VAR_UNKNOWN ) { 2204get_dict = (bool )tv_get_bool (& argvars [3 ]); 2205 } 2206 } 2207 }else { 2208which = "" ; 2209 } 2210if (which == NULL ) { 2211return ; 2212 } 2213 2214char * keys_buf = NULL ; 2215char * alt_keys_buf = NULL ; 2216bool did_simplify = false; 2217const int flags = REPTERM_FROM_PART |REPTERM_DO_LT ; 2218const int mode = get_map_mode ((char ** )& which ,0 ); 2219 2220char * keys_simplified = replace_termcodes (keys ,strlen (keys ),& keys_buf ,0 , 2221flags ,& did_simplify ,p_cpo ); 2222mapblock_T * mp = NULL ; 2223int buffer_local ; 2224LuaRef rhs_lua ; 2225char * rhs = check_map (keys_simplified ,mode ,exact , false,abbr ,& mp ,& buffer_local , 2226& rhs_lua ); 2227if (did_simplify ) { 2228// When the lhs is being simplified the not-simplified keys are 2229// preferred for printing, like in do_map(). 2230replace_termcodes (keys ,strlen (keys ),& alt_keys_buf ,0 , 2231flags |REPTERM_NO_SIMPLIFY ,NULL ,p_cpo ); 2232rhs = check_map (alt_keys_buf ,mode ,exact , false,abbr ,& mp ,& buffer_local ,& rhs_lua ); 2233 } 2234 2235if (!get_dict ) { 2236// Return a string. 2237if (rhs != NULL ) { 2238if (* rhs == NUL ) { 2239rettv -> vval .v_string = xstrdup ("<Nop>" ); 2240 }else { 2241rettv -> vval .v_string = str2special_save (rhs , false, false); 2242 } 2243 }else if (rhs_lua != LUA_NOREF ) { 2244rettv -> vval .v_string = nlua_funcref_str (mp -> m_luaref ,NULL , true); 2245 } 2246 }else { 2247// Return a dictionary. 2248if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF )) { 2249Arena arena = ARENA_EMPTY ; 2250Dict dict = mapblock_fill_dict (mp ,did_simplify ?keys_simplified :NULL , 2251buffer_local ,abbr , true,& arena ); 2252object_to_vim_take_luaref (& DICT_OBJ (dict ),rettv , true,NULL ); 2253arena_mem_free (arena_finish (& arena )); 2254 }else { 2255// Return an empty dictionary. 2256tv_dict_alloc_ret (rettv ); 2257 } 2258 } 2259 2260xfree (keys_buf ); 2261xfree (alt_keys_buf ); 2262} 2263 2264/// Get the mapping mode from the mode string. 2265/// It may contain multiple characters, eg "nox", or "!", or ' ' 2266/// Return 0 if there is an error. 2267static int get_map_mode_string (const char * const mode_string ,const bool abbr ) 2268{ 2269const char * p = mode_string ; 2270const int MASK_V = MODE_VISUAL |MODE_SELECT ; 2271const int MASK_MAP = MODE_VISUAL |MODE_SELECT |MODE_NORMAL |MODE_OP_PENDING ; 2272const int MASK_BANG = MODE_INSERT |MODE_CMDLINE ; 2273 2274if (* p == NUL ) { 2275p = " " ;// compatibility 2276 } 2277int mode = 0 ; 2278int modec ; 2279while ((modec = (uint8_t )(* p ++ ))) { 2280int tmode ; 2281switch (modec ) { 2282case 'i' : 2283tmode = MODE_INSERT ;break ; 2284case 'l' : 2285tmode = MODE_LANGMAP ;break ; 2286case 'c' : 2287tmode = MODE_CMDLINE ;break ; 2288case 'n' : 2289tmode = MODE_NORMAL ;break ; 2290case 'x' : 2291tmode = MODE_VISUAL ;break ; 2292case 's' : 2293tmode = MODE_SELECT ;break ; 2294case 'o' : 2295tmode = MODE_OP_PENDING ;break ; 2296case 't' : 2297tmode = MODE_TERMINAL ;break ; 2298case 'v' : 2299tmode = MASK_V ;break ; 2300case '!' : 2301tmode = MASK_BANG ;break ; 2302case ' ' : 2303tmode = MASK_MAP ;break ; 2304default : 2305return 0 ;// error, unknown mode character 2306 } 2307mode |=tmode ; 2308 } 2309if ((abbr && (mode & ~MASK_BANG )!= 0 ) 2310|| (!abbr && (mode & (mode - 1 ))!= 0 // more than one bit set 2311&& ( 2312// false if multiple bits set in mode and mode is fully 2313// contained in one mask 2314 !(((mode & MASK_BANG )!= 0 && (mode & ~MASK_BANG )== 0 ) 2315|| ((mode & MASK_MAP )!= 0 && (mode & ~MASK_MAP )== 0 ))))) { 2316return 0 ; 2317 } 2318 2319return mode ; 2320} 2321 2322/// "mapset()" function 2323void f_mapset (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2324{ 2325if (check_secure ()) { 2326return ; 2327 } 2328 2329const char * which ; 2330char buf [NUMBUFLEN ]; 2331int is_abbr ; 2332dict_T * d ; 2333 2334// If first arg is a dict, then that's the only arg permitted. 2335const bool dict_only = argvars [0 ].v_type == VAR_DICT ; 2336 2337if (dict_only ) { 2338d = argvars [0 ].vval .v_dict ; 2339which = tv_dict_get_string (d ,"mode" , false); 2340is_abbr = (int )tv_dict_get_bool (d ,"abbr" ,-1 ); 2341if (which == NULL || is_abbr < 0 ) { 2342emsg (_ (e_entries_missing_in_mapset_dict_argument )); 2343return ; 2344 } 2345 }else { 2346which = tv_get_string_buf_chk (& argvars [0 ],buf ); 2347if (which == NULL ) { 2348return ; 2349 } 2350is_abbr = (int )tv_get_bool (& argvars [1 ]); 2351if (tv_check_for_dict_arg (argvars ,2 )== FAIL ) { 2352return ; 2353 } 2354d = argvars [2 ].vval .v_dict ; 2355 } 2356const int mode = get_map_mode_string (which ,is_abbr ); 2357if (mode == 0 ) { 2358semsg (_ (e_illegal_map_mode_string_str ),which ); 2359return ; 2360 } 2361 2362// Get the values in the same order as above in get_maparg(). 2363char * lhs = tv_dict_get_string (d ,"lhs" , false); 2364char * lhsraw = tv_dict_get_string (d ,"lhsraw" , false); 2365char * lhsrawalt = tv_dict_get_string (d ,"lhsrawalt" , false); 2366char * orig_rhs = tv_dict_get_string (d ,"rhs" , false); 2367LuaRef rhs_lua = LUA_NOREF ; 2368dictitem_T * callback_di = tv_dict_find (d ,S_LEN ("callback" )); 2369if (callback_di != NULL ) { 2370if (callback_di -> di_tv .v_type == VAR_FUNC ) { 2371ufunc_T * fp = find_func (callback_di -> di_tv .vval .v_string ); 2372if (fp != NULL && (fp -> uf_flags & FC_LUAREF )) { 2373rhs_lua = api_new_luaref (fp -> uf_luaref ); 2374orig_rhs = "" ; 2375 } 2376 } 2377 } 2378if (lhs == NULL || lhsraw == NULL || orig_rhs == NULL ) { 2379emsg (_ (e_entries_missing_in_mapset_dict_argument )); 2380api_free_luaref (rhs_lua ); 2381return ; 2382 } 2383 2384int noremap = tv_dict_get_number (d ,"noremap" )!= 0 ?REMAP_NONE :0 ; 2385if (tv_dict_get_number (d ,"script" )!= 0 ) { 2386noremap = REMAP_SCRIPT ; 2387 } 2388MapArguments args = { 2389 .expr = tv_dict_get_number (d ,"expr" )!= 0 , 2390 .silent = tv_dict_get_number (d ,"silent" )!= 0 , 2391 .nowait = tv_dict_get_number (d ,"nowait" )!= 0 , 2392 .replace_keycodes = tv_dict_get_number (d ,"replace_keycodes" )!= 0 , 2393 .desc = tv_dict_get_string (d ,"desc" , true), 2394 }; 2395scid_T sid = (scid_T )tv_dict_get_number (d ,"sid" ); 2396linenr_T lnum = (linenr_T )tv_dict_get_number (d ,"lnum" ); 2397bool buffer = tv_dict_get_number (d ,"buffer" )!= 0 ; 2398// mode from the dict is not used 2399 2400set_maparg_rhs (orig_rhs ,strlen (orig_rhs ),rhs_lua ,sid ,p_cpo ,& args ); 2401 2402mapblock_T ** map_table = buffer ?curbuf -> b_maphash :maphash ; 2403mapblock_T ** abbr_table = buffer ?& curbuf -> b_first_abbr :& first_abbr ; 2404 2405// Delete any existing mapping for this lhs and mode. 2406MapArguments unmap_args = MAP_ARGUMENTS_INIT ; 2407set_maparg_lhs_rhs (lhs ,strlen (lhs ),"" ,0 ,LUA_NOREF ,p_cpo ,& unmap_args ); 2408unmap_args .buffer = buffer ; 2409buf_do_map (MAPTYPE_UNMAP_LHS ,& unmap_args ,mode ,is_abbr ,curbuf ); 2410xfree (unmap_args .rhs ); 2411xfree (unmap_args .orig_rhs ); 2412 2413mapblock_T * mp_result [2 ]= {NULL ,NULL }; 2414 2415mp_result [0 ]= map_add (curbuf ,map_table ,abbr_table ,lhsraw ,& args , 2416noremap ,mode ,is_abbr ,sid ,lnum , false); 2417if (lhsrawalt != NULL ) { 2418mp_result [1 ]= map_add (curbuf ,map_table ,abbr_table ,lhsrawalt ,& args , 2419noremap ,mode ,is_abbr ,sid ,lnum , true); 2420 } 2421 2422if (mp_result [0 ]!= NULL && mp_result [1 ]!= NULL ) { 2423mp_result [0 ]-> m_alt = mp_result [1 ]; 2424mp_result [1 ]-> m_alt = mp_result [0 ]; 2425 } 2426} 2427 2428/// "maplist()" function 2429void f_maplist (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2430{ 2431const int flags = REPTERM_FROM_PART |REPTERM_DO_LT ; 2432const bool abbr = argvars [0 ].v_type != VAR_UNKNOWN && tv_get_bool (& argvars [0 ]); 2433 2434tv_list_alloc_ret (rettv ,kListLenUnknown ); 2435 2436// Do it twice: once for global maps and once for local maps. 2437for (int buffer_local = 0 ;buffer_local <=1 ;buffer_local ++ ) { 2438for (int hash = 0 ;hash < 256 ;hash ++ ) { 2439mapblock_T * mp ; 2440if (abbr ) { 2441if (hash > 0 ) {// there is only one abbr list 2442break ; 2443 } 2444if (buffer_local ) { 2445mp = curbuf -> b_first_abbr ; 2446 }else { 2447mp = first_abbr ; 2448 } 2449 }else if (buffer_local ) { 2450mp = curbuf -> b_maphash [hash ]; 2451 }else { 2452mp = maphash [hash ]; 2453 } 2454for (;mp ;mp = mp -> m_next ) { 2455if (mp -> m_simplified ) { 2456continue ; 2457 } 2458 2459char * keys_buf = NULL ; 2460bool did_simplify = false; 2461 2462Arena arena = ARENA_EMPTY ; 2463char * lhs = str2special_arena (mp -> m_keys , true, false,& arena ); 2464replace_termcodes (lhs ,strlen (lhs ),& keys_buf ,0 ,flags ,& did_simplify , 2465p_cpo ); 2466 2467Dict dict = mapblock_fill_dict (mp ,did_simplify ?keys_buf :NULL ,buffer_local ,abbr , true, 2468& arena ); 2469typval_T d = TV_INITIAL_VALUE ; 2470object_to_vim_take_luaref (& DICT_OBJ (dict ),& d , true,NULL ); 2471assert (d .v_type == VAR_DICT ); 2472tv_list_append_dict (rettv -> vval .v_list ,d .vval .v_dict ); 2473arena_mem_free (arena_finish (& arena )); 2474xfree (keys_buf ); 2475 } 2476 } 2477 } 2478} 2479 2480/// "maparg()" function 2481void f_maparg (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2482{ 2483get_maparg (argvars ,rettv , true); 2484} 2485 2486/// "mapcheck()" function 2487void f_mapcheck (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2488{ 2489get_maparg (argvars ,rettv , false); 2490} 2491 2492/// Add a mapping. Unlike @ref do_map this copies the string arguments, so 2493/// static or read-only strings can be used. 2494/// 2495/// @param lhs C-string containing the lhs of the mapping 2496/// @param rhs C-string containing the rhs of the mapping 2497/// @param mode Bitflags representing the mode in which to set the mapping. 2498/// See @ref get_map_mode. 2499/// @param buffer If true, make a buffer-local mapping for curbuf 2500void add_map (char * lhs ,char * rhs ,int mode ,bool buffer ) 2501{ 2502MapArguments args = MAP_ARGUMENTS_INIT ; 2503set_maparg_lhs_rhs (lhs ,strlen (lhs ),rhs ,strlen (rhs ),LUA_NOREF ,p_cpo ,& args ); 2504args .buffer = buffer ; 2505 2506buf_do_map (MAPTYPE_NOREMAP ,& args ,mode , false,curbuf ); 2507xfree (args .rhs ); 2508xfree (args .orig_rhs ); 2509} 2510 2511/// Any character has an equivalent 'langmap' character. This is used for 2512/// keyboards that have a special language mode that sends characters above 2513/// 128 (although other characters can be translated too). The "to" field is a 2514/// Vim command character. This avoids having to switch the keyboard back to 2515/// ASCII mode when leaving Insert mode. 2516/// 2517/// langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim 2518/// commands. 2519/// langmap_mapga.ga_data is a sorted table of langmap_entry_T. 2520/// This does the same as langmap_mapchar[] for characters >= 256. 2521/// 2522/// With multi-byte support use growarray for 'langmap' chars >= 256 2523typedef struct { 2524int from ; 2525int to ; 2526}langmap_entry_T ; 2527 2528static garray_T langmap_mapga = GA_EMPTY_INIT_VALUE ; 2529 2530/// Search for an entry in "langmap_mapga" for "from". If found set the "to" 2531/// field. If not found insert a new entry at the appropriate location. 2532static void langmap_set_entry (int from ,int to ) 2533{ 2534langmap_entry_T * entries = (langmap_entry_T * )(langmap_mapga .ga_data ); 2535unsigned a = 0 ; 2536assert (langmap_mapga .ga_len >=0 ); 2537unsigned b = (unsigned )langmap_mapga .ga_len ; 2538 2539// Do a binary search for an existing entry. 2540while (a != b ) { 2541unsigned i = (a + b ) /2 ; 2542int d = entries [i ].from - from ; 2543 2544if (d == 0 ) { 2545entries [i ].to = to ; 2546return ; 2547 } 2548if (d < 0 ) { 2549a = i + 1 ; 2550 }else { 2551b = i ; 2552 } 2553 } 2554 2555ga_grow (& langmap_mapga ,1 ); 2556 2557// insert new entry at position "a" 2558entries = (langmap_entry_T * )(langmap_mapga .ga_data )+ a ; 2559memmove (entries + 1 ,entries , 2560 ((unsigned )langmap_mapga .ga_len - a )* sizeof (langmap_entry_T )); 2561langmap_mapga .ga_len ++ ; 2562entries [0 ].from = from ; 2563entries [0 ].to = to ; 2564} 2565 2566/// Apply 'langmap' to multi-byte character "c" and return the result. 2567int langmap_adjust_mb (int c ) 2568{ 2569langmap_entry_T * entries = (langmap_entry_T * )(langmap_mapga .ga_data ); 2570int a = 0 ; 2571int b = langmap_mapga .ga_len ; 2572 2573while (a != b ) { 2574int i = (a + b ) /2 ; 2575int d = entries [i ].from - c ; 2576 2577if (d == 0 ) { 2578return entries [i ].to ;// found matching entry 2579 } 2580if (d < 0 ) { 2581a = i + 1 ; 2582 }else { 2583b = i ; 2584 } 2585 } 2586return c ;// no entry found, return "c" unmodified 2587} 2588 2589void langmap_init (void ) 2590{ 2591for (int i = 0 ;i < 256 ;i ++ ) { 2592langmap_mapchar [i ]= (uint8_t )i ;// we init with a one-to-one map 2593 } 2594ga_init (& langmap_mapga ,sizeof (langmap_entry_T ),8 ); 2595} 2596 2597/// Called when langmap option is set; the language map can be 2598/// changed at any time! 2599const char * did_set_langmap (optset_T * args ) 2600{ 2601ga_clear (& langmap_mapga );// clear the previous map first 2602langmap_init ();// back to one-to-one map 2603 2604for (char * p = p_langmap ;p [0 ]!= NUL ;) { 2605char * p2 ; 2606for (p2 = p ;p2 [0 ]!= NUL && p2 [0 ]!= ',' && p2 [0 ]!= ';' ; 2607MB_PTR_ADV (p2 )) { 2608if (p2 [0 ]== '\\' && p2 [1 ]!= NUL ) { 2609p2 ++ ; 2610 } 2611 } 2612if (p2 [0 ]== ';' ) { 2613p2 ++ ;// abcd;ABCD form, p2 points to A 2614 }else { 2615p2 = NULL ;// aAbBcCdD form, p2 is NULL 2616 } 2617while (p [0 ]) { 2618if (p [0 ]== ',' ) { 2619p ++ ; 2620break ; 2621 } 2622if (p [0 ]== '\\' && p [1 ]!= NUL ) { 2623p ++ ; 2624 } 2625int from = utf_ptr2char (p ); 2626const char * const from_ptr = p ; 2627int to = NUL ; 2628const char * to_ptr = "" ; 2629if (p2 == NULL ) { 2630MB_PTR_ADV (p ); 2631if (p [0 ]!= ',' ) { 2632if (p [0 ]== '\\' ) { 2633p ++ ; 2634 } 2635to = utf_ptr2char (to_ptr = p ); 2636 } 2637 }else { 2638if (p2 [0 ]!= ',' ) { 2639if (p2 [0 ]== '\\' ) { 2640p2 ++ ; 2641 } 2642to = utf_ptr2char (to_ptr = p2 ); 2643 } 2644 } 2645if (to == NUL ) { 2646return opt_error (args -> os_errbuf ,N_ ("E357: 'langmap': Matching character missing for %s" ), 2647transchar (from )); 2648 } 2649 2650if (from >=256 ) { 2651langmap_set_entry (from ,to ); 2652 }else { 2653if (to > UCHAR_MAX ) { 2654swmsg (true,"'langmap': Mapping from %.*s to %.*s will not work properly" , 2655utf_ptr2len (from_ptr ),from_ptr ,utf_ptr2len (to_ptr ),to_ptr ); 2656 } 2657langmap_mapchar [from & 255 ]= (uint8_t )to ; 2658 } 2659 2660// Advance to next pair 2661MB_PTR_ADV (p ); 2662if (p2 != NULL ) { 2663MB_PTR_ADV (p2 ); 2664if (* p == ';' ) { 2665p = p2 ; 2666if (p [0 ]!= NUL ) { 2667if (p [0 ]!= ',' ) { 2668return opt_error (args -> os_errbuf , 2669N_ ("E358: 'langmap': Extra characters after semicolon: %s" ),p ); 2670 } 2671p ++ ; 2672 } 2673break ; 2674 } 2675 } 2676 } 2677 } 2678 2679return NULL ; 2680} 2681 2682static void do_exmap (exarg_T * eap ,int isabbrev ) 2683{ 2684char * cmdp = eap -> cmd ; 2685int mode = get_map_mode (& cmdp ,eap -> forceit || isabbrev ); 2686 2687int maptype ; 2688if (* cmdp == 'n' ) { 2689maptype = MAPTYPE_NOREMAP ; 2690 }else if (* cmdp == 'u' ) { 2691maptype = MAPTYPE_UNMAP ; 2692 }else { 2693maptype = MAPTYPE_MAP ; 2694 } 2695MapArguments parsed_args ; 2696int result = str_to_mapargs (eap -> arg ,maptype == MAPTYPE_UNMAP ,& parsed_args ); 2697switch (result ) { 2698case 0 : 2699break ; 2700case 1 : 2701emsg (_ (e_invarg )); 2702 gotofree_rhs ; 2703break ; 2704default : 2705assert (false&& "Unknown return code from str_to_mapargs!" ); 2706 gotofree_rhs ; 2707 } 2708switch (buf_do_map (maptype ,& parsed_args ,mode ,isabbrev ,curbuf )) { 2709case 1 : 2710emsg (_ (e_invarg )); 2711break ; 2712case 2 : 2713emsg (isabbrev ?_ (e_noabbr ) :_ (e_nomap )); 2714break ; 2715case 5 : 2716semsg (isabbrev ?_ (e_abbreviation_already_exists_for_str ) 2717 :_ (e_mapping_already_exists_for_str ), 2718parsed_args .lhs ); 2719break ; 2720case 6 : 2721semsg (isabbrev ?_ (e_global_abbreviation_already_exists_for_str ) 2722 :_ (e_global_mapping_already_exists_for_str ), 2723parsed_args .lhs ); 2724 } 2725free_rhs : 2726xfree (parsed_args .rhs ); 2727xfree (parsed_args .orig_rhs ); 2728} 2729 2730/// ":abbreviate" and friends. 2731void ex_abbreviate (exarg_T * eap ) 2732{ 2733do_exmap (eap , true);// almost the same as mapping 2734} 2735 2736/// ":map" and friends. 2737void ex_map (exarg_T * eap ) 2738{ 2739// If we are in a secure mode we print the mappings for security reasons. 2740if (secure ) { 2741secure = 2 ; 2742msg_outtrans (eap -> cmd ,0 , false); 2743msg_putchar ('\n' ); 2744 } 2745do_exmap (eap , false); 2746} 2747 2748/// ":unmap" and friends. 2749void ex_unmap (exarg_T * eap ) 2750{ 2751do_exmap (eap , false); 2752} 2753 2754/// ":mapclear" and friends. 2755void ex_mapclear (exarg_T * eap ) 2756{ 2757do_mapclear (eap -> cmd ,eap -> arg ,eap -> forceit , false); 2758} 2759 2760/// ":abclear" and friends. 2761void ex_abclear (exarg_T * eap ) 2762{ 2763do_mapclear (eap -> cmd ,eap -> arg , true, true); 2764} 2765 2766/// Set, tweak, or remove a mapping in a mode. Acts as the implementation for 2767/// functions like @ref nvim_buf_set_keymap. 2768/// 2769/// Arguments are handled like @ref nvim_set_keymap unless noted. 2770/// @param buffer Buffer handle for a specific buffer, or 0 for the current 2771/// buffer, or -1 to signify global behavior ("all buffers") 2772/// @param maptype MAPTYPE_MAP to set a mapping, MAPTYPE_UNMAP to remove the mapping that 2773/// matches {lhs} or {rhs}, MAPTYPE_UNMAP_LHS to only match {lhs}. 2774void modify_keymap (uint64_t channel_id ,Buffer buffer ,int maptype ,String mode ,String lhs , 2775String rhs ,Dict (keymap )* opts ,Error * err ) 2776{ 2777LuaRef lua_funcref = LUA_NOREF ; 2778bool is_unmap = maptype == MAPTYPE_UNMAP || maptype == MAPTYPE_UNMAP_LHS ; 2779bool global = (buffer == -1 ); 2780if (global ) { 2781buffer = 0 ; 2782 } 2783buf_T * target_buf = find_buffer_by_handle (buffer ,err ); 2784 2785if (!target_buf ) { 2786return ; 2787 } 2788 2789const sctx_T save_current_sctx = api_set_sctx (channel_id ); 2790 2791MapArguments parsed_args = MAP_ARGUMENTS_INIT ; 2792if (opts ) { 2793parsed_args .nowait = opts -> nowait ; 2794parsed_args .noremap = opts -> noremap ; 2795parsed_args .silent = opts -> silent ; 2796parsed_args .script = opts -> script ; 2797parsed_args .expr = opts -> expr ; 2798parsed_args .unique = opts -> unique ; 2799parsed_args .replace_keycodes = opts -> replace_keycodes ; 2800if (HAS_KEY (opts ,keymap ,callback )) { 2801lua_funcref = opts -> callback ; 2802opts -> callback = LUA_NOREF ; 2803 } 2804if (HAS_KEY (opts ,keymap ,desc )) { 2805parsed_args .desc = string_to_cstr (opts -> desc ); 2806 } 2807 } 2808parsed_args .buffer = !global ; 2809 2810if (parsed_args .replace_keycodes && !parsed_args .expr ) { 2811api_set_error (err ,kErrorTypeValidation ,"\"replace_keycodes\" requires \"expr\"" ); 2812 gotofail_and_free ; 2813 } 2814 2815if (!set_maparg_lhs_rhs (lhs .data ,lhs .size , 2816rhs .data ,rhs .size ,lua_funcref , 2817p_cpo ,& parsed_args )) { 2818api_set_error (err ,kErrorTypeValidation ,"LHS exceeds maximum map length: %s" ,lhs .data ); 2819 gotofail_and_free ; 2820 } 2821 2822if (parsed_args .lhs_len > MAXMAPLEN || parsed_args .alt_lhs_len > MAXMAPLEN ) { 2823api_set_error (err ,kErrorTypeValidation ,"LHS exceeds maximum map length: %s" ,lhs .data ); 2824 gotofail_and_free ; 2825 } 2826 2827char * p = mode .size > 0 ?mode .data :"m" ; 2828bool forceit = * p == '!' ; 2829// integer value of the mapping mode, to be passed to do_map() 2830int mode_val = get_map_mode (& p ,forceit ); 2831if (forceit ) { 2832assert (p == mode .data ); 2833p ++ ; 2834 } 2835bool is_abbrev = (mode_val & (MODE_INSERT |MODE_CMDLINE ))!= 0 && * p == 'a' ; 2836if (is_abbrev ) { 2837p ++ ; 2838 } 2839if (mode .size > 0 && (size_t )(p - mode .data )!= mode .size ) { 2840api_set_error (err ,kErrorTypeValidation ,"Invalid mode shortname: \"%s\"" ,mode .data ); 2841 gotofail_and_free ; 2842 } 2843 2844if (parsed_args .lhs_len == 0 ) { 2845api_set_error (err ,kErrorTypeValidation ,"Invalid (empty) LHS" ); 2846 gotofail_and_free ; 2847 } 2848 2849bool is_noremap = parsed_args .noremap ; 2850assert (!(is_unmap && is_noremap )); 2851 2852if (!is_unmap && lua_funcref == LUA_NOREF 2853&& (parsed_args .rhs_len == 0 && !parsed_args .rhs_is_noop )) { 2854if (rhs .size == 0 ) {// assume that the user wants RHS to be a <Nop> 2855parsed_args .rhs_is_noop = true; 2856 }else { 2857abort ();// should never happen 2858 } 2859 }else if (is_unmap && (parsed_args .rhs_len || parsed_args .rhs_lua != LUA_NOREF )) { 2860if (parsed_args .rhs_len ) { 2861api_set_error (err ,kErrorTypeValidation , 2862"Gave nonempty RHS in unmap command: %s" ,parsed_args .rhs ); 2863 }else { 2864api_set_error (err ,kErrorTypeValidation ,"Gave nonempty RHS for unmap" ); 2865 } 2866 gotofail_and_free ; 2867 } 2868 2869// buf_do_map() reads noremap/unmap as its own argument. 2870if (maptype == MAPTYPE_MAP && is_noremap ) { 2871maptype = MAPTYPE_NOREMAP ; 2872 } 2873 2874switch (buf_do_map (maptype ,& parsed_args ,mode_val ,is_abbrev ,target_buf )) { 2875case 0 : 2876break ; 2877case 1 : 2878api_set_error (err ,kErrorTypeException ,e_invarg ,0 ); 2879 gotofail_and_free ; 2880case 2 : 2881api_set_error (err ,kErrorTypeException ,e_nomap ,0 ); 2882 gotofail_and_free ; 2883case 5 : 2884api_set_error (err ,kErrorTypeException , 2885is_abbrev ?e_abbreviation_already_exists_for_str 2886 :e_mapping_already_exists_for_str ,lhs .data ); 2887 gotofail_and_free ; 2888break ; 2889case 6 : 2890api_set_error (err ,kErrorTypeException , 2891is_abbrev ?e_global_abbreviation_already_exists_for_str 2892 :e_global_mapping_already_exists_for_str ,lhs .data ); 2893 gotofail_and_free ; 2894default : 2895assert (false&& "Unrecognized return code!" ); 2896 gotofail_and_free ; 2897 }// switch 2898 2899fail_and_free : 2900current_sctx = save_current_sctx ; 2901NLUA_CLEAR_REF (parsed_args .rhs_lua ); 2902xfree (parsed_args .rhs ); 2903xfree (parsed_args .orig_rhs ); 2904xfree (parsed_args .desc ); 2905} 2906 2907/// Get an array containing dictionaries describing mappings 2908/// based on mode and buffer id 2909/// 2910/// @param mode The abbreviation for the mode 2911/// @param buf The buffer to get the mapping array. NULL for global 2912/// @returns Array of maparg()-like dictionaries describing mappings 2913ArrayOf (Dict )keymap_array (String mode ,buf_T * buf ,Arena * arena ) 2914{ 2915ArrayBuilder mappings = KV_INITIAL_VALUE ; 2916kvi_init (mappings ); 2917 2918char * p = mode .size > 0 ?mode .data :"m" ; 2919bool forceit = * p == '!' ; 2920// Convert the string mode to the integer mode stored within each mapblock. 2921int int_mode = get_map_mode (& p ,forceit ); 2922if (forceit ) { 2923assert (p == mode .data ); 2924p ++ ; 2925 } 2926bool is_abbrev = (int_mode & (MODE_INSERT |MODE_CMDLINE ))!= 0 && * p == 'a' ; 2927 2928// Determine the desired buffer value 2929int buffer_value = (buf == NULL ) ?0 :buf -> handle ; 2930 2931for (int i = 0 ;i < (is_abbrev ?1 :MAX_MAPHASH );i ++ ) { 2932for (const mapblock_T * current_maphash = is_abbrev 2933 ? (buf ?buf -> b_first_abbr :first_abbr ) 2934 : (buf ?buf -> b_maphash [i ] :maphash [i ]); 2935current_maphash ; 2936current_maphash = current_maphash -> m_next ) { 2937if (current_maphash -> m_simplified ) { 2938continue ; 2939 } 2940// Check for correct mode 2941if (int_mode & current_maphash -> m_mode ) { 2942kvi_push (mappings ,DICT_OBJ (mapblock_fill_dict (current_maphash , 2943current_maphash -> m_alt 2944 ?current_maphash -> m_alt -> m_keys :NULL , 2945buffer_value , 2946is_abbrev , false,arena ))); 2947 } 2948 } 2949 } 2950 2951return arena_take_arraybuilder (arena ,& mappings ); 2952}