xref: /vim-8.2.3635/src/getchar.c (revision 94688b8a)
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  * getchar.c
12  *
13  * functions related with getting a character from the user/mapping/redo/...
14  *
15  * manipulations with redo buffer and stuff buffer
16  * mappings and abbreviations
17  */
18 
19 #include "vim.h"
20 
21 /*
22  * These buffers are used for storing:
23  * - stuffed characters: A command that is translated into another command.
24  * - redo characters: will redo the last change.
25  * - recorded characters: for the "q" command.
26  *
27  * The bytes are stored like in the typeahead buffer:
28  * - K_SPECIAL introduces a special key (two more bytes follow).  A literal
29  *   K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
30  * - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
31  *   otherwise switching the GUI on would make mappings invalid).
32  *   A literal CSI is stored as CSI KS_EXTRA KE_CSI.
33  * These translations are also done on multi-byte characters!
34  *
35  * Escaping CSI bytes is done by the system-specific input functions, called
36  * by ui_inchar().
37  * Escaping K_SPECIAL is done by inchar().
38  * Un-escaping is done by vgetc().
39  */
40 
41 #define MINIMAL_SIZE 20			/* minimal size for b_str */
42 
43 static buffheader_T redobuff = {{NULL, {NUL}}, NULL, 0, 0};
44 static buffheader_T old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
45 static buffheader_T recordbuff = {{NULL, {NUL}}, NULL, 0, 0};
46 
47 static int typeahead_char = 0;		/* typeahead char that's not flushed */
48 
49 /*
50  * when block_redo is TRUE redo buffer will not be changed
51  * used by edit() to repeat insertions and 'V' command for redoing
52  */
53 static int	block_redo = FALSE;
54 
55 /*
56  * Make a hash value for a mapping.
57  * "mode" is the lower 4 bits of the State for the mapping.
58  * "c1" is the first character of the "lhs".
59  * Returns a value between 0 and 255, index in maphash.
60  * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
61  */
62 #define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING + TERMINAL)) ? (c1) : ((c1) ^ 0x80))
63 
64 /*
65  * Each mapping is put in one of the 256 hash lists, to speed up finding it.
66  */
67 static mapblock_T	*(maphash[256]);
68 static int		maphash_valid = FALSE;
69 
70 /*
71  * List used for abbreviations.
72  */
73 static mapblock_T	*first_abbr = NULL; /* first entry in abbrlist */
74 
75 static int		KeyNoremap = 0;	    /* remapping flags */
76 
77 /*
78  * Variables used by vgetorpeek() and flush_buffers().
79  *
80  * typebuf.tb_buf[] contains all characters that are not consumed yet.
81  * typebuf.tb_buf[typebuf.tb_off] is the first valid character.
82  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
83  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
84  * The head of the buffer may contain the result of mappings, abbreviations
85  * and @a commands.  The length of this part is typebuf.tb_maplen.
86  * typebuf.tb_silent is the part where <silent> applies.
87  * After the head are characters that come from the terminal.
88  * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
89  * should not be considered for abbreviations.
90  * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
91  * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
92  * contains RM_NONE for the characters that are not to be remapped.
93  * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
94  * (typebuf has been put in globals.h, because check_termcode() needs it).
95  */
96 #define RM_YES		0	/* tb_noremap: remap */
97 #define RM_NONE		1	/* tb_noremap: don't remap */
98 #define RM_SCRIPT	2	/* tb_noremap: remap local script mappings */
99 #define RM_ABBR		4	/* tb_noremap: don't remap, do abbrev. */
100 
101 /* typebuf.tb_buf has three parts: room in front (for result of mappings), the
102  * middle for typeahead and room for new characters (which needs to be 3 *
103  * MAXMAPLEN) for the Amiga).
104  */
105 #define TYPELEN_INIT	(5 * (MAXMAPLEN + 3))
106 static char_u	typebuf_init[TYPELEN_INIT];	/* initial typebuf.tb_buf */
107 static char_u	noremapbuf_init[TYPELEN_INIT];	/* initial typebuf.tb_noremap */
108 
109 static int	last_recorded_len = 0;	/* number of last recorded chars */
110 
111 static int	read_readbuf(buffheader_T *buf, int advance);
112 static void	init_typebuf(void);
113 static void	may_sync_undo(void);
114 static void	closescript(void);
115 static int	vgetorpeek(int);
116 static void	map_free(mapblock_T **);
117 static void	validate_maphash(void);
118 static void	showmap(mapblock_T *mp, int local);
119 static int	inchar(char_u *buf, int maxlen, long wait_time);
120 #ifdef FEAT_EVAL
121 static char_u	*eval_map_expr(char_u *str, int c);
122 #endif
123 
124 /*
125  * Free and clear a buffer.
126  */
127     void
128 free_buff(buffheader_T *buf)
129 {
130     buffblock_T	*p, *np;
131 
132     for (p = buf->bh_first.b_next; p != NULL; p = np)
133     {
134 	np = p->b_next;
135 	vim_free(p);
136     }
137     buf->bh_first.b_next = NULL;
138 }
139 
140 /*
141  * Return the contents of a buffer as a single string.
142  * K_SPECIAL and CSI in the returned string are escaped.
143  */
144     static char_u *
145 get_buffcont(
146     buffheader_T	*buffer,
147     int			dozero)	    /* count == zero is not an error */
148 {
149     long_u	    count = 0;
150     char_u	    *p = NULL;
151     char_u	    *p2;
152     char_u	    *str;
153     buffblock_T *bp;
154 
155     /* compute the total length of the string */
156     for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
157 	count += (long_u)STRLEN(bp->b_str);
158 
159     if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL)
160     {
161 	p2 = p;
162 	for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
163 	    for (str = bp->b_str; *str; )
164 		*p2++ = *str++;
165 	*p2 = NUL;
166     }
167     return (p);
168 }
169 
170 /*
171  * Return the contents of the record buffer as a single string
172  * and clear the record buffer.
173  * K_SPECIAL and CSI in the returned string are escaped.
174  */
175     char_u *
176 get_recorded(void)
177 {
178     char_u	*p;
179     size_t	len;
180 
181     p = get_buffcont(&recordbuff, TRUE);
182     free_buff(&recordbuff);
183 
184     /*
185      * Remove the characters that were added the last time, these must be the
186      * (possibly mapped) characters that stopped the recording.
187      */
188     len = STRLEN(p);
189     if ((int)len >= last_recorded_len)
190     {
191 	len -= last_recorded_len;
192 	p[len] = NUL;
193     }
194 
195     /*
196      * When stopping recording from Insert mode with CTRL-O q, also remove the
197      * CTRL-O.
198      */
199     if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
200 	p[len - 1] = NUL;
201 
202     return (p);
203 }
204 
205 /*
206  * Return the contents of the redo buffer as a single string.
207  * K_SPECIAL and CSI in the returned string are escaped.
208  */
209     char_u *
210 get_inserted(void)
211 {
212     return get_buffcont(&redobuff, FALSE);
213 }
214 
215 /*
216  * Add string "s" after the current block of buffer "buf".
217  * K_SPECIAL and CSI should have been escaped already.
218  */
219     static void
220 add_buff(
221     buffheader_T	*buf,
222     char_u		*s,
223     long		slen)	/* length of "s" or -1 */
224 {
225     buffblock_T *p;
226     long_u	    len;
227 
228     if (slen < 0)
229 	slen = (long)STRLEN(s);
230     if (slen == 0)				/* don't add empty strings */
231 	return;
232 
233     if (buf->bh_first.b_next == NULL)	/* first add to list */
234     {
235 	buf->bh_space = 0;
236 	buf->bh_curr = &(buf->bh_first);
237     }
238     else if (buf->bh_curr == NULL)	/* buffer has already been read */
239     {
240 	iemsg(_("E222: Add to read buffer"));
241 	return;
242     }
243     else if (buf->bh_index != 0)
244 	mch_memmove(buf->bh_first.b_next->b_str,
245 		    buf->bh_first.b_next->b_str + buf->bh_index,
246 		    STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1);
247     buf->bh_index = 0;
248 
249     if (buf->bh_space >= (int)slen)
250     {
251 	len = (long_u)STRLEN(buf->bh_curr->b_str);
252 	vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen);
253 	buf->bh_space -= slen;
254     }
255     else
256     {
257 	if (slen < MINIMAL_SIZE)
258 	    len = MINIMAL_SIZE;
259 	else
260 	    len = slen;
261 	p = (buffblock_T *)lalloc((long_u)(sizeof(buffblock_T) + len),
262 									TRUE);
263 	if (p == NULL)
264 	    return; /* no space, just forget it */
265 	buf->bh_space = (int)(len - slen);
266 	vim_strncpy(p->b_str, s, (size_t)slen);
267 
268 	p->b_next = buf->bh_curr->b_next;
269 	buf->bh_curr->b_next = p;
270 	buf->bh_curr = p;
271     }
272     return;
273 }
274 
275 /*
276  * Add number "n" to buffer "buf".
277  */
278     static void
279 add_num_buff(buffheader_T *buf, long n)
280 {
281     char_u	number[32];
282 
283     sprintf((char *)number, "%ld", n);
284     add_buff(buf, number, -1L);
285 }
286 
287 /*
288  * Add character 'c' to buffer "buf".
289  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
290  */
291     static void
292 add_char_buff(buffheader_T *buf, int c)
293 {
294     char_u	bytes[MB_MAXBYTES + 1];
295     int		len;
296     int		i;
297     char_u	temp[4];
298 
299     if (IS_SPECIAL(c))
300 	len = 1;
301     else
302 	len = (*mb_char2bytes)(c, bytes);
303     for (i = 0; i < len; ++i)
304     {
305 	if (!IS_SPECIAL(c))
306 	    c = bytes[i];
307 
308 	if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
309 	{
310 	    /* translate special key code into three byte sequence */
311 	    temp[0] = K_SPECIAL;
312 	    temp[1] = K_SECOND(c);
313 	    temp[2] = K_THIRD(c);
314 	    temp[3] = NUL;
315 	}
316 #ifdef FEAT_GUI
317 	else if (c == CSI)
318 	{
319 	    /* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */
320 	    temp[0] = CSI;
321 	    temp[1] = KS_EXTRA;
322 	    temp[2] = (int)KE_CSI;
323 	    temp[3] = NUL;
324 	}
325 #endif
326 	else
327 	{
328 	    temp[0] = c;
329 	    temp[1] = NUL;
330 	}
331 	add_buff(buf, temp, -1L);
332     }
333 }
334 
335 /* First read ahead buffer. Used for translated commands. */
336 static buffheader_T readbuf1 = {{NULL, {NUL}}, NULL, 0, 0};
337 
338 /* Second read ahead buffer. Used for redo. */
339 static buffheader_T readbuf2 = {{NULL, {NUL}}, NULL, 0, 0};
340 
341 /*
342  * Get one byte from the read buffers.  Use readbuf1 one first, use readbuf2
343  * if that one is empty.
344  * If advance == TRUE go to the next char.
345  * No translation is done K_SPECIAL and CSI are escaped.
346  */
347     static int
348 read_readbuffers(int advance)
349 {
350     int c;
351 
352     c = read_readbuf(&readbuf1, advance);
353     if (c == NUL)
354 	c = read_readbuf(&readbuf2, advance);
355     return c;
356 }
357 
358     static int
359 read_readbuf(buffheader_T *buf, int advance)
360 {
361     char_u	c;
362     buffblock_T	*curr;
363 
364     if (buf->bh_first.b_next == NULL)  /* buffer is empty */
365 	return NUL;
366 
367     curr = buf->bh_first.b_next;
368     c = curr->b_str[buf->bh_index];
369 
370     if (advance)
371     {
372 	if (curr->b_str[++buf->bh_index] == NUL)
373 	{
374 	    buf->bh_first.b_next = curr->b_next;
375 	    vim_free(curr);
376 	    buf->bh_index = 0;
377 	}
378     }
379     return c;
380 }
381 
382 /*
383  * Prepare the read buffers for reading (if they contain something).
384  */
385     static void
386 start_stuff(void)
387 {
388     if (readbuf1.bh_first.b_next != NULL)
389     {
390 	readbuf1.bh_curr = &(readbuf1.bh_first);
391 	readbuf1.bh_space = 0;
392     }
393     if (readbuf2.bh_first.b_next != NULL)
394     {
395 	readbuf2.bh_curr = &(readbuf2.bh_first);
396 	readbuf2.bh_space = 0;
397     }
398 }
399 
400 /*
401  * Return TRUE if the stuff buffer is empty.
402  */
403     int
404 stuff_empty(void)
405 {
406     return (readbuf1.bh_first.b_next == NULL
407 	 && readbuf2.bh_first.b_next == NULL);
408 }
409 
410 #if defined(FEAT_EVAL) || defined(PROTO)
411 /*
412  * Return TRUE if readbuf1 is empty.  There may still be redo characters in
413  * redbuf2.
414  */
415     int
416 readbuf1_empty(void)
417 {
418     return (readbuf1.bh_first.b_next == NULL);
419 }
420 #endif
421 
422 /*
423  * Set a typeahead character that won't be flushed.
424  */
425     void
426 typeahead_noflush(int c)
427 {
428     typeahead_char = c;
429 }
430 
431 /*
432  * Remove the contents of the stuff buffer and the mapped characters in the
433  * typeahead buffer (used in case of an error).  If "flush_typeahead" is true,
434  * flush all typeahead characters (used when interrupted by a CTRL-C).
435  */
436     void
437 flush_buffers(flush_buffers_T flush_typeahead)
438 {
439     init_typebuf();
440 
441     start_stuff();
442     while (read_readbuffers(TRUE) != NUL)
443 	;
444 
445     if (flush_typeahead == FLUSH_MINIMAL)
446     {
447 	// remove mapped characters at the start only
448 	typebuf.tb_off += typebuf.tb_maplen;
449 	typebuf.tb_len -= typebuf.tb_maplen;
450     }
451     else
452     {
453 	// remove typeahead
454 	if (flush_typeahead == FLUSH_INPUT)
455 	    // We have to get all characters, because we may delete the first
456 	    // part of an escape sequence.  In an xterm we get one char at a
457 	    // time and we have to get them all.
458 	    while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L) != 0)
459 		;
460 	typebuf.tb_off = MAXMAPLEN;
461 	typebuf.tb_len = 0;
462 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
463 	/* Reset the flag that text received from a client or from feedkeys()
464 	 * was inserted in the typeahead buffer. */
465 	typebuf_was_filled = FALSE;
466 #endif
467     }
468     typebuf.tb_maplen = 0;
469     typebuf.tb_silent = 0;
470     cmd_silent = FALSE;
471     typebuf.tb_no_abbr_cnt = 0;
472 }
473 
474 /*
475  * The previous contents of the redo buffer is kept in old_redobuffer.
476  * This is used for the CTRL-O <.> command in insert mode.
477  */
478     void
479 ResetRedobuff(void)
480 {
481     if (!block_redo)
482     {
483 	free_buff(&old_redobuff);
484 	old_redobuff = redobuff;
485 	redobuff.bh_first.b_next = NULL;
486     }
487 }
488 
489 /*
490  * Discard the contents of the redo buffer and restore the previous redo
491  * buffer.
492  */
493     void
494 CancelRedo(void)
495 {
496     if (!block_redo)
497     {
498 	free_buff(&redobuff);
499 	redobuff = old_redobuff;
500 	old_redobuff.bh_first.b_next = NULL;
501 	start_stuff();
502 	while (read_readbuffers(TRUE) != NUL)
503 	    ;
504     }
505 }
506 
507 /*
508  * Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
509  * Used before executing autocommands and user functions.
510  */
511     void
512 saveRedobuff(save_redo_T *save_redo)
513 {
514     char_u	*s;
515 
516     save_redo->sr_redobuff = redobuff;
517     redobuff.bh_first.b_next = NULL;
518     save_redo->sr_old_redobuff = old_redobuff;
519     old_redobuff.bh_first.b_next = NULL;
520 
521     /* Make a copy, so that ":normal ." in a function works. */
522     s = get_buffcont(&save_redo->sr_redobuff, FALSE);
523     if (s != NULL)
524     {
525 	add_buff(&redobuff, s, -1L);
526 	vim_free(s);
527     }
528 }
529 
530 /*
531  * Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
532  * Used after executing autocommands and user functions.
533  */
534     void
535 restoreRedobuff(save_redo_T *save_redo)
536 {
537     free_buff(&redobuff);
538     redobuff = save_redo->sr_redobuff;
539     free_buff(&old_redobuff);
540     old_redobuff = save_redo->sr_old_redobuff;
541 }
542 
543 /*
544  * Append "s" to the redo buffer.
545  * K_SPECIAL and CSI should already have been escaped.
546  */
547     void
548 AppendToRedobuff(char_u *s)
549 {
550     if (!block_redo)
551 	add_buff(&redobuff, s, -1L);
552 }
553 
554 /*
555  * Append to Redo buffer literally, escaping special characters with CTRL-V.
556  * K_SPECIAL and CSI are escaped as well.
557  */
558     void
559 AppendToRedobuffLit(
560     char_u	*str,
561     int		len)	    /* length of "str" or -1 for up to the NUL */
562 {
563     char_u	*s = str;
564     int		c;
565     char_u	*start;
566 
567     if (block_redo)
568 	return;
569 
570     while (len < 0 ? *s != NUL : s - str < len)
571     {
572 	/* Put a string of normal characters in the redo buffer (that's
573 	 * faster). */
574 	start = s;
575 	while (*s >= ' '
576 #ifndef EBCDIC
577 		&& *s < DEL	/* EBCDIC: all chars above space are normal */
578 #endif
579 		&& (len < 0 || s - str < len))
580 	    ++s;
581 
582 	/* Don't put '0' or '^' as last character, just in case a CTRL-D is
583 	 * typed next. */
584 	if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
585 	    --s;
586 	if (s > start)
587 	    add_buff(&redobuff, start, (long)(s - start));
588 
589 	if (*s == NUL || (len >= 0 && s - str >= len))
590 	    break;
591 
592 	/* Handle a special or multibyte character. */
593 	if (has_mbyte)
594 	    /* Handle composing chars separately. */
595 	    c = mb_cptr2char_adv(&s);
596 	else
597 	    c = *s++;
598 	if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
599 	    add_char_buff(&redobuff, Ctrl_V);
600 
601 	/* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */
602 	if (*s == NUL && c == '0')
603 #ifdef EBCDIC
604 	    add_buff(&redobuff, (char_u *)"xf0", 3L);
605 #else
606 	    add_buff(&redobuff, (char_u *)"048", 3L);
607 #endif
608 	else
609 	    add_char_buff(&redobuff, c);
610     }
611 }
612 
613 /*
614  * Append a character to the redo buffer.
615  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
616  */
617     void
618 AppendCharToRedobuff(int c)
619 {
620     if (!block_redo)
621 	add_char_buff(&redobuff, c);
622 }
623 
624 /*
625  * Append a number to the redo buffer.
626  */
627     void
628 AppendNumberToRedobuff(long n)
629 {
630     if (!block_redo)
631 	add_num_buff(&redobuff, n);
632 }
633 
634 /*
635  * Append string "s" to the stuff buffer.
636  * CSI and K_SPECIAL must already have been escaped.
637  */
638     void
639 stuffReadbuff(char_u *s)
640 {
641     add_buff(&readbuf1, s, -1L);
642 }
643 
644 /*
645  * Append string "s" to the redo stuff buffer.
646  * CSI and K_SPECIAL must already have been escaped.
647  */
648     void
649 stuffRedoReadbuff(char_u *s)
650 {
651     add_buff(&readbuf2, s, -1L);
652 }
653 
654     void
655 stuffReadbuffLen(char_u *s, long len)
656 {
657     add_buff(&readbuf1, s, len);
658 }
659 
660 #if defined(FEAT_EVAL) || defined(PROTO)
661 /*
662  * Stuff "s" into the stuff buffer, leaving special key codes unmodified and
663  * escaping other K_SPECIAL and CSI bytes.
664  * Change CR, LF and ESC into a space.
665  */
666     void
667 stuffReadbuffSpec(char_u *s)
668 {
669     int c;
670 
671     while (*s != NUL)
672     {
673 	if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
674 	{
675 	    /* Insert special key literally. */
676 	    stuffReadbuffLen(s, 3L);
677 	    s += 3;
678 	}
679 	else
680 	{
681 	    c = mb_ptr2char_adv(&s);
682 	    if (c == CAR || c == NL || c == ESC)
683 		c = ' ';
684 	    stuffcharReadbuff(c);
685 	}
686     }
687 }
688 #endif
689 
690 /*
691  * Append a character to the stuff buffer.
692  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
693  */
694     void
695 stuffcharReadbuff(int c)
696 {
697     add_char_buff(&readbuf1, c);
698 }
699 
700 /*
701  * Append a number to the stuff buffer.
702  */
703     void
704 stuffnumReadbuff(long n)
705 {
706     add_num_buff(&readbuf1, n);
707 }
708 
709 /*
710  * Read a character from the redo buffer.  Translates K_SPECIAL, CSI and
711  * multibyte characters.
712  * The redo buffer is left as it is.
713  * If init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
714  * otherwise.
715  * If old is TRUE, use old_redobuff instead of redobuff.
716  */
717     static int
718 read_redo(int init, int old_redo)
719 {
720     static buffblock_T	*bp;
721     static char_u	*p;
722     int			c;
723     int			n;
724     char_u		buf[MB_MAXBYTES + 1];
725     int			i;
726 
727     if (init)
728     {
729 	if (old_redo)
730 	    bp = old_redobuff.bh_first.b_next;
731 	else
732 	    bp = redobuff.bh_first.b_next;
733 	if (bp == NULL)
734 	    return FAIL;
735 	p = bp->b_str;
736 	return OK;
737     }
738     if ((c = *p) != NUL)
739     {
740 	/* Reverse the conversion done by add_char_buff() */
741 	/* For a multi-byte character get all the bytes and return the
742 	 * converted character. */
743 	if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
744 	    n = MB_BYTE2LEN_CHECK(c);
745 	else
746 	    n = 1;
747 	for (i = 0; ; ++i)
748 	{
749 	    if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */
750 	    {
751 		c = TO_SPECIAL(p[1], p[2]);
752 		p += 2;
753 	    }
754 #ifdef FEAT_GUI
755 	    if (c == CSI)	/* escaped CSI */
756 		p += 2;
757 #endif
758 	    if (*++p == NUL && bp->b_next != NULL)
759 	    {
760 		bp = bp->b_next;
761 		p = bp->b_str;
762 	    }
763 	    buf[i] = c;
764 	    if (i == n - 1)	/* last byte of a character */
765 	    {
766 		if (n != 1)
767 		    c = (*mb_ptr2char)(buf);
768 		break;
769 	    }
770 	    c = *p;
771 	    if (c == NUL)	/* cannot happen? */
772 		break;
773 	}
774     }
775 
776     return c;
777 }
778 
779 /*
780  * Copy the rest of the redo buffer into the stuff buffer (in a slow way).
781  * If old_redo is TRUE, use old_redobuff instead of redobuff.
782  * The escaped K_SPECIAL and CSI are copied without translation.
783  */
784     static void
785 copy_redo(int old_redo)
786 {
787     int	    c;
788 
789     while ((c = read_redo(FALSE, old_redo)) != NUL)
790 	add_char_buff(&readbuf2, c);
791 }
792 
793 /*
794  * Stuff the redo buffer into readbuf2.
795  * Insert the redo count into the command.
796  * If "old_redo" is TRUE, the last but one command is repeated
797  * instead of the last command (inserting text). This is used for
798  * CTRL-O <.> in insert mode
799  *
800  * return FAIL for failure, OK otherwise
801  */
802     int
803 start_redo(long count, int old_redo)
804 {
805     int	    c;
806 
807     /* init the pointers; return if nothing to redo */
808     if (read_redo(TRUE, old_redo) == FAIL)
809 	return FAIL;
810 
811     c = read_redo(FALSE, old_redo);
812 
813     /* copy the buffer name, if present */
814     if (c == '"')
815     {
816 	add_buff(&readbuf2, (char_u *)"\"", 1L);
817 	c = read_redo(FALSE, old_redo);
818 
819 	/* if a numbered buffer is used, increment the number */
820 	if (c >= '1' && c < '9')
821 	    ++c;
822 	add_char_buff(&readbuf2, c);
823 
824 	/* the expression register should be re-evaluated */
825 	if (c == '=')
826 	{
827 	    add_char_buff(&readbuf2, CAR);
828 	    cmd_silent = TRUE;
829 	}
830 
831 	c = read_redo(FALSE, old_redo);
832     }
833 
834     if (c == 'v')   /* redo Visual */
835     {
836 	VIsual = curwin->w_cursor;
837 	VIsual_active = TRUE;
838 	VIsual_select = FALSE;
839 	VIsual_reselect = TRUE;
840 	redo_VIsual_busy = TRUE;
841 	c = read_redo(FALSE, old_redo);
842     }
843 
844     /* try to enter the count (in place of a previous count) */
845     if (count)
846     {
847 	while (VIM_ISDIGIT(c))	/* skip "old" count */
848 	    c = read_redo(FALSE, old_redo);
849 	add_num_buff(&readbuf2, count);
850     }
851 
852     /* copy from the redo buffer into the stuff buffer */
853     add_char_buff(&readbuf2, c);
854     copy_redo(old_redo);
855     return OK;
856 }
857 
858 /*
859  * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
860  * the redo buffer into readbuf2.
861  * return FAIL for failure, OK otherwise
862  */
863     int
864 start_redo_ins(void)
865 {
866     int	    c;
867 
868     if (read_redo(TRUE, FALSE) == FAIL)
869 	return FAIL;
870     start_stuff();
871 
872     /* skip the count and the command character */
873     while ((c = read_redo(FALSE, FALSE)) != NUL)
874     {
875 	if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
876 	{
877 	    if (c == 'O' || c == 'o')
878 		add_buff(&readbuf2, NL_STR, -1L);
879 	    break;
880 	}
881     }
882 
883     /* copy the typed text from the redo buffer into the stuff buffer */
884     copy_redo(FALSE);
885     block_redo = TRUE;
886     return OK;
887 }
888 
889     void
890 stop_redo_ins(void)
891 {
892     block_redo = FALSE;
893 }
894 
895 /*
896  * Initialize typebuf.tb_buf to point to typebuf_init.
897  * alloc() cannot be used here: In out-of-memory situations it would
898  * be impossible to type anything.
899  */
900     static void
901 init_typebuf(void)
902 {
903     if (typebuf.tb_buf == NULL)
904     {
905 	typebuf.tb_buf = typebuf_init;
906 	typebuf.tb_noremap = noremapbuf_init;
907 	typebuf.tb_buflen = TYPELEN_INIT;
908 	typebuf.tb_len = 0;
909 	typebuf.tb_off = MAXMAPLEN + 4;
910 	typebuf.tb_change_cnt = 1;
911     }
912 }
913 
914 /*
915  * Insert a string in position 'offset' in the typeahead buffer (for "@r"
916  * and ":normal" command, vgetorpeek() and check_termcode()).
917  *
918  * If noremap is REMAP_YES, new string can be mapped again.
919  * If noremap is REMAP_NONE, new string cannot be mapped again.
920  * If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
921  * but abbreviations are allowed.
922  * If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
923  *			script-local mappings.
924  * If noremap is > 0, that many characters of the new string cannot be mapped.
925  *
926  * If nottyped is TRUE, the string does not return KeyTyped (don't use when
927  * offset is non-zero!).
928  *
929  * If silent is TRUE, cmd_silent is set when the characters are obtained.
930  *
931  * return FAIL for failure, OK otherwise
932  */
933     int
934 ins_typebuf(
935     char_u	*str,
936     int		noremap,
937     int		offset,
938     int		nottyped,
939     int		silent)
940 {
941     char_u	*s1, *s2;
942     int		newlen;
943     int		addlen;
944     int		i;
945     int		newoff;
946     int		val;
947     int		nrm;
948 
949     init_typebuf();
950     if (++typebuf.tb_change_cnt == 0)
951 	typebuf.tb_change_cnt = 1;
952 
953     addlen = (int)STRLEN(str);
954 
955     if (offset == 0 && addlen <= typebuf.tb_off)
956     {
957 	/*
958 	 * Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
959 	 */
960 	typebuf.tb_off -= addlen;
961 	mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
962     }
963     else if (typebuf.tb_len == 0 && typebuf.tb_buflen
964 					       >= addlen + 3 * (MAXMAPLEN + 4))
965     {
966 	/*
967 	 * Buffer is empty and string fits in the existing buffer.
968 	 * Leave some space before and after, if possible.
969 	 */
970 	typebuf.tb_off = (typebuf.tb_buflen - addlen - 3 * (MAXMAPLEN + 4)) / 2;
971 	mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
972     }
973     else
974     {
975 	/*
976 	 * Need to allocate a new buffer.
977 	 * In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4)
978 	 * characters.  We add some extra room to avoid having to allocate too
979 	 * often.
980 	 */
981 	newoff = MAXMAPLEN + 4;
982 	newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
983 	if (newlen < 0)		    /* string is getting too long */
984 	{
985 	    emsg(_(e_toocompl));    /* also calls flush_buffers */
986 	    setcursor();
987 	    return FAIL;
988 	}
989 	s1 = alloc(newlen);
990 	if (s1 == NULL)		    /* out of memory */
991 	    return FAIL;
992 	s2 = alloc(newlen);
993 	if (s2 == NULL)		    /* out of memory */
994 	{
995 	    vim_free(s1);
996 	    return FAIL;
997 	}
998 	typebuf.tb_buflen = newlen;
999 
1000 	/* copy the old chars, before the insertion point */
1001 	mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
1002 							      (size_t)offset);
1003 	/* copy the new chars */
1004 	mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
1005 	/* copy the old chars, after the insertion point, including the	NUL at
1006 	 * the end */
1007 	mch_memmove(s1 + newoff + offset + addlen,
1008 				     typebuf.tb_buf + typebuf.tb_off + offset,
1009 				       (size_t)(typebuf.tb_len - offset + 1));
1010 	if (typebuf.tb_buf != typebuf_init)
1011 	    vim_free(typebuf.tb_buf);
1012 	typebuf.tb_buf = s1;
1013 
1014 	mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
1015 							      (size_t)offset);
1016 	mch_memmove(s2 + newoff + offset + addlen,
1017 		   typebuf.tb_noremap + typebuf.tb_off + offset,
1018 					   (size_t)(typebuf.tb_len - offset));
1019 	if (typebuf.tb_noremap != noremapbuf_init)
1020 	    vim_free(typebuf.tb_noremap);
1021 	typebuf.tb_noremap = s2;
1022 
1023 	typebuf.tb_off = newoff;
1024     }
1025     typebuf.tb_len += addlen;
1026 
1027     /* If noremap == REMAP_SCRIPT: do remap script-local mappings. */
1028     if (noremap == REMAP_SCRIPT)
1029 	val = RM_SCRIPT;
1030     else if (noremap == REMAP_SKIP)
1031 	val = RM_ABBR;
1032     else
1033 	val = RM_NONE;
1034 
1035     /*
1036      * Adjust typebuf.tb_noremap[] for the new characters:
1037      * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
1038      *			(sometimes) not remappable
1039      * If noremap == REMAP_YES: all the new characters are mappable
1040      * If noremap  > 0: "noremap" characters are not remappable, the rest
1041      *			mappable
1042      */
1043     if (noremap == REMAP_SKIP)
1044 	nrm = 1;
1045     else if (noremap < 0)
1046 	nrm = addlen;
1047     else
1048 	nrm = noremap;
1049     for (i = 0; i < addlen; ++i)
1050 	typebuf.tb_noremap[typebuf.tb_off + i + offset] =
1051 						  (--nrm >= 0) ? val : RM_YES;
1052 
1053     /* tb_maplen and tb_silent only remember the length of mapped and/or
1054      * silent mappings at the start of the buffer, assuming that a mapped
1055      * sequence doesn't result in typed characters. */
1056     if (nottyped || typebuf.tb_maplen > offset)
1057 	typebuf.tb_maplen += addlen;
1058     if (silent || typebuf.tb_silent > offset)
1059     {
1060 	typebuf.tb_silent += addlen;
1061 	cmd_silent = TRUE;
1062     }
1063     if (typebuf.tb_no_abbr_cnt && offset == 0)	/* and not used for abbrev.s */
1064 	typebuf.tb_no_abbr_cnt += addlen;
1065 
1066     return OK;
1067 }
1068 
1069 /*
1070  * Put character "c" back into the typeahead buffer.
1071  * Can be used for a character obtained by vgetc() that needs to be put back.
1072  * Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
1073  * the char.
1074  */
1075     void
1076 ins_char_typebuf(int c)
1077 {
1078     char_u	buf[MB_MAXBYTES + 1];
1079     if (IS_SPECIAL(c))
1080     {
1081 	buf[0] = K_SPECIAL;
1082 	buf[1] = K_SECOND(c);
1083 	buf[2] = K_THIRD(c);
1084 	buf[3] = NUL;
1085     }
1086     else
1087 	buf[(*mb_char2bytes)(c, buf)] = NUL;
1088     (void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
1089 }
1090 
1091 /*
1092  * Return TRUE if the typeahead buffer was changed (while waiting for a
1093  * character to arrive).  Happens when a message was received from a client or
1094  * from feedkeys().
1095  * But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
1096  * changed it was reallocated and the old pointer can no longer be used.
1097  * Or "typebuf.tb_off" may have been changed and we would overwrite characters
1098  * that was just added.
1099  */
1100     int
1101 typebuf_changed(
1102     int		tb_change_cnt)	/* old value of typebuf.tb_change_cnt */
1103 {
1104     return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
1105 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1106 	    || typebuf_was_filled
1107 #endif
1108 	   ));
1109 }
1110 
1111 /*
1112  * Return TRUE if there are no characters in the typeahead buffer that have
1113  * not been typed (result from a mapping or come from ":normal").
1114  */
1115     int
1116 typebuf_typed(void)
1117 {
1118     return typebuf.tb_maplen == 0;
1119 }
1120 
1121 /*
1122  * Return the number of characters that are mapped (or not typed).
1123  */
1124     int
1125 typebuf_maplen(void)
1126 {
1127     return typebuf.tb_maplen;
1128 }
1129 
1130 /*
1131  * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
1132  */
1133     void
1134 del_typebuf(int len, int offset)
1135 {
1136     int	    i;
1137 
1138     if (len == 0)
1139 	return;		/* nothing to do */
1140 
1141     typebuf.tb_len -= len;
1142 
1143     /*
1144      * Easy case: Just increase typebuf.tb_off.
1145      */
1146     if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
1147 							 >= 3 * MAXMAPLEN + 3)
1148 	typebuf.tb_off += len;
1149     /*
1150      * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
1151      */
1152     else
1153     {
1154 	i = typebuf.tb_off + offset;
1155 	/*
1156 	 * Leave some extra room at the end to avoid reallocation.
1157 	 */
1158 	if (typebuf.tb_off > MAXMAPLEN)
1159 	{
1160 	    mch_memmove(typebuf.tb_buf + MAXMAPLEN,
1161 			     typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
1162 	    mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
1163 			 typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
1164 	    typebuf.tb_off = MAXMAPLEN;
1165 	}
1166 	/* adjust typebuf.tb_buf (include the NUL at the end) */
1167 	mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
1168 						     typebuf.tb_buf + i + len,
1169 				       (size_t)(typebuf.tb_len - offset + 1));
1170 	/* adjust typebuf.tb_noremap[] */
1171 	mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
1172 						 typebuf.tb_noremap + i + len,
1173 					   (size_t)(typebuf.tb_len - offset));
1174     }
1175 
1176     if (typebuf.tb_maplen > offset)		/* adjust tb_maplen */
1177     {
1178 	if (typebuf.tb_maplen < offset + len)
1179 	    typebuf.tb_maplen = offset;
1180 	else
1181 	    typebuf.tb_maplen -= len;
1182     }
1183     if (typebuf.tb_silent > offset)		/* adjust tb_silent */
1184     {
1185 	if (typebuf.tb_silent < offset + len)
1186 	    typebuf.tb_silent = offset;
1187 	else
1188 	    typebuf.tb_silent -= len;
1189     }
1190     if (typebuf.tb_no_abbr_cnt > offset)	/* adjust tb_no_abbr_cnt */
1191     {
1192 	if (typebuf.tb_no_abbr_cnt < offset + len)
1193 	    typebuf.tb_no_abbr_cnt = offset;
1194 	else
1195 	    typebuf.tb_no_abbr_cnt -= len;
1196     }
1197 
1198 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1199     /* Reset the flag that text received from a client or from feedkeys()
1200      * was inserted in the typeahead buffer. */
1201     typebuf_was_filled = FALSE;
1202 #endif
1203     if (++typebuf.tb_change_cnt == 0)
1204 	typebuf.tb_change_cnt = 1;
1205 }
1206 
1207 /*
1208  * Write typed characters to script file.
1209  * If recording is on put the character in the recordbuffer.
1210  */
1211     static void
1212 gotchars(char_u *chars, int len)
1213 {
1214     char_u		*s = chars;
1215     int			i;
1216     static char_u	buf[4];
1217     static int		buflen = 0;
1218     int			todo = len;
1219 
1220     while (todo--)
1221     {
1222 	buf[buflen++] = *s++;
1223 
1224 	// When receiving a special key sequence, store it until we have all
1225 	// the bytes and we can decide what to do with it.
1226 	if (buflen == 1 && buf[0] == K_SPECIAL)
1227 	    continue;
1228 	if (buflen == 2)
1229 	    continue;
1230 	if (buflen == 3 && buf[1] == KS_EXTRA
1231 		       && (buf[2] == KE_FOCUSGAINED || buf[2] == KE_FOCUSLOST))
1232 	{
1233 	    // Drop K_FOCUSGAINED and K_FOCUSLOST, they are not useful in a
1234 	    // recording.
1235 	    buflen = 0;
1236 	    continue;
1237 	}
1238 
1239 	/* Handle one byte at a time; no translation to be done. */
1240 	for (i = 0; i < buflen; ++i)
1241 	    updatescript(buf[i]);
1242 
1243 	if (reg_recording != 0)
1244 	{
1245 	    buf[buflen] = NUL;
1246 	    add_buff(&recordbuff, buf, (long)buflen);
1247 	    /* remember how many chars were last recorded */
1248 	    last_recorded_len += buflen;
1249 	}
1250 	buflen = 0;
1251     }
1252     may_sync_undo();
1253 
1254 #ifdef FEAT_EVAL
1255     /* output "debug mode" message next time in debug mode */
1256     debug_did_msg = FALSE;
1257 #endif
1258 
1259     /* Since characters have been typed, consider the following to be in
1260      * another mapping.  Search string will be kept in history. */
1261     ++maptick;
1262 }
1263 
1264 /*
1265  * Sync undo.  Called when typed characters are obtained from the typeahead
1266  * buffer, or when a menu is used.
1267  * Do not sync:
1268  * - In Insert mode, unless cursor key has been used.
1269  * - While reading a script file.
1270  * - When no_u_sync is non-zero.
1271  */
1272     static void
1273 may_sync_undo(void)
1274 {
1275     if ((!(State & (INSERT + CMDLINE)) || arrow_used)
1276 					       && scriptin[curscript] == NULL)
1277 	u_sync(FALSE);
1278 }
1279 
1280 /*
1281  * Make "typebuf" empty and allocate new buffers.
1282  * Returns FAIL when out of memory.
1283  */
1284     int
1285 alloc_typebuf(void)
1286 {
1287     typebuf.tb_buf = alloc(TYPELEN_INIT);
1288     typebuf.tb_noremap = alloc(TYPELEN_INIT);
1289     if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
1290     {
1291 	free_typebuf();
1292 	return FAIL;
1293     }
1294     typebuf.tb_buflen = TYPELEN_INIT;
1295     typebuf.tb_off = MAXMAPLEN + 4;  /* can insert without realloc */
1296     typebuf.tb_len = 0;
1297     typebuf.tb_maplen = 0;
1298     typebuf.tb_silent = 0;
1299     typebuf.tb_no_abbr_cnt = 0;
1300     if (++typebuf.tb_change_cnt == 0)
1301 	typebuf.tb_change_cnt = 1;
1302     return OK;
1303 }
1304 
1305 /*
1306  * Free the buffers of "typebuf".
1307  */
1308     void
1309 free_typebuf(void)
1310 {
1311     if (typebuf.tb_buf == typebuf_init)
1312 	internal_error("Free typebuf 1");
1313     else
1314 	vim_free(typebuf.tb_buf);
1315     if (typebuf.tb_noremap == noremapbuf_init)
1316 	internal_error("Free typebuf 2");
1317     else
1318 	vim_free(typebuf.tb_noremap);
1319 }
1320 
1321 /*
1322  * When doing ":so! file", the current typeahead needs to be saved, and
1323  * restored when "file" has been read completely.
1324  */
1325 static typebuf_T saved_typebuf[NSCRIPT];
1326 
1327     int
1328 save_typebuf(void)
1329 {
1330     init_typebuf();
1331     saved_typebuf[curscript] = typebuf;
1332     /* If out of memory: restore typebuf and close file. */
1333     if (alloc_typebuf() == FAIL)
1334     {
1335 	closescript();
1336 	return FAIL;
1337     }
1338     return OK;
1339 }
1340 
1341 static int old_char = -1;	/* character put back by vungetc() */
1342 static int old_mod_mask;	/* mod_mask for ungotten character */
1343 #ifdef FEAT_MOUSE
1344 static int old_mouse_row;	/* mouse_row related to old_char */
1345 static int old_mouse_col;	/* mouse_col related to old_char */
1346 #endif
1347 
1348 /*
1349  * Save all three kinds of typeahead, so that the user must type at a prompt.
1350  */
1351     void
1352 save_typeahead(tasave_T *tp)
1353 {
1354     tp->save_typebuf = typebuf;
1355     tp->typebuf_valid = (alloc_typebuf() == OK);
1356     if (!tp->typebuf_valid)
1357 	typebuf = tp->save_typebuf;
1358 
1359     tp->old_char = old_char;
1360     tp->old_mod_mask = old_mod_mask;
1361     old_char = -1;
1362 
1363     tp->save_readbuf1 = readbuf1;
1364     readbuf1.bh_first.b_next = NULL;
1365     tp->save_readbuf2 = readbuf2;
1366     readbuf2.bh_first.b_next = NULL;
1367 # ifdef USE_INPUT_BUF
1368     tp->save_inputbuf = get_input_buf();
1369 # endif
1370 }
1371 
1372 /*
1373  * Restore the typeahead to what it was before calling save_typeahead().
1374  * The allocated memory is freed, can only be called once!
1375  */
1376     void
1377 restore_typeahead(tasave_T *tp)
1378 {
1379     if (tp->typebuf_valid)
1380     {
1381 	free_typebuf();
1382 	typebuf = tp->save_typebuf;
1383     }
1384 
1385     old_char = tp->old_char;
1386     old_mod_mask = tp->old_mod_mask;
1387 
1388     free_buff(&readbuf1);
1389     readbuf1 = tp->save_readbuf1;
1390     free_buff(&readbuf2);
1391     readbuf2 = tp->save_readbuf2;
1392 # ifdef USE_INPUT_BUF
1393     set_input_buf(tp->save_inputbuf);
1394 # endif
1395 }
1396 
1397 /*
1398  * Open a new script file for the ":source!" command.
1399  */
1400     void
1401 openscript(
1402     char_u	*name,
1403     int		directly)	/* when TRUE execute directly */
1404 {
1405     if (curscript + 1 == NSCRIPT)
1406     {
1407 	emsg(_(e_nesting));
1408 	return;
1409     }
1410 #ifdef FEAT_EVAL
1411     if (ignore_script)
1412 	/* Not reading from script, also don't open one.  Warning message? */
1413 	return;
1414 #endif
1415 
1416     if (scriptin[curscript] != NULL)	/* already reading script */
1417 	++curscript;
1418 				/* use NameBuff for expanded name */
1419     expand_env(name, NameBuff, MAXPATHL);
1420     if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
1421     {
1422 	semsg(_(e_notopen), name);
1423 	if (curscript)
1424 	    --curscript;
1425 	return;
1426     }
1427     if (save_typebuf() == FAIL)
1428 	return;
1429 
1430     /*
1431      * Execute the commands from the file right now when using ":source!"
1432      * after ":global" or ":argdo" or in a loop.  Also when another command
1433      * follows.  This means the display won't be updated.  Don't do this
1434      * always, "make test" would fail.
1435      */
1436     if (directly)
1437     {
1438 	oparg_T	oa;
1439 	int	oldcurscript;
1440 	int	save_State = State;
1441 	int	save_restart_edit = restart_edit;
1442 	int	save_insertmode = p_im;
1443 	int	save_finish_op = finish_op;
1444 	int	save_msg_scroll = msg_scroll;
1445 
1446 	State = NORMAL;
1447 	msg_scroll = FALSE;	/* no msg scrolling in Normal mode */
1448 	restart_edit = 0;	/* don't go to Insert mode */
1449 	p_im = FALSE;		/* don't use 'insertmode' */
1450 	clear_oparg(&oa);
1451 	finish_op = FALSE;
1452 
1453 	oldcurscript = curscript;
1454 	do
1455 	{
1456 	    update_topline_cursor();	/* update cursor position and topline */
1457 	    normal_cmd(&oa, FALSE);	/* execute one command */
1458 	    vpeekc();			/* check for end of file */
1459 	}
1460 	while (scriptin[oldcurscript] != NULL);
1461 
1462 	State = save_State;
1463 	msg_scroll = save_msg_scroll;
1464 	restart_edit = save_restart_edit;
1465 	p_im = save_insertmode;
1466 	finish_op = save_finish_op;
1467     }
1468 }
1469 
1470 /*
1471  * Close the currently active input script.
1472  */
1473     static void
1474 closescript(void)
1475 {
1476     free_typebuf();
1477     typebuf = saved_typebuf[curscript];
1478 
1479     fclose(scriptin[curscript]);
1480     scriptin[curscript] = NULL;
1481     if (curscript > 0)
1482 	--curscript;
1483 }
1484 
1485 #if defined(EXITFREE) || defined(PROTO)
1486     void
1487 close_all_scripts(void)
1488 {
1489     while (scriptin[0] != NULL)
1490 	closescript();
1491 }
1492 #endif
1493 
1494 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1495 /*
1496  * Return TRUE when reading keys from a script file.
1497  */
1498     int
1499 using_script(void)
1500 {
1501     return scriptin[curscript] != NULL;
1502 }
1503 #endif
1504 
1505 /*
1506  * This function is called just before doing a blocking wait.  Thus after
1507  * waiting 'updatetime' for a character to arrive.
1508  */
1509     void
1510 before_blocking(void)
1511 {
1512     updatescript(0);
1513 #ifdef FEAT_EVAL
1514     if (may_garbage_collect)
1515 	garbage_collect(FALSE);
1516 #endif
1517 }
1518 
1519 /*
1520  * updatescipt() is called when a character can be written into the script file
1521  * or when we have waited some time for a character (c == 0)
1522  *
1523  * All the changed memfiles are synced if c == 0 or when the number of typed
1524  * characters reaches 'updatecount' and 'updatecount' is non-zero.
1525  */
1526     void
1527 updatescript(int c)
1528 {
1529     static int	    count = 0;
1530 
1531     if (c && scriptout)
1532 	putc(c, scriptout);
1533     if (c == 0 || (p_uc > 0 && ++count >= p_uc))
1534     {
1535 	ml_sync_all(c == 0, TRUE);
1536 	count = 0;
1537     }
1538 }
1539 
1540 /*
1541  * Get the next input character.
1542  * Can return a special key or a multi-byte character.
1543  * Can return NUL when called recursively, use safe_vgetc() if that's not
1544  * wanted.
1545  * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
1546  * Collects the bytes of a multibyte character into the whole character.
1547  * Returns the modifiers in the global "mod_mask".
1548  */
1549     int
1550 vgetc(void)
1551 {
1552     int		c, c2;
1553     int		n;
1554     char_u	buf[MB_MAXBYTES + 1];
1555     int		i;
1556 
1557 #ifdef FEAT_EVAL
1558     /* Do garbage collection when garbagecollect() was called previously and
1559      * we are now at the toplevel. */
1560     if (may_garbage_collect && want_garbage_collect)
1561 	garbage_collect(FALSE);
1562 #endif
1563 
1564     /*
1565      * If a character was put back with vungetc, it was already processed.
1566      * Return it directly.
1567      */
1568     if (old_char != -1)
1569     {
1570 	c = old_char;
1571 	old_char = -1;
1572 	mod_mask = old_mod_mask;
1573 #ifdef FEAT_MOUSE
1574 	mouse_row = old_mouse_row;
1575 	mouse_col = old_mouse_col;
1576 #endif
1577     }
1578     else
1579     {
1580       mod_mask = 0x0;
1581       last_recorded_len = 0;
1582       for (;;)			/* this is done twice if there are modifiers */
1583       {
1584 	int did_inc = FALSE;
1585 
1586 	if (mod_mask
1587 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
1588 	    || im_is_preediting()
1589 #endif
1590 		)
1591 	{
1592 	    /* no mapping after modifier has been read */
1593 	    ++no_mapping;
1594 	    ++allow_keys;
1595 	    did_inc = TRUE;	/* mod_mask may change value */
1596 	}
1597 	c = vgetorpeek(TRUE);
1598 	if (did_inc)
1599 	{
1600 	    --no_mapping;
1601 	    --allow_keys;
1602 	}
1603 
1604 	/* Get two extra bytes for special keys */
1605 	if (c == K_SPECIAL
1606 #ifdef FEAT_GUI
1607 		|| c == CSI
1608 #endif
1609 	   )
1610 	{
1611 	    int	    save_allow_keys = allow_keys;
1612 
1613 	    ++no_mapping;
1614 	    allow_keys = 0;		/* make sure BS is not found */
1615 	    c2 = vgetorpeek(TRUE);	/* no mapping for these chars */
1616 	    c = vgetorpeek(TRUE);
1617 	    --no_mapping;
1618 	    allow_keys = save_allow_keys;
1619 	    if (c2 == KS_MODIFIER)
1620 	    {
1621 		mod_mask = c;
1622 		continue;
1623 	    }
1624 	    c = TO_SPECIAL(c2, c);
1625 
1626 #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
1627 	    /* Handle K_TEAROFF here, the caller of vgetc() doesn't need to
1628 	     * know that a menu was torn off */
1629 	    if (c == K_TEAROFF)
1630 	    {
1631 		char_u	name[200];
1632 		int	i;
1633 
1634 		/* get menu path, it ends with a <CR> */
1635 		for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
1636 		{
1637 		    name[i] = c;
1638 		    if (i < 199)
1639 			++i;
1640 		}
1641 		name[i] = NUL;
1642 		gui_make_tearoff(name);
1643 		continue;
1644 	    }
1645 #endif
1646 #if defined(FEAT_GUI) && defined(FEAT_GUI_GTK) && defined(FEAT_MENU)
1647 	    /* GTK: <F10> normally selects the menu, but it's passed until
1648 	     * here to allow mapping it.  Intercept and invoke the GTK
1649 	     * behavior if it's not mapped. */
1650 	    if (c == K_F10 && gui.menubar != NULL)
1651 	    {
1652 		gtk_menu_shell_select_first(GTK_MENU_SHELL(gui.menubar), FALSE);
1653 		continue;
1654 	    }
1655 #endif
1656 #ifdef FEAT_GUI
1657 	    /* Handle focus event here, so that the caller doesn't need to
1658 	     * know about it.  Return K_IGNORE so that we loop once (needed if
1659 	     * 'lazyredraw' is set). */
1660 	    if (c == K_FOCUSGAINED || c == K_FOCUSLOST)
1661 	    {
1662 		ui_focus_change(c == K_FOCUSGAINED);
1663 		c = K_IGNORE;
1664 	    }
1665 
1666 	    /* Translate K_CSI to CSI.  The special key is only used to avoid
1667 	     * it being recognized as the start of a special key. */
1668 	    if (c == K_CSI)
1669 		c = CSI;
1670 #endif
1671 	}
1672 	/* a keypad or special function key was not mapped, use it like
1673 	 * its ASCII equivalent */
1674 	switch (c)
1675 	{
1676 	    case K_KPLUS:	c = '+'; break;
1677 	    case K_KMINUS:	c = '-'; break;
1678 	    case K_KDIVIDE:	c = '/'; break;
1679 	    case K_KMULTIPLY:	c = '*'; break;
1680 	    case K_KENTER:	c = CAR; break;
1681 	    case K_KPOINT:
1682 #ifdef WIN32
1683 				// Can be either '.' or a ',',
1684 				// depending on the type of keypad.
1685 				c = MapVirtualKey(VK_DECIMAL, 2); break;
1686 #else
1687 				c = '.'; break;
1688 #endif
1689 	    case K_K0:		c = '0'; break;
1690 	    case K_K1:		c = '1'; break;
1691 	    case K_K2:		c = '2'; break;
1692 	    case K_K3:		c = '3'; break;
1693 	    case K_K4:		c = '4'; break;
1694 	    case K_K5:		c = '5'; break;
1695 	    case K_K6:		c = '6'; break;
1696 	    case K_K7:		c = '7'; break;
1697 	    case K_K8:		c = '8'; break;
1698 	    case K_K9:		c = '9'; break;
1699 
1700 	    case K_XHOME:
1701 	    case K_ZHOME:	if (mod_mask == MOD_MASK_SHIFT)
1702 				{
1703 				    c = K_S_HOME;
1704 				    mod_mask = 0;
1705 				}
1706 				else if (mod_mask == MOD_MASK_CTRL)
1707 				{
1708 				    c = K_C_HOME;
1709 				    mod_mask = 0;
1710 				}
1711 				else
1712 				    c = K_HOME;
1713 				break;
1714 	    case K_XEND:
1715 	    case K_ZEND:	if (mod_mask == MOD_MASK_SHIFT)
1716 				{
1717 				    c = K_S_END;
1718 				    mod_mask = 0;
1719 				}
1720 				else if (mod_mask == MOD_MASK_CTRL)
1721 				{
1722 				    c = K_C_END;
1723 				    mod_mask = 0;
1724 				}
1725 				else
1726 				    c = K_END;
1727 				break;
1728 
1729 	    case K_XUP:		c = K_UP; break;
1730 	    case K_XDOWN:	c = K_DOWN; break;
1731 	    case K_XLEFT:	c = K_LEFT; break;
1732 	    case K_XRIGHT:	c = K_RIGHT; break;
1733 	}
1734 
1735 	/* For a multi-byte character get all the bytes and return the
1736 	 * converted character.
1737 	 * Note: This will loop until enough bytes are received!
1738 	 */
1739 	if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
1740 	{
1741 	    ++no_mapping;
1742 	    buf[0] = c;
1743 	    for (i = 1; i < n; ++i)
1744 	    {
1745 		buf[i] = vgetorpeek(TRUE);
1746 		if (buf[i] == K_SPECIAL
1747 #ifdef FEAT_GUI
1748 			|| buf[i] == CSI
1749 #endif
1750 			)
1751 		{
1752 		    /* Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence,
1753 		     * which represents a K_SPECIAL (0x80),
1754 		     * or a CSI - KS_EXTRA - KE_CSI sequence, which represents
1755 		     * a CSI (0x9B),
1756 		     * of a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI too. */
1757 		    c = vgetorpeek(TRUE);
1758 		    if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
1759 			buf[i] = CSI;
1760 		}
1761 	    }
1762 	    --no_mapping;
1763 	    c = (*mb_ptr2char)(buf);
1764 	}
1765 
1766 	break;
1767       }
1768     }
1769 
1770 #ifdef FEAT_EVAL
1771     /*
1772      * In the main loop "may_garbage_collect" can be set to do garbage
1773      * collection in the first next vgetc().  It's disabled after that to
1774      * avoid internally used Lists and Dicts to be freed.
1775      */
1776     may_garbage_collect = FALSE;
1777 #endif
1778 #ifdef FEAT_BEVAL_TERM
1779     if (c != K_MOUSEMOVE && c != K_IGNORE)
1780     {
1781 	/* Don't trigger 'balloonexpr' unless only the mouse was moved. */
1782 	bevalexpr_due_set = FALSE;
1783 	ui_remove_balloon();
1784     }
1785 #endif
1786 
1787     return c;
1788 }
1789 
1790 /*
1791  * Like vgetc(), but never return a NUL when called recursively, get a key
1792  * directly from the user (ignoring typeahead).
1793  */
1794     int
1795 safe_vgetc(void)
1796 {
1797     int	c;
1798 
1799     c = vgetc();
1800     if (c == NUL)
1801 	c = get_keystroke();
1802     return c;
1803 }
1804 
1805 /*
1806  * Like safe_vgetc(), but loop to handle K_IGNORE.
1807  * Also ignore scrollbar events.
1808  */
1809     int
1810 plain_vgetc(void)
1811 {
1812     int c;
1813 
1814     do
1815     {
1816 	c = safe_vgetc();
1817     } while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
1818 
1819     if (c == K_PS)
1820 	/* Only handle the first pasted character.  Drop the rest, since we
1821 	 * don't know what to do with it. */
1822 	c = bracketed_paste(PASTE_ONE_CHAR, FALSE, NULL);
1823 
1824     return c;
1825 }
1826 
1827 /*
1828  * Check if a character is available, such that vgetc() will not block.
1829  * If the next character is a special character or multi-byte, the returned
1830  * character is not valid!.
1831  * Returns NUL if no character is available.
1832  */
1833     int
1834 vpeekc(void)
1835 {
1836     if (old_char != -1)
1837 	return old_char;
1838     return vgetorpeek(FALSE);
1839 }
1840 
1841 #if defined(FEAT_TERMRESPONSE) || defined(FEAT_TERMINAL) || defined(PROTO)
1842 /*
1843  * Like vpeekc(), but don't allow mapping.  Do allow checking for terminal
1844  * codes.
1845  */
1846     int
1847 vpeekc_nomap(void)
1848 {
1849     int		c;
1850 
1851     ++no_mapping;
1852     ++allow_keys;
1853     c = vpeekc();
1854     --no_mapping;
1855     --allow_keys;
1856     return c;
1857 }
1858 #endif
1859 
1860 #if defined(FEAT_INS_EXPAND) || defined(FEAT_EVAL) || defined(PROTO)
1861 /*
1862  * Check if any character is available, also half an escape sequence.
1863  * Trick: when no typeahead found, but there is something in the typeahead
1864  * buffer, it must be an ESC that is recognized as the start of a key code.
1865  */
1866     int
1867 vpeekc_any(void)
1868 {
1869     int		c;
1870 
1871     c = vpeekc();
1872     if (c == NUL && typebuf.tb_len > 0)
1873 	c = ESC;
1874     return c;
1875 }
1876 #endif
1877 
1878 /*
1879  * Call vpeekc() without causing anything to be mapped.
1880  * Return TRUE if a character is available, FALSE otherwise.
1881  */
1882     int
1883 char_avail(void)
1884 {
1885     int	    retval;
1886 
1887 #ifdef FEAT_EVAL
1888     /* When test_override("char_avail", 1) was called pretend there is no
1889      * typeahead. */
1890     if (disable_char_avail_for_testing)
1891 	return FALSE;
1892 #endif
1893     ++no_mapping;
1894     retval = vpeekc();
1895     --no_mapping;
1896     return (retval != NUL);
1897 }
1898 
1899 /*
1900  * unget one character (can only be done once!)
1901  */
1902     void
1903 vungetc(int c)
1904 {
1905     old_char = c;
1906     old_mod_mask = mod_mask;
1907 #ifdef FEAT_MOUSE
1908     old_mouse_row = mouse_row;
1909     old_mouse_col = mouse_col;
1910 #endif
1911 }
1912 
1913 /*
1914  * Get a byte:
1915  * 1. from the stuffbuffer
1916  *	This is used for abbreviated commands like "D" -> "d$".
1917  *	Also used to redo a command for ".".
1918  * 2. from the typeahead buffer
1919  *	Stores text obtained previously but not used yet.
1920  *	Also stores the result of mappings.
1921  *	Also used for the ":normal" command.
1922  * 3. from the user
1923  *	This may do a blocking wait if "advance" is TRUE.
1924  *
1925  * if "advance" is TRUE (vgetc()):
1926  *	Really get the character.
1927  *	KeyTyped is set to TRUE in the case the user typed the key.
1928  *	KeyStuffed is TRUE if the character comes from the stuff buffer.
1929  * if "advance" is FALSE (vpeekc()):
1930  *	Just look whether there is a character available.
1931  *	Return NUL if not.
1932  *
1933  * When "no_mapping" is zero, checks for mappings in the current mode.
1934  * Only returns one byte (of a multi-byte character).
1935  * K_SPECIAL and CSI may be escaped, need to get two more bytes then.
1936  */
1937     static int
1938 vgetorpeek(int advance)
1939 {
1940     int		c, c1;
1941     int		keylen;
1942     char_u	*s;
1943     mapblock_T	*mp;
1944 #ifdef FEAT_LOCALMAP
1945     mapblock_T	*mp2;
1946 #endif
1947     mapblock_T	*mp_match;
1948     int		mp_match_len = 0;
1949     int		timedout = FALSE;	    /* waited for more than 1 second
1950 						for mapping to complete */
1951     int		mapdepth = 0;	    /* check for recursive mapping */
1952     int		mode_deleted = FALSE;   /* set when mode has been deleted */
1953     int		local_State;
1954     int		mlen;
1955     int		max_mlen;
1956     int		i;
1957 #ifdef FEAT_CMDL_INFO
1958     int		new_wcol, new_wrow;
1959 #endif
1960 #ifdef FEAT_GUI
1961 # ifdef FEAT_MENU
1962     int		idx;
1963 # endif
1964     int		shape_changed = FALSE;  /* adjusted cursor shape */
1965 #endif
1966     int		n;
1967 #ifdef FEAT_LANGMAP
1968     int		nolmaplen;
1969 #endif
1970     int		old_wcol, old_wrow;
1971     int		wait_tb_len;
1972 
1973     /*
1974      * This function doesn't work very well when called recursively.  This may
1975      * happen though, because of:
1976      * 1. The call to add_to_showcmd().	char_avail() is then used to check if
1977      * there is a character available, which calls this function.  In that
1978      * case we must return NUL, to indicate no character is available.
1979      * 2. A GUI callback function writes to the screen, causing a
1980      * wait_return().
1981      * Using ":normal" can also do this, but it saves the typeahead buffer,
1982      * thus it should be OK.  But don't get a key from the user then.
1983      */
1984     if (vgetc_busy > 0 && ex_normal_busy == 0)
1985 	return NUL;
1986 
1987     local_State = get_real_state();
1988 
1989     ++vgetc_busy;
1990 
1991     if (advance)
1992 	KeyStuffed = FALSE;
1993 
1994     init_typebuf();
1995     start_stuff();
1996     if (advance && typebuf.tb_maplen == 0)
1997 	reg_executing = 0;
1998     do
1999     {
2000 /*
2001  * get a character: 1. from the stuffbuffer
2002  */
2003 	if (typeahead_char != 0)
2004 	{
2005 	    c = typeahead_char;
2006 	    if (advance)
2007 		typeahead_char = 0;
2008 	}
2009 	else
2010 	    c = read_readbuffers(advance);
2011 	if (c != NUL && !got_int)
2012 	{
2013 	    if (advance)
2014 	    {
2015 		/* KeyTyped = FALSE;  When the command that stuffed something
2016 		 * was typed, behave like the stuffed command was typed.
2017 		 * needed for CTRL-W CTRL-] to open a fold, for example. */
2018 		KeyStuffed = TRUE;
2019 	    }
2020 	    if (typebuf.tb_no_abbr_cnt == 0)
2021 		typebuf.tb_no_abbr_cnt = 1;	/* no abbreviations now */
2022 	}
2023 	else
2024 	{
2025 	    /*
2026 	     * Loop until we either find a matching mapped key, or we
2027 	     * are sure that it is not a mapped key.
2028 	     * If a mapped key sequence is found we go back to the start to
2029 	     * try re-mapping.
2030 	     */
2031 	    for (;;)
2032 	    {
2033 		/*
2034 		 * ui_breakcheck() is slow, don't use it too often when
2035 		 * inside a mapping.  But call it each time for typed
2036 		 * characters.
2037 		 */
2038 		if (typebuf.tb_maplen)
2039 		    line_breakcheck();
2040 		else
2041 		    ui_breakcheck();		/* check for CTRL-C */
2042 		keylen = 0;
2043 		if (got_int)
2044 		{
2045 		    /* flush all input */
2046 		    c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L);
2047 		    /*
2048 		     * If inchar() returns TRUE (script file was active) or we
2049 		     * are inside a mapping, get out of Insert mode.
2050 		     * Otherwise we behave like having gotten a CTRL-C.
2051 		     * As a result typing CTRL-C in insert mode will
2052 		     * really insert a CTRL-C.
2053 		     */
2054 		    if ((c || typebuf.tb_maplen)
2055 					      && (State & (INSERT + CMDLINE)))
2056 			c = ESC;
2057 		    else
2058 			c = Ctrl_C;
2059 		    flush_buffers(FLUSH_INPUT);	// flush all typeahead
2060 
2061 		    if (advance)
2062 		    {
2063 			/* Also record this character, it might be needed to
2064 			 * get out of Insert mode. */
2065 			*typebuf.tb_buf = c;
2066 			gotchars(typebuf.tb_buf, 1);
2067 		    }
2068 		    cmd_silent = FALSE;
2069 
2070 		    break;
2071 		}
2072 		else if (typebuf.tb_len > 0)
2073 		{
2074 		    /*
2075 		     * Check for a mappable key sequence.
2076 		     * Walk through one maphash[] list until we find an
2077 		     * entry that matches.
2078 		     *
2079 		     * Don't look for mappings if:
2080 		     * - no_mapping set: mapping disabled (e.g. for CTRL-V)
2081 		     * - maphash_valid not set: no mappings present.
2082 		     * - typebuf.tb_buf[typebuf.tb_off] should not be remapped
2083 		     * - in insert or cmdline mode and 'paste' option set
2084 		     * - waiting for "hit return to continue" and CR or SPACE
2085 		     *	 typed
2086 		     * - waiting for a char with --more--
2087 		     * - in Ctrl-X mode, and we get a valid char for that mode
2088 		     */
2089 		    mp = NULL;
2090 		    max_mlen = 0;
2091 		    c1 = typebuf.tb_buf[typebuf.tb_off];
2092 		    if (no_mapping == 0 && maphash_valid
2093 			    && (no_zero_mapping == 0 || c1 != '0')
2094 			    && (typebuf.tb_maplen == 0
2095 				|| (p_remap
2096 				    && (typebuf.tb_noremap[typebuf.tb_off]
2097 						    & (RM_NONE|RM_ABBR)) == 0))
2098 			    && !(p_paste && (State & (INSERT + CMDLINE)))
2099 			    && !(State == HITRETURN && (c1 == CAR || c1 == ' '))
2100 			    && State != ASKMORE
2101 			    && State != CONFIRM
2102 #ifdef FEAT_INS_EXPAND
2103 			    && !((ctrl_x_mode_not_default()
2104 						      && vim_is_ctrl_x_key(c1))
2105 				    || ((compl_cont_status & CONT_LOCAL)
2106 					&& (c1 == Ctrl_N || c1 == Ctrl_P)))
2107 #endif
2108 			    )
2109 		    {
2110 #ifdef FEAT_LANGMAP
2111 			if (c1 == K_SPECIAL)
2112 			    nolmaplen = 2;
2113 			else
2114 			{
2115 			    LANGMAP_ADJUST(c1,
2116 					   (State & (CMDLINE | INSERT)) == 0
2117 					   && get_real_state() != SELECTMODE);
2118 			    nolmaplen = 0;
2119 			}
2120 #endif
2121 #ifdef FEAT_LOCALMAP
2122 			/* First try buffer-local mappings. */
2123 			mp = curbuf->b_maphash[MAP_HASH(local_State, c1)];
2124 			mp2 = maphash[MAP_HASH(local_State, c1)];
2125 			if (mp == NULL)
2126 			{
2127 			    /* There are no buffer-local mappings. */
2128 			    mp = mp2;
2129 			    mp2 = NULL;
2130 			}
2131 #else
2132 			mp = maphash[MAP_HASH(local_State, c1)];
2133 #endif
2134 			/*
2135 			 * Loop until a partly matching mapping is found or
2136 			 * all (local) mappings have been checked.
2137 			 * The longest full match is remembered in "mp_match".
2138 			 * A full match is only accepted if there is no partly
2139 			 * match, so "aa" and "aaa" can both be mapped.
2140 			 */
2141 			mp_match = NULL;
2142 			mp_match_len = 0;
2143 			for ( ; mp != NULL;
2144 #ifdef FEAT_LOCALMAP
2145 				mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
2146 #endif
2147 				(mp = mp->m_next))
2148 			{
2149 			    /*
2150 			     * Only consider an entry if the first character
2151 			     * matches and it is for the current state.
2152 			     * Skip ":lmap" mappings if keys were mapped.
2153 			     */
2154 			    if (mp->m_keys[0] == c1
2155 				    && (mp->m_mode & local_State)
2156 				    && ((mp->m_mode & LANGMAP) == 0
2157 					|| typebuf.tb_maplen == 0))
2158 			    {
2159 #ifdef FEAT_LANGMAP
2160 				int	nomap = nolmaplen;
2161 				int	c2;
2162 #endif
2163 				/* find the match length of this mapping */
2164 				for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
2165 				{
2166 #ifdef FEAT_LANGMAP
2167 				    c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
2168 				    if (nomap > 0)
2169 					--nomap;
2170 				    else if (c2 == K_SPECIAL)
2171 					nomap = 2;
2172 				    else
2173 					LANGMAP_ADJUST(c2, TRUE);
2174 				    if (mp->m_keys[mlen] != c2)
2175 #else
2176 				    if (mp->m_keys[mlen] !=
2177 					typebuf.tb_buf[typebuf.tb_off + mlen])
2178 #endif
2179 					break;
2180 				}
2181 
2182 				/* Don't allow mapping the first byte(s) of a
2183 				 * multi-byte char.  Happens when mapping
2184 				 * <M-a> and then changing 'encoding'. Beware
2185 				 * that 0x80 is escaped. */
2186 				{
2187 				    char_u *p1 = mp->m_keys;
2188 				    char_u *p2 = mb_unescape(&p1);
2189 
2190 				    if (has_mbyte && p2 != NULL
2191 					  && MB_BYTE2LEN(c1) > MB_PTR2LEN(p2))
2192 					mlen = 0;
2193 				}
2194 				/*
2195 				 * Check an entry whether it matches.
2196 				 * - Full match: mlen == keylen
2197 				 * - Partly match: mlen == typebuf.tb_len
2198 				 */
2199 				keylen = mp->m_keylen;
2200 				if (mlen == keylen
2201 				     || (mlen == typebuf.tb_len
2202 						  && typebuf.tb_len < keylen))
2203 				{
2204 				    /*
2205 				     * If only script-local mappings are
2206 				     * allowed, check if the mapping starts
2207 				     * with K_SNR.
2208 				     */
2209 				    s = typebuf.tb_noremap + typebuf.tb_off;
2210 				    if (*s == RM_SCRIPT
2211 					    && (mp->m_keys[0] != K_SPECIAL
2212 						|| mp->m_keys[1] != KS_EXTRA
2213 						|| mp->m_keys[2]
2214 							      != (int)KE_SNR))
2215 					continue;
2216 				    /*
2217 				     * If one of the typed keys cannot be
2218 				     * remapped, skip the entry.
2219 				     */
2220 				    for (n = mlen; --n >= 0; )
2221 					if (*s++ & (RM_NONE|RM_ABBR))
2222 					    break;
2223 				    if (n >= 0)
2224 					continue;
2225 
2226 				    if (keylen > typebuf.tb_len)
2227 				    {
2228 					if (!timedout && !(mp_match != NULL
2229 						       && mp_match->m_nowait))
2230 					{
2231 					    /* break at a partly match */
2232 					    keylen = KEYLEN_PART_MAP;
2233 					    break;
2234 					}
2235 				    }
2236 				    else if (keylen > mp_match_len)
2237 				    {
2238 					/* found a longer match */
2239 					mp_match = mp;
2240 					mp_match_len = keylen;
2241 				    }
2242 				}
2243 				else
2244 				    /* No match; may have to check for
2245 				     * termcode at next character. */
2246 				    if (max_mlen < mlen)
2247 					max_mlen = mlen;
2248 			    }
2249 			}
2250 
2251 			/* If no partly match found, use the longest full
2252 			 * match. */
2253 			if (keylen != KEYLEN_PART_MAP)
2254 			{
2255 			    mp = mp_match;
2256 			    keylen = mp_match_len;
2257 			}
2258 		    }
2259 
2260 		    /* Check for match with 'pastetoggle' */
2261 		    if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
2262 		    {
2263 			for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen];
2264 								       ++mlen)
2265 			    if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off
2266 								      + mlen])
2267 				    break;
2268 			if (p_pt[mlen] == NUL)	/* match */
2269 			{
2270 			    /* write chars to script file(s) */
2271 			    if (mlen > typebuf.tb_maplen)
2272 				gotchars(typebuf.tb_buf + typebuf.tb_off
2273 							  + typebuf.tb_maplen,
2274 						    mlen - typebuf.tb_maplen);
2275 
2276 			    del_typebuf(mlen, 0); /* remove the chars */
2277 			    set_option_value((char_u *)"paste",
2278 						     (long)!p_paste, NULL, 0);
2279 			    if (!(State & INSERT))
2280 			    {
2281 				msg_col = 0;
2282 				msg_row = Rows - 1;
2283 				msg_clr_eos();		/* clear ruler */
2284 			    }
2285 			    status_redraw_all();
2286 			    redraw_statuslines();
2287 			    showmode();
2288 			    setcursor();
2289 			    continue;
2290 			}
2291 			/* Need more chars for partly match. */
2292 			if (mlen == typebuf.tb_len)
2293 			    keylen = KEYLEN_PART_KEY;
2294 			else if (max_mlen < mlen)
2295 			    /* no match, may have to check for termcode at
2296 			     * next character */
2297 			    max_mlen = mlen + 1;
2298 		    }
2299 
2300 		    if ((mp == NULL || max_mlen >= mp_match_len)
2301 						 && keylen != KEYLEN_PART_MAP)
2302 		    {
2303 			int	save_keylen = keylen;
2304 
2305 			/*
2306 			 * When no matching mapping found or found a
2307 			 * non-matching mapping that matches at least what the
2308 			 * matching mapping matched:
2309 			 * Check if we have a terminal code, when:
2310 			 *  mapping is allowed,
2311 			 *  keys have not been mapped,
2312 			 *  and not an ESC sequence, not in insert mode or
2313 			 *	p_ek is on,
2314 			 *  and when not timed out,
2315 			 */
2316 			if ((no_mapping == 0 || allow_keys != 0)
2317 				&& (typebuf.tb_maplen == 0
2318 				    || (p_remap && typebuf.tb_noremap[
2319 						   typebuf.tb_off] == RM_YES))
2320 				&& !timedout)
2321 			{
2322 			    keylen = check_termcode(max_mlen + 1,
2323 							       NULL, 0, NULL);
2324 
2325 			    /* If no termcode matched but 'pastetoggle'
2326 			     * matched partially it's like an incomplete key
2327 			     * sequence. */
2328 			    if (keylen == 0 && save_keylen == KEYLEN_PART_KEY)
2329 				keylen = KEYLEN_PART_KEY;
2330 
2331 			    /*
2332 			     * When getting a partial match, but the last
2333 			     * characters were not typed, don't wait for a
2334 			     * typed character to complete the termcode.
2335 			     * This helps a lot when a ":normal" command ends
2336 			     * in an ESC.
2337 			     */
2338 			    if (keylen < 0
2339 				       && typebuf.tb_len == typebuf.tb_maplen)
2340 				keylen = 0;
2341 			}
2342 			else
2343 			    keylen = 0;
2344 			if (keylen == 0)	/* no matching terminal code */
2345 			{
2346 #ifdef AMIGA			/* check for window bounds report */
2347 			    if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
2348 					       typebuf.tb_off] & 0xff) == CSI)
2349 			    {
2350 				for (s = typebuf.tb_buf + typebuf.tb_off + 1;
2351 					s < typebuf.tb_buf + typebuf.tb_off
2352 							      + typebuf.tb_len
2353 				   && (VIM_ISDIGIT(*s) || *s == ';'
2354 								|| *s == ' ');
2355 					++s)
2356 				    ;
2357 				if (*s == 'r' || *s == '|') /* found one */
2358 				{
2359 				    del_typebuf((int)(s + 1 -
2360 				       (typebuf.tb_buf + typebuf.tb_off)), 0);
2361 				    /* get size and redraw screen */
2362 				    shell_resized();
2363 				    continue;
2364 				}
2365 				if (*s == NUL)	    /* need more characters */
2366 				    keylen = KEYLEN_PART_KEY;
2367 			    }
2368 			    if (keylen >= 0)
2369 #endif
2370 			      /* When there was a matching mapping and no
2371 			       * termcode could be replaced after another one,
2372 			       * use that mapping (loop around). If there was
2373 			       * no mapping use the character from the
2374 			       * typeahead buffer right here. */
2375 			      if (mp == NULL)
2376 			      {
2377 /*
2378  * get a character: 2. from the typeahead buffer
2379  */
2380 				c = typebuf.tb_buf[typebuf.tb_off] & 255;
2381 				if (advance)	/* remove chars from tb_buf */
2382 				{
2383 				    cmd_silent = (typebuf.tb_silent > 0);
2384 				    if (typebuf.tb_maplen > 0)
2385 					KeyTyped = FALSE;
2386 				    else
2387 				    {
2388 					KeyTyped = TRUE;
2389 					/* write char to script file(s) */
2390 					gotchars(typebuf.tb_buf
2391 							 + typebuf.tb_off, 1);
2392 				    }
2393 				    KeyNoremap = typebuf.tb_noremap[
2394 							      typebuf.tb_off];
2395 				    del_typebuf(1, 0);
2396 				}
2397 				break;	    /* got character, break for loop */
2398 			      }
2399 			}
2400 			if (keylen > 0)	    /* full matching terminal code */
2401 			{
2402 #if defined(FEAT_GUI) && defined(FEAT_MENU)
2403 			    if (typebuf.tb_len >= 2
2404 				&& typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
2405 					 && typebuf.tb_buf[typebuf.tb_off + 1]
2406 								   == KS_MENU)
2407 			    {
2408 				/*
2409 				 * Using a menu may cause a break in undo!
2410 				 * It's like using gotchars(), but without
2411 				 * recording or writing to a script file.
2412 				 */
2413 				may_sync_undo();
2414 				del_typebuf(3, 0);
2415 				idx = get_menu_index(current_menu, local_State);
2416 				if (idx != MENU_INDEX_INVALID)
2417 				{
2418 				    /*
2419 				     * In Select mode and a Visual mode menu
2420 				     * is used:  Switch to Visual mode
2421 				     * temporarily.  Append K_SELECT to switch
2422 				     * back to Select mode.
2423 				     */
2424 				    if (VIsual_active && VIsual_select
2425 					    && (current_menu->modes & VISUAL))
2426 				    {
2427 					VIsual_select = FALSE;
2428 					(void)ins_typebuf(K_SELECT_STRING,
2429 						  REMAP_NONE, 0, TRUE, FALSE);
2430 				    }
2431 				    ins_typebuf(current_menu->strings[idx],
2432 						current_menu->noremap[idx],
2433 						0, TRUE,
2434 						   current_menu->silent[idx]);
2435 				}
2436 			    }
2437 #endif /* FEAT_GUI && FEAT_MENU */
2438 			    continue;	/* try mapping again */
2439 			}
2440 
2441 			/* Partial match: get some more characters.  When a
2442 			 * matching mapping was found use that one. */
2443 			if (mp == NULL || keylen < 0)
2444 			    keylen = KEYLEN_PART_KEY;
2445 			else
2446 			    keylen = mp_match_len;
2447 		    }
2448 
2449 		    /* complete match */
2450 		    if (keylen >= 0 && keylen <= typebuf.tb_len)
2451 		    {
2452 #ifdef FEAT_EVAL
2453 			int save_m_expr;
2454 			int save_m_noremap;
2455 			int save_m_silent;
2456 			char_u *save_m_keys;
2457 			char_u *save_m_str;
2458 #else
2459 # define save_m_noremap mp->m_noremap
2460 # define save_m_silent mp->m_silent
2461 #endif
2462 
2463 			/* write chars to script file(s) */
2464 			if (keylen > typebuf.tb_maplen)
2465 			    gotchars(typebuf.tb_buf + typebuf.tb_off
2466 							  + typebuf.tb_maplen,
2467 						  keylen - typebuf.tb_maplen);
2468 
2469 			cmd_silent = (typebuf.tb_silent > 0);
2470 			del_typebuf(keylen, 0);	/* remove the mapped keys */
2471 
2472 			/*
2473 			 * Put the replacement string in front of mapstr.
2474 			 * The depth check catches ":map x y" and ":map y x".
2475 			 */
2476 			if (++mapdepth >= p_mmd)
2477 			{
2478 			    emsg(_("E223: recursive mapping"));
2479 			    if (State & CMDLINE)
2480 				redrawcmdline();
2481 			    else
2482 				setcursor();
2483 			    flush_buffers(FLUSH_MINIMAL);
2484 			    mapdepth = 0;	/* for next one */
2485 			    c = -1;
2486 			    break;
2487 			}
2488 
2489 			/*
2490 			 * In Select mode and a Visual mode mapping is used:
2491 			 * Switch to Visual mode temporarily.  Append K_SELECT
2492 			 * to switch back to Select mode.
2493 			 */
2494 			if (VIsual_active && VIsual_select
2495 						     && (mp->m_mode & VISUAL))
2496 			{
2497 			    VIsual_select = FALSE;
2498 			    (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE,
2499 							      0, TRUE, FALSE);
2500 			}
2501 
2502 #ifdef FEAT_EVAL
2503 			/* Copy the values from *mp that are used, because
2504 			 * evaluating the expression may invoke a function
2505 			 * that redefines the mapping, thereby making *mp
2506 			 * invalid. */
2507 			save_m_expr = mp->m_expr;
2508 			save_m_noremap = mp->m_noremap;
2509 			save_m_silent = mp->m_silent;
2510 			save_m_keys = NULL;  /* only saved when needed */
2511 			save_m_str = NULL;  /* only saved when needed */
2512 
2513 			/*
2514 			 * Handle ":map <expr>": evaluate the {rhs} as an
2515 			 * expression.  Also save and restore the command line
2516 			 * for "normal :".
2517 			 */
2518 			if (mp->m_expr)
2519 			{
2520 			    int		save_vgetc_busy = vgetc_busy;
2521 
2522 			    vgetc_busy = 0;
2523 			    save_m_keys = vim_strsave(mp->m_keys);
2524 			    save_m_str = vim_strsave(mp->m_str);
2525 			    s = eval_map_expr(save_m_str, NUL);
2526 			    vgetc_busy = save_vgetc_busy;
2527 			}
2528 			else
2529 #endif
2530 			    s = mp->m_str;
2531 
2532 			/*
2533 			 * Insert the 'to' part in the typebuf.tb_buf.
2534 			 * If 'from' field is the same as the start of the
2535 			 * 'to' field, don't remap the first character (but do
2536 			 * allow abbreviations).
2537 			 * If m_noremap is set, don't remap the whole 'to'
2538 			 * part.
2539 			 */
2540 			if (s == NULL)
2541 			    i = FAIL;
2542 			else
2543 			{
2544 			    int noremap;
2545 
2546 			    if (save_m_noremap != REMAP_YES)
2547 				noremap = save_m_noremap;
2548 			    else if (
2549 #ifdef FEAT_EVAL
2550 				STRNCMP(s, save_m_keys != NULL
2551 						   ? save_m_keys : mp->m_keys,
2552 							 (size_t)keylen)
2553 #else
2554 				STRNCMP(s, mp->m_keys, (size_t)keylen)
2555 #endif
2556 				   != 0)
2557 				noremap = REMAP_YES;
2558 			    else
2559 				noremap = REMAP_SKIP;
2560 			    i = ins_typebuf(s, noremap,
2561 					0, TRUE, cmd_silent || save_m_silent);
2562 #ifdef FEAT_EVAL
2563 			    if (save_m_expr)
2564 				vim_free(s);
2565 #endif
2566 			}
2567 #ifdef FEAT_EVAL
2568 			vim_free(save_m_keys);
2569 			vim_free(save_m_str);
2570 #endif
2571 			if (i == FAIL)
2572 			{
2573 			    c = -1;
2574 			    break;
2575 			}
2576 			continue;
2577 		    }
2578 		}
2579 
2580 /*
2581  * get a character: 3. from the user - handle <Esc> in Insert mode
2582  */
2583 		/*
2584 		 * Special case: if we get an <ESC> in insert mode and there
2585 		 * are no more characters at once, we pretend to go out of
2586 		 * insert mode.  This prevents the one second delay after
2587 		 * typing an <ESC>.  If we get something after all, we may
2588 		 * have to redisplay the mode. That the cursor is in the wrong
2589 		 * place does not matter.
2590 		 */
2591 		c = 0;
2592 #ifdef FEAT_CMDL_INFO
2593 		new_wcol = curwin->w_wcol;
2594 		new_wrow = curwin->w_wrow;
2595 #endif
2596 		if (	   advance
2597 			&& typebuf.tb_len == 1
2598 			&& typebuf.tb_buf[typebuf.tb_off] == ESC
2599 			&& !no_mapping
2600 			&& ex_normal_busy == 0
2601 			&& typebuf.tb_maplen == 0
2602 			&& (State & INSERT)
2603 			&& (p_timeout
2604 			    || (keylen == KEYLEN_PART_KEY && p_ttimeout))
2605 			&& (c = inchar(typebuf.tb_buf + typebuf.tb_off
2606 					       + typebuf.tb_len, 3, 25L)) == 0)
2607 		{
2608 		    colnr_T	col = 0, vcol;
2609 		    char_u	*ptr;
2610 
2611 		    if (mode_displayed)
2612 		    {
2613 			unshowmode(TRUE);
2614 			mode_deleted = TRUE;
2615 		    }
2616 #ifdef FEAT_GUI
2617 		    /* may show a different cursor shape */
2618 		    if (gui.in_use && State != NORMAL && !cmd_silent)
2619 		    {
2620 			int	    save_State;
2621 
2622 			save_State = State;
2623 			State = NORMAL;
2624 			gui_update_cursor(TRUE, FALSE);
2625 			State = save_State;
2626 			shape_changed = TRUE;
2627 		    }
2628 #endif
2629 		    validate_cursor();
2630 		    old_wcol = curwin->w_wcol;
2631 		    old_wrow = curwin->w_wrow;
2632 
2633 		    /* move cursor left, if possible */
2634 		    if (curwin->w_cursor.col != 0)
2635 		    {
2636 			if (curwin->w_wcol > 0)
2637 			{
2638 			    if (did_ai)
2639 			    {
2640 				/*
2641 				 * We are expecting to truncate the trailing
2642 				 * white-space, so find the last non-white
2643 				 * character -- webb
2644 				 */
2645 				col = vcol = curwin->w_wcol = 0;
2646 				ptr = ml_get_curline();
2647 				while (col < curwin->w_cursor.col)
2648 				{
2649 				    if (!VIM_ISWHITE(ptr[col]))
2650 					curwin->w_wcol = vcol;
2651 				    vcol += lbr_chartabsize(ptr, ptr + col,
2652 							       (colnr_T)vcol);
2653 				    if (has_mbyte)
2654 					col += (*mb_ptr2len)(ptr + col);
2655 				    else
2656 					++col;
2657 				}
2658 				curwin->w_wrow = curwin->w_cline_row
2659 					   + curwin->w_wcol / curwin->w_width;
2660 				curwin->w_wcol %= curwin->w_width;
2661 				curwin->w_wcol += curwin_col_off();
2662 				col = 0;	/* no correction needed */
2663 			    }
2664 			    else
2665 			    {
2666 				--curwin->w_wcol;
2667 				col = curwin->w_cursor.col - 1;
2668 			    }
2669 			}
2670 			else if (curwin->w_p_wrap && curwin->w_wrow)
2671 			{
2672 			    --curwin->w_wrow;
2673 			    curwin->w_wcol = curwin->w_width - 1;
2674 			    col = curwin->w_cursor.col - 1;
2675 			}
2676 			if (has_mbyte && col > 0 && curwin->w_wcol > 0)
2677 			{
2678 			    /* Correct when the cursor is on the right halve
2679 			     * of a double-wide character. */
2680 			    ptr = ml_get_curline();
2681 			    col -= (*mb_head_off)(ptr, ptr + col);
2682 			    if ((*mb_ptr2cells)(ptr + col) > 1)
2683 				--curwin->w_wcol;
2684 			}
2685 		    }
2686 		    setcursor();
2687 		    out_flush();
2688 #ifdef FEAT_CMDL_INFO
2689 		    new_wcol = curwin->w_wcol;
2690 		    new_wrow = curwin->w_wrow;
2691 #endif
2692 		    curwin->w_wcol = old_wcol;
2693 		    curwin->w_wrow = old_wrow;
2694 		}
2695 		if (c < 0)
2696 		    continue;	/* end of input script reached */
2697 
2698 		/* Allow mapping for just typed characters. When we get here c
2699 		 * is the number of extra bytes and typebuf.tb_len is 1. */
2700 		for (n = 1; n <= c; ++n)
2701 		    typebuf.tb_noremap[typebuf.tb_off + n] = RM_YES;
2702 		typebuf.tb_len += c;
2703 
2704 		/* buffer full, don't map */
2705 		if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
2706 		{
2707 		    timedout = TRUE;
2708 		    continue;
2709 		}
2710 
2711 		if (ex_normal_busy > 0)
2712 		{
2713 #ifdef FEAT_CMDWIN
2714 		    static int tc = 0;
2715 #endif
2716 
2717 		    /* No typeahead left and inside ":normal".  Must return
2718 		     * something to avoid getting stuck.  When an incomplete
2719 		     * mapping is present, behave like it timed out. */
2720 		    if (typebuf.tb_len > 0)
2721 		    {
2722 			timedout = TRUE;
2723 			continue;
2724 		    }
2725 		    /* When 'insertmode' is set, ESC just beeps in Insert
2726 		     * mode.  Use CTRL-L to make edit() return.
2727 		     * For the command line only CTRL-C always breaks it.
2728 		     * For the cmdline window: Alternate between ESC and
2729 		     * CTRL-C: ESC for most situations and CTRL-C to close the
2730 		     * cmdline window. */
2731 		    if (p_im && (State & INSERT))
2732 			c = Ctrl_L;
2733 #ifdef FEAT_TERMINAL
2734 		    else if (terminal_is_active())
2735 			c = K_CANCEL;
2736 #endif
2737 		    else if ((State & CMDLINE)
2738 #ifdef FEAT_CMDWIN
2739 			    || (cmdwin_type > 0 && tc == ESC)
2740 #endif
2741 			    )
2742 			c = Ctrl_C;
2743 		    else
2744 			c = ESC;
2745 #ifdef FEAT_CMDWIN
2746 		    tc = c;
2747 #endif
2748 		    break;
2749 		}
2750 
2751 /*
2752  * get a character: 3. from the user - update display
2753  */
2754 		/* In insert mode a screen update is skipped when characters
2755 		 * are still available.  But when those available characters
2756 		 * are part of a mapping, and we are going to do a blocking
2757 		 * wait here.  Need to update the screen to display the
2758 		 * changed text so far. Also for when 'lazyredraw' is set and
2759 		 * redrawing was postponed because there was something in the
2760 		 * input buffer (e.g., termresponse). */
2761 		if (((State & INSERT) != 0 || p_lz) && (State & CMDLINE) == 0
2762 			  && advance && must_redraw != 0 && !need_wait_return)
2763 		{
2764 		    update_screen(0);
2765 		    setcursor(); /* put cursor back where it belongs */
2766 		}
2767 
2768 		/*
2769 		 * If we have a partial match (and are going to wait for more
2770 		 * input from the user), show the partially matched characters
2771 		 * to the user with showcmd.
2772 		 */
2773 #ifdef FEAT_CMDL_INFO
2774 		i = 0;
2775 #endif
2776 		c1 = 0;
2777 		if (typebuf.tb_len > 0 && advance && !exmode_active)
2778 		{
2779 		    if (((State & (NORMAL | INSERT)) || State == LANGMAP)
2780 			    && State != HITRETURN)
2781 		    {
2782 			/* this looks nice when typing a dead character map */
2783 			if (State & INSERT
2784 			    && ptr2cells(typebuf.tb_buf + typebuf.tb_off
2785 						   + typebuf.tb_len - 1) == 1)
2786 			{
2787 			    edit_putchar(typebuf.tb_buf[typebuf.tb_off
2788 						+ typebuf.tb_len - 1], FALSE);
2789 			    setcursor(); /* put cursor back where it belongs */
2790 			    c1 = 1;
2791 			}
2792 #ifdef FEAT_CMDL_INFO
2793 			/* need to use the col and row from above here */
2794 			old_wcol = curwin->w_wcol;
2795 			old_wrow = curwin->w_wrow;
2796 			curwin->w_wcol = new_wcol;
2797 			curwin->w_wrow = new_wrow;
2798 			push_showcmd();
2799 			if (typebuf.tb_len > SHOWCMD_COLS)
2800 			    i = typebuf.tb_len - SHOWCMD_COLS;
2801 			while (i < typebuf.tb_len)
2802 			    (void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off
2803 								      + i++]);
2804 			curwin->w_wcol = old_wcol;
2805 			curwin->w_wrow = old_wrow;
2806 #endif
2807 		    }
2808 
2809 		    /* this looks nice when typing a dead character map */
2810 		    if ((State & CMDLINE)
2811 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2812 			    && cmdline_star == 0
2813 #endif
2814 			    && ptr2cells(typebuf.tb_buf + typebuf.tb_off
2815 						   + typebuf.tb_len - 1) == 1)
2816 		    {
2817 			putcmdline(typebuf.tb_buf[typebuf.tb_off
2818 						+ typebuf.tb_len - 1], FALSE);
2819 			c1 = 1;
2820 		    }
2821 		}
2822 
2823 /*
2824  * get a character: 3. from the user - get it
2825  */
2826 		if (typebuf.tb_len == 0)
2827 		    // timedout may have been set while waiting for a mapping
2828 		    // that has a <Nop> RHS.
2829 		    timedout = FALSE;
2830 
2831 		wait_tb_len = typebuf.tb_len;
2832 		c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
2833 			typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
2834 			!advance
2835 			    ? 0
2836 			    : ((typebuf.tb_len == 0
2837 				    || !(p_timeout || (p_ttimeout
2838 					       && keylen == KEYLEN_PART_KEY)))
2839 				    ? -1L
2840 				    : ((keylen == KEYLEN_PART_KEY && p_ttm >= 0)
2841 					    ? p_ttm
2842 					    : p_tm)));
2843 
2844 #ifdef FEAT_CMDL_INFO
2845 		if (i != 0)
2846 		    pop_showcmd();
2847 #endif
2848 		if (c1 == 1)
2849 		{
2850 		    if (State & INSERT)
2851 			edit_unputchar();
2852 		    if (State & CMDLINE)
2853 			unputcmdline();
2854 		    else
2855 			setcursor();	/* put cursor back where it belongs */
2856 		}
2857 
2858 		if (c < 0)
2859 		    continue;		/* end of input script reached */
2860 		if (c == NUL)		/* no character available */
2861 		{
2862 		    if (!advance)
2863 			break;
2864 		    if (wait_tb_len > 0)	/* timed out */
2865 		    {
2866 			timedout = TRUE;
2867 			continue;
2868 		    }
2869 		}
2870 		else
2871 		{	    /* allow mapping for just typed characters */
2872 		    while (typebuf.tb_buf[typebuf.tb_off
2873 						     + typebuf.tb_len] != NUL)
2874 			typebuf.tb_noremap[typebuf.tb_off
2875 						 + typebuf.tb_len++] = RM_YES;
2876 #ifdef HAVE_INPUT_METHOD
2877 		    /* Get IM status right after getting keys, not after the
2878 		     * timeout for a mapping (focus may be lost by then). */
2879 		    vgetc_im_active = im_get_status();
2880 #endif
2881 		}
2882 	    }	    /* for (;;) */
2883 	}	/* if (!character from stuffbuf) */
2884 
2885 	/* if advance is FALSE don't loop on NULs */
2886     } while ((c < 0 && c != K_CANCEL) || (advance && c == NUL));
2887 
2888     /*
2889      * The "INSERT" message is taken care of here:
2890      *	 if we return an ESC to exit insert mode, the message is deleted
2891      *	 if we don't return an ESC but deleted the message before, redisplay it
2892      */
2893     if (advance && p_smd && msg_silent == 0 && (State & INSERT))
2894     {
2895 	if (c == ESC && !mode_deleted && !no_mapping && mode_displayed)
2896 	{
2897 	    if (typebuf.tb_len && !KeyTyped)
2898 		redraw_cmdline = TRUE;	    /* delete mode later */
2899 	    else
2900 		unshowmode(FALSE);
2901 	}
2902 	else if (c != ESC && mode_deleted)
2903 	{
2904 	    if (typebuf.tb_len && !KeyTyped)
2905 		redraw_cmdline = TRUE;	    /* show mode later */
2906 	    else
2907 		showmode();
2908 	}
2909     }
2910 #ifdef FEAT_GUI
2911     /* may unshow different cursor shape */
2912     if (gui.in_use && shape_changed)
2913 	gui_update_cursor(TRUE, FALSE);
2914 #endif
2915 
2916     --vgetc_busy;
2917 
2918     return c;
2919 }
2920 
2921 /*
2922  * inchar() - get one character from
2923  *	1. a scriptfile
2924  *	2. the keyboard
2925  *
2926  *  As much characters as we can get (upto 'maxlen') are put in "buf" and
2927  *  NUL terminated (buffer length must be 'maxlen' + 1).
2928  *  Minimum for "maxlen" is 3!!!!
2929  *
2930  *  "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
2931  *  it.  When typebuf.tb_change_cnt changes (e.g., when a message is received
2932  *  from a remote client) "buf" can no longer be used.  "tb_change_cnt" is 0
2933  *  otherwise.
2934  *
2935  *  If we got an interrupt all input is read until none is available.
2936  *
2937  *  If wait_time == 0  there is no waiting for the char.
2938  *  If wait_time == n  we wait for n msec for a character to arrive.
2939  *  If wait_time == -1 we wait forever for a character to arrive.
2940  *
2941  *  Return the number of obtained characters.
2942  *  Return -1 when end of input script reached.
2943  */
2944     static int
2945 inchar(
2946     char_u	*buf,
2947     int		maxlen,
2948     long	wait_time)	    /* milli seconds */
2949 {
2950     int		len = 0;	    /* init for GCC */
2951     int		retesc = FALSE;	    /* return ESC with gotint */
2952     int		script_char;
2953     int		tb_change_cnt = typebuf.tb_change_cnt;
2954 
2955     if (wait_time == -1L || wait_time > 100L)  /* flush output before waiting */
2956     {
2957 	cursor_on();
2958 	out_flush_cursor(FALSE, FALSE);
2959 #if defined(FEAT_GUI) && defined(FEAT_MOUSESHAPE)
2960 	if (gui.in_use && postponed_mouseshape)
2961 	    update_mouseshape(-1);
2962 #endif
2963     }
2964 
2965     /*
2966      * Don't reset these when at the hit-return prompt, otherwise a endless
2967      * recursive loop may result (write error in swapfile, hit-return, timeout
2968      * on char wait, flush swapfile, write error....).
2969      */
2970     if (State != HITRETURN)
2971     {
2972 	did_outofmem_msg = FALSE;   /* display out of memory message (again) */
2973 	did_swapwrite_msg = FALSE;  /* display swap file write error again */
2974     }
2975     undo_off = FALSE;		    /* restart undo now */
2976 
2977     /*
2978      * Get a character from a script file if there is one.
2979      * If interrupted: Stop reading script files, close them all.
2980      */
2981     script_char = -1;
2982     while (scriptin[curscript] != NULL && script_char < 0
2983 #ifdef FEAT_EVAL
2984 	    && !ignore_script
2985 #endif
2986 	    )
2987     {
2988 
2989 #ifdef MESSAGE_QUEUE
2990 	parse_queued_messages();
2991 #endif
2992 
2993 	if (got_int || (script_char = getc(scriptin[curscript])) < 0)
2994 	{
2995 	    /* Reached EOF.
2996 	     * Careful: closescript() frees typebuf.tb_buf[] and buf[] may
2997 	     * point inside typebuf.tb_buf[].  Don't use buf[] after this! */
2998 	    closescript();
2999 	    /*
3000 	     * When reading script file is interrupted, return an ESC to get
3001 	     * back to normal mode.
3002 	     * Otherwise return -1, because typebuf.tb_buf[] has changed.
3003 	     */
3004 	    if (got_int)
3005 		retesc = TRUE;
3006 	    else
3007 		return -1;
3008 	}
3009 	else
3010 	{
3011 	    buf[0] = script_char;
3012 	    len = 1;
3013 	}
3014     }
3015 
3016     if (script_char < 0)	/* did not get a character from script */
3017     {
3018 	/*
3019 	 * If we got an interrupt, skip all previously typed characters and
3020 	 * return TRUE if quit reading script file.
3021 	 * Stop reading typeahead when a single CTRL-C was read,
3022 	 * fill_input_buf() returns this when not able to read from stdin.
3023 	 * Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
3024 	 * and buf may be pointing inside typebuf.tb_buf[].
3025 	 */
3026 	if (got_int)
3027 	{
3028 #define DUM_LEN MAXMAPLEN * 3 + 3
3029 	    char_u	dum[DUM_LEN + 1];
3030 
3031 	    for (;;)
3032 	    {
3033 		len = ui_inchar(dum, DUM_LEN, 0L, 0);
3034 		if (len == 0 || (len == 1 && dum[0] == 3))
3035 		    break;
3036 	    }
3037 	    return retesc;
3038 	}
3039 
3040 	/*
3041 	 * Always flush the output characters when getting input characters
3042 	 * from the user and not just peeking.
3043 	 */
3044 	if (wait_time == -1L || wait_time > 10L)
3045 	    out_flush();
3046 
3047 	/*
3048 	 * Fill up to a third of the buffer, because each character may be
3049 	 * tripled below.
3050 	 */
3051 	len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt);
3052     }
3053 
3054     /* If the typebuf was changed further down, it is like nothing was added by
3055      * this call. */
3056     if (typebuf_changed(tb_change_cnt))
3057 	return 0;
3058 
3059     /* Note the change in the typeahead buffer, this matters for when
3060      * vgetorpeek() is called recursively, e.g. using getchar(1) in a timer
3061      * function. */
3062     if (len > 0 && ++typebuf.tb_change_cnt == 0)
3063 	typebuf.tb_change_cnt = 1;
3064 
3065     return fix_input_buffer(buf, len);
3066 }
3067 
3068 /*
3069  * Fix typed characters for use by vgetc() and check_termcode().
3070  * buf[] must have room to triple the number of bytes!
3071  * Returns the new length.
3072  */
3073     int
3074 fix_input_buffer(char_u *buf, int len)
3075 {
3076     int		i;
3077     char_u	*p = buf;
3078 
3079     /*
3080      * Two characters are special: NUL and K_SPECIAL.
3081      * When compiled With the GUI CSI is also special.
3082      * Replace	     NUL by K_SPECIAL KS_ZERO	 KE_FILLER
3083      * Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
3084      * Replace       CSI by K_SPECIAL KS_EXTRA   KE_CSI
3085      */
3086     for (i = len; --i >= 0; ++p)
3087     {
3088 #ifdef FEAT_GUI
3089 	/* When the GUI is used any character can come after a CSI, don't
3090 	 * escape it. */
3091 	if (gui.in_use && p[0] == CSI && i >= 2)
3092 	{
3093 	    p += 2;
3094 	    i -= 2;
3095 	}
3096 	/* When the GUI is not used CSI needs to be escaped. */
3097 	else if (!gui.in_use && p[0] == CSI)
3098 	{
3099 	    mch_memmove(p + 3, p + 1, (size_t)i);
3100 	    *p++ = K_SPECIAL;
3101 	    *p++ = KS_EXTRA;
3102 	    *p = (int)KE_CSI;
3103 	    len += 2;
3104 	}
3105 	else
3106 #endif
3107 	if (p[0] == NUL || (p[0] == K_SPECIAL
3108 		    /* timeout may generate K_CURSORHOLD */
3109 		    && (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD)
3110 #if defined(WIN3264) && !defined(FEAT_GUI)
3111 		    /* Win32 console passes modifiers */
3112 		    && (i < 2 || p[1] != KS_MODIFIER)
3113 #endif
3114 		    ))
3115 	{
3116 	    mch_memmove(p + 3, p + 1, (size_t)i);
3117 	    p[2] = K_THIRD(p[0]);
3118 	    p[1] = K_SECOND(p[0]);
3119 	    p[0] = K_SPECIAL;
3120 	    p += 2;
3121 	    len += 2;
3122 	}
3123     }
3124     *p = NUL;		/* add trailing NUL */
3125     return len;
3126 }
3127 
3128 #if defined(USE_INPUT_BUF) || defined(PROTO)
3129 /*
3130  * Return TRUE when bytes are in the input buffer or in the typeahead buffer.
3131  * Normally the input buffer would be sufficient, but the server_to_input_buf()
3132  * or feedkeys() may insert characters in the typeahead buffer while we are
3133  * waiting for input to arrive.
3134  */
3135     int
3136 input_available(void)
3137 {
3138     return (!vim_is_input_buf_empty()
3139 # if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
3140 	    || typebuf_was_filled
3141 # endif
3142 	    );
3143 }
3144 #endif
3145 
3146 /*
3147  * map[!]		    : show all key mappings
3148  * map[!] {lhs}		    : show key mapping for {lhs}
3149  * map[!] {lhs} {rhs}	    : set key mapping for {lhs} to {rhs}
3150  * noremap[!] {lhs} {rhs}   : same, but no remapping for {rhs}
3151  * unmap[!] {lhs}	    : remove key mapping for {lhs}
3152  * abbr			    : show all abbreviations
3153  * abbr {lhs}		    : show abbreviations for {lhs}
3154  * abbr {lhs} {rhs}	    : set abbreviation for {lhs} to {rhs}
3155  * noreabbr {lhs} {rhs}	    : same, but no remapping for {rhs}
3156  * unabbr {lhs}		    : remove abbreviation for {lhs}
3157  *
3158  * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
3159  *
3160  * arg is pointer to any arguments. Note: arg cannot be a read-only string,
3161  * it will be modified.
3162  *
3163  * for :map   mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING
3164  * for :map!  mode is INSERT + CMDLINE
3165  * for :cmap  mode is CMDLINE
3166  * for :imap  mode is INSERT
3167  * for :lmap  mode is LANGMAP
3168  * for :nmap  mode is NORMAL
3169  * for :vmap  mode is VISUAL + SELECTMODE
3170  * for :xmap  mode is VISUAL
3171  * for :smap  mode is SELECTMODE
3172  * for :omap  mode is OP_PENDING
3173  * for :tmap  mode is TERMINAL
3174  *
3175  * for :abbr  mode is INSERT + CMDLINE
3176  * for :iabbr mode is INSERT
3177  * for :cabbr mode is CMDLINE
3178  *
3179  * Return 0 for success
3180  *	  1 for invalid arguments
3181  *	  2 for no match
3182  *	  4 for out of mem
3183  *	  5 for entry not unique
3184  */
3185     int
3186 do_map(
3187     int		maptype,
3188     char_u	*arg,
3189     int		mode,
3190     int		abbrev)		/* not a mapping but an abbreviation */
3191 {
3192     char_u	*keys;
3193     mapblock_T	*mp, **mpp;
3194     char_u	*rhs;
3195     char_u	*p;
3196     int		n;
3197     int		len = 0;	/* init for GCC */
3198     char_u	*newstr;
3199     int		hasarg;
3200     int		haskey;
3201     int		did_it = FALSE;
3202 #ifdef FEAT_LOCALMAP
3203     int		did_local = FALSE;
3204 #endif
3205     int		round;
3206     char_u	*keys_buf = NULL;
3207     char_u	*arg_buf = NULL;
3208     int		retval = 0;
3209     int		do_backslash;
3210     int		hash;
3211     int		new_hash;
3212     mapblock_T	**abbr_table;
3213     mapblock_T	**map_table;
3214     int		unique = FALSE;
3215     int		nowait = FALSE;
3216     int		silent = FALSE;
3217     int		special = FALSE;
3218 #ifdef FEAT_EVAL
3219     int		expr = FALSE;
3220 #endif
3221     int		noremap;
3222     char_u      *orig_rhs;
3223 
3224     keys = arg;
3225     map_table = maphash;
3226     abbr_table = &first_abbr;
3227 
3228     /* For ":noremap" don't remap, otherwise do remap. */
3229     if (maptype == 2)
3230 	noremap = REMAP_NONE;
3231     else
3232 	noremap = REMAP_YES;
3233 
3234     /* Accept <buffer>, <nowait>, <silent>, <expr> <script> and <unique> in
3235      * any order. */
3236     for (;;)
3237     {
3238 #ifdef FEAT_LOCALMAP
3239 	/*
3240 	 * Check for "<buffer>": mapping local to buffer.
3241 	 */
3242 	if (STRNCMP(keys, "<buffer>", 8) == 0)
3243 	{
3244 	    keys = skipwhite(keys + 8);
3245 	    map_table = curbuf->b_maphash;
3246 	    abbr_table = &curbuf->b_first_abbr;
3247 	    continue;
3248 	}
3249 #endif
3250 
3251 	/*
3252 	 * Check for "<nowait>": don't wait for more characters.
3253 	 */
3254 	if (STRNCMP(keys, "<nowait>", 8) == 0)
3255 	{
3256 	    keys = skipwhite(keys + 8);
3257 	    nowait = TRUE;
3258 	    continue;
3259 	}
3260 
3261 	/*
3262 	 * Check for "<silent>": don't echo commands.
3263 	 */
3264 	if (STRNCMP(keys, "<silent>", 8) == 0)
3265 	{
3266 	    keys = skipwhite(keys + 8);
3267 	    silent = TRUE;
3268 	    continue;
3269 	}
3270 
3271 	/*
3272 	 * Check for "<special>": accept special keys in <>
3273 	 */
3274 	if (STRNCMP(keys, "<special>", 9) == 0)
3275 	{
3276 	    keys = skipwhite(keys + 9);
3277 	    special = TRUE;
3278 	    continue;
3279 	}
3280 
3281 #ifdef FEAT_EVAL
3282 	/*
3283 	 * Check for "<script>": remap script-local mappings only
3284 	 */
3285 	if (STRNCMP(keys, "<script>", 8) == 0)
3286 	{
3287 	    keys = skipwhite(keys + 8);
3288 	    noremap = REMAP_SCRIPT;
3289 	    continue;
3290 	}
3291 
3292 	/*
3293 	 * Check for "<expr>": {rhs} is an expression.
3294 	 */
3295 	if (STRNCMP(keys, "<expr>", 6) == 0)
3296 	{
3297 	    keys = skipwhite(keys + 6);
3298 	    expr = TRUE;
3299 	    continue;
3300 	}
3301 #endif
3302 	/*
3303 	 * Check for "<unique>": don't overwrite an existing mapping.
3304 	 */
3305 	if (STRNCMP(keys, "<unique>", 8) == 0)
3306 	{
3307 	    keys = skipwhite(keys + 8);
3308 	    unique = TRUE;
3309 	    continue;
3310 	}
3311 	break;
3312     }
3313 
3314     validate_maphash();
3315 
3316     /*
3317      * Find end of keys and skip CTRL-Vs (and backslashes) in it.
3318      * Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
3319      * with :unmap white space is included in the keys, no argument possible.
3320      */
3321     p = keys;
3322     do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
3323     while (*p && (maptype == 1 || !VIM_ISWHITE(*p)))
3324     {
3325 	if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
3326 								  p[1] != NUL)
3327 	    ++p;		/* skip CTRL-V or backslash */
3328 	++p;
3329     }
3330     if (*p != NUL)
3331 	*p++ = NUL;
3332 
3333     p = skipwhite(p);
3334     rhs = p;
3335     hasarg = (*rhs != NUL);
3336     haskey = (*keys != NUL);
3337 
3338     /* check for :unmap without argument */
3339     if (maptype == 1 && !haskey)
3340     {
3341 	retval = 1;
3342 	goto theend;
3343     }
3344 
3345     /*
3346      * If mapping has been given as ^V<C_UP> say, then replace the term codes
3347      * with the appropriate two bytes. If it is a shifted special key, unshift
3348      * it too, giving another two bytes.
3349      * replace_termcodes() may move the result to allocated memory, which
3350      * needs to be freed later (*keys_buf and *arg_buf).
3351      * replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
3352      */
3353     if (haskey)
3354 	keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special);
3355     orig_rhs = rhs;
3356     if (hasarg)
3357     {
3358 	if (STRICMP(rhs, "<nop>") == 0)	    /* "<Nop>" means nothing */
3359 	    rhs = (char_u *)"";
3360 	else
3361 	    rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special);
3362     }
3363 
3364 #ifdef FEAT_FKMAP
3365     /*
3366      * When in right-to-left mode and alternate keymap option set,
3367      * reverse the character flow in the rhs in Farsi.
3368      */
3369     if (p_altkeymap && curwin->w_p_rl)
3370 	lrswap(rhs);
3371 #endif
3372 
3373     /*
3374      * check arguments and translate function keys
3375      */
3376     if (haskey)
3377     {
3378 	len = (int)STRLEN(keys);
3379 	if (len > MAXMAPLEN)		/* maximum length of MAXMAPLEN chars */
3380 	{
3381 	    retval = 1;
3382 	    goto theend;
3383 	}
3384 
3385 	if (abbrev && maptype != 1)
3386 	{
3387 	    /*
3388 	     * If an abbreviation ends in a keyword character, the
3389 	     * rest must be all keyword-char or all non-keyword-char.
3390 	     * Otherwise we won't be able to find the start of it in a
3391 	     * vi-compatible way.
3392 	     */
3393 	    if (has_mbyte)
3394 	    {
3395 		int	first, last;
3396 		int	same = -1;
3397 
3398 		first = vim_iswordp(keys);
3399 		last = first;
3400 		p = keys + (*mb_ptr2len)(keys);
3401 		n = 1;
3402 		while (p < keys + len)
3403 		{
3404 		    ++n;			/* nr of (multi-byte) chars */
3405 		    last = vim_iswordp(p);	/* type of last char */
3406 		    if (same == -1 && last != first)
3407 			same = n - 1;		/* count of same char type */
3408 		    p += (*mb_ptr2len)(p);
3409 		}
3410 		if (last && n > 2 && same >= 0 && same < n - 1)
3411 		{
3412 		    retval = 1;
3413 		    goto theend;
3414 		}
3415 	    }
3416 	    else if (vim_iswordc(keys[len - 1]))  // ends in keyword char
3417 		    for (n = 0; n < len - 2; ++n)
3418 			if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
3419 			{
3420 			    retval = 1;
3421 			    goto theend;
3422 			}
3423 	    /* An abbreviation cannot contain white space. */
3424 	    for (n = 0; n < len; ++n)
3425 		if (VIM_ISWHITE(keys[n]))
3426 		{
3427 		    retval = 1;
3428 		    goto theend;
3429 		}
3430 	}
3431     }
3432 
3433     if (haskey && hasarg && abbrev)	/* if we will add an abbreviation */
3434 	no_abbr = FALSE;		/* reset flag that indicates there are
3435 							    no abbreviations */
3436 
3437     if (!haskey || (maptype != 1 && !hasarg))
3438 	msg_start();
3439 
3440 #ifdef FEAT_LOCALMAP
3441     /*
3442      * Check if a new local mapping wasn't already defined globally.
3443      */
3444     if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
3445     {
3446 	/* need to loop over all global hash lists */
3447 	for (hash = 0; hash < 256 && !got_int; ++hash)
3448 	{
3449 	    if (abbrev)
3450 	    {
3451 		if (hash != 0)	/* there is only one abbreviation list */
3452 		    break;
3453 		mp = first_abbr;
3454 	    }
3455 	    else
3456 		mp = maphash[hash];
3457 	    for ( ; mp != NULL && !got_int; mp = mp->m_next)
3458 	    {
3459 		/* check entries with the same mode */
3460 		if ((mp->m_mode & mode) != 0
3461 			&& mp->m_keylen == len
3462 			&& unique
3463 			&& STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
3464 		{
3465 		    if (abbrev)
3466 			semsg(_("E224: global abbreviation already exists for %s"),
3467 				mp->m_keys);
3468 		    else
3469 			semsg(_("E225: global mapping already exists for %s"),
3470 				mp->m_keys);
3471 		    retval = 5;
3472 		    goto theend;
3473 		}
3474 	    }
3475 	}
3476     }
3477 
3478     /*
3479      * When listing global mappings, also list buffer-local ones here.
3480      */
3481     if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
3482     {
3483 	/* need to loop over all global hash lists */
3484 	for (hash = 0; hash < 256 && !got_int; ++hash)
3485 	{
3486 	    if (abbrev)
3487 	    {
3488 		if (hash != 0)	/* there is only one abbreviation list */
3489 		    break;
3490 		mp = curbuf->b_first_abbr;
3491 	    }
3492 	    else
3493 		mp = curbuf->b_maphash[hash];
3494 	    for ( ; mp != NULL && !got_int; mp = mp->m_next)
3495 	    {
3496 		/* check entries with the same mode */
3497 		if ((mp->m_mode & mode) != 0)
3498 		{
3499 		    if (!haskey)		    /* show all entries */
3500 		    {
3501 			showmap(mp, TRUE);
3502 			did_local = TRUE;
3503 		    }
3504 		    else
3505 		    {
3506 			n = mp->m_keylen;
3507 			if (STRNCMP(mp->m_keys, keys,
3508 					    (size_t)(n < len ? n : len)) == 0)
3509 			{
3510 			    showmap(mp, TRUE);
3511 			    did_local = TRUE;
3512 			}
3513 		    }
3514 		}
3515 	    }
3516 	}
3517     }
3518 #endif
3519 
3520     /*
3521      * Find an entry in the maphash[] list that matches.
3522      * For :unmap we may loop two times: once to try to unmap an entry with a
3523      * matching 'from' part, a second time, if the first fails, to unmap an
3524      * entry with a matching 'to' part. This was done to allow ":ab foo bar"
3525      * to be unmapped by typing ":unab foo", where "foo" will be replaced by
3526      * "bar" because of the abbreviation.
3527      */
3528     for (round = 0; (round == 0 || maptype == 1) && round <= 1
3529 					      && !did_it && !got_int; ++round)
3530     {
3531 	/* need to loop over all hash lists */
3532 	for (hash = 0; hash < 256 && !got_int; ++hash)
3533 	{
3534 	    if (abbrev)
3535 	    {
3536 		if (hash > 0)	/* there is only one abbreviation list */
3537 		    break;
3538 		mpp = abbr_table;
3539 	    }
3540 	    else
3541 		mpp = &(map_table[hash]);
3542 	    for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
3543 	    {
3544 
3545 		if (!(mp->m_mode & mode))   /* skip entries with wrong mode */
3546 		{
3547 		    mpp = &(mp->m_next);
3548 		    continue;
3549 		}
3550 		if (!haskey)		    /* show all entries */
3551 		{
3552 		    showmap(mp, map_table != maphash);
3553 		    did_it = TRUE;
3554 		}
3555 		else			    /* do we have a match? */
3556 		{
3557 		    if (round)	    /* second round: Try unmap "rhs" string */
3558 		    {
3559 			n = (int)STRLEN(mp->m_str);
3560 			p = mp->m_str;
3561 		    }
3562 		    else
3563 		    {
3564 			n = mp->m_keylen;
3565 			p = mp->m_keys;
3566 		    }
3567 		    if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
3568 		    {
3569 			if (maptype == 1)	/* delete entry */
3570 			{
3571 			    /* Only accept a full match.  For abbreviations we
3572 			     * ignore trailing space when matching with the
3573 			     * "lhs", since an abbreviation can't have
3574 			     * trailing space. */
3575 			    if (n != len && (!abbrev || round || n > len
3576 					       || *skipwhite(keys + n) != NUL))
3577 			    {
3578 				mpp = &(mp->m_next);
3579 				continue;
3580 			    }
3581 			    /*
3582 			     * We reset the indicated mode bits. If nothing is
3583 			     * left the entry is deleted below.
3584 			     */
3585 			    mp->m_mode &= ~mode;
3586 			    did_it = TRUE;	/* remember we did something */
3587 			}
3588 			else if (!hasarg)	/* show matching entry */
3589 			{
3590 			    showmap(mp, map_table != maphash);
3591 			    did_it = TRUE;
3592 			}
3593 			else if (n != len)	/* new entry is ambiguous */
3594 			{
3595 			    mpp = &(mp->m_next);
3596 			    continue;
3597 			}
3598 			else if (unique)
3599 			{
3600 			    if (abbrev)
3601 				semsg(_("E226: abbreviation already exists for %s"),
3602 									   p);
3603 			    else
3604 				semsg(_("E227: mapping already exists for %s"), p);
3605 			    retval = 5;
3606 			    goto theend;
3607 			}
3608 			else			/* new rhs for existing entry */
3609 			{
3610 			    mp->m_mode &= ~mode;	/* remove mode bits */
3611 			    if (mp->m_mode == 0 && !did_it) /* reuse entry */
3612 			    {
3613 				newstr = vim_strsave(rhs);
3614 				if (newstr == NULL)
3615 				{
3616 				    retval = 4;		/* no mem */
3617 				    goto theend;
3618 				}
3619 				vim_free(mp->m_str);
3620 				mp->m_str = newstr;
3621 				vim_free(mp->m_orig_str);
3622 				mp->m_orig_str = vim_strsave(orig_rhs);
3623 				mp->m_noremap = noremap;
3624 				mp->m_nowait = nowait;
3625 				mp->m_silent = silent;
3626 				mp->m_mode = mode;
3627 #ifdef FEAT_EVAL
3628 				mp->m_expr = expr;
3629 				mp->m_script_ctx = current_sctx;
3630 				mp->m_script_ctx.sc_lnum += sourcing_lnum;
3631 #endif
3632 				did_it = TRUE;
3633 			    }
3634 			}
3635 			if (mp->m_mode == 0)	/* entry can be deleted */
3636 			{
3637 			    map_free(mpp);
3638 			    continue;		/* continue with *mpp */
3639 			}
3640 
3641 			/*
3642 			 * May need to put this entry into another hash list.
3643 			 */
3644 			new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3645 			if (!abbrev && new_hash != hash)
3646 			{
3647 			    *mpp = mp->m_next;
3648 			    mp->m_next = map_table[new_hash];
3649 			    map_table[new_hash] = mp;
3650 
3651 			    continue;		/* continue with *mpp */
3652 			}
3653 		    }
3654 		}
3655 		mpp = &(mp->m_next);
3656 	    }
3657 	}
3658     }
3659 
3660     if (maptype == 1)			    /* delete entry */
3661     {
3662 	if (!did_it)
3663 	    retval = 2;			    /* no match */
3664 	else if (*keys == Ctrl_C)
3665 	{
3666 	    /* If CTRL-C has been unmapped, reuse it for Interrupting. */
3667 #ifdef FEAT_LOCALMAP
3668 	    if (map_table == curbuf->b_maphash)
3669 		curbuf->b_mapped_ctrl_c &= ~mode;
3670 	    else
3671 #endif
3672 		mapped_ctrl_c &= ~mode;
3673 	}
3674 	goto theend;
3675     }
3676 
3677     if (!haskey || !hasarg)		    /* print entries */
3678     {
3679 	if (!did_it
3680 #ifdef FEAT_LOCALMAP
3681 		&& !did_local
3682 #endif
3683 		)
3684 	{
3685 	    if (abbrev)
3686 		msg(_("No abbreviation found"));
3687 	    else
3688 		msg(_("No mapping found"));
3689 	}
3690 	goto theend;			    /* listing finished */
3691     }
3692 
3693     if (did_it)			/* have added the new entry already */
3694 	goto theend;
3695 
3696     /*
3697      * Get here when adding a new entry to the maphash[] list or abbrlist.
3698      */
3699     mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T));
3700     if (mp == NULL)
3701     {
3702 	retval = 4;	    /* no mem */
3703 	goto theend;
3704     }
3705 
3706     /* If CTRL-C has been mapped, don't always use it for Interrupting. */
3707     if (*keys == Ctrl_C)
3708     {
3709 #ifdef FEAT_LOCALMAP
3710 	if (map_table == curbuf->b_maphash)
3711 	    curbuf->b_mapped_ctrl_c |= mode;
3712 	else
3713 #endif
3714 	    mapped_ctrl_c |= mode;
3715     }
3716 
3717     mp->m_keys = vim_strsave(keys);
3718     mp->m_str = vim_strsave(rhs);
3719     mp->m_orig_str = vim_strsave(orig_rhs);
3720     if (mp->m_keys == NULL || mp->m_str == NULL)
3721     {
3722 	vim_free(mp->m_keys);
3723 	vim_free(mp->m_str);
3724 	vim_free(mp->m_orig_str);
3725 	vim_free(mp);
3726 	retval = 4;	/* no mem */
3727 	goto theend;
3728     }
3729     mp->m_keylen = (int)STRLEN(mp->m_keys);
3730     mp->m_noremap = noremap;
3731     mp->m_nowait = nowait;
3732     mp->m_silent = silent;
3733     mp->m_mode = mode;
3734 #ifdef FEAT_EVAL
3735     mp->m_expr = expr;
3736     mp->m_script_ctx = current_sctx;
3737     mp->m_script_ctx.sc_lnum += sourcing_lnum;
3738 #endif
3739 
3740     /* add the new entry in front of the abbrlist or maphash[] list */
3741     if (abbrev)
3742     {
3743 	mp->m_next = *abbr_table;
3744 	*abbr_table = mp;
3745     }
3746     else
3747     {
3748 	n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3749 	mp->m_next = map_table[n];
3750 	map_table[n] = mp;
3751     }
3752 
3753 theend:
3754     vim_free(keys_buf);
3755     vim_free(arg_buf);
3756     return retval;
3757 }
3758 
3759 /*
3760  * Delete one entry from the abbrlist or maphash[].
3761  * "mpp" is a pointer to the m_next field of the PREVIOUS entry!
3762  */
3763     static void
3764 map_free(mapblock_T **mpp)
3765 {
3766     mapblock_T	*mp;
3767 
3768     mp = *mpp;
3769     vim_free(mp->m_keys);
3770     vim_free(mp->m_str);
3771     vim_free(mp->m_orig_str);
3772     *mpp = mp->m_next;
3773     vim_free(mp);
3774 }
3775 
3776 /*
3777  * Initialize maphash[] for first use.
3778  */
3779     static void
3780 validate_maphash(void)
3781 {
3782     if (!maphash_valid)
3783     {
3784 	vim_memset(maphash, 0, sizeof(maphash));
3785 	maphash_valid = TRUE;
3786     }
3787 }
3788 
3789 /*
3790  * Get the mapping mode from the command name.
3791  */
3792     int
3793 get_map_mode(char_u **cmdp, int forceit)
3794 {
3795     char_u	*p;
3796     int		modec;
3797     int		mode;
3798 
3799     p = *cmdp;
3800     modec = *p++;
3801     if (modec == 'i')
3802 	mode = INSERT;				/* :imap */
3803     else if (modec == 'l')
3804 	mode = LANGMAP;				/* :lmap */
3805     else if (modec == 'c')
3806 	mode = CMDLINE;				/* :cmap */
3807     else if (modec == 'n' && *p != 'o')		    /* avoid :noremap */
3808 	mode = NORMAL;				/* :nmap */
3809     else if (modec == 'v')
3810 	mode = VISUAL + SELECTMODE;		/* :vmap */
3811     else if (modec == 'x')
3812 	mode = VISUAL;				/* :xmap */
3813     else if (modec == 's')
3814 	mode = SELECTMODE;			/* :smap */
3815     else if (modec == 'o')
3816 	mode = OP_PENDING;			/* :omap */
3817     else if (modec == 't')
3818 	mode = TERMINAL;			/* :tmap */
3819     else
3820     {
3821 	--p;
3822 	if (forceit)
3823 	    mode = INSERT + CMDLINE;		/* :map ! */
3824 	else
3825 	    mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;/* :map */
3826     }
3827 
3828     *cmdp = p;
3829     return mode;
3830 }
3831 
3832 /*
3833  * Clear all mappings or abbreviations.
3834  * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
3835  */
3836     void
3837 map_clear(
3838     char_u	*cmdp,
3839     char_u	*arg UNUSED,
3840     int		forceit,
3841     int		abbr)
3842 {
3843     int		mode;
3844 #ifdef FEAT_LOCALMAP
3845     int		local;
3846 
3847     local = (STRCMP(arg, "<buffer>") == 0);
3848     if (!local && *arg != NUL)
3849     {
3850 	emsg(_(e_invarg));
3851 	return;
3852     }
3853 #endif
3854 
3855     mode = get_map_mode(&cmdp, forceit);
3856     map_clear_int(curbuf, mode,
3857 #ifdef FEAT_LOCALMAP
3858 	    local,
3859 #else
3860 	    FALSE,
3861 #endif
3862 	    abbr);
3863 }
3864 
3865 /*
3866  * Clear all mappings in "mode".
3867  */
3868     void
3869 map_clear_int(
3870     buf_T	*buf UNUSED,	/* buffer for local mappings */
3871     int		mode,		/* mode in which to delete */
3872     int		local UNUSED,	/* TRUE for buffer-local mappings */
3873     int		abbr)		/* TRUE for abbreviations */
3874 {
3875     mapblock_T	*mp, **mpp;
3876     int		hash;
3877     int		new_hash;
3878 
3879     validate_maphash();
3880 
3881     for (hash = 0; hash < 256; ++hash)
3882     {
3883 	if (abbr)
3884 	{
3885 	    if (hash > 0)	/* there is only one abbrlist */
3886 		break;
3887 #ifdef FEAT_LOCALMAP
3888 	    if (local)
3889 		mpp = &buf->b_first_abbr;
3890 	    else
3891 #endif
3892 		mpp = &first_abbr;
3893 	}
3894 	else
3895 	{
3896 #ifdef FEAT_LOCALMAP
3897 	    if (local)
3898 		mpp = &buf->b_maphash[hash];
3899 	    else
3900 #endif
3901 		mpp = &maphash[hash];
3902 	}
3903 	while (*mpp != NULL)
3904 	{
3905 	    mp = *mpp;
3906 	    if (mp->m_mode & mode)
3907 	    {
3908 		mp->m_mode &= ~mode;
3909 		if (mp->m_mode == 0) /* entry can be deleted */
3910 		{
3911 		    map_free(mpp);
3912 		    continue;
3913 		}
3914 		/*
3915 		 * May need to put this entry into another hash list.
3916 		 */
3917 		new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
3918 		if (!abbr && new_hash != hash)
3919 		{
3920 		    *mpp = mp->m_next;
3921 #ifdef FEAT_LOCALMAP
3922 		    if (local)
3923 		    {
3924 			mp->m_next = buf->b_maphash[new_hash];
3925 			buf->b_maphash[new_hash] = mp;
3926 		    }
3927 		    else
3928 #endif
3929 		    {
3930 			mp->m_next = maphash[new_hash];
3931 			maphash[new_hash] = mp;
3932 		    }
3933 		    continue;		/* continue with *mpp */
3934 		}
3935 	    }
3936 	    mpp = &(mp->m_next);
3937 	}
3938     }
3939 }
3940 
3941 /*
3942  * Return characters to represent the map mode in an allocated string.
3943  * Returns NULL when out of memory.
3944  */
3945     char_u *
3946 map_mode_to_chars(int mode)
3947 {
3948     garray_T    mapmode;
3949 
3950     ga_init2(&mapmode, 1, 7);
3951 
3952     if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
3953 	ga_append(&mapmode, '!');			/* :map! */
3954     else if (mode & INSERT)
3955 	ga_append(&mapmode, 'i');			/* :imap */
3956     else if (mode & LANGMAP)
3957 	ga_append(&mapmode, 'l');			/* :lmap */
3958     else if (mode & CMDLINE)
3959 	ga_append(&mapmode, 'c');			/* :cmap */
3960     else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING))
3961 				 == NORMAL + VISUAL + SELECTMODE + OP_PENDING)
3962 	ga_append(&mapmode, ' ');			/* :map */
3963     else
3964     {
3965 	if (mode & NORMAL)
3966 	    ga_append(&mapmode, 'n');			/* :nmap */
3967 	if (mode & OP_PENDING)
3968 	    ga_append(&mapmode, 'o');			/* :omap */
3969 	if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE)
3970 	    ga_append(&mapmode, 'v');			/* :vmap */
3971 	else
3972 	{
3973 	    if (mode & VISUAL)
3974 		ga_append(&mapmode, 'x');		/* :xmap */
3975 	    if (mode & SELECTMODE)
3976 		ga_append(&mapmode, 's');		/* :smap */
3977 	}
3978     }
3979 
3980     ga_append(&mapmode, NUL);
3981     return (char_u *)mapmode.ga_data;
3982 }
3983 
3984     static void
3985 showmap(
3986     mapblock_T	*mp,
3987     int		local)	    /* TRUE for buffer-local map */
3988 {
3989     int		len = 1;
3990     char_u	*mapchars;
3991 
3992     if (message_filtered(mp->m_keys) && message_filtered(mp->m_str))
3993 	return;
3994 
3995     if (msg_didout || msg_silent != 0)
3996     {
3997 	msg_putchar('\n');
3998 	if (got_int)	    /* 'q' typed at MORE prompt */
3999 	    return;
4000     }
4001 
4002     mapchars = map_mode_to_chars(mp->m_mode);
4003     if (mapchars != NULL)
4004     {
4005 	msg_puts((char *)mapchars);
4006 	len = (int)STRLEN(mapchars);
4007 	vim_free(mapchars);
4008     }
4009 
4010     while (++len <= 3)
4011 	msg_putchar(' ');
4012 
4013     /* Display the LHS.  Get length of what we write. */
4014     len = msg_outtrans_special(mp->m_keys, TRUE);
4015     do
4016     {
4017 	msg_putchar(' ');		/* padd with blanks */
4018 	++len;
4019     } while (len < 12);
4020 
4021     if (mp->m_noremap == REMAP_NONE)
4022 	msg_puts_attr("*", HL_ATTR(HLF_8));
4023     else if (mp->m_noremap == REMAP_SCRIPT)
4024 	msg_puts_attr("&", HL_ATTR(HLF_8));
4025     else
4026 	msg_putchar(' ');
4027 
4028     if (local)
4029 	msg_putchar('@');
4030     else
4031 	msg_putchar(' ');
4032 
4033     /* Use FALSE below if we only want things like <Up> to show up as such on
4034      * the rhs, and not M-x etc, TRUE gets both -- webb */
4035     if (*mp->m_str == NUL)
4036 	msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
4037     else
4038     {
4039 	/* Remove escaping of CSI, because "m_str" is in a format to be used
4040 	 * as typeahead. */
4041 	char_u *s = vim_strsave(mp->m_str);
4042 	if (s != NULL)
4043 	{
4044 	    vim_unescape_csi(s);
4045 	    msg_outtrans_special(s, FALSE);
4046 	    vim_free(s);
4047 	}
4048     }
4049 #ifdef FEAT_EVAL
4050     if (p_verbose > 0)
4051 	last_set_msg(mp->m_script_ctx);
4052 #endif
4053     out_flush();			/* show one line at a time */
4054 }
4055 
4056 #if defined(FEAT_EVAL) || defined(PROTO)
4057 /*
4058  * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
4059  * Recognize termcap codes in "str".
4060  * Also checks mappings local to the current buffer.
4061  */
4062     int
4063 map_to_exists(char_u *str, char_u *modechars, int abbr)
4064 {
4065     int		mode = 0;
4066     char_u	*rhs;
4067     char_u	*buf;
4068     int		retval;
4069 
4070     rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE);
4071 
4072     if (vim_strchr(modechars, 'n') != NULL)
4073 	mode |= NORMAL;
4074     if (vim_strchr(modechars, 'v') != NULL)
4075 	mode |= VISUAL + SELECTMODE;
4076     if (vim_strchr(modechars, 'x') != NULL)
4077 	mode |= VISUAL;
4078     if (vim_strchr(modechars, 's') != NULL)
4079 	mode |= SELECTMODE;
4080     if (vim_strchr(modechars, 'o') != NULL)
4081 	mode |= OP_PENDING;
4082     if (vim_strchr(modechars, 'i') != NULL)
4083 	mode |= INSERT;
4084     if (vim_strchr(modechars, 'l') != NULL)
4085 	mode |= LANGMAP;
4086     if (vim_strchr(modechars, 'c') != NULL)
4087 	mode |= CMDLINE;
4088 
4089     retval = map_to_exists_mode(rhs, mode, abbr);
4090     vim_free(buf);
4091 
4092     return retval;
4093 }
4094 #endif
4095 
4096 /*
4097  * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
4098  * Also checks mappings local to the current buffer.
4099  */
4100     int
4101 map_to_exists_mode(char_u *rhs, int mode, int abbr)
4102 {
4103     mapblock_T	*mp;
4104     int		hash;
4105 # ifdef FEAT_LOCALMAP
4106     int		exp_buffer = FALSE;
4107 
4108     validate_maphash();
4109 
4110     /* Do it twice: once for global maps and once for local maps. */
4111     for (;;)
4112     {
4113 # endif
4114 	for (hash = 0; hash < 256; ++hash)
4115 	{
4116 	    if (abbr)
4117 	    {
4118 		if (hash > 0)		/* there is only one abbr list */
4119 		    break;
4120 #ifdef FEAT_LOCALMAP
4121 		if (exp_buffer)
4122 		    mp = curbuf->b_first_abbr;
4123 		else
4124 #endif
4125 		    mp = first_abbr;
4126 	    }
4127 # ifdef FEAT_LOCALMAP
4128 	    else if (exp_buffer)
4129 		mp = curbuf->b_maphash[hash];
4130 # endif
4131 	    else
4132 		mp = maphash[hash];
4133 	    for (; mp; mp = mp->m_next)
4134 	    {
4135 		if ((mp->m_mode & mode)
4136 			&& strstr((char *)mp->m_str, (char *)rhs) != NULL)
4137 		    return TRUE;
4138 	    }
4139 	}
4140 # ifdef FEAT_LOCALMAP
4141 	if (exp_buffer)
4142 	    break;
4143 	exp_buffer = TRUE;
4144     }
4145 # endif
4146 
4147     return FALSE;
4148 }
4149 
4150 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4151 /*
4152  * Used below when expanding mapping/abbreviation names.
4153  */
4154 static int	expand_mapmodes = 0;
4155 static int	expand_isabbrev = 0;
4156 #ifdef FEAT_LOCALMAP
4157 static int	expand_buffer = FALSE;
4158 #endif
4159 
4160 /*
4161  * Work out what to complete when doing command line completion of mapping
4162  * or abbreviation names.
4163  */
4164     char_u *
4165 set_context_in_map_cmd(
4166     expand_T	*xp,
4167     char_u	*cmd,
4168     char_u	*arg,
4169     int		forceit,	/* TRUE if '!' given */
4170     int		isabbrev,	/* TRUE if abbreviation */
4171     int		isunmap,	/* TRUE if unmap/unabbrev command */
4172     cmdidx_T	cmdidx)
4173 {
4174     if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
4175 	xp->xp_context = EXPAND_NOTHING;
4176     else
4177     {
4178 	if (isunmap)
4179 	    expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
4180 	else
4181 	{
4182 	    expand_mapmodes = INSERT + CMDLINE;
4183 	    if (!isabbrev)
4184 		expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING;
4185 	}
4186 	expand_isabbrev = isabbrev;
4187 	xp->xp_context = EXPAND_MAPPINGS;
4188 #ifdef FEAT_LOCALMAP
4189 	expand_buffer = FALSE;
4190 #endif
4191 	for (;;)
4192 	{
4193 #ifdef FEAT_LOCALMAP
4194 	    if (STRNCMP(arg, "<buffer>", 8) == 0)
4195 	    {
4196 		expand_buffer = TRUE;
4197 		arg = skipwhite(arg + 8);
4198 		continue;
4199 	    }
4200 #endif
4201 	    if (STRNCMP(arg, "<unique>", 8) == 0)
4202 	    {
4203 		arg = skipwhite(arg + 8);
4204 		continue;
4205 	    }
4206 	    if (STRNCMP(arg, "<nowait>", 8) == 0)
4207 	    {
4208 		arg = skipwhite(arg + 8);
4209 		continue;
4210 	    }
4211 	    if (STRNCMP(arg, "<silent>", 8) == 0)
4212 	    {
4213 		arg = skipwhite(arg + 8);
4214 		continue;
4215 	    }
4216 	    if (STRNCMP(arg, "<special>", 9) == 0)
4217 	    {
4218 		arg = skipwhite(arg + 9);
4219 		continue;
4220 	    }
4221 #ifdef FEAT_EVAL
4222 	    if (STRNCMP(arg, "<script>", 8) == 0)
4223 	    {
4224 		arg = skipwhite(arg + 8);
4225 		continue;
4226 	    }
4227 	    if (STRNCMP(arg, "<expr>", 6) == 0)
4228 	    {
4229 		arg = skipwhite(arg + 6);
4230 		continue;
4231 	    }
4232 #endif
4233 	    break;
4234 	}
4235 	xp->xp_pattern = arg;
4236     }
4237 
4238     return NULL;
4239 }
4240 
4241 /*
4242  * Find all mapping/abbreviation names that match regexp 'prog'.
4243  * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
4244  * Return OK if matches found, FAIL otherwise.
4245  */
4246     int
4247 ExpandMappings(
4248     regmatch_T	*regmatch,
4249     int		*num_file,
4250     char_u	***file)
4251 {
4252     mapblock_T	*mp;
4253     int		hash;
4254     int		count;
4255     int		round;
4256     char_u	*p;
4257     int		i;
4258 
4259     validate_maphash();
4260 
4261     *num_file = 0;		    /* return values in case of FAIL */
4262     *file = NULL;
4263 
4264     /*
4265      * round == 1: Count the matches.
4266      * round == 2: Build the array to keep the matches.
4267      */
4268     for (round = 1; round <= 2; ++round)
4269     {
4270 	count = 0;
4271 
4272 	for (i = 0; i < 7; ++i)
4273 	{
4274 	    if (i == 0)
4275 		p = (char_u *)"<silent>";
4276 	    else if (i == 1)
4277 		p = (char_u *)"<unique>";
4278 #ifdef FEAT_EVAL
4279 	    else if (i == 2)
4280 		p = (char_u *)"<script>";
4281 	    else if (i == 3)
4282 		p = (char_u *)"<expr>";
4283 #endif
4284 #ifdef FEAT_LOCALMAP
4285 	    else if (i == 4 && !expand_buffer)
4286 		p = (char_u *)"<buffer>";
4287 #endif
4288 	    else if (i == 5)
4289 		p = (char_u *)"<nowait>";
4290 	    else if (i == 6)
4291 		p = (char_u *)"<special>";
4292 	    else
4293 		continue;
4294 
4295 	    if (vim_regexec(regmatch, p, (colnr_T)0))
4296 	    {
4297 		if (round == 1)
4298 		    ++count;
4299 		else
4300 		    (*file)[count++] = vim_strsave(p);
4301 	    }
4302 	}
4303 
4304 	for (hash = 0; hash < 256; ++hash)
4305 	{
4306 	    if (expand_isabbrev)
4307 	    {
4308 		if (hash > 0)	/* only one abbrev list */
4309 		    break; /* for (hash) */
4310 		mp = first_abbr;
4311 	    }
4312 #ifdef FEAT_LOCALMAP
4313 	    else if (expand_buffer)
4314 		mp = curbuf->b_maphash[hash];
4315 #endif
4316 	    else
4317 		mp = maphash[hash];
4318 	    for (; mp; mp = mp->m_next)
4319 	    {
4320 		if (mp->m_mode & expand_mapmodes)
4321 		{
4322 		    p = translate_mapping(mp->m_keys, TRUE);
4323 		    if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
4324 		    {
4325 			if (round == 1)
4326 			    ++count;
4327 			else
4328 			{
4329 			    (*file)[count++] = p;
4330 			    p = NULL;
4331 			}
4332 		    }
4333 		    vim_free(p);
4334 		}
4335 	    } /* for (mp) */
4336 	} /* for (hash) */
4337 
4338 	if (count == 0)			/* no match found */
4339 	    break; /* for (round) */
4340 
4341 	if (round == 1)
4342 	{
4343 	    *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
4344 	    if (*file == NULL)
4345 		return FAIL;
4346 	}
4347     } /* for (round) */
4348 
4349     if (count > 1)
4350     {
4351 	char_u	**ptr1;
4352 	char_u	**ptr2;
4353 	char_u	**ptr3;
4354 
4355 	/* Sort the matches */
4356 	sort_strings(*file, count);
4357 
4358 	/* Remove multiple entries */
4359 	ptr1 = *file;
4360 	ptr2 = ptr1 + 1;
4361 	ptr3 = ptr1 + count;
4362 
4363 	while (ptr2 < ptr3)
4364 	{
4365 	    if (STRCMP(*ptr1, *ptr2))
4366 		*++ptr1 = *ptr2++;
4367 	    else
4368 	    {
4369 		vim_free(*ptr2++);
4370 		count--;
4371 	    }
4372 	}
4373     }
4374 
4375     *num_file = count;
4376     return (count == 0 ? FAIL : OK);
4377 }
4378 #endif /* FEAT_CMDL_COMPL */
4379 
4380 /*
4381  * Check for an abbreviation.
4382  * Cursor is at ptr[col].
4383  * When inserting, mincol is where insert started.
4384  * For the command line, mincol is what is to be skipped over.
4385  * "c" is the character typed before check_abbr was called.  It may have
4386  * ABBR_OFF added to avoid prepending a CTRL-V to it.
4387  *
4388  * Historic vi practice: The last character of an abbreviation must be an id
4389  * character ([a-zA-Z0-9_]). The characters in front of it must be all id
4390  * characters or all non-id characters. This allows for abbr. "#i" to
4391  * "#include".
4392  *
4393  * Vim addition: Allow for abbreviations that end in a non-keyword character.
4394  * Then there must be white space before the abbr.
4395  *
4396  * return TRUE if there is an abbreviation, FALSE if not
4397  */
4398     int
4399 check_abbr(
4400     int		c,
4401     char_u	*ptr,
4402     int		col,
4403     int		mincol)
4404 {
4405     int		len;
4406     int		scol;		/* starting column of the abbr. */
4407     int		j;
4408     char_u	*s;
4409     char_u	tb[MB_MAXBYTES + 4];
4410     mapblock_T	*mp;
4411 #ifdef FEAT_LOCALMAP
4412     mapblock_T	*mp2;
4413 #endif
4414     int		clen = 0;	/* length in characters */
4415     int		is_id = TRUE;
4416     int		vim_abbr;
4417 
4418     if (typebuf.tb_no_abbr_cnt)	/* abbrev. are not recursive */
4419 	return FALSE;
4420 
4421     /* no remapping implies no abbreviation, except for CTRL-] */
4422     if ((KeyNoremap & (RM_NONE|RM_SCRIPT)) != 0 && c != Ctrl_RSB)
4423 	return FALSE;
4424 
4425     /*
4426      * Check for word before the cursor: If it ends in a keyword char all
4427      * chars before it must be keyword chars or non-keyword chars, but not
4428      * white space. If it ends in a non-keyword char we accept any characters
4429      * before it except white space.
4430      */
4431     if (col == 0)				/* cannot be an abbr. */
4432 	return FALSE;
4433 
4434     if (has_mbyte)
4435     {
4436 	char_u *p;
4437 
4438 	p = mb_prevptr(ptr, ptr + col);
4439 	if (!vim_iswordp(p))
4440 	    vim_abbr = TRUE;			/* Vim added abbr. */
4441 	else
4442 	{
4443 	    vim_abbr = FALSE;			/* vi compatible abbr. */
4444 	    if (p > ptr)
4445 		is_id = vim_iswordp(mb_prevptr(ptr, p));
4446 	}
4447 	clen = 1;
4448 	while (p > ptr + mincol)
4449 	{
4450 	    p = mb_prevptr(ptr, p);
4451 	    if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
4452 	    {
4453 		p += (*mb_ptr2len)(p);
4454 		break;
4455 	    }
4456 	    ++clen;
4457 	}
4458 	scol = (int)(p - ptr);
4459     }
4460     else
4461     {
4462 	if (!vim_iswordc(ptr[col - 1]))
4463 	    vim_abbr = TRUE;			/* Vim added abbr. */
4464 	else
4465 	{
4466 	    vim_abbr = FALSE;			/* vi compatible abbr. */
4467 	    if (col > 1)
4468 		is_id = vim_iswordc(ptr[col - 2]);
4469 	}
4470 	for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1])
4471 		&& (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol)
4472 	    ;
4473     }
4474 
4475     if (scol < mincol)
4476 	scol = mincol;
4477     if (scol < col)		/* there is a word in front of the cursor */
4478     {
4479 	ptr += scol;
4480 	len = col - scol;
4481 #ifdef FEAT_LOCALMAP
4482 	mp = curbuf->b_first_abbr;
4483 	mp2 = first_abbr;
4484 	if (mp == NULL)
4485 	{
4486 	    mp = mp2;
4487 	    mp2 = NULL;
4488 	}
4489 #else
4490 	mp = first_abbr;
4491 #endif
4492 	for ( ; mp;
4493 #ifdef FEAT_LOCALMAP
4494 		mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
4495 #endif
4496 		(mp = mp->m_next))
4497 	{
4498 	    int		qlen = mp->m_keylen;
4499 	    char_u	*q = mp->m_keys;
4500 	    int		match;
4501 
4502 	    if (vim_strbyte(mp->m_keys, K_SPECIAL) != NULL)
4503 	    {
4504 		char_u *qe = vim_strsave(mp->m_keys);
4505 
4506 		/* might have CSI escaped mp->m_keys */
4507 		if (qe != NULL)
4508 		{
4509 		    q = qe;
4510 		    vim_unescape_csi(q);
4511 		    qlen = (int)STRLEN(q);
4512 		}
4513 	    }
4514 
4515 	    /* find entries with right mode and keys */
4516 	    match =    (mp->m_mode & State)
4517 		    && qlen == len
4518 		    && !STRNCMP(q, ptr, (size_t)len);
4519 	    if (q != mp->m_keys)
4520 		vim_free(q);
4521 	    if (match)
4522 		break;
4523 	}
4524 	if (mp != NULL)
4525 	{
4526 	    /*
4527 	     * Found a match:
4528 	     * Insert the rest of the abbreviation in typebuf.tb_buf[].
4529 	     * This goes from end to start.
4530 	     *
4531 	     * Characters 0x000 - 0x100: normal chars, may need CTRL-V,
4532 	     * except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
4533 	     * Characters where IS_SPECIAL() == TRUE: key codes, need
4534 	     * K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
4535 	     *
4536 	     * Character CTRL-] is treated specially - it completes the
4537 	     * abbreviation, but is not inserted into the input stream.
4538 	     */
4539 	    j = 0;
4540 	    if (c != Ctrl_RSB)
4541 	    {
4542 					/* special key code, split up */
4543 		if (IS_SPECIAL(c) || c == K_SPECIAL)
4544 		{
4545 		    tb[j++] = K_SPECIAL;
4546 		    tb[j++] = K_SECOND(c);
4547 		    tb[j++] = K_THIRD(c);
4548 		}
4549 		else
4550 		{
4551 		    if (c < ABBR_OFF && (c < ' ' || c > '~'))
4552 			tb[j++] = Ctrl_V;	/* special char needs CTRL-V */
4553 		    if (has_mbyte)
4554 		    {
4555 			/* if ABBR_OFF has been added, remove it here */
4556 			if (c >= ABBR_OFF)
4557 			    c -= ABBR_OFF;
4558 			j += (*mb_char2bytes)(c, tb + j);
4559 		    }
4560 		    else
4561 			tb[j++] = c;
4562 		}
4563 		tb[j] = NUL;
4564 					/* insert the last typed char */
4565 		(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
4566 	    }
4567 #ifdef FEAT_EVAL
4568 	    if (mp->m_expr)
4569 		s = eval_map_expr(mp->m_str, c);
4570 	    else
4571 #endif
4572 		s = mp->m_str;
4573 	    if (s != NULL)
4574 	    {
4575 					/* insert the to string */
4576 		(void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent);
4577 					/* no abbrev. for these chars */
4578 		typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1;
4579 #ifdef FEAT_EVAL
4580 		if (mp->m_expr)
4581 		    vim_free(s);
4582 #endif
4583 	    }
4584 
4585 	    tb[0] = Ctrl_H;
4586 	    tb[1] = NUL;
4587 	    if (has_mbyte)
4588 		len = clen;	/* Delete characters instead of bytes */
4589 	    while (len-- > 0)		/* delete the from string */
4590 		(void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
4591 	    return TRUE;
4592 	}
4593     }
4594     return FALSE;
4595 }
4596 
4597 #ifdef FEAT_EVAL
4598 /*
4599  * Evaluate the RHS of a mapping or abbreviations and take care of escaping
4600  * special characters.
4601  */
4602     static char_u *
4603 eval_map_expr(
4604     char_u	*str,
4605     int		c)	    /* NUL or typed character for abbreviation */
4606 {
4607     char_u	*res;
4608     char_u	*p;
4609     char_u	*expr;
4610     pos_T	save_cursor;
4611     int		save_msg_col;
4612     int		save_msg_row;
4613 
4614     /* Remove escaping of CSI, because "str" is in a format to be used as
4615      * typeahead. */
4616     expr = vim_strsave(str);
4617     if (expr == NULL)
4618 	return NULL;
4619     vim_unescape_csi(expr);
4620 
4621     /* Forbid changing text or using ":normal" to avoid most of the bad side
4622      * effects.  Also restore the cursor position. */
4623     ++textlock;
4624     ++ex_normal_lock;
4625     set_vim_var_char(c);  /* set v:char to the typed character */
4626     save_cursor = curwin->w_cursor;
4627     save_msg_col = msg_col;
4628     save_msg_row = msg_row;
4629     p = eval_to_string(expr, NULL, FALSE);
4630     --textlock;
4631     --ex_normal_lock;
4632     curwin->w_cursor = save_cursor;
4633     msg_col = save_msg_col;
4634     msg_row = save_msg_row;
4635 
4636     vim_free(expr);
4637 
4638     if (p == NULL)
4639 	return NULL;
4640     /* Escape CSI in the result to be able to use the string as typeahead. */
4641     res = vim_strsave_escape_csi(p);
4642     vim_free(p);
4643 
4644     return res;
4645 }
4646 #endif
4647 
4648 /*
4649  * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
4650  * can be put in the typeahead buffer.
4651  * Returns NULL when out of memory.
4652  */
4653     char_u *
4654 vim_strsave_escape_csi(
4655     char_u *p)
4656 {
4657     char_u	*res;
4658     char_u	*s, *d;
4659 
4660     /* Need a buffer to hold up to three times as much.  Four in case of an
4661      * illegal utf-8 byte:
4662      * 0xc0 -> 0xc3 0x80 -> 0xc3 K_SPECIAL KS_SPECIAL KE_FILLER */
4663     res = alloc((unsigned)(STRLEN(p) * 4) + 1);
4664     if (res != NULL)
4665     {
4666 	d = res;
4667 	for (s = p; *s != NUL; )
4668 	{
4669 	    if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL)
4670 	    {
4671 		/* Copy special key unmodified. */
4672 		*d++ = *s++;
4673 		*d++ = *s++;
4674 		*d++ = *s++;
4675 	    }
4676 	    else
4677 	    {
4678 		/* Add character, possibly multi-byte to destination, escaping
4679 		 * CSI and K_SPECIAL. Be careful, it can be an illegal byte! */
4680 		d = add_char2buf(PTR2CHAR(s), d);
4681 		s += MB_CPTR2LEN(s);
4682 	    }
4683 	}
4684 	*d = NUL;
4685     }
4686     return res;
4687 }
4688 
4689 /*
4690  * Remove escaping from CSI and K_SPECIAL characters.  Reverse of
4691  * vim_strsave_escape_csi().  Works in-place.
4692  */
4693     void
4694 vim_unescape_csi(char_u *p)
4695 {
4696     char_u	*s = p, *d = p;
4697 
4698     while (*s != NUL)
4699     {
4700 	if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER)
4701 	{
4702 	    *d++ = K_SPECIAL;
4703 	    s += 3;
4704 	}
4705 	else if ((s[0] == K_SPECIAL || s[0] == CSI)
4706 				   && s[1] == KS_EXTRA && s[2] == (int)KE_CSI)
4707 	{
4708 	    *d++ = CSI;
4709 	    s += 3;
4710 	}
4711 	else
4712 	    *d++ = *s++;
4713     }
4714     *d = NUL;
4715 }
4716 
4717 /*
4718  * Write map commands for the current mappings to an .exrc file.
4719  * Return FAIL on error, OK otherwise.
4720  */
4721     int
4722 makemap(
4723     FILE	*fd,
4724     buf_T	*buf)	    /* buffer for local mappings or NULL */
4725 {
4726     mapblock_T	*mp;
4727     char_u	c1, c2, c3;
4728     char_u	*p;
4729     char	*cmd;
4730     int		abbr;
4731     int		hash;
4732     int		did_cpo = FALSE;
4733     int		i;
4734 
4735     validate_maphash();
4736 
4737     /*
4738      * Do the loop twice: Once for mappings, once for abbreviations.
4739      * Then loop over all map hash lists.
4740      */
4741     for (abbr = 0; abbr < 2; ++abbr)
4742 	for (hash = 0; hash < 256; ++hash)
4743 	{
4744 	    if (abbr)
4745 	    {
4746 		if (hash > 0)		/* there is only one abbr list */
4747 		    break;
4748 #ifdef FEAT_LOCALMAP
4749 		if (buf != NULL)
4750 		    mp = buf->b_first_abbr;
4751 		else
4752 #endif
4753 		    mp = first_abbr;
4754 	    }
4755 	    else
4756 	    {
4757 #ifdef FEAT_LOCALMAP
4758 		if (buf != NULL)
4759 		    mp = buf->b_maphash[hash];
4760 		else
4761 #endif
4762 		    mp = maphash[hash];
4763 	    }
4764 
4765 	    for ( ; mp; mp = mp->m_next)
4766 	    {
4767 		/* skip script-local mappings */
4768 		if (mp->m_noremap == REMAP_SCRIPT)
4769 		    continue;
4770 
4771 		/* skip mappings that contain a <SNR> (script-local thing),
4772 		 * they probably don't work when loaded again */
4773 		for (p = mp->m_str; *p != NUL; ++p)
4774 		    if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
4775 						       && p[2] == (int)KE_SNR)
4776 			break;
4777 		if (*p != NUL)
4778 		    continue;
4779 
4780 		/* It's possible to create a mapping and then ":unmap" certain
4781 		 * modes.  We recreate this here by mapping the individual
4782 		 * modes, which requires up to three of them. */
4783 		c1 = NUL;
4784 		c2 = NUL;
4785 		c3 = NUL;
4786 		if (abbr)
4787 		    cmd = "abbr";
4788 		else
4789 		    cmd = "map";
4790 		switch (mp->m_mode)
4791 		{
4792 		    case NORMAL + VISUAL + SELECTMODE + OP_PENDING:
4793 			break;
4794 		    case NORMAL:
4795 			c1 = 'n';
4796 			break;
4797 		    case VISUAL:
4798 			c1 = 'x';
4799 			break;
4800 		    case SELECTMODE:
4801 			c1 = 's';
4802 			break;
4803 		    case OP_PENDING:
4804 			c1 = 'o';
4805 			break;
4806 		    case NORMAL + VISUAL:
4807 			c1 = 'n';
4808 			c2 = 'x';
4809 			break;
4810 		    case NORMAL + SELECTMODE:
4811 			c1 = 'n';
4812 			c2 = 's';
4813 			break;
4814 		    case NORMAL + OP_PENDING:
4815 			c1 = 'n';
4816 			c2 = 'o';
4817 			break;
4818 		    case VISUAL + SELECTMODE:
4819 			c1 = 'v';
4820 			break;
4821 		    case VISUAL + OP_PENDING:
4822 			c1 = 'x';
4823 			c2 = 'o';
4824 			break;
4825 		    case SELECTMODE + OP_PENDING:
4826 			c1 = 's';
4827 			c2 = 'o';
4828 			break;
4829 		    case NORMAL + VISUAL + SELECTMODE:
4830 			c1 = 'n';
4831 			c2 = 'v';
4832 			break;
4833 		    case NORMAL + VISUAL + OP_PENDING:
4834 			c1 = 'n';
4835 			c2 = 'x';
4836 			c3 = 'o';
4837 			break;
4838 		    case NORMAL + SELECTMODE + OP_PENDING:
4839 			c1 = 'n';
4840 			c2 = 's';
4841 			c3 = 'o';
4842 			break;
4843 		    case VISUAL + SELECTMODE + OP_PENDING:
4844 			c1 = 'v';
4845 			c2 = 'o';
4846 			break;
4847 		    case CMDLINE + INSERT:
4848 			if (!abbr)
4849 			    cmd = "map!";
4850 			break;
4851 		    case CMDLINE:
4852 			c1 = 'c';
4853 			break;
4854 		    case INSERT:
4855 			c1 = 'i';
4856 			break;
4857 		    case LANGMAP:
4858 			c1 = 'l';
4859 			break;
4860 		    case TERMINAL:
4861 			c1 = 't';
4862 			break;
4863 		    default:
4864 			iemsg(_("E228: makemap: Illegal mode"));
4865 			return FAIL;
4866 		}
4867 		do	/* do this twice if c2 is set, 3 times with c3 */
4868 		{
4869 		    /* When outputting <> form, need to make sure that 'cpo'
4870 		     * is set to the Vim default. */
4871 		    if (!did_cpo)
4872 		    {
4873 			if (*mp->m_str == NUL)		/* will use <Nop> */
4874 			    did_cpo = TRUE;
4875 			else
4876 			    for (i = 0; i < 2; ++i)
4877 				for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
4878 				    if (*p == K_SPECIAL || *p == NL)
4879 					did_cpo = TRUE;
4880 			if (did_cpo)
4881 			{
4882 			    if (fprintf(fd, "let s:cpo_save=&cpo") < 0
4883 				    || put_eol(fd) < 0
4884 				    || fprintf(fd, "set cpo&vim") < 0
4885 				    || put_eol(fd) < 0)
4886 				return FAIL;
4887 			}
4888 		    }
4889 		    if (c1 && putc(c1, fd) < 0)
4890 			return FAIL;
4891 		    if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
4892 			return FAIL;
4893 		    if (fputs(cmd, fd) < 0)
4894 			return FAIL;
4895 		    if (buf != NULL && fputs(" <buffer>", fd) < 0)
4896 			return FAIL;
4897 		    if (mp->m_nowait && fputs(" <nowait>", fd) < 0)
4898 			return FAIL;
4899 		    if (mp->m_silent && fputs(" <silent>", fd) < 0)
4900 			return FAIL;
4901 #ifdef FEAT_EVAL
4902 		    if (mp->m_noremap == REMAP_SCRIPT
4903 						 && fputs("<script>", fd) < 0)
4904 			return FAIL;
4905 		    if (mp->m_expr && fputs(" <expr>", fd) < 0)
4906 			return FAIL;
4907 #endif
4908 
4909 		    if (       putc(' ', fd) < 0
4910 			    || put_escstr(fd, mp->m_keys, 0) == FAIL
4911 			    || putc(' ', fd) < 0
4912 			    || put_escstr(fd, mp->m_str, 1) == FAIL
4913 			    || put_eol(fd) < 0)
4914 			return FAIL;
4915 		    c1 = c2;
4916 		    c2 = c3;
4917 		    c3 = NUL;
4918 		} while (c1 != NUL);
4919 	    }
4920 	}
4921 
4922     if (did_cpo)
4923 	if (fprintf(fd, "let &cpo=s:cpo_save") < 0
4924 		|| put_eol(fd) < 0
4925 		|| fprintf(fd, "unlet s:cpo_save") < 0
4926 		|| put_eol(fd) < 0)
4927 	    return FAIL;
4928     return OK;
4929 }
4930 
4931 /*
4932  * write escape string to file
4933  * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
4934  *
4935  * return FAIL for failure, OK otherwise
4936  */
4937     int
4938 put_escstr(FILE *fd, char_u *strstart, int what)
4939 {
4940     char_u	*str = strstart;
4941     int		c;
4942     int		modifiers;
4943 
4944     /* :map xx <Nop> */
4945     if (*str == NUL && what == 1)
4946     {
4947 	if (fprintf(fd, "<Nop>") < 0)
4948 	    return FAIL;
4949 	return OK;
4950     }
4951 
4952     for ( ; *str != NUL; ++str)
4953     {
4954 	char_u	*p;
4955 
4956 	/* Check for a multi-byte character, which may contain escaped
4957 	 * K_SPECIAL and CSI bytes */
4958 	p = mb_unescape(&str);
4959 	if (p != NULL)
4960 	{
4961 	    while (*p != NUL)
4962 		if (fputc(*p++, fd) < 0)
4963 		    return FAIL;
4964 	    --str;
4965 	    continue;
4966 	}
4967 
4968 	c = *str;
4969 	/*
4970 	 * Special key codes have to be translated to be able to make sense
4971 	 * when they are read back.
4972 	 */
4973 	if (c == K_SPECIAL && what != 2)
4974 	{
4975 	    modifiers = 0x0;
4976 	    if (str[1] == KS_MODIFIER)
4977 	    {
4978 		modifiers = str[2];
4979 		str += 3;
4980 		c = *str;
4981 	    }
4982 	    if (c == K_SPECIAL)
4983 	    {
4984 		c = TO_SPECIAL(str[1], str[2]);
4985 		str += 2;
4986 	    }
4987 	    if (IS_SPECIAL(c) || modifiers)	/* special key */
4988 	    {
4989 		if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0)
4990 		    return FAIL;
4991 		continue;
4992 	    }
4993 	}
4994 
4995 	/*
4996 	 * A '\n' in a map command should be written as <NL>.
4997 	 * A '\n' in a set command should be written as \^V^J.
4998 	 */
4999 	if (c == NL)
5000 	{
5001 	    if (what == 2)
5002 	    {
5003 		if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
5004 		    return FAIL;
5005 	    }
5006 	    else
5007 	    {
5008 		if (fprintf(fd, "<NL>") < 0)
5009 		    return FAIL;
5010 	    }
5011 	    continue;
5012 	}
5013 
5014 	/*
5015 	 * Some characters have to be escaped with CTRL-V to
5016 	 * prevent them from misinterpreted in DoOneCmd().
5017 	 * A space, Tab and '"' has to be escaped with a backslash to
5018 	 * prevent it to be misinterpreted in do_set().
5019 	 * A space has to be escaped with a CTRL-V when it's at the start of a
5020 	 * ":map" rhs.
5021 	 * A '<' has to be escaped with a CTRL-V to prevent it being
5022 	 * interpreted as the start of a special key name.
5023 	 * A space in the lhs of a :map needs a CTRL-V.
5024 	 */
5025 	if (what == 2 && (VIM_ISWHITE(c) || c == '"' || c == '\\'))
5026 	{
5027 	    if (putc('\\', fd) < 0)
5028 		return FAIL;
5029 	}
5030 	else if (c < ' ' || c > '~' || c == '|'
5031 		|| (what == 0 && c == ' ')
5032 		|| (what == 1 && str == strstart && c == ' ')
5033 		|| (what != 2 && c == '<'))
5034 	{
5035 	    if (putc(Ctrl_V, fd) < 0)
5036 		return FAIL;
5037 	}
5038 	if (putc(c, fd) < 0)
5039 	    return FAIL;
5040     }
5041     return OK;
5042 }
5043 
5044 /*
5045  * Check all mappings for the presence of special key codes.
5046  * Used after ":set term=xxx".
5047  */
5048     void
5049 check_map_keycodes(void)
5050 {
5051     mapblock_T	*mp;
5052     char_u	*p;
5053     int		i;
5054     char_u	buf[3];
5055     char_u	*save_name;
5056     int		abbr;
5057     int		hash;
5058 #ifdef FEAT_LOCALMAP
5059     buf_T	*bp;
5060 #endif
5061 
5062     validate_maphash();
5063     save_name = sourcing_name;
5064     sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */
5065 
5066 #ifdef FEAT_LOCALMAP
5067     /* This this once for each buffer, and then once for global
5068      * mappings/abbreviations with bp == NULL */
5069     for (bp = firstbuf; ; bp = bp->b_next)
5070     {
5071 #endif
5072 	/*
5073 	 * Do the loop twice: Once for mappings, once for abbreviations.
5074 	 * Then loop over all map hash lists.
5075 	 */
5076 	for (abbr = 0; abbr <= 1; ++abbr)
5077 	    for (hash = 0; hash < 256; ++hash)
5078 	    {
5079 		if (abbr)
5080 		{
5081 		    if (hash)	    /* there is only one abbr list */
5082 			break;
5083 #ifdef FEAT_LOCALMAP
5084 		    if (bp != NULL)
5085 			mp = bp->b_first_abbr;
5086 		    else
5087 #endif
5088 			mp = first_abbr;
5089 		}
5090 		else
5091 		{
5092 #ifdef FEAT_LOCALMAP
5093 		    if (bp != NULL)
5094 			mp = bp->b_maphash[hash];
5095 		    else
5096 #endif
5097 			mp = maphash[hash];
5098 		}
5099 		for ( ; mp != NULL; mp = mp->m_next)
5100 		{
5101 		    for (i = 0; i <= 1; ++i)	/* do this twice */
5102 		    {
5103 			if (i == 0)
5104 			    p = mp->m_keys;	/* once for the "from" part */
5105 			else
5106 			    p = mp->m_str;	/* and once for the "to" part */
5107 			while (*p)
5108 			{
5109 			    if (*p == K_SPECIAL)
5110 			    {
5111 				++p;
5112 				if (*p < 128)   /* for "normal" tcap entries */
5113 				{
5114 				    buf[0] = p[0];
5115 				    buf[1] = p[1];
5116 				    buf[2] = NUL;
5117 				    (void)add_termcap_entry(buf, FALSE);
5118 				}
5119 				++p;
5120 			    }
5121 			    ++p;
5122 			}
5123 		    }
5124 		}
5125 	    }
5126 #ifdef FEAT_LOCALMAP
5127 	if (bp == NULL)
5128 	    break;
5129     }
5130 #endif
5131     sourcing_name = save_name;
5132 }
5133 
5134 #if defined(FEAT_EVAL) || defined(PROTO)
5135 /*
5136  * Check the string "keys" against the lhs of all mappings.
5137  * Return pointer to rhs of mapping (mapblock->m_str).
5138  * NULL when no mapping found.
5139  */
5140     char_u *
5141 check_map(
5142     char_u	*keys,
5143     int		mode,
5144     int		exact,		/* require exact match */
5145     int		ign_mod,	/* ignore preceding modifier */
5146     int		abbr,		/* do abbreviations */
5147     mapblock_T	**mp_ptr,	/* return: pointer to mapblock or NULL */
5148     int		*local_ptr)	/* return: buffer-local mapping or NULL */
5149 {
5150     int		hash;
5151     int		len, minlen;
5152     mapblock_T	*mp;
5153     char_u	*s;
5154 #ifdef FEAT_LOCALMAP
5155     int		local;
5156 #endif
5157 
5158     validate_maphash();
5159 
5160     len = (int)STRLEN(keys);
5161 #ifdef FEAT_LOCALMAP
5162     for (local = 1; local >= 0; --local)
5163 #endif
5164 	/* loop over all hash lists */
5165 	for (hash = 0; hash < 256; ++hash)
5166 	{
5167 	    if (abbr)
5168 	    {
5169 		if (hash > 0)		/* there is only one list. */
5170 		    break;
5171 #ifdef FEAT_LOCALMAP
5172 		if (local)
5173 		    mp = curbuf->b_first_abbr;
5174 		else
5175 #endif
5176 		    mp = first_abbr;
5177 	    }
5178 #ifdef FEAT_LOCALMAP
5179 	    else if (local)
5180 		mp = curbuf->b_maphash[hash];
5181 #endif
5182 	    else
5183 		mp = maphash[hash];
5184 	    for ( ; mp != NULL; mp = mp->m_next)
5185 	    {
5186 		/* skip entries with wrong mode, wrong length and not matching
5187 		 * ones */
5188 		if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len))
5189 		{
5190 		    if (len > mp->m_keylen)
5191 			minlen = mp->m_keylen;
5192 		    else
5193 			minlen = len;
5194 		    s = mp->m_keys;
5195 		    if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER
5196 							       && s[2] != NUL)
5197 		    {
5198 			s += 3;
5199 			if (len > mp->m_keylen - 3)
5200 			    minlen = mp->m_keylen - 3;
5201 		    }
5202 		    if (STRNCMP(s, keys, minlen) == 0)
5203 		    {
5204 			if (mp_ptr != NULL)
5205 			    *mp_ptr = mp;
5206 			if (local_ptr != NULL)
5207 #ifdef FEAT_LOCALMAP
5208 			    *local_ptr = local;
5209 #else
5210 			    *local_ptr = 0;
5211 #endif
5212 			return mp->m_str;
5213 		    }
5214 		}
5215 	    }
5216 	}
5217 
5218     return NULL;
5219 }
5220 #endif
5221 
5222 #if defined(MSWIN) || defined(MACOS_X)
5223 
5224 #define VIS_SEL	(VISUAL+SELECTMODE)	/* abbreviation */
5225 
5226 /*
5227  * Default mappings for some often used keys.
5228  */
5229 static struct initmap
5230 {
5231     char_u	*arg;
5232     int		mode;
5233 } initmappings[] =
5234 {
5235 #if defined(MSWIN)
5236 	/* Use the Windows (CUA) keybindings. */
5237 # ifdef FEAT_GUI
5238 	/* paste, copy and cut */
5239 	{(char_u *)"<S-Insert> \"*P", NORMAL},
5240 	{(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL},
5241 	{(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
5242 	{(char_u *)"<C-Insert> \"*y", VIS_SEL},
5243 	{(char_u *)"<S-Del> \"*d", VIS_SEL},
5244 	{(char_u *)"<C-Del> \"*d", VIS_SEL},
5245 	{(char_u *)"<C-X> \"*d", VIS_SEL},
5246 	/* Missing: CTRL-C (cancel) and CTRL-V (block selection) */
5247 # else
5248 	{(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL},
5249 	{(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
5250 	{(char_u *)"\316u <C-End>", NORMAL+VIS_SEL},
5251 	{(char_u *)"\316u <C-End>", INSERT+CMDLINE},
5252 
5253 	/* paste, copy and cut */
5254 #  ifdef FEAT_CLIPBOARD
5255 	{(char_u *)"\316\324 \"*P", NORMAL},	    /* SHIFT-Insert is "*P */
5256 	{(char_u *)"\316\324 \"-d\"*P", VIS_SEL},   /* SHIFT-Insert is "-d"*P */
5257 	{(char_u *)"\316\324 \022\017*", INSERT},  /* SHIFT-Insert is ^R^O* */
5258 	{(char_u *)"\316\325 \"*y", VIS_SEL},	    /* CTRL-Insert is "*y */
5259 	{(char_u *)"\316\327 \"*d", VIS_SEL},	    /* SHIFT-Del is "*d */
5260 	{(char_u *)"\316\330 \"*d", VIS_SEL},	    /* CTRL-Del is "*d */
5261 	{(char_u *)"\030 \"-d", VIS_SEL},	    /* CTRL-X is "-d */
5262 #  else
5263 	{(char_u *)"\316\324 P", NORMAL},	    /* SHIFT-Insert is P */
5264 	{(char_u *)"\316\324 \"-dP", VIS_SEL},	    /* SHIFT-Insert is "-dP */
5265 	{(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */
5266 	{(char_u *)"\316\325 y", VIS_SEL},	    /* CTRL-Insert is y */
5267 	{(char_u *)"\316\327 d", VIS_SEL},	    /* SHIFT-Del is d */
5268 	{(char_u *)"\316\330 d", VIS_SEL},	    /* CTRL-Del is d */
5269 #  endif
5270 # endif
5271 #endif
5272 
5273 #if defined(MACOS_X)
5274 	/* Use the Standard MacOS binding. */
5275 	/* paste, copy and cut */
5276 	{(char_u *)"<D-v> \"*P", NORMAL},
5277 	{(char_u *)"<D-v> \"-d\"*P", VIS_SEL},
5278 	{(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
5279 	{(char_u *)"<D-c> \"*y", VIS_SEL},
5280 	{(char_u *)"<D-x> \"*d", VIS_SEL},
5281 	{(char_u *)"<Backspace> \"-d", VIS_SEL},
5282 #endif
5283 };
5284 
5285 # undef VIS_SEL
5286 #endif
5287 
5288 /*
5289  * Set up default mappings.
5290  */
5291     void
5292 init_mappings(void)
5293 {
5294 #if defined(MSWIN) || defined(MACOS_X)
5295     int		i;
5296 
5297     for (i = 0; i < (int)(sizeof(initmappings) / sizeof(struct initmap)); ++i)
5298 	add_map(initmappings[i].arg, initmappings[i].mode);
5299 #endif
5300 }
5301 
5302 #if defined(MSWIN) || defined(FEAT_CMDWIN) || defined(MACOS_X) \
5303 							     || defined(PROTO)
5304 /*
5305  * Add a mapping "map" for mode "mode".
5306  * Need to put string in allocated memory, because do_map() will modify it.
5307  */
5308     void
5309 add_map(char_u *map, int mode)
5310 {
5311     char_u	*s;
5312     char_u	*cpo_save = p_cpo;
5313 
5314     p_cpo = (char_u *)"";	/* Allow <> notation */
5315     s = vim_strsave(map);
5316     if (s != NULL)
5317     {
5318 	(void)do_map(0, s, mode, FALSE);
5319 	vim_free(s);
5320     }
5321     p_cpo = cpo_save;
5322 }
5323 #endif
5324