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