xref: /vim-8.2.3635/src/getchar.c (revision 4c295027)
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 static int	KeyNoremap = 0;	    // remapping flags
56 
57 /*
58  * Variables used by vgetorpeek() and flush_buffers().
59  *
60  * typebuf.tb_buf[] contains all characters that are not consumed yet.
61  * typebuf.tb_buf[typebuf.tb_off] is the first valid character.
62  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
63  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
64  * The head of the buffer may contain the result of mappings, abbreviations
65  * and @a commands.  The length of this part is typebuf.tb_maplen.
66  * typebuf.tb_silent is the part where <silent> applies.
67  * After the head are characters that come from the terminal.
68  * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
69  * should not be considered for abbreviations.
70  * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
71  * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
72  * contains RM_NONE for the characters that are not to be remapped.
73  * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
74  * (typebuf has been put in globals.h, because check_termcode() needs it).
75  */
76 #define RM_YES		0	// tb_noremap: remap
77 #define RM_NONE		1	// tb_noremap: don't remap
78 #define RM_SCRIPT	2	// tb_noremap: remap local script mappings
79 #define RM_ABBR		4	// tb_noremap: don't remap, do abbrev.
80 
81 // typebuf.tb_buf has three parts: room in front (for result of mappings), the
82 // middle for typeahead and room for new characters (which needs to be 3 *
83 // MAXMAPLEN) for the Amiga).
84 #define TYPELEN_INIT	(5 * (MAXMAPLEN + 3))
85 static char_u	typebuf_init[TYPELEN_INIT];	// initial typebuf.tb_buf
86 static char_u	noremapbuf_init[TYPELEN_INIT];	// initial typebuf.tb_noremap
87 
88 static int	last_recorded_len = 0;	// number of last recorded chars
89 
90 static int	read_readbuf(buffheader_T *buf, int advance);
91 static void	init_typebuf(void);
92 static void	may_sync_undo(void);
93 static void	free_typebuf(void);
94 static void	closescript(void);
95 static void	updatescript(int c);
96 static int	vgetorpeek(int);
97 static int	inchar(char_u *buf, int maxlen, long wait_time);
98 
99 /*
100  * Free and clear a buffer.
101  */
102     static void
103 free_buff(buffheader_T *buf)
104 {
105     buffblock_T	*p, *np;
106 
107     for (p = buf->bh_first.b_next; p != NULL; p = np)
108     {
109 	np = p->b_next;
110 	vim_free(p);
111     }
112     buf->bh_first.b_next = NULL;
113 }
114 
115 /*
116  * Return the contents of a buffer as a single string.
117  * K_SPECIAL and CSI in the returned string are escaped.
118  */
119     static char_u *
120 get_buffcont(
121     buffheader_T	*buffer,
122     int			dozero)	    // count == zero is not an error
123 {
124     long_u	    count = 0;
125     char_u	    *p = NULL;
126     char_u	    *p2;
127     char_u	    *str;
128     buffblock_T *bp;
129 
130     // compute the total length of the string
131     for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
132 	count += (long_u)STRLEN(bp->b_str);
133 
134     if ((count || dozero) && (p = alloc(count + 1)) != NULL)
135     {
136 	p2 = p;
137 	for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
138 	    for (str = bp->b_str; *str; )
139 		*p2++ = *str++;
140 	*p2 = NUL;
141     }
142     return (p);
143 }
144 
145 /*
146  * Return the contents of the record buffer as a single string
147  * and clear the record buffer.
148  * K_SPECIAL and CSI in the returned string are escaped.
149  */
150     char_u *
151 get_recorded(void)
152 {
153     char_u	*p;
154     size_t	len;
155 
156     p = get_buffcont(&recordbuff, TRUE);
157     free_buff(&recordbuff);
158 
159     /*
160      * Remove the characters that were added the last time, these must be the
161      * (possibly mapped) characters that stopped the recording.
162      */
163     len = STRLEN(p);
164     if ((int)len >= last_recorded_len)
165     {
166 	len -= last_recorded_len;
167 	p[len] = NUL;
168     }
169 
170     /*
171      * When stopping recording from Insert mode with CTRL-O q, also remove the
172      * CTRL-O.
173      */
174     if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
175 	p[len - 1] = NUL;
176 
177     return (p);
178 }
179 
180 /*
181  * Return the contents of the redo buffer as a single string.
182  * K_SPECIAL and CSI in the returned string are escaped.
183  */
184     char_u *
185 get_inserted(void)
186 {
187     return get_buffcont(&redobuff, FALSE);
188 }
189 
190 /*
191  * Add string "s" after the current block of buffer "buf".
192  * K_SPECIAL and CSI should have been escaped already.
193  */
194     static void
195 add_buff(
196     buffheader_T	*buf,
197     char_u		*s,
198     long		slen)	// length of "s" or -1
199 {
200     buffblock_T *p;
201     long_u	    len;
202 
203     if (slen < 0)
204 	slen = (long)STRLEN(s);
205     if (slen == 0)				// don't add empty strings
206 	return;
207 
208     if (buf->bh_first.b_next == NULL)	// first add to list
209     {
210 	buf->bh_space = 0;
211 	buf->bh_curr = &(buf->bh_first);
212     }
213     else if (buf->bh_curr == NULL)	// buffer has already been read
214     {
215 	iemsg(_("E222: Add to read buffer"));
216 	return;
217     }
218     else if (buf->bh_index != 0)
219 	mch_memmove(buf->bh_first.b_next->b_str,
220 		    buf->bh_first.b_next->b_str + buf->bh_index,
221 		    STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1);
222     buf->bh_index = 0;
223 
224     if (buf->bh_space >= (int)slen)
225     {
226 	len = (long_u)STRLEN(buf->bh_curr->b_str);
227 	vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen);
228 	buf->bh_space -= slen;
229     }
230     else
231     {
232 	if (slen < MINIMAL_SIZE)
233 	    len = MINIMAL_SIZE;
234 	else
235 	    len = slen;
236 	p = alloc(offsetof(buffblock_T, b_str) + len + 1);
237 	if (p == NULL)
238 	    return; // no space, just forget it
239 	buf->bh_space = (int)(len - slen);
240 	vim_strncpy(p->b_str, s, (size_t)slen);
241 
242 	p->b_next = buf->bh_curr->b_next;
243 	buf->bh_curr->b_next = p;
244 	buf->bh_curr = p;
245     }
246     return;
247 }
248 
249 /*
250  * Add number "n" to buffer "buf".
251  */
252     static void
253 add_num_buff(buffheader_T *buf, long n)
254 {
255     char_u	number[32];
256 
257     sprintf((char *)number, "%ld", n);
258     add_buff(buf, number, -1L);
259 }
260 
261 /*
262  * Add character 'c' to buffer "buf".
263  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
264  */
265     static void
266 add_char_buff(buffheader_T *buf, int c)
267 {
268     char_u	bytes[MB_MAXBYTES + 1];
269     int		len;
270     int		i;
271     char_u	temp[4];
272 
273     if (IS_SPECIAL(c))
274 	len = 1;
275     else
276 	len = (*mb_char2bytes)(c, bytes);
277     for (i = 0; i < len; ++i)
278     {
279 	if (!IS_SPECIAL(c))
280 	    c = bytes[i];
281 
282 	if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
283 	{
284 	    // translate special key code into three byte sequence
285 	    temp[0] = K_SPECIAL;
286 	    temp[1] = K_SECOND(c);
287 	    temp[2] = K_THIRD(c);
288 	    temp[3] = NUL;
289 	}
290 #ifdef FEAT_GUI
291 	else if (c == CSI)
292 	{
293 	    // Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence
294 	    temp[0] = CSI;
295 	    temp[1] = KS_EXTRA;
296 	    temp[2] = (int)KE_CSI;
297 	    temp[3] = NUL;
298 	}
299 #endif
300 	else
301 	{
302 	    temp[0] = c;
303 	    temp[1] = NUL;
304 	}
305 	add_buff(buf, temp, -1L);
306     }
307 }
308 
309 // First read ahead buffer. Used for translated commands.
310 static buffheader_T readbuf1 = {{NULL, {NUL}}, NULL, 0, 0};
311 
312 // Second read ahead buffer. Used for redo.
313 static buffheader_T readbuf2 = {{NULL, {NUL}}, NULL, 0, 0};
314 
315 /*
316  * Get one byte from the read buffers.  Use readbuf1 one first, use readbuf2
317  * if that one is empty.
318  * If advance == TRUE go to the next char.
319  * No translation is done K_SPECIAL and CSI are escaped.
320  */
321     static int
322 read_readbuffers(int advance)
323 {
324     int c;
325 
326     c = read_readbuf(&readbuf1, advance);
327     if (c == NUL)
328 	c = read_readbuf(&readbuf2, advance);
329     return c;
330 }
331 
332     static int
333 read_readbuf(buffheader_T *buf, int advance)
334 {
335     char_u	c;
336     buffblock_T	*curr;
337 
338     if (buf->bh_first.b_next == NULL)  // buffer is empty
339 	return NUL;
340 
341     curr = buf->bh_first.b_next;
342     c = curr->b_str[buf->bh_index];
343 
344     if (advance)
345     {
346 	if (curr->b_str[++buf->bh_index] == NUL)
347 	{
348 	    buf->bh_first.b_next = curr->b_next;
349 	    vim_free(curr);
350 	    buf->bh_index = 0;
351 	}
352     }
353     return c;
354 }
355 
356 /*
357  * Prepare the read buffers for reading (if they contain something).
358  */
359     static void
360 start_stuff(void)
361 {
362     if (readbuf1.bh_first.b_next != NULL)
363     {
364 	readbuf1.bh_curr = &(readbuf1.bh_first);
365 	readbuf1.bh_space = 0;
366     }
367     if (readbuf2.bh_first.b_next != NULL)
368     {
369 	readbuf2.bh_curr = &(readbuf2.bh_first);
370 	readbuf2.bh_space = 0;
371     }
372 }
373 
374 /*
375  * Return TRUE if the stuff buffer is empty.
376  */
377     int
378 stuff_empty(void)
379 {
380     return (readbuf1.bh_first.b_next == NULL
381 	 && readbuf2.bh_first.b_next == NULL);
382 }
383 
384 #if defined(FEAT_EVAL) || defined(PROTO)
385 /*
386  * Return TRUE if readbuf1 is empty.  There may still be redo characters in
387  * redbuf2.
388  */
389     int
390 readbuf1_empty(void)
391 {
392     return (readbuf1.bh_first.b_next == NULL);
393 }
394 #endif
395 
396 /*
397  * Set a typeahead character that won't be flushed.
398  */
399     void
400 typeahead_noflush(int c)
401 {
402     typeahead_char = c;
403 }
404 
405 /*
406  * Remove the contents of the stuff buffer and the mapped characters in the
407  * typeahead buffer (used in case of an error).  If "flush_typeahead" is true,
408  * flush all typeahead characters (used when interrupted by a CTRL-C).
409  */
410     void
411 flush_buffers(flush_buffers_T flush_typeahead)
412 {
413     init_typebuf();
414 
415     start_stuff();
416     while (read_readbuffers(TRUE) != NUL)
417 	;
418 
419     if (flush_typeahead == FLUSH_MINIMAL)
420     {
421 	// remove mapped characters at the start only
422 	typebuf.tb_off += typebuf.tb_maplen;
423 	typebuf.tb_len -= typebuf.tb_maplen;
424 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
425 	if (typebuf.tb_len == 0)
426 	    typebuf_was_filled = FALSE;
427 #endif
428     }
429     else
430     {
431 	// remove typeahead
432 	if (flush_typeahead == FLUSH_INPUT)
433 	    // We have to get all characters, because we may delete the first
434 	    // part of an escape sequence.  In an xterm we get one char at a
435 	    // time and we have to get them all.
436 	    while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L) != 0)
437 		;
438 	typebuf.tb_off = MAXMAPLEN;
439 	typebuf.tb_len = 0;
440 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
441 	// Reset the flag that text received from a client or from feedkeys()
442 	// was inserted in the typeahead buffer.
443 	typebuf_was_filled = FALSE;
444 #endif
445     }
446     typebuf.tb_maplen = 0;
447     typebuf.tb_silent = 0;
448     cmd_silent = FALSE;
449     typebuf.tb_no_abbr_cnt = 0;
450     if (++typebuf.tb_change_cnt == 0)
451 	typebuf.tb_change_cnt = 1;
452 }
453 
454 /*
455  * The previous contents of the redo buffer is kept in old_redobuffer.
456  * This is used for the CTRL-O <.> command in insert mode.
457  */
458     void
459 ResetRedobuff(void)
460 {
461     if (!block_redo)
462     {
463 	free_buff(&old_redobuff);
464 	old_redobuff = redobuff;
465 	redobuff.bh_first.b_next = NULL;
466     }
467 }
468 
469 /*
470  * Discard the contents of the redo buffer and restore the previous redo
471  * buffer.
472  */
473     void
474 CancelRedo(void)
475 {
476     if (!block_redo)
477     {
478 	free_buff(&redobuff);
479 	redobuff = old_redobuff;
480 	old_redobuff.bh_first.b_next = NULL;
481 	start_stuff();
482 	while (read_readbuffers(TRUE) != NUL)
483 	    ;
484     }
485 }
486 
487 /*
488  * Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
489  * Used before executing autocommands and user functions.
490  */
491     void
492 saveRedobuff(save_redo_T *save_redo)
493 {
494     char_u	*s;
495 
496     save_redo->sr_redobuff = redobuff;
497     redobuff.bh_first.b_next = NULL;
498     save_redo->sr_old_redobuff = old_redobuff;
499     old_redobuff.bh_first.b_next = NULL;
500 
501     // Make a copy, so that ":normal ." in a function works.
502     s = get_buffcont(&save_redo->sr_redobuff, FALSE);
503     if (s != NULL)
504     {
505 	add_buff(&redobuff, s, -1L);
506 	vim_free(s);
507     }
508 }
509 
510 /*
511  * Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
512  * Used after executing autocommands and user functions.
513  */
514     void
515 restoreRedobuff(save_redo_T *save_redo)
516 {
517     free_buff(&redobuff);
518     redobuff = save_redo->sr_redobuff;
519     free_buff(&old_redobuff);
520     old_redobuff = save_redo->sr_old_redobuff;
521 }
522 
523 /*
524  * Append "s" to the redo buffer.
525  * K_SPECIAL and CSI should already have been escaped.
526  */
527     void
528 AppendToRedobuff(char_u *s)
529 {
530     if (!block_redo)
531 	add_buff(&redobuff, s, -1L);
532 }
533 
534 /*
535  * Append to Redo buffer literally, escaping special characters with CTRL-V.
536  * K_SPECIAL and CSI are escaped as well.
537  */
538     void
539 AppendToRedobuffLit(
540     char_u	*str,
541     int		len)	    // length of "str" or -1 for up to the NUL
542 {
543     char_u	*s = str;
544     int		c;
545     char_u	*start;
546 
547     if (block_redo)
548 	return;
549 
550     while (len < 0 ? *s != NUL : s - str < len)
551     {
552 	// Put a string of normal characters in the redo buffer (that's
553 	// faster).
554 	start = s;
555 	while (*s >= ' '
556 #ifndef EBCDIC
557 		&& *s < DEL	// EBCDIC: all chars above space are normal
558 #endif
559 		&& (len < 0 || s - str < len))
560 	    ++s;
561 
562 	// Don't put '0' or '^' as last character, just in case a CTRL-D is
563 	// typed next.
564 	if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
565 	    --s;
566 	if (s > start)
567 	    add_buff(&redobuff, start, (long)(s - start));
568 
569 	if (*s == NUL || (len >= 0 && s - str >= len))
570 	    break;
571 
572 	// Handle a special or multibyte character.
573 	if (has_mbyte)
574 	    // Handle composing chars separately.
575 	    c = mb_cptr2char_adv(&s);
576 	else
577 	    c = *s++;
578 	if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
579 	    add_char_buff(&redobuff, Ctrl_V);
580 
581 	// CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0)
582 	if (*s == NUL && c == '0')
583 #ifdef EBCDIC
584 	    add_buff(&redobuff, (char_u *)"xf0", 3L);
585 #else
586 	    add_buff(&redobuff, (char_u *)"048", 3L);
587 #endif
588 	else
589 	    add_char_buff(&redobuff, c);
590     }
591 }
592 
593 /*
594  * Append a character to the redo buffer.
595  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
596  */
597     void
598 AppendCharToRedobuff(int c)
599 {
600     if (!block_redo)
601 	add_char_buff(&redobuff, c);
602 }
603 
604 /*
605  * Append a number to the redo buffer.
606  */
607     void
608 AppendNumberToRedobuff(long n)
609 {
610     if (!block_redo)
611 	add_num_buff(&redobuff, n);
612 }
613 
614 /*
615  * Append string "s" to the stuff buffer.
616  * CSI and K_SPECIAL must already have been escaped.
617  */
618     void
619 stuffReadbuff(char_u *s)
620 {
621     add_buff(&readbuf1, s, -1L);
622 }
623 
624 /*
625  * Append string "s" to the redo stuff buffer.
626  * CSI and K_SPECIAL must already have been escaped.
627  */
628     void
629 stuffRedoReadbuff(char_u *s)
630 {
631     add_buff(&readbuf2, s, -1L);
632 }
633 
634     void
635 stuffReadbuffLen(char_u *s, long len)
636 {
637     add_buff(&readbuf1, s, len);
638 }
639 
640 #if defined(FEAT_EVAL) || defined(PROTO)
641 /*
642  * Stuff "s" into the stuff buffer, leaving special key codes unmodified and
643  * escaping other K_SPECIAL and CSI bytes.
644  * Change CR, LF and ESC into a space.
645  */
646     void
647 stuffReadbuffSpec(char_u *s)
648 {
649     int c;
650 
651     while (*s != NUL)
652     {
653 	if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
654 	{
655 	    // Insert special key literally.
656 	    stuffReadbuffLen(s, 3L);
657 	    s += 3;
658 	}
659 	else
660 	{
661 	    c = mb_ptr2char_adv(&s);
662 	    if (c == CAR || c == NL || c == ESC)
663 		c = ' ';
664 	    stuffcharReadbuff(c);
665 	}
666     }
667 }
668 #endif
669 
670 /*
671  * Append a character to the stuff buffer.
672  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
673  */
674     void
675 stuffcharReadbuff(int c)
676 {
677     add_char_buff(&readbuf1, c);
678 }
679 
680 /*
681  * Append a number to the stuff buffer.
682  */
683     void
684 stuffnumReadbuff(long n)
685 {
686     add_num_buff(&readbuf1, n);
687 }
688 
689 /*
690  * Stuff a string into the typeahead buffer, such that edit() will insert it
691  * literally ("literally" TRUE) or interpret is as typed characters.
692  */
693     void
694 stuffescaped(char_u *arg, int literally)
695 {
696     int		c;
697     char_u	*start;
698 
699     while (*arg != NUL)
700     {
701 	// Stuff a sequence of normal ASCII characters, that's fast.  Also
702 	// stuff K_SPECIAL to get the effect of a special key when "literally"
703 	// is TRUE.
704 	start = arg;
705 	while ((*arg >= ' '
706 #ifndef EBCDIC
707 		    && *arg < DEL // EBCDIC: chars above space are normal
708 #endif
709 		    )
710 		|| (*arg == K_SPECIAL && !literally))
711 	    ++arg;
712 	if (arg > start)
713 	    stuffReadbuffLen(start, (long)(arg - start));
714 
715 	// stuff a single special character
716 	if (*arg != NUL)
717 	{
718 	    if (has_mbyte)
719 		c = mb_cptr2char_adv(&arg);
720 	    else
721 		c = *arg++;
722 	    if (literally && ((c < ' ' && c != TAB) || c == DEL))
723 		stuffcharReadbuff(Ctrl_V);
724 	    stuffcharReadbuff(c);
725 	}
726     }
727 }
728 
729 /*
730  * Read a character from the redo buffer.  Translates K_SPECIAL, CSI and
731  * multibyte characters.
732  * The redo buffer is left as it is.
733  * If init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
734  * otherwise.
735  * If old is TRUE, use old_redobuff instead of redobuff.
736  */
737     static int
738 read_redo(int init, int old_redo)
739 {
740     static buffblock_T	*bp;
741     static char_u	*p;
742     int			c;
743     int			n;
744     char_u		buf[MB_MAXBYTES + 1];
745     int			i;
746 
747     if (init)
748     {
749 	if (old_redo)
750 	    bp = old_redobuff.bh_first.b_next;
751 	else
752 	    bp = redobuff.bh_first.b_next;
753 	if (bp == NULL)
754 	    return FAIL;
755 	p = bp->b_str;
756 	return OK;
757     }
758     if ((c = *p) != NUL)
759     {
760 	// Reverse the conversion done by add_char_buff()
761 	// For a multi-byte character get all the bytes and return the
762 	// converted character.
763 	if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
764 	    n = MB_BYTE2LEN_CHECK(c);
765 	else
766 	    n = 1;
767 	for (i = 0; ; ++i)
768 	{
769 	    if (c == K_SPECIAL) // special key or escaped K_SPECIAL
770 	    {
771 		c = TO_SPECIAL(p[1], p[2]);
772 		p += 2;
773 	    }
774 #ifdef FEAT_GUI
775 	    if (c == CSI)	// escaped CSI
776 		p += 2;
777 #endif
778 	    if (*++p == NUL && bp->b_next != NULL)
779 	    {
780 		bp = bp->b_next;
781 		p = bp->b_str;
782 	    }
783 	    buf[i] = c;
784 	    if (i == n - 1)	// last byte of a character
785 	    {
786 		if (n != 1)
787 		    c = (*mb_ptr2char)(buf);
788 		break;
789 	    }
790 	    c = *p;
791 	    if (c == NUL)	// cannot happen?
792 		break;
793 	}
794     }
795 
796     return c;
797 }
798 
799 /*
800  * Copy the rest of the redo buffer into the stuff buffer (in a slow way).
801  * If old_redo is TRUE, use old_redobuff instead of redobuff.
802  * The escaped K_SPECIAL and CSI are copied without translation.
803  */
804     static void
805 copy_redo(int old_redo)
806 {
807     int	    c;
808 
809     while ((c = read_redo(FALSE, old_redo)) != NUL)
810 	add_char_buff(&readbuf2, c);
811 }
812 
813 /*
814  * Stuff the redo buffer into readbuf2.
815  * Insert the redo count into the command.
816  * If "old_redo" is TRUE, the last but one command is repeated
817  * instead of the last command (inserting text). This is used for
818  * CTRL-O <.> in insert mode
819  *
820  * return FAIL for failure, OK otherwise
821  */
822     int
823 start_redo(long count, int old_redo)
824 {
825     int	    c;
826 
827     // init the pointers; return if nothing to redo
828     if (read_redo(TRUE, old_redo) == FAIL)
829 	return FAIL;
830 
831     c = read_redo(FALSE, old_redo);
832 
833     // copy the buffer name, if present
834     if (c == '"')
835     {
836 	add_buff(&readbuf2, (char_u *)"\"", 1L);
837 	c = read_redo(FALSE, old_redo);
838 
839 	// if a numbered buffer is used, increment the number
840 	if (c >= '1' && c < '9')
841 	    ++c;
842 	add_char_buff(&readbuf2, c);
843 
844 	// the expression register should be re-evaluated
845 	if (c == '=')
846 	{
847 	    add_char_buff(&readbuf2, CAR);
848 	    cmd_silent = TRUE;
849 	}
850 
851 	c = read_redo(FALSE, old_redo);
852     }
853 
854     if (c == 'v')   // redo Visual
855     {
856 	VIsual = curwin->w_cursor;
857 	VIsual_active = TRUE;
858 	VIsual_select = FALSE;
859 	VIsual_reselect = TRUE;
860 	redo_VIsual_busy = TRUE;
861 	c = read_redo(FALSE, old_redo);
862     }
863 
864     // try to enter the count (in place of a previous count)
865     if (count)
866     {
867 	while (VIM_ISDIGIT(c))	// skip "old" count
868 	    c = read_redo(FALSE, old_redo);
869 	add_num_buff(&readbuf2, count);
870     }
871 
872     // copy from the redo buffer into the stuff buffer
873     add_char_buff(&readbuf2, c);
874     copy_redo(old_redo);
875     return OK;
876 }
877 
878 /*
879  * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
880  * the redo buffer into readbuf2.
881  * return FAIL for failure, OK otherwise
882  */
883     int
884 start_redo_ins(void)
885 {
886     int	    c;
887 
888     if (read_redo(TRUE, FALSE) == FAIL)
889 	return FAIL;
890     start_stuff();
891 
892     // skip the count and the command character
893     while ((c = read_redo(FALSE, FALSE)) != NUL)
894     {
895 	if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
896 	{
897 	    if (c == 'O' || c == 'o')
898 		add_buff(&readbuf2, NL_STR, -1L);
899 	    break;
900 	}
901     }
902 
903     // copy the typed text from the redo buffer into the stuff buffer
904     copy_redo(FALSE);
905     block_redo = TRUE;
906     return OK;
907 }
908 
909     void
910 stop_redo_ins(void)
911 {
912     block_redo = FALSE;
913 }
914 
915 /*
916  * Initialize typebuf.tb_buf to point to typebuf_init.
917  * alloc() cannot be used here: In out-of-memory situations it would
918  * be impossible to type anything.
919  */
920     static void
921 init_typebuf(void)
922 {
923     if (typebuf.tb_buf == NULL)
924     {
925 	typebuf.tb_buf = typebuf_init;
926 	typebuf.tb_noremap = noremapbuf_init;
927 	typebuf.tb_buflen = TYPELEN_INIT;
928 	typebuf.tb_len = 0;
929 	typebuf.tb_off = MAXMAPLEN + 4;
930 	typebuf.tb_change_cnt = 1;
931     }
932 }
933 
934 /*
935  * Returns TRUE when keys cannot be remapped.
936  */
937     int
938 noremap_keys(void)
939 {
940     return KeyNoremap & (RM_NONE|RM_SCRIPT);
941 }
942 
943 /*
944  * Insert a string in position 'offset' in the typeahead buffer (for "@r"
945  * and ":normal" command, vgetorpeek() and check_termcode()).
946  *
947  * If noremap is REMAP_YES, new string can be mapped again.
948  * If noremap is REMAP_NONE, new string cannot be mapped again.
949  * If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
950  * but abbreviations are allowed.
951  * If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
952  *			script-local mappings.
953  * If noremap is > 0, that many characters of the new string cannot be mapped.
954  *
955  * If nottyped is TRUE, the string does not return KeyTyped (don't use when
956  * offset is non-zero!).
957  *
958  * If silent is TRUE, cmd_silent is set when the characters are obtained.
959  *
960  * return FAIL for failure, OK otherwise
961  */
962     int
963 ins_typebuf(
964     char_u	*str,
965     int		noremap,
966     int		offset,
967     int		nottyped,
968     int		silent)
969 {
970     char_u	*s1, *s2;
971     int		newlen;
972     int		addlen;
973     int		i;
974     int		newoff;
975     int		val;
976     int		nrm;
977 
978     init_typebuf();
979     if (++typebuf.tb_change_cnt == 0)
980 	typebuf.tb_change_cnt = 1;
981     state_no_longer_safe("ins_typebuf()");
982 
983     addlen = (int)STRLEN(str);
984 
985     if (offset == 0 && addlen <= typebuf.tb_off)
986     {
987 	/*
988 	 * Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
989 	 */
990 	typebuf.tb_off -= addlen;
991 	mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
992     }
993     else if (typebuf.tb_len == 0 && typebuf.tb_buflen
994 					       >= addlen + 3 * (MAXMAPLEN + 4))
995     {
996 	/*
997 	 * Buffer is empty and string fits in the existing buffer.
998 	 * Leave some space before and after, if possible.
999 	 */
1000 	typebuf.tb_off = (typebuf.tb_buflen - addlen - 3 * (MAXMAPLEN + 4)) / 2;
1001 	mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
1002     }
1003     else
1004     {
1005 	/*
1006 	 * Need to allocate a new buffer.
1007 	 * In typebuf.tb_buf there must always be room for 3 * (MAXMAPLEN + 4)
1008 	 * characters.  We add some extra room to avoid having to allocate too
1009 	 * often.
1010 	 */
1011 	newoff = MAXMAPLEN + 4;
1012 	newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
1013 	if (newlen < 0)		    // string is getting too long
1014 	{
1015 	    emsg(_(e_toocompl));    // also calls flush_buffers
1016 	    setcursor();
1017 	    return FAIL;
1018 	}
1019 	s1 = alloc(newlen);
1020 	if (s1 == NULL)		    // out of memory
1021 	    return FAIL;
1022 	s2 = alloc(newlen);
1023 	if (s2 == NULL)		    // out of memory
1024 	{
1025 	    vim_free(s1);
1026 	    return FAIL;
1027 	}
1028 	typebuf.tb_buflen = newlen;
1029 
1030 	// copy the old chars, before the insertion point
1031 	mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
1032 							      (size_t)offset);
1033 	// copy the new chars
1034 	mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
1035 	// copy the old chars, after the insertion point, including the	NUL at
1036 	// the end
1037 	mch_memmove(s1 + newoff + offset + addlen,
1038 				     typebuf.tb_buf + typebuf.tb_off + offset,
1039 				       (size_t)(typebuf.tb_len - offset + 1));
1040 	if (typebuf.tb_buf != typebuf_init)
1041 	    vim_free(typebuf.tb_buf);
1042 	typebuf.tb_buf = s1;
1043 
1044 	mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
1045 							      (size_t)offset);
1046 	mch_memmove(s2 + newoff + offset + addlen,
1047 		   typebuf.tb_noremap + typebuf.tb_off + offset,
1048 					   (size_t)(typebuf.tb_len - offset));
1049 	if (typebuf.tb_noremap != noremapbuf_init)
1050 	    vim_free(typebuf.tb_noremap);
1051 	typebuf.tb_noremap = s2;
1052 
1053 	typebuf.tb_off = newoff;
1054     }
1055     typebuf.tb_len += addlen;
1056 
1057     // If noremap == REMAP_SCRIPT: do remap script-local mappings.
1058     if (noremap == REMAP_SCRIPT)
1059 	val = RM_SCRIPT;
1060     else if (noremap == REMAP_SKIP)
1061 	val = RM_ABBR;
1062     else
1063 	val = RM_NONE;
1064 
1065     /*
1066      * Adjust typebuf.tb_noremap[] for the new characters:
1067      * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
1068      *			(sometimes) not remappable
1069      * If noremap == REMAP_YES: all the new characters are mappable
1070      * If noremap  > 0: "noremap" characters are not remappable, the rest
1071      *			mappable
1072      */
1073     if (noremap == REMAP_SKIP)
1074 	nrm = 1;
1075     else if (noremap < 0)
1076 	nrm = addlen;
1077     else
1078 	nrm = noremap;
1079     for (i = 0; i < addlen; ++i)
1080 	typebuf.tb_noremap[typebuf.tb_off + i + offset] =
1081 						  (--nrm >= 0) ? val : RM_YES;
1082 
1083     // tb_maplen and tb_silent only remember the length of mapped and/or
1084     // silent mappings at the start of the buffer, assuming that a mapped
1085     // sequence doesn't result in typed characters.
1086     if (nottyped || typebuf.tb_maplen > offset)
1087 	typebuf.tb_maplen += addlen;
1088     if (silent || typebuf.tb_silent > offset)
1089     {
1090 	typebuf.tb_silent += addlen;
1091 	cmd_silent = TRUE;
1092     }
1093     if (typebuf.tb_no_abbr_cnt && offset == 0)	// and not used for abbrev.s
1094 	typebuf.tb_no_abbr_cnt += addlen;
1095 
1096     return OK;
1097 }
1098 
1099 /*
1100  * Put character "c" back into the typeahead buffer.
1101  * Can be used for a character obtained by vgetc() that needs to be put back.
1102  * Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
1103  * the char.
1104  */
1105     void
1106 ins_char_typebuf(int c, int modifier)
1107 {
1108     char_u	buf[MB_MAXBYTES + 4];
1109     int		idx = 0;
1110 
1111     if (modifier != 0)
1112     {
1113 	buf[0] = K_SPECIAL;
1114 	buf[1] = KS_MODIFIER;
1115 	buf[2] = modifier;
1116 	buf[3] = NUL;
1117 	idx = 3;
1118     }
1119     if (IS_SPECIAL(c))
1120     {
1121 	buf[idx] = K_SPECIAL;
1122 	buf[idx + 1] = K_SECOND(c);
1123 	buf[idx + 2] = K_THIRD(c);
1124 	buf[idx + 3] = NUL;
1125 	idx += 3;
1126     }
1127     else
1128 	buf[(*mb_char2bytes)(c, buf + idx) + idx] = NUL;
1129     (void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
1130 }
1131 
1132 /*
1133  * Return TRUE if the typeahead buffer was changed (while waiting for a
1134  * character to arrive).  Happens when a message was received from a client or
1135  * from feedkeys().
1136  * But check in a more generic way to avoid trouble: When "typebuf.tb_buf"
1137  * changed it was reallocated and the old pointer can no longer be used.
1138  * Or "typebuf.tb_off" may have been changed and we would overwrite characters
1139  * that was just added.
1140  */
1141     int
1142 typebuf_changed(
1143     int		tb_change_cnt)	// old value of typebuf.tb_change_cnt
1144 {
1145     return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt
1146 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1147 	    || typebuf_was_filled
1148 #endif
1149 	   ));
1150 }
1151 
1152 /*
1153  * Return TRUE if there are no characters in the typeahead buffer that have
1154  * not been typed (result from a mapping or come from ":normal").
1155  */
1156     int
1157 typebuf_typed(void)
1158 {
1159     return typebuf.tb_maplen == 0;
1160 }
1161 
1162 /*
1163  * Return the number of characters that are mapped (or not typed).
1164  */
1165     int
1166 typebuf_maplen(void)
1167 {
1168     return typebuf.tb_maplen;
1169 }
1170 
1171 /*
1172  * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
1173  */
1174     void
1175 del_typebuf(int len, int offset)
1176 {
1177     int	    i;
1178 
1179     if (len == 0)
1180 	return;		// nothing to do
1181 
1182     typebuf.tb_len -= len;
1183 
1184     /*
1185      * Easy case: Just increase typebuf.tb_off.
1186      */
1187     if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
1188 							 >= 3 * MAXMAPLEN + 3)
1189 	typebuf.tb_off += len;
1190     /*
1191      * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
1192      */
1193     else
1194     {
1195 	i = typebuf.tb_off + offset;
1196 	/*
1197 	 * Leave some extra room at the end to avoid reallocation.
1198 	 */
1199 	if (typebuf.tb_off > MAXMAPLEN)
1200 	{
1201 	    mch_memmove(typebuf.tb_buf + MAXMAPLEN,
1202 			     typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
1203 	    mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
1204 			 typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
1205 	    typebuf.tb_off = MAXMAPLEN;
1206 	}
1207 	// adjust typebuf.tb_buf (include the NUL at the end)
1208 	mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
1209 						     typebuf.tb_buf + i + len,
1210 				       (size_t)(typebuf.tb_len - offset + 1));
1211 	// adjust typebuf.tb_noremap[]
1212 	mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
1213 						 typebuf.tb_noremap + i + len,
1214 					   (size_t)(typebuf.tb_len - offset));
1215     }
1216 
1217     if (typebuf.tb_maplen > offset)		// adjust tb_maplen
1218     {
1219 	if (typebuf.tb_maplen < offset + len)
1220 	    typebuf.tb_maplen = offset;
1221 	else
1222 	    typebuf.tb_maplen -= len;
1223     }
1224     if (typebuf.tb_silent > offset)		// adjust tb_silent
1225     {
1226 	if (typebuf.tb_silent < offset + len)
1227 	    typebuf.tb_silent = offset;
1228 	else
1229 	    typebuf.tb_silent -= len;
1230     }
1231     if (typebuf.tb_no_abbr_cnt > offset)	// adjust tb_no_abbr_cnt
1232     {
1233 	if (typebuf.tb_no_abbr_cnt < offset + len)
1234 	    typebuf.tb_no_abbr_cnt = offset;
1235 	else
1236 	    typebuf.tb_no_abbr_cnt -= len;
1237     }
1238 
1239 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1240     // Reset the flag that text received from a client or from feedkeys()
1241     // was inserted in the typeahead buffer.
1242     typebuf_was_filled = FALSE;
1243 #endif
1244     if (++typebuf.tb_change_cnt == 0)
1245 	typebuf.tb_change_cnt = 1;
1246 }
1247 
1248 /*
1249  * Write typed characters to script file.
1250  * If recording is on put the character in the recordbuffer.
1251  */
1252     static void
1253 gotchars(char_u *chars, int len)
1254 {
1255     char_u		*s = chars;
1256     int			i;
1257     static char_u	buf[4];
1258     static int		buflen = 0;
1259     int			todo = len;
1260 
1261     while (todo--)
1262     {
1263 	buf[buflen++] = *s++;
1264 
1265 	// When receiving a special key sequence, store it until we have all
1266 	// the bytes and we can decide what to do with it.
1267 	if (buflen == 1 && buf[0] == K_SPECIAL)
1268 	    continue;
1269 	if (buflen == 2)
1270 	    continue;
1271 	if (buflen == 3 && buf[1] == KS_EXTRA
1272 		       && (buf[2] == KE_FOCUSGAINED || buf[2] == KE_FOCUSLOST))
1273 	{
1274 	    // Drop K_FOCUSGAINED and K_FOCUSLOST, they are not useful in a
1275 	    // recording.
1276 	    buflen = 0;
1277 	    continue;
1278 	}
1279 
1280 	// Handle one byte at a time; no translation to be done.
1281 	for (i = 0; i < buflen; ++i)
1282 	    updatescript(buf[i]);
1283 
1284 	if (reg_recording != 0)
1285 	{
1286 	    buf[buflen] = NUL;
1287 	    add_buff(&recordbuff, buf, (long)buflen);
1288 	    // remember how many chars were last recorded
1289 	    last_recorded_len += buflen;
1290 	}
1291 	buflen = 0;
1292     }
1293     may_sync_undo();
1294 
1295 #ifdef FEAT_EVAL
1296     // output "debug mode" message next time in debug mode
1297     debug_did_msg = FALSE;
1298 #endif
1299 
1300     // Since characters have been typed, consider the following to be in
1301     // another mapping.  Search string will be kept in history.
1302     ++maptick;
1303 }
1304 
1305 /*
1306  * Sync undo.  Called when typed characters are obtained from the typeahead
1307  * buffer, or when a menu is used.
1308  * Do not sync:
1309  * - In Insert mode, unless cursor key has been used.
1310  * - While reading a script file.
1311  * - When no_u_sync is non-zero.
1312  */
1313     static void
1314 may_sync_undo(void)
1315 {
1316     if ((!(State & (INSERT + CMDLINE)) || arrow_used)
1317 					       && scriptin[curscript] == NULL)
1318 	u_sync(FALSE);
1319 }
1320 
1321 /*
1322  * Make "typebuf" empty and allocate new buffers.
1323  * Returns FAIL when out of memory.
1324  */
1325     static int
1326 alloc_typebuf(void)
1327 {
1328     typebuf.tb_buf = alloc(TYPELEN_INIT);
1329     typebuf.tb_noremap = alloc(TYPELEN_INIT);
1330     if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
1331     {
1332 	free_typebuf();
1333 	return FAIL;
1334     }
1335     typebuf.tb_buflen = TYPELEN_INIT;
1336     typebuf.tb_off = MAXMAPLEN + 4;  // can insert without realloc
1337     typebuf.tb_len = 0;
1338     typebuf.tb_maplen = 0;
1339     typebuf.tb_silent = 0;
1340     typebuf.tb_no_abbr_cnt = 0;
1341     if (++typebuf.tb_change_cnt == 0)
1342 	typebuf.tb_change_cnt = 1;
1343 #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
1344     typebuf_was_filled = FALSE;
1345 #endif
1346     return OK;
1347 }
1348 
1349 /*
1350  * Free the buffers of "typebuf".
1351  */
1352     static void
1353 free_typebuf(void)
1354 {
1355     if (typebuf.tb_buf == typebuf_init)
1356 	internal_error("Free typebuf 1");
1357     else
1358 	VIM_CLEAR(typebuf.tb_buf);
1359     if (typebuf.tb_noremap == noremapbuf_init)
1360 	internal_error("Free typebuf 2");
1361     else
1362 	VIM_CLEAR(typebuf.tb_noremap);
1363 }
1364 
1365 /*
1366  * When doing ":so! file", the current typeahead needs to be saved, and
1367  * restored when "file" has been read completely.
1368  */
1369 static typebuf_T saved_typebuf[NSCRIPT];
1370 
1371     int
1372 save_typebuf(void)
1373 {
1374     init_typebuf();
1375     saved_typebuf[curscript] = typebuf;
1376     // If out of memory: restore typebuf and close file.
1377     if (alloc_typebuf() == FAIL)
1378     {
1379 	closescript();
1380 	return FAIL;
1381     }
1382     return OK;
1383 }
1384 
1385 static int old_char = -1;	// character put back by vungetc()
1386 static int old_mod_mask;	// mod_mask for ungotten character
1387 static int old_mouse_row;	// mouse_row related to old_char
1388 static int old_mouse_col;	// mouse_col related to old_char
1389 
1390 /*
1391  * Save all three kinds of typeahead, so that the user must type at a prompt.
1392  */
1393     void
1394 save_typeahead(tasave_T *tp)
1395 {
1396     tp->save_typebuf = typebuf;
1397     tp->typebuf_valid = (alloc_typebuf() == OK);
1398     if (!tp->typebuf_valid)
1399 	typebuf = tp->save_typebuf;
1400 
1401     tp->old_char = old_char;
1402     tp->old_mod_mask = old_mod_mask;
1403     old_char = -1;
1404 
1405     tp->save_readbuf1 = readbuf1;
1406     readbuf1.bh_first.b_next = NULL;
1407     tp->save_readbuf2 = readbuf2;
1408     readbuf2.bh_first.b_next = NULL;
1409 # ifdef USE_INPUT_BUF
1410     tp->save_inputbuf = get_input_buf();
1411 # endif
1412 }
1413 
1414 /*
1415  * Restore the typeahead to what it was before calling save_typeahead().
1416  * The allocated memory is freed, can only be called once!
1417  */
1418     void
1419 restore_typeahead(tasave_T *tp)
1420 {
1421     if (tp->typebuf_valid)
1422     {
1423 	free_typebuf();
1424 	typebuf = tp->save_typebuf;
1425     }
1426 
1427     old_char = tp->old_char;
1428     old_mod_mask = tp->old_mod_mask;
1429 
1430     free_buff(&readbuf1);
1431     readbuf1 = tp->save_readbuf1;
1432     free_buff(&readbuf2);
1433     readbuf2 = tp->save_readbuf2;
1434 # ifdef USE_INPUT_BUF
1435     set_input_buf(tp->save_inputbuf);
1436 # endif
1437 }
1438 
1439 /*
1440  * Open a new script file for the ":source!" command.
1441  */
1442     void
1443 openscript(
1444     char_u	*name,
1445     int		directly)	// when TRUE execute directly
1446 {
1447     if (curscript + 1 == NSCRIPT)
1448     {
1449 	emsg(_(e_nesting));
1450 	return;
1451     }
1452 
1453     // Disallow sourcing a file in the sandbox, the commands would be executed
1454     // later, possibly outside of the sandbox.
1455     if (check_secure())
1456 	return;
1457 
1458 #ifdef FEAT_EVAL
1459     if (ignore_script)
1460 	// Not reading from script, also don't open one.  Warning message?
1461 	return;
1462 #endif
1463 
1464     if (scriptin[curscript] != NULL)	// already reading script
1465 	++curscript;
1466 				// use NameBuff for expanded name
1467     expand_env(name, NameBuff, MAXPATHL);
1468     if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
1469     {
1470 	semsg(_(e_notopen), name);
1471 	if (curscript)
1472 	    --curscript;
1473 	return;
1474     }
1475     if (save_typebuf() == FAIL)
1476 	return;
1477 
1478     /*
1479      * Execute the commands from the file right now when using ":source!"
1480      * after ":global" or ":argdo" or in a loop.  Also when another command
1481      * follows.  This means the display won't be updated.  Don't do this
1482      * always, "make test" would fail.
1483      */
1484     if (directly)
1485     {
1486 	oparg_T	oa;
1487 	int	oldcurscript;
1488 	int	save_State = State;
1489 	int	save_restart_edit = restart_edit;
1490 	int	save_insertmode = p_im;
1491 	int	save_finish_op = finish_op;
1492 	int	save_msg_scroll = msg_scroll;
1493 
1494 	State = NORMAL;
1495 	msg_scroll = FALSE;	// no msg scrolling in Normal mode
1496 	restart_edit = 0;	// don't go to Insert mode
1497 	p_im = FALSE;		// don't use 'insertmode'
1498 	clear_oparg(&oa);
1499 	finish_op = FALSE;
1500 
1501 	oldcurscript = curscript;
1502 	do
1503 	{
1504 	    update_topline_cursor();	// update cursor position and topline
1505 	    normal_cmd(&oa, FALSE);	// execute one command
1506 	    (void)vpeekc();		// check for end of file
1507 	}
1508 	while (scriptin[oldcurscript] != NULL);
1509 
1510 	State = save_State;
1511 	msg_scroll = save_msg_scroll;
1512 	restart_edit = save_restart_edit;
1513 	p_im = save_insertmode;
1514 	finish_op = save_finish_op;
1515     }
1516 }
1517 
1518 /*
1519  * Close the currently active input script.
1520  */
1521     static void
1522 closescript(void)
1523 {
1524     free_typebuf();
1525     typebuf = saved_typebuf[curscript];
1526 
1527     fclose(scriptin[curscript]);
1528     scriptin[curscript] = NULL;
1529     if (curscript > 0)
1530 	--curscript;
1531 }
1532 
1533 #if defined(EXITFREE) || defined(PROTO)
1534     void
1535 close_all_scripts(void)
1536 {
1537     while (scriptin[0] != NULL)
1538 	closescript();
1539 }
1540 #endif
1541 
1542 /*
1543  * Return TRUE when reading keys from a script file.
1544  */
1545     int
1546 using_script(void)
1547 {
1548     return scriptin[curscript] != NULL;
1549 }
1550 
1551 /*
1552  * This function is called just before doing a blocking wait.  Thus after
1553  * waiting 'updatetime' for a character to arrive.
1554  */
1555     void
1556 before_blocking(void)
1557 {
1558     updatescript(0);
1559 #ifdef FEAT_EVAL
1560     if (may_garbage_collect)
1561 	garbage_collect(FALSE);
1562 #endif
1563 }
1564 
1565 /*
1566  * updatescript() is called when a character can be written into the script file
1567  * or when we have waited some time for a character (c == 0)
1568  *
1569  * All the changed memfiles are synced if c == 0 or when the number of typed
1570  * characters reaches 'updatecount' and 'updatecount' is non-zero.
1571  */
1572     static void
1573 updatescript(int c)
1574 {
1575     static int	    count = 0;
1576 
1577     if (c && scriptout)
1578 	putc(c, scriptout);
1579     if (c == 0 || (p_uc > 0 && ++count >= p_uc))
1580     {
1581 	ml_sync_all(c == 0, TRUE);
1582 	count = 0;
1583     }
1584 }
1585 
1586 /*
1587  * Convert "c" plus "modifiers" to merge the effect of modifyOtherKeys into the
1588  * character.
1589  */
1590     int
1591 merge_modifyOtherKeys(int c_arg, int *modifiers)
1592 {
1593     int c = c_arg;
1594 
1595     if (*modifiers & MOD_MASK_CTRL)
1596     {
1597 	if ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_'))
1598 	    c &= 0x1f;
1599 	else if (c == '6')
1600 	    // CTRL-6 is equivalent to CTRL-^
1601 	    c = 0x1e;
1602 #ifdef FEAT_GUI_GTK
1603 	// These mappings look arbitrary at the first glance, but in fact
1604 	// resemble quite exactly the behaviour of the GTK+ 1.2 GUI on my
1605 	// machine.  The only difference is BS vs. DEL for CTRL-8 (makes
1606 	// more sense and is consistent with usual terminal behaviour).
1607 	else if (c == '2')
1608 	    c = NUL;
1609 	else if (c >= '3' && c <= '7')
1610 	    c = c ^ 0x28;
1611 	else if (c == '8')
1612 	    c = BS;
1613 	else if (c == '?')
1614 	    c = DEL;
1615 #endif
1616 	if (c != c_arg)
1617 	    *modifiers &= ~MOD_MASK_CTRL;
1618     }
1619     if ((*modifiers & (MOD_MASK_META | MOD_MASK_ALT))
1620 	    && c >= 0 && c <= 127)
1621     {
1622 	c += 0x80;
1623 	*modifiers &= ~(MOD_MASK_META|MOD_MASK_ALT);
1624     }
1625     return c;
1626 }
1627 
1628 /*
1629  * Get the next input character.
1630  * Can return a special key or a multi-byte character.
1631  * Can return NUL when called recursively, use safe_vgetc() if that's not
1632  * wanted.
1633  * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
1634  * Collects the bytes of a multibyte character into the whole character.
1635  * Returns the modifiers in the global "mod_mask".
1636  */
1637     int
1638 vgetc(void)
1639 {
1640     int		c, c2;
1641     int		n;
1642     char_u	buf[MB_MAXBYTES + 1];
1643     int		i;
1644 
1645 #ifdef FEAT_EVAL
1646     // Do garbage collection when garbagecollect() was called previously and
1647     // we are now at the toplevel.
1648     if (may_garbage_collect && want_garbage_collect)
1649 	garbage_collect(FALSE);
1650 #endif
1651 
1652     /*
1653      * If a character was put back with vungetc, it was already processed.
1654      * Return it directly.
1655      */
1656     if (old_char != -1)
1657     {
1658 	c = old_char;
1659 	old_char = -1;
1660 	mod_mask = old_mod_mask;
1661 	mouse_row = old_mouse_row;
1662 	mouse_col = old_mouse_col;
1663     }
1664     else
1665     {
1666 	mod_mask = 0;
1667 	vgetc_mod_mask = 0;
1668 	vgetc_char = 0;
1669 	last_recorded_len = 0;
1670 
1671 	for (;;)		// this is done twice if there are modifiers
1672 	{
1673 	    int did_inc = FALSE;
1674 
1675 	    if (mod_mask
1676 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
1677 		    || im_is_preediting()
1678 #endif
1679 #if defined(FEAT_PROP_POPUP)
1680 		    || popup_no_mapping()
1681 #endif
1682 		    )
1683 	    {
1684 		// no mapping after modifier has been read
1685 		++no_mapping;
1686 		++allow_keys;
1687 		did_inc = TRUE;	// mod_mask may change value
1688 	    }
1689 	    c = vgetorpeek(TRUE);
1690 	    if (did_inc)
1691 	    {
1692 		--no_mapping;
1693 		--allow_keys;
1694 	    }
1695 
1696 	    // Get two extra bytes for special keys
1697 	    if (c == K_SPECIAL
1698 #ifdef FEAT_GUI
1699 		    || (c == CSI)
1700 #endif
1701 	       )
1702 	    {
1703 		int	    save_allow_keys = allow_keys;
1704 
1705 		++no_mapping;
1706 		allow_keys = 0;		// make sure BS is not found
1707 		c2 = vgetorpeek(TRUE);	// no mapping for these chars
1708 		c = vgetorpeek(TRUE);
1709 		--no_mapping;
1710 		allow_keys = save_allow_keys;
1711 		if (c2 == KS_MODIFIER)
1712 		{
1713 		    mod_mask = c;
1714 		    continue;
1715 		}
1716 		c = TO_SPECIAL(c2, c);
1717 
1718 #if defined(FEAT_GUI_MSWIN) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
1719 		// Handle K_TEAROFF here, the caller of vgetc() doesn't need to
1720 		// know that a menu was torn off
1721 		if (
1722 # ifdef VIMDLL
1723 		    gui.in_use &&
1724 # endif
1725 		    c == K_TEAROFF)
1726 		{
1727 		    char_u	name[200];
1728 		    int		i;
1729 
1730 		    // get menu path, it ends with a <CR>
1731 		    for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
1732 		    {
1733 			name[i] = c;
1734 			if (i < 199)
1735 			    ++i;
1736 		    }
1737 		    name[i] = NUL;
1738 		    gui_make_tearoff(name);
1739 		    continue;
1740 		}
1741 #endif
1742 #if defined(FEAT_GUI) && defined(FEAT_GUI_GTK) && defined(FEAT_MENU)
1743 		// GTK: <F10> normally selects the menu, but it's passed until
1744 		// here to allow mapping it.  Intercept and invoke the GTK
1745 		// behavior if it's not mapped.
1746 		if (c == K_F10 && gui.menubar != NULL)
1747 		{
1748 		    gtk_menu_shell_select_first(
1749 					   GTK_MENU_SHELL(gui.menubar), FALSE);
1750 		    continue;
1751 		}
1752 #endif
1753 #ifdef FEAT_GUI
1754 		// Handle focus event here, so that the caller doesn't need to
1755 		// know about it.  Return K_IGNORE so that we loop once (needed
1756 		// if 'lazyredraw' is set).
1757 		if (c == K_FOCUSGAINED || c == K_FOCUSLOST)
1758 		{
1759 		    ui_focus_change(c == K_FOCUSGAINED);
1760 		    c = K_IGNORE;
1761 		}
1762 
1763 		// Translate K_CSI to CSI.  The special key is only used to
1764 		// avoid it being recognized as the start of a special key.
1765 		if (c == K_CSI)
1766 		    c = CSI;
1767 #endif
1768 	    }
1769 	    // a keypad or special function key was not mapped, use it like
1770 	    // its ASCII equivalent
1771 	    switch (c)
1772 	    {
1773 		case K_KPLUS:	c = '+'; break;
1774 		case K_KMINUS:	c = '-'; break;
1775 		case K_KDIVIDE:	c = '/'; break;
1776 		case K_KMULTIPLY: c = '*'; break;
1777 		case K_KENTER:	c = CAR; break;
1778 		case K_KPOINT:
1779 #ifdef MSWIN
1780 				// Can be either '.' or a ',',
1781 				// depending on the type of keypad.
1782 				c = MapVirtualKey(VK_DECIMAL, 2); break;
1783 #else
1784 				c = '.'; break;
1785 #endif
1786 		case K_K0:	c = '0'; break;
1787 		case K_K1:	c = '1'; break;
1788 		case K_K2:	c = '2'; break;
1789 		case K_K3:	c = '3'; break;
1790 		case K_K4:	c = '4'; break;
1791 		case K_K5:	c = '5'; break;
1792 		case K_K6:	c = '6'; break;
1793 		case K_K7:	c = '7'; break;
1794 		case K_K8:	c = '8'; break;
1795 		case K_K9:	c = '9'; break;
1796 
1797 		case K_XHOME:
1798 		case K_ZHOME:	if (mod_mask == MOD_MASK_SHIFT)
1799 				{
1800 				    c = K_S_HOME;
1801 				    mod_mask = 0;
1802 				}
1803 				else if (mod_mask == MOD_MASK_CTRL)
1804 				{
1805 				    c = K_C_HOME;
1806 				    mod_mask = 0;
1807 				}
1808 				else
1809 				    c = K_HOME;
1810 				break;
1811 		case K_XEND:
1812 		case K_ZEND:	if (mod_mask == MOD_MASK_SHIFT)
1813 				{
1814 				    c = K_S_END;
1815 				    mod_mask = 0;
1816 				}
1817 				else if (mod_mask == MOD_MASK_CTRL)
1818 				{
1819 				    c = K_C_END;
1820 				    mod_mask = 0;
1821 				}
1822 				else
1823 				    c = K_END;
1824 				break;
1825 
1826 		case K_XUP:	c = K_UP; break;
1827 		case K_XDOWN:	c = K_DOWN; break;
1828 		case K_XLEFT:	c = K_LEFT; break;
1829 		case K_XRIGHT:	c = K_RIGHT; break;
1830 	    }
1831 
1832 	    // For a multi-byte character get all the bytes and return the
1833 	    // converted character.
1834 	    // Note: This will loop until enough bytes are received!
1835 	    if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
1836 	    {
1837 		++no_mapping;
1838 		buf[0] = c;
1839 		for (i = 1; i < n; ++i)
1840 		{
1841 		    buf[i] = vgetorpeek(TRUE);
1842 		    if (buf[i] == K_SPECIAL
1843 #ifdef FEAT_GUI
1844 			    || (buf[i] == CSI)
1845 #endif
1846 			    )
1847 		    {
1848 			// Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER
1849 			// sequence, which represents a K_SPECIAL (0x80),
1850 			// or a CSI - KS_EXTRA - KE_CSI sequence, which
1851 			// represents a CSI (0x9B),
1852 			// or a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI
1853 			// too.
1854 			c = vgetorpeek(TRUE);
1855 			if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
1856 			    buf[i] = CSI;
1857 		    }
1858 		}
1859 		--no_mapping;
1860 		c = (*mb_ptr2char)(buf);
1861 	    }
1862 
1863 	    if (vgetc_char == 0)
1864 	    {
1865 		vgetc_mod_mask = mod_mask;
1866 		vgetc_char = c;
1867 	    }
1868 
1869 	    break;
1870 	}
1871     }
1872 
1873 #ifdef FEAT_EVAL
1874     /*
1875      * In the main loop "may_garbage_collect" can be set to do garbage
1876      * collection in the first next vgetc().  It's disabled after that to
1877      * avoid internally used Lists and Dicts to be freed.
1878      */
1879     may_garbage_collect = FALSE;
1880 #endif
1881 
1882 #ifdef FEAT_BEVAL_TERM
1883     if (c != K_MOUSEMOVE && c != K_IGNORE && c != K_CURSORHOLD)
1884     {
1885 	// Don't trigger 'balloonexpr' unless only the mouse was moved.
1886 	bevalexpr_due_set = FALSE;
1887 	ui_remove_balloon();
1888     }
1889 #endif
1890 #ifdef FEAT_PROP_POPUP
1891     // Only filter keys that do not come from ":normal".  Keys from feedkeys()
1892     // are filtered.
1893     if ((!ex_normal_busy || in_feedkeys) && popup_do_filter(c))
1894     {
1895 	if (c == Ctrl_C)
1896 	    got_int = FALSE;  // avoid looping
1897 	c = K_IGNORE;
1898     }
1899 #endif
1900 
1901     // Need to process the character before we know it's safe to do something
1902     // else.
1903     if (c != K_IGNORE)
1904 	state_no_longer_safe("key typed");
1905 
1906     return c;
1907 }
1908 
1909 /*
1910  * Like vgetc(), but never return a NUL when called recursively, get a key
1911  * directly from the user (ignoring typeahead).
1912  */
1913     int
1914 safe_vgetc(void)
1915 {
1916     int	c;
1917 
1918     c = vgetc();
1919     if (c == NUL)
1920 	c = get_keystroke();
1921     return c;
1922 }
1923 
1924 /*
1925  * Like safe_vgetc(), but loop to handle K_IGNORE.
1926  * Also ignore scrollbar events.
1927  */
1928     int
1929 plain_vgetc(void)
1930 {
1931     int c;
1932 
1933     do
1934 	c = safe_vgetc();
1935     while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
1936 
1937     if (c == K_PS)
1938 	// Only handle the first pasted character.  Drop the rest, since we
1939 	// don't know what to do with it.
1940 	c = bracketed_paste(PASTE_ONE_CHAR, FALSE, NULL);
1941 
1942     return c;
1943 }
1944 
1945 /*
1946  * Check if a character is available, such that vgetc() will not block.
1947  * If the next character is a special character or multi-byte, the returned
1948  * character is not valid!.
1949  * Returns NUL if no character is available.
1950  */
1951     int
1952 vpeekc(void)
1953 {
1954     if (old_char != -1)
1955 	return old_char;
1956     return vgetorpeek(FALSE);
1957 }
1958 
1959 #if defined(FEAT_TERMRESPONSE) || defined(FEAT_TERMINAL) || defined(PROTO)
1960 /*
1961  * Like vpeekc(), but don't allow mapping.  Do allow checking for terminal
1962  * codes.
1963  */
1964     int
1965 vpeekc_nomap(void)
1966 {
1967     int		c;
1968 
1969     ++no_mapping;
1970     ++allow_keys;
1971     c = vpeekc();
1972     --no_mapping;
1973     --allow_keys;
1974     return c;
1975 }
1976 #endif
1977 
1978 /*
1979  * Check if any character is available, also half an escape sequence.
1980  * Trick: when no typeahead found, but there is something in the typeahead
1981  * buffer, it must be an ESC that is recognized as the start of a key code.
1982  */
1983     int
1984 vpeekc_any(void)
1985 {
1986     int		c;
1987 
1988     c = vpeekc();
1989     if (c == NUL && typebuf.tb_len > 0)
1990 	c = ESC;
1991     return c;
1992 }
1993 
1994 /*
1995  * Call vpeekc() without causing anything to be mapped.
1996  * Return TRUE if a character is available, FALSE otherwise.
1997  */
1998     int
1999 char_avail(void)
2000 {
2001     int	    retval;
2002 
2003 #ifdef FEAT_EVAL
2004     // When test_override("char_avail", 1) was called pretend there is no
2005     // typeahead.
2006     if (disable_char_avail_for_testing)
2007 	return FALSE;
2008 #endif
2009     ++no_mapping;
2010     retval = vpeekc();
2011     --no_mapping;
2012     return (retval != NUL);
2013 }
2014 
2015 #if defined(FEAT_EVAL) || defined(PROTO)
2016 /*
2017  * "getchar()" function
2018  */
2019     void
2020 f_getchar(typval_T *argvars, typval_T *rettv)
2021 {
2022     varnumber_T		n;
2023     int			error = FALSE;
2024 
2025 #ifdef MESSAGE_QUEUE
2026     // vpeekc() used to check for messages, but that caused problems, invoking
2027     // a callback where it was not expected.  Some plugins use getchar(1) in a
2028     // loop to await a message, therefore make sure we check for messages here.
2029     parse_queued_messages();
2030 #endif
2031 
2032     // Position the cursor.  Needed after a message that ends in a space.
2033     windgoto(msg_row, msg_col);
2034 
2035     ++no_mapping;
2036     ++allow_keys;
2037     for (;;)
2038     {
2039 	if (argvars[0].v_type == VAR_UNKNOWN)
2040 	    // getchar(): blocking wait.
2041 	    n = plain_vgetc();
2042 	else if (tv_get_bool_chk(&argvars[0], &error))
2043 	    // getchar(1): only check if char avail
2044 	    n = vpeekc_any();
2045 	else if (error || vpeekc_any() == NUL)
2046 	    // illegal argument or getchar(0) and no char avail: return zero
2047 	    n = 0;
2048 	else
2049 	    // getchar(0) and char avail() != NUL: get a character.
2050 	    // Note that vpeekc_any() returns K_SPECIAL for K_IGNORE.
2051 	    n = safe_vgetc();
2052 
2053 	if (n == K_IGNORE || n == K_MOUSEMOVE
2054 		|| n == K_VER_SCROLLBAR || n == K_HOR_SCROLLBAR)
2055 	    continue;
2056 	break;
2057     }
2058     --no_mapping;
2059     --allow_keys;
2060 
2061     set_vim_var_nr(VV_MOUSE_WIN, 0);
2062     set_vim_var_nr(VV_MOUSE_WINID, 0);
2063     set_vim_var_nr(VV_MOUSE_LNUM, 0);
2064     set_vim_var_nr(VV_MOUSE_COL, 0);
2065 
2066     rettv->vval.v_number = n;
2067     if (IS_SPECIAL(n) || mod_mask != 0)
2068     {
2069 	char_u		temp[10];   // modifier: 3, mbyte-char: 6, NUL: 1
2070 	int		i = 0;
2071 
2072 	// Turn a special key into three bytes, plus modifier.
2073 	if (mod_mask != 0)
2074 	{
2075 	    temp[i++] = K_SPECIAL;
2076 	    temp[i++] = KS_MODIFIER;
2077 	    temp[i++] = mod_mask;
2078 	}
2079 	if (IS_SPECIAL(n))
2080 	{
2081 	    temp[i++] = K_SPECIAL;
2082 	    temp[i++] = K_SECOND(n);
2083 	    temp[i++] = K_THIRD(n);
2084 	}
2085 	else if (has_mbyte)
2086 	    i += (*mb_char2bytes)(n, temp + i);
2087 	else
2088 	    temp[i++] = n;
2089 	temp[i++] = NUL;
2090 	rettv->v_type = VAR_STRING;
2091 	rettv->vval.v_string = vim_strsave(temp);
2092 
2093 	if (is_mouse_key(n))
2094 	{
2095 	    int		row = mouse_row;
2096 	    int		col = mouse_col;
2097 	    win_T	*win;
2098 	    linenr_T	lnum;
2099 	    win_T	*wp;
2100 	    int		winnr = 1;
2101 
2102 	    if (row >= 0 && col >= 0)
2103 	    {
2104 		// Find the window at the mouse coordinates and compute the
2105 		// text position.
2106 		win = mouse_find_win(&row, &col, FIND_POPUP);
2107 		if (win == NULL)
2108 		    return;
2109 		(void)mouse_comp_pos(win, &row, &col, &lnum, NULL);
2110 #ifdef FEAT_PROP_POPUP
2111 		if (WIN_IS_POPUP(win))
2112 		    winnr = 0;
2113 		else
2114 #endif
2115 		    for (wp = firstwin; wp != win && wp != NULL;
2116 							       wp = wp->w_next)
2117 			++winnr;
2118 		set_vim_var_nr(VV_MOUSE_WIN, winnr);
2119 		set_vim_var_nr(VV_MOUSE_WINID, win->w_id);
2120 		set_vim_var_nr(VV_MOUSE_LNUM, lnum);
2121 		set_vim_var_nr(VV_MOUSE_COL, col + 1);
2122 	    }
2123 	}
2124     }
2125 }
2126 
2127 /*
2128  * "getcharmod()" function
2129  */
2130     void
2131 f_getcharmod(typval_T *argvars UNUSED, typval_T *rettv)
2132 {
2133     rettv->vval.v_number = mod_mask;
2134 }
2135 #endif // FEAT_EVAL
2136 
2137 #if defined(MESSAGE_QUEUE) || defined(PROTO)
2138 # define MAX_REPEAT_PARSE 8
2139 
2140 /*
2141  * Process messages that have been queued for netbeans or clientserver.
2142  * Also check if any jobs have ended.
2143  * These functions can call arbitrary vimscript and should only be called when
2144  * it is safe to do so.
2145  */
2146     void
2147 parse_queued_messages(void)
2148 {
2149     int	    old_curwin_id;
2150     int	    old_curbuf_fnum;
2151     int	    i;
2152     int	    save_may_garbage_collect = may_garbage_collect;
2153     static int entered = 0;
2154     int	    was_safe = get_was_safe_state();
2155 
2156     // Do not handle messages while redrawing, because it may cause buffers to
2157     // change or be wiped while they are being redrawn.
2158     // Also bail out when parsing messages was explicitly disabled.
2159     if (updating_screen || dont_parse_messages)
2160 	return;
2161 
2162     // If memory allocation fails during startup we'll exit but curbuf or
2163     // curwin could be NULL.
2164     if (curbuf == NULL || curwin == NULL)
2165        return;
2166 
2167     old_curbuf_fnum = curbuf->b_fnum;
2168     old_curwin_id = curwin->w_id;
2169 
2170     ++entered;
2171 
2172     // may_garbage_collect is set in main_loop() to do garbage collection when
2173     // blocking to wait on a character.  We don't want that while parsing
2174     // messages, a callback may invoke vgetc() while lists and dicts are in use
2175     // in the call stack.
2176     may_garbage_collect = FALSE;
2177 
2178     // Loop when a job ended, but don't keep looping forever.
2179     for (i = 0; i < MAX_REPEAT_PARSE; ++i)
2180     {
2181 	// For Win32 mch_breakcheck() does not check for input, do it here.
2182 # if (defined(MSWIN) || defined(__HAIKU__)) && defined(FEAT_JOB_CHANNEL)
2183 	channel_handle_events(FALSE);
2184 # endif
2185 
2186 # ifdef FEAT_NETBEANS_INTG
2187 	// Process the queued netbeans messages.
2188 	netbeans_parse_messages();
2189 # endif
2190 # ifdef FEAT_JOB_CHANNEL
2191 	// Write any buffer lines still to be written.
2192 	channel_write_any_lines();
2193 
2194 	// Process the messages queued on channels.
2195 	channel_parse_messages();
2196 # endif
2197 # if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
2198 	// Process the queued clientserver messages.
2199 	server_parse_messages();
2200 # endif
2201 # ifdef FEAT_JOB_CHANNEL
2202 	// Check if any jobs have ended.  If so, repeat the above to handle
2203 	// changes, e.g. stdin may have been closed.
2204 	if (job_check_ended())
2205 	    continue;
2206 # endif
2207 # ifdef FEAT_TERMINAL
2208 	free_unused_terminals();
2209 # endif
2210 # ifdef FEAT_SOUND_CANBERRA
2211 	if (has_sound_callback_in_queue())
2212 	    invoke_sound_callback();
2213 # endif
2214 #ifdef SIGUSR1
2215 	if (got_sigusr1)
2216 	{
2217 	    apply_autocmds(EVENT_SIGUSR1, NULL, NULL, FALSE, curbuf);
2218 	    got_sigusr1 = FALSE;
2219 	}
2220 #endif
2221 	break;
2222     }
2223 
2224     // When not nested we'll go back to waiting for a typed character.  If it
2225     // was safe before then this triggers a SafeStateAgain autocommand event.
2226     if (entered == 1 && was_safe)
2227 	may_trigger_safestateagain();
2228 
2229     may_garbage_collect = save_may_garbage_collect;
2230 
2231     // If the current window or buffer changed we need to bail out of the
2232     // waiting loop.  E.g. when a job exit callback closes the terminal window.
2233     if (curwin->w_id != old_curwin_id || curbuf->b_fnum != old_curbuf_fnum)
2234 	ins_char_typebuf(K_IGNORE, 0);
2235 
2236     --entered;
2237 }
2238 #endif
2239 
2240 
2241 typedef enum {
2242     map_result_fail,    // failed, break loop
2243     map_result_get,     // get a character from typeahead
2244     map_result_retry,   // try to map again
2245     map_result_nomatch  // no matching mapping, get char
2246 } map_result_T;
2247 
2248 /*
2249  * Check if the bytes at the start of the typeahead buffer are a character used
2250  * in CTRL-X mode.  This includes the form with a CTRL modifier.
2251  */
2252     static int
2253 at_ctrl_x_key(void)
2254 {
2255     char_u  *p = typebuf.tb_buf + typebuf.tb_off;
2256     int	    c = *p;
2257 
2258     if (typebuf.tb_len > 3
2259 	    && c == K_SPECIAL
2260 	    && p[1] == KS_MODIFIER
2261 	    && (p[2] & MOD_MASK_CTRL))
2262 	c = p[3] & 0x1f;
2263     return vim_is_ctrl_x_key(c);
2264 }
2265 
2266 /*
2267  * Check if typebuf.tb_buf[] contains a modifier plus key that can be changed
2268  * into just a key, apply that.
2269  * Check from typebuf.tb_buf[typebuf.tb_off] to typebuf.tb_buf[typebuf.tb_off
2270  * + "max_offset"].
2271  * Return the length of the replaced bytes, zero if nothing changed.
2272  */
2273     static int
2274 check_simplify_modifier(int max_offset)
2275 {
2276     int		offset;
2277     char_u	*tp;
2278 
2279     for (offset = 0; offset < max_offset; ++offset)
2280     {
2281 	if (offset + 3 >= typebuf.tb_len)
2282 	    break;
2283 	tp = typebuf.tb_buf + typebuf.tb_off + offset;
2284 	if (tp[0] == K_SPECIAL && tp[1] == KS_MODIFIER)
2285 	{
2286 	    // A modifier was not used for a mapping, apply it to ASCII keys.
2287 	    // Shift would already have been applied.
2288 	    int modifier = tp[2];
2289 	    int	c = tp[3];
2290 	    int new_c = merge_modifyOtherKeys(c, &modifier);
2291 
2292 	    if (new_c != c)
2293 	    {
2294 		char_u	new_string[MB_MAXBYTES];
2295 		int	len;
2296 
2297 		if (offset == 0)
2298 		{
2299 		    // At the start: remember the character and mod_mask before
2300 		    // merging, in some cases, e.g. at the hit-return prompt,
2301 		    // they are put back in the typeahead buffer.
2302 		    vgetc_char = c;
2303 		    vgetc_mod_mask = tp[2];
2304 		}
2305 		len = mb_char2bytes(new_c, new_string);
2306 		if (modifier == 0)
2307 		{
2308 		    if (put_string_in_typebuf(offset, 4, new_string, len,
2309 							   NULL, 0, 0) == FAIL)
2310 		    return -1;
2311 		}
2312 		else
2313 		{
2314 		    tp[2] = modifier;
2315 		    if (put_string_in_typebuf(offset + 3, 1, new_string, len,
2316 							   NULL, 0, 0) == FAIL)
2317 		    return -1;
2318 		}
2319 		return len;
2320 	    }
2321 	}
2322     }
2323     return 0;
2324 }
2325 
2326 /*
2327  * Handle mappings in the typeahead buffer.
2328  * - When something was mapped, return map_result_retry for recursive mappings.
2329  * - When nothing mapped and typeahead has a character: return map_result_get.
2330  * - When there is no match yet, return map_result_nomatch, need to get more
2331  *   typeahead.
2332  */
2333     static int
2334 handle_mapping(
2335 	    int *keylenp,
2336 	    int *timedout,
2337 	    int *mapdepth)
2338 {
2339     mapblock_T	*mp = NULL;
2340     mapblock_T	*mp2;
2341     mapblock_T	*mp_match;
2342     int		mp_match_len = 0;
2343     int		max_mlen = 0;
2344     int		tb_c1;
2345     int		mlen;
2346 #ifdef FEAT_LANGMAP
2347     int		nolmaplen;
2348 #endif
2349     int		keylen = *keylenp;
2350     int		i;
2351     int		local_State = get_real_state();
2352 
2353     /*
2354      * Check for a mappable key sequence.
2355      * Walk through one maphash[] list until we find an entry that matches.
2356      *
2357      * Don't look for mappings if:
2358      * - no_mapping set: mapping disabled (e.g. for CTRL-V)
2359      * - maphash_valid not set: no mappings present.
2360      * - typebuf.tb_buf[typebuf.tb_off] should not be remapped
2361      * - in insert or cmdline mode and 'paste' option set
2362      * - waiting for "hit return to continue" and CR or SPACE typed
2363      * - waiting for a char with --more--
2364      * - in Ctrl-X mode, and we get a valid char for that mode
2365      */
2366     tb_c1 = typebuf.tb_buf[typebuf.tb_off];
2367     if (no_mapping == 0 && is_maphash_valid()
2368 	    && (no_zero_mapping == 0 || tb_c1 != '0')
2369 	    && (typebuf.tb_maplen == 0
2370 		|| (p_remap
2371 		    && (typebuf.tb_noremap[typebuf.tb_off]
2372 				    & (RM_NONE|RM_ABBR)) == 0))
2373 	    && !(p_paste && (State & (INSERT + CMDLINE)))
2374 	    && !(State == HITRETURN && (tb_c1 == CAR || tb_c1 == ' '))
2375 	    && State != ASKMORE
2376 	    && State != CONFIRM
2377 	    && !((ctrl_x_mode_not_default() && at_ctrl_x_key())
2378 		    || ((compl_cont_status & CONT_LOCAL)
2379 			&& (tb_c1 == Ctrl_N || tb_c1 == Ctrl_P))))
2380     {
2381 #ifdef FEAT_GUI
2382 	if (gui.in_use && tb_c1 == CSI && typebuf.tb_len >= 2
2383 		&& typebuf.tb_buf[typebuf.tb_off + 1] == KS_MODIFIER)
2384 	{
2385 	    // The GUI code sends CSI KS_MODIFIER {flags}, but mappings expect
2386 	    // K_SPECIAL KS_MODIFIER {flags}.
2387 	    tb_c1 = K_SPECIAL;
2388 	}
2389 #endif
2390 #ifdef FEAT_LANGMAP
2391 	if (tb_c1 == K_SPECIAL)
2392 	    nolmaplen = 2;
2393 	else
2394 	{
2395 	    LANGMAP_ADJUST(tb_c1, (State & (CMDLINE | INSERT)) == 0
2396 					    && get_real_state() != SELECTMODE);
2397 	    nolmaplen = 0;
2398 	}
2399 #endif
2400 	// First try buffer-local mappings.
2401 	mp = get_buf_maphash_list(local_State, tb_c1);
2402 	mp2 = get_maphash_list(local_State, tb_c1);
2403 	if (mp == NULL)
2404 	{
2405 	    // There are no buffer-local mappings.
2406 	    mp = mp2;
2407 	    mp2 = NULL;
2408 	}
2409 
2410 	/*
2411 	 * Loop until a partly matching mapping is found or all (local)
2412 	 * mappings have been checked.
2413 	 * The longest full match is remembered in "mp_match".
2414 	 * A full match is only accepted if there is no partly match, so "aa"
2415 	 * and "aaa" can both be mapped.
2416 	 */
2417 	mp_match = NULL;
2418 	mp_match_len = 0;
2419 	for ( ; mp != NULL;
2420 	       mp->m_next == NULL ? (mp = mp2, mp2 = NULL) : (mp = mp->m_next))
2421 	{
2422 	    // Only consider an entry if the first character matches and it is
2423 	    // for the current state.
2424 	    // Skip ":lmap" mappings if keys were mapped.
2425 	    if (mp->m_keys[0] == tb_c1
2426 		    && (mp->m_mode & local_State)
2427 		    && !(mp->m_simplified && seenModifyOtherKeys
2428 						     && typebuf.tb_maplen == 0)
2429 		    && ((mp->m_mode & LANGMAP) == 0 || typebuf.tb_maplen == 0))
2430 	    {
2431 #ifdef FEAT_LANGMAP
2432 		int	nomap = nolmaplen;
2433 		int	c2;
2434 #endif
2435 		// find the match length of this mapping
2436 		for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
2437 		{
2438 #ifdef FEAT_LANGMAP
2439 		    c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
2440 		    if (nomap > 0)
2441 			--nomap;
2442 		    else if (c2 == K_SPECIAL)
2443 			nomap = 2;
2444 		    else
2445 			LANGMAP_ADJUST(c2, TRUE);
2446 		    if (mp->m_keys[mlen] != c2)
2447 #else
2448 		    if (mp->m_keys[mlen] !=
2449 					 typebuf.tb_buf[typebuf.tb_off + mlen])
2450 #endif
2451 			break;
2452 		}
2453 
2454 		// Don't allow mapping the first byte(s) of a multi-byte char.
2455 		// Happens when mapping <M-a> and then changing 'encoding'.
2456 		// Beware that 0x80 is escaped.
2457 		{
2458 		    char_u *p1 = mp->m_keys;
2459 		    char_u *p2 = mb_unescape(&p1);
2460 
2461 		    if (has_mbyte && p2 != NULL
2462 					&& MB_BYTE2LEN(tb_c1) > mb_ptr2len(p2))
2463 			mlen = 0;
2464 		}
2465 
2466 		// Check an entry whether it matches.
2467 		// - Full match: mlen == keylen
2468 		// - Partly match: mlen == typebuf.tb_len
2469 		keylen = mp->m_keylen;
2470 		if (mlen == keylen || (mlen == typebuf.tb_len
2471 						   && typebuf.tb_len < keylen))
2472 		{
2473 		    char_u  *s;
2474 		    int	    n;
2475 
2476 		    // If only script-local mappings are allowed, check if the
2477 		    // mapping starts with K_SNR.
2478 		    s = typebuf.tb_noremap + typebuf.tb_off;
2479 		    if (*s == RM_SCRIPT
2480 			    && (mp->m_keys[0] != K_SPECIAL
2481 				|| mp->m_keys[1] != KS_EXTRA
2482 				|| mp->m_keys[2] != (int)KE_SNR))
2483 			continue;
2484 
2485 		    // If one of the typed keys cannot be remapped, skip the
2486 		    // entry.
2487 		    for (n = mlen; --n >= 0; )
2488 			if (*s++ & (RM_NONE|RM_ABBR))
2489 			    break;
2490 		    if (n >= 0)
2491 			continue;
2492 
2493 		    if (keylen > typebuf.tb_len)
2494 		    {
2495 			if (!*timedout && !(mp_match != NULL
2496 							&& mp_match->m_nowait))
2497 			{
2498 			    // break at a partly match
2499 			    keylen = KEYLEN_PART_MAP;
2500 			    break;
2501 			}
2502 		    }
2503 		    else if (keylen > mp_match_len)
2504 		    {
2505 			// found a longer match
2506 			mp_match = mp;
2507 			mp_match_len = keylen;
2508 		    }
2509 		}
2510 		else
2511 		    // No match; may have to check for termcode at next
2512 		    // character.
2513 		    if (max_mlen < mlen)
2514 			max_mlen = mlen;
2515 	    }
2516 	}
2517 
2518 	// If no partly match found, use the longest full match.
2519 	if (keylen != KEYLEN_PART_MAP)
2520 	{
2521 	    mp = mp_match;
2522 	    keylen = mp_match_len;
2523 	}
2524     }
2525 
2526     /*
2527      * Check for match with 'pastetoggle'
2528      */
2529     if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
2530     {
2531 	for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen]; ++mlen)
2532 	    if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off + mlen])
2533 		    break;
2534 	if (p_pt[mlen] == NUL)	// match
2535 	{
2536 	    // write chars to script file(s)
2537 	    if (mlen > typebuf.tb_maplen)
2538 		gotchars(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_maplen,
2539 						     mlen - typebuf.tb_maplen);
2540 
2541 	    del_typebuf(mlen, 0); // remove the chars
2542 	    set_option_value((char_u *)"paste", (long)!p_paste, NULL, 0);
2543 	    if (!(State & INSERT))
2544 	    {
2545 		msg_col = 0;
2546 		msg_row = Rows - 1;
2547 		msg_clr_eos();		// clear ruler
2548 	    }
2549 	    status_redraw_all();
2550 	    redraw_statuslines();
2551 	    showmode();
2552 	    setcursor();
2553 	    *keylenp = keylen;
2554 	    return map_result_retry;
2555 	}
2556 	// Need more chars for partly match.
2557 	if (mlen == typebuf.tb_len)
2558 	    keylen = KEYLEN_PART_KEY;
2559 	else if (max_mlen < mlen)
2560 	    // no match, may have to check for termcode at next character
2561 	    max_mlen = mlen + 1;
2562     }
2563 
2564     if ((mp == NULL || max_mlen >= mp_match_len) && keylen != KEYLEN_PART_MAP)
2565     {
2566 	int	save_keylen = keylen;
2567 
2568 	/*
2569 	 * When no matching mapping found or found a non-matching mapping that
2570 	 * matches at least what the matching mapping matched:
2571 	 * Check if we have a terminal code, when:
2572 	 * - mapping is allowed,
2573 	 * - keys have not been mapped,
2574 	 * - and not an ESC sequence, not in insert mode or p_ek is on,
2575 	 * - and when not timed out,
2576 	 */
2577 	if ((no_mapping == 0 || allow_keys != 0)
2578 		&& (typebuf.tb_maplen == 0
2579 		    || (p_remap && typebuf.tb_noremap[
2580 						    typebuf.tb_off] == RM_YES))
2581 		&& !*timedout)
2582 	{
2583 	    keylen = check_termcode(max_mlen + 1, NULL, 0, NULL);
2584 
2585 	    // If no termcode matched but 'pastetoggle' matched partially
2586 	    // it's like an incomplete key sequence.
2587 	    if (keylen == 0 && save_keylen == KEYLEN_PART_KEY)
2588 		keylen = KEYLEN_PART_KEY;
2589 
2590 	    // If no termcode matched, try to include the modifier into the
2591 	    // key.  This for when modifyOtherKeys is working.
2592 	    if (keylen == 0 && !no_reduce_keys)
2593 		keylen = check_simplify_modifier(max_mlen + 1);
2594 
2595 	    // When getting a partial match, but the last characters were not
2596 	    // typed, don't wait for a typed character to complete the
2597 	    // termcode.  This helps a lot when a ":normal" command ends in an
2598 	    // ESC.
2599 	    if (keylen < 0 && typebuf.tb_len == typebuf.tb_maplen)
2600 		keylen = 0;
2601 	}
2602 	else
2603 	    keylen = 0;
2604 	if (keylen == 0)	// no matching terminal code
2605 	{
2606 #ifdef AMIGA
2607 	    // check for window bounds report
2608 	    if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
2609 						typebuf.tb_off] & 0xff) == CSI)
2610 	    {
2611 		char_u *s;
2612 
2613 		for (s = typebuf.tb_buf + typebuf.tb_off + 1;
2614 			   s < typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len
2615 		   && (VIM_ISDIGIT(*s) || *s == ';' || *s == ' ');
2616 			++s)
2617 		    ;
2618 		if (*s == 'r' || *s == '|') // found one
2619 		{
2620 		    del_typebuf(
2621 			  (int)(s + 1 - (typebuf.tb_buf + typebuf.tb_off)), 0);
2622 		    // get size and redraw screen
2623 		    shell_resized();
2624 		    *keylenp = keylen;
2625 		    return map_result_retry;
2626 		}
2627 		if (*s == NUL)	    // need more characters
2628 		    keylen = KEYLEN_PART_KEY;
2629 	    }
2630 	    if (keylen >= 0)
2631 #endif
2632 		// When there was a matching mapping and no termcode could be
2633 		// replaced after another one, use that mapping (loop around).
2634 		// If there was no mapping at all use the character from the
2635 		// typeahead buffer right here.
2636 		if (mp == NULL)
2637 		{
2638 		    *keylenp = keylen;
2639 		    return map_result_get;    // got character, break for loop
2640 		}
2641 	}
2642 
2643 	if (keylen > 0)	    // full matching terminal code
2644 	{
2645 #if defined(FEAT_GUI) && defined(FEAT_MENU)
2646 	    if (typebuf.tb_len >= 2
2647 		    && typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
2648 			      && typebuf.tb_buf[typebuf.tb_off + 1] == KS_MENU)
2649 	    {
2650 		int	idx;
2651 
2652 		// Using a menu may cause a break in undo!  It's like using
2653 		// gotchars(), but without recording or writing to a script
2654 		// file.
2655 		may_sync_undo();
2656 		del_typebuf(3, 0);
2657 		idx = get_menu_index(current_menu, local_State);
2658 		if (idx != MENU_INDEX_INVALID)
2659 		{
2660 		    // In Select mode and a Visual mode menu is used:  Switch
2661 		    // to Visual mode temporarily.  Append K_SELECT to switch
2662 		    // back to Select mode.
2663 		    if (VIsual_active && VIsual_select
2664 					     && (current_menu->modes & VISUAL))
2665 		    {
2666 			VIsual_select = FALSE;
2667 			(void)ins_typebuf(K_SELECT_STRING,
2668 						   REMAP_NONE, 0, TRUE, FALSE);
2669 		    }
2670 		    ins_typebuf(current_menu->strings[idx],
2671 				current_menu->noremap[idx],
2672 				0, TRUE, current_menu->silent[idx]);
2673 		}
2674 	    }
2675 #endif // FEAT_GUI && FEAT_MENU
2676 	    *keylenp = keylen;
2677 	    return map_result_retry;	// try mapping again
2678 	}
2679 
2680 	// Partial match: get some more characters.  When a matching mapping
2681 	// was found use that one.
2682 	if (mp == NULL || keylen < 0)
2683 	    keylen = KEYLEN_PART_KEY;
2684 	else
2685 	    keylen = mp_match_len;
2686     }
2687 
2688     /*
2689      * complete match
2690      */
2691     if (keylen >= 0 && keylen <= typebuf.tb_len)
2692     {
2693 	char_u *map_str;
2694 
2695 #ifdef FEAT_EVAL
2696 	int	save_m_expr;
2697 	int	save_m_noremap;
2698 	int	save_m_silent;
2699 	char_u	*save_m_keys;
2700 	char_u	*save_m_str;
2701 #else
2702 # define save_m_noremap mp->m_noremap
2703 # define save_m_silent mp->m_silent
2704 #endif
2705 
2706 	// write chars to script file(s)
2707 	if (keylen > typebuf.tb_maplen)
2708 	    gotchars(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_maplen,
2709 						   keylen - typebuf.tb_maplen);
2710 
2711 	cmd_silent = (typebuf.tb_silent > 0);
2712 	del_typebuf(keylen, 0);	// remove the mapped keys
2713 
2714 	/*
2715 	 * Put the replacement string in front of mapstr.
2716 	 * The depth check catches ":map x y" and ":map y x".
2717 	 */
2718 	if (++*mapdepth >= p_mmd)
2719 	{
2720 	    emsg(_("E223: recursive mapping"));
2721 	    if (State & CMDLINE)
2722 		redrawcmdline();
2723 	    else
2724 		setcursor();
2725 	    flush_buffers(FLUSH_MINIMAL);
2726 	    *mapdepth = 0;	// for next one
2727 	    *keylenp = keylen;
2728 	    return map_result_fail;
2729 	}
2730 
2731 	/*
2732 	 * In Select mode and a Visual mode mapping is used: Switch to Visual
2733 	 * mode temporarily.  Append K_SELECT to switch back to Select mode.
2734 	 */
2735 	if (VIsual_active && VIsual_select && (mp->m_mode & VISUAL))
2736 	{
2737 	    VIsual_select = FALSE;
2738 	    (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE, 0, TRUE, FALSE);
2739 	}
2740 
2741 #ifdef FEAT_EVAL
2742 	// Copy the values from *mp that are used, because evaluating the
2743 	// expression may invoke a function that redefines the mapping, thereby
2744 	// making *mp invalid.
2745 	save_m_expr = mp->m_expr;
2746 	save_m_noremap = mp->m_noremap;
2747 	save_m_silent = mp->m_silent;
2748 	save_m_keys = NULL;  // only saved when needed
2749 	save_m_str = NULL;  // only saved when needed
2750 
2751 	/*
2752 	 * Handle ":map <expr>": evaluate the {rhs} as an expression.  Also
2753 	 * save and restore the command line for "normal :".
2754 	 */
2755 	if (mp->m_expr)
2756 	{
2757 	    int save_vgetc_busy = vgetc_busy;
2758 	    int save_may_garbage_collect = may_garbage_collect;
2759 	    int was_screen_col = screen_cur_col;
2760 	    int was_screen_row = screen_cur_row;
2761 
2762 	    vgetc_busy = 0;
2763 	    may_garbage_collect = FALSE;
2764 
2765 	    save_m_keys = vim_strsave(mp->m_keys);
2766 	    save_m_str = vim_strsave(mp->m_str);
2767 	    map_str = eval_map_expr(save_m_str, NUL);
2768 
2769 	    // The mapping may do anything, but we expect it to take care of
2770 	    // redrawing.  Do put the cursor back where it was.
2771 	    windgoto(was_screen_row, was_screen_col);
2772 	    out_flush();
2773 
2774 	    vgetc_busy = save_vgetc_busy;
2775 	    may_garbage_collect = save_may_garbage_collect;
2776 	}
2777 	else
2778 #endif
2779 	    map_str = mp->m_str;
2780 
2781 	/*
2782 	 * Insert the 'to' part in the typebuf.tb_buf.
2783 	 * If 'from' field is the same as the start of the 'to' field, don't
2784 	 * remap the first character (but do allow abbreviations).
2785 	 * If m_noremap is set, don't remap the whole 'to' part.
2786 	 */
2787 	if (map_str == NULL)
2788 	    i = FAIL;
2789 	else
2790 	{
2791 	    int noremap;
2792 
2793 	    if (save_m_noremap != REMAP_YES)
2794 		noremap = save_m_noremap;
2795 	    else if (
2796 #ifdef FEAT_EVAL
2797 		STRNCMP(map_str, save_m_keys != NULL ? save_m_keys : mp->m_keys,
2798 								(size_t)keylen)
2799 #else
2800 		STRNCMP(map_str, mp->m_keys, (size_t)keylen)
2801 #endif
2802 		   != 0)
2803 		noremap = REMAP_YES;
2804 	    else
2805 		noremap = REMAP_SKIP;
2806 	    i = ins_typebuf(map_str, noremap,
2807 					 0, TRUE, cmd_silent || save_m_silent);
2808 #ifdef FEAT_EVAL
2809 	    if (save_m_expr)
2810 		vim_free(map_str);
2811 #endif
2812 	}
2813 #ifdef FEAT_EVAL
2814 	vim_free(save_m_keys);
2815 	vim_free(save_m_str);
2816 #endif
2817 	*keylenp = keylen;
2818 	if (i == FAIL)
2819 	    return map_result_fail;
2820 	return map_result_retry;
2821     }
2822 
2823     *keylenp = keylen;
2824     return map_result_nomatch;
2825 }
2826 
2827 /*
2828  * unget one character (can only be done once!)
2829  */
2830     void
2831 vungetc(int c)
2832 {
2833     old_char = c;
2834     old_mod_mask = mod_mask;
2835     old_mouse_row = mouse_row;
2836     old_mouse_col = mouse_col;
2837 }
2838 
2839 /*
2840  * Get a byte:
2841  * 1. from the stuffbuffer
2842  *	This is used for abbreviated commands like "D" -> "d$".
2843  *	Also used to redo a command for ".".
2844  * 2. from the typeahead buffer
2845  *	Stores text obtained previously but not used yet.
2846  *	Also stores the result of mappings.
2847  *	Also used for the ":normal" command.
2848  * 3. from the user
2849  *	This may do a blocking wait if "advance" is TRUE.
2850  *
2851  * if "advance" is TRUE (vgetc()):
2852  *	Really get the character.
2853  *	KeyTyped is set to TRUE in the case the user typed the key.
2854  *	KeyStuffed is TRUE if the character comes from the stuff buffer.
2855  * if "advance" is FALSE (vpeekc()):
2856  *	Just look whether there is a character available.
2857  *	Return NUL if not.
2858  *
2859  * When "no_mapping" is zero, checks for mappings in the current mode.
2860  * Only returns one byte (of a multi-byte character).
2861  * K_SPECIAL and CSI may be escaped, need to get two more bytes then.
2862  */
2863     static int
2864 vgetorpeek(int advance)
2865 {
2866     int		c, c1;
2867     int		timedout = FALSE;	// waited for more than 1 second
2868 					// for mapping to complete
2869     int		mapdepth = 0;		// check for recursive mapping
2870     int		mode_deleted = FALSE;   // set when mode has been deleted
2871 #ifdef FEAT_CMDL_INFO
2872     int		new_wcol, new_wrow;
2873 #endif
2874 #ifdef FEAT_GUI
2875     int		shape_changed = FALSE;  // adjusted cursor shape
2876 #endif
2877     int		n;
2878     int		old_wcol, old_wrow;
2879     int		wait_tb_len;
2880 
2881     /*
2882      * This function doesn't work very well when called recursively.  This may
2883      * happen though, because of:
2884      * 1. The call to add_to_showcmd().	char_avail() is then used to check if
2885      * there is a character available, which calls this function.  In that
2886      * case we must return NUL, to indicate no character is available.
2887      * 2. A GUI callback function writes to the screen, causing a
2888      * wait_return().
2889      * Using ":normal" can also do this, but it saves the typeahead buffer,
2890      * thus it should be OK.  But don't get a key from the user then.
2891      */
2892     if (vgetc_busy > 0 && ex_normal_busy == 0)
2893 	return NUL;
2894 
2895     ++vgetc_busy;
2896 
2897     if (advance)
2898 	KeyStuffed = FALSE;
2899 
2900     init_typebuf();
2901     start_stuff();
2902     if (advance && typebuf.tb_maplen == 0)
2903 	reg_executing = 0;
2904     do
2905     {
2906 /*
2907  * get a character: 1. from the stuffbuffer
2908  */
2909 	if (typeahead_char != 0)
2910 	{
2911 	    c = typeahead_char;
2912 	    if (advance)
2913 		typeahead_char = 0;
2914 	}
2915 	else
2916 	    c = read_readbuffers(advance);
2917 	if (c != NUL && !got_int)
2918 	{
2919 	    if (advance)
2920 	    {
2921 		// KeyTyped = FALSE;  When the command that stuffed something
2922 		// was typed, behave like the stuffed command was typed.
2923 		// needed for CTRL-W CTRL-] to open a fold, for example.
2924 		KeyStuffed = TRUE;
2925 	    }
2926 	    if (typebuf.tb_no_abbr_cnt == 0)
2927 		typebuf.tb_no_abbr_cnt = 1;	// no abbreviations now
2928 	}
2929 	else
2930 	{
2931 	    /*
2932 	     * Loop until we either find a matching mapped key, or we
2933 	     * are sure that it is not a mapped key.
2934 	     * If a mapped key sequence is found we go back to the start to
2935 	     * try re-mapping.
2936 	     */
2937 	    for (;;)
2938 	    {
2939 		long	wait_time;
2940 		int	keylen = 0;
2941 #ifdef FEAT_CMDL_INFO
2942 		int	showcmd_idx;
2943 #endif
2944 		/*
2945 		 * ui_breakcheck() is slow, don't use it too often when
2946 		 * inside a mapping.  But call it each time for typed
2947 		 * characters.
2948 		 */
2949 		if (typebuf.tb_maplen)
2950 		    line_breakcheck();
2951 		else
2952 		    ui_breakcheck();		// check for CTRL-C
2953 		if (got_int)
2954 		{
2955 		    // flush all input
2956 		    c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L);
2957 
2958 		    /*
2959 		     * If inchar() returns TRUE (script file was active) or we
2960 		     * are inside a mapping, get out of Insert mode.
2961 		     * Otherwise we behave like having gotten a CTRL-C.
2962 		     * As a result typing CTRL-C in insert mode will
2963 		     * really insert a CTRL-C.
2964 		     */
2965 		    if ((c || typebuf.tb_maplen)
2966 					      && (State & (INSERT + CMDLINE)))
2967 			c = ESC;
2968 		    else
2969 			c = Ctrl_C;
2970 		    flush_buffers(FLUSH_INPUT);	// flush all typeahead
2971 
2972 		    if (advance)
2973 		    {
2974 			// Also record this character, it might be needed to
2975 			// get out of Insert mode.
2976 			*typebuf.tb_buf = c;
2977 			gotchars(typebuf.tb_buf, 1);
2978 		    }
2979 		    cmd_silent = FALSE;
2980 
2981 		    break;
2982 		}
2983 		else if (typebuf.tb_len > 0)
2984 		{
2985 		    /*
2986 		     * Check for a mapping in "typebuf".
2987 		     */
2988 		    map_result_T result = handle_mapping(
2989 						&keylen, &timedout, &mapdepth);
2990 
2991 		    if (result == map_result_retry)
2992 			// try mapping again
2993 			continue;
2994 		    if (result == map_result_fail)
2995 		    {
2996 			// failed, use the outer loop
2997 			c = -1;
2998 			break;
2999 		    }
3000 		    if (result == map_result_get)
3001 		    {
3002 /*
3003  * get a character: 2. from the typeahead buffer
3004  */
3005 			c = typebuf.tb_buf[typebuf.tb_off];
3006 			if (advance)	// remove chars from tb_buf
3007 			{
3008 			    cmd_silent = (typebuf.tb_silent > 0);
3009 			    if (typebuf.tb_maplen > 0)
3010 				KeyTyped = FALSE;
3011 			    else
3012 			    {
3013 				KeyTyped = TRUE;
3014 				// write char to script file(s)
3015 				gotchars(typebuf.tb_buf
3016 						 + typebuf.tb_off, 1);
3017 			    }
3018 			    KeyNoremap = typebuf.tb_noremap[
3019 						      typebuf.tb_off];
3020 			    del_typebuf(1, 0);
3021 			}
3022 			break;
3023 		    }
3024 
3025 		    // not enough characters, get more
3026 		}
3027 
3028 /*
3029  * get a character: 3. from the user - handle <Esc> in Insert mode
3030  */
3031 		/*
3032 		 * Special case: if we get an <ESC> in insert mode and there
3033 		 * are no more characters at once, we pretend to go out of
3034 		 * insert mode.  This prevents the one second delay after
3035 		 * typing an <ESC>.  If we get something after all, we may
3036 		 * have to redisplay the mode. That the cursor is in the wrong
3037 		 * place does not matter.
3038 		 */
3039 		c = 0;
3040 #ifdef FEAT_CMDL_INFO
3041 		new_wcol = curwin->w_wcol;
3042 		new_wrow = curwin->w_wrow;
3043 #endif
3044 		if (	   advance
3045 			&& typebuf.tb_len == 1
3046 			&& typebuf.tb_buf[typebuf.tb_off] == ESC
3047 			&& !no_mapping
3048 			&& ex_normal_busy == 0
3049 			&& typebuf.tb_maplen == 0
3050 			&& (State & INSERT)
3051 			&& (p_timeout
3052 			    || (keylen == KEYLEN_PART_KEY && p_ttimeout))
3053 			&& (c = inchar(typebuf.tb_buf + typebuf.tb_off
3054 					       + typebuf.tb_len, 3, 25L)) == 0)
3055 		{
3056 		    colnr_T	col = 0, vcol;
3057 		    char_u	*ptr;
3058 
3059 		    if (mode_displayed)
3060 		    {
3061 			unshowmode(TRUE);
3062 			mode_deleted = TRUE;
3063 		    }
3064 #ifdef FEAT_GUI
3065 		    // may show a different cursor shape
3066 		    if (gui.in_use && State != NORMAL && !cmd_silent)
3067 		    {
3068 			int	    save_State;
3069 
3070 			save_State = State;
3071 			State = NORMAL;
3072 			gui_update_cursor(TRUE, FALSE);
3073 			State = save_State;
3074 			shape_changed = TRUE;
3075 		    }
3076 #endif
3077 		    validate_cursor();
3078 		    old_wcol = curwin->w_wcol;
3079 		    old_wrow = curwin->w_wrow;
3080 
3081 		    // move cursor left, if possible
3082 		    if (curwin->w_cursor.col != 0)
3083 		    {
3084 			if (curwin->w_wcol > 0)
3085 			{
3086 			    if (did_ai)
3087 			    {
3088 				/*
3089 				 * We are expecting to truncate the trailing
3090 				 * white-space, so find the last non-white
3091 				 * character -- webb
3092 				 */
3093 				col = vcol = curwin->w_wcol = 0;
3094 				ptr = ml_get_curline();
3095 				while (col < curwin->w_cursor.col)
3096 				{
3097 				    if (!VIM_ISWHITE(ptr[col]))
3098 					curwin->w_wcol = vcol;
3099 				    vcol += lbr_chartabsize(ptr, ptr + col,
3100 							       (colnr_T)vcol);
3101 				    if (has_mbyte)
3102 					col += (*mb_ptr2len)(ptr + col);
3103 				    else
3104 					++col;
3105 				}
3106 				curwin->w_wrow = curwin->w_cline_row
3107 					   + curwin->w_wcol / curwin->w_width;
3108 				curwin->w_wcol %= curwin->w_width;
3109 				curwin->w_wcol += curwin_col_off();
3110 				col = 0;	// no correction needed
3111 			    }
3112 			    else
3113 			    {
3114 				--curwin->w_wcol;
3115 				col = curwin->w_cursor.col - 1;
3116 			    }
3117 			}
3118 			else if (curwin->w_p_wrap && curwin->w_wrow)
3119 			{
3120 			    --curwin->w_wrow;
3121 			    curwin->w_wcol = curwin->w_width - 1;
3122 			    col = curwin->w_cursor.col - 1;
3123 			}
3124 			if (has_mbyte && col > 0 && curwin->w_wcol > 0)
3125 			{
3126 			    // Correct when the cursor is on the right halve
3127 			    // of a double-wide character.
3128 			    ptr = ml_get_curline();
3129 			    col -= (*mb_head_off)(ptr, ptr + col);
3130 			    if ((*mb_ptr2cells)(ptr + col) > 1)
3131 				--curwin->w_wcol;
3132 			}
3133 		    }
3134 		    setcursor();
3135 		    out_flush();
3136 #ifdef FEAT_CMDL_INFO
3137 		    new_wcol = curwin->w_wcol;
3138 		    new_wrow = curwin->w_wrow;
3139 #endif
3140 		    curwin->w_wcol = old_wcol;
3141 		    curwin->w_wrow = old_wrow;
3142 		}
3143 		if (c < 0)
3144 		    continue;	// end of input script reached
3145 
3146 		// Allow mapping for just typed characters. When we get here c
3147 		// is the number of extra bytes and typebuf.tb_len is 1.
3148 		for (n = 1; n <= c; ++n)
3149 		    typebuf.tb_noremap[typebuf.tb_off + n] = RM_YES;
3150 		typebuf.tb_len += c;
3151 
3152 		// buffer full, don't map
3153 		if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
3154 		{
3155 		    timedout = TRUE;
3156 		    continue;
3157 		}
3158 
3159 		if (ex_normal_busy > 0)
3160 		{
3161 #ifdef FEAT_CMDWIN
3162 		    static int tc = 0;
3163 #endif
3164 
3165 		    // No typeahead left and inside ":normal".  Must return
3166 		    // something to avoid getting stuck.  When an incomplete
3167 		    // mapping is present, behave like it timed out.
3168 		    if (typebuf.tb_len > 0)
3169 		    {
3170 			timedout = TRUE;
3171 			continue;
3172 		    }
3173 
3174 		    // When 'insertmode' is set, ESC just beeps in Insert
3175 		    // mode.  Use CTRL-L to make edit() return.
3176 		    // For the command line only CTRL-C always breaks it.
3177 		    // For the cmdline window: Alternate between ESC and
3178 		    // CTRL-C: ESC for most situations and CTRL-C to close the
3179 		    // cmdline window.
3180 		    if (p_im && (State & INSERT))
3181 			c = Ctrl_L;
3182 #ifdef FEAT_TERMINAL
3183 		    else if (terminal_is_active())
3184 			c = K_CANCEL;
3185 #endif
3186 		    else if ((State & CMDLINE)
3187 #ifdef FEAT_CMDWIN
3188 			    || (cmdwin_type > 0 && tc == ESC)
3189 #endif
3190 			    )
3191 			c = Ctrl_C;
3192 		    else
3193 			c = ESC;
3194 #ifdef FEAT_CMDWIN
3195 		    tc = c;
3196 #endif
3197 		    // return from main_loop()
3198 		    if (pending_exmode_active)
3199 			exmode_active = EXMODE_NORMAL;
3200 
3201 		    break;
3202 		}
3203 
3204 /*
3205  * get a character: 3. from the user - update display
3206  */
3207 		// In insert mode a screen update is skipped when characters
3208 		// are still available.  But when those available characters
3209 		// are part of a mapping, and we are going to do a blocking
3210 		// wait here.  Need to update the screen to display the
3211 		// changed text so far. Also for when 'lazyredraw' is set and
3212 		// redrawing was postponed because there was something in the
3213 		// input buffer (e.g., termresponse).
3214 		if (((State & INSERT) != 0 || p_lz) && (State & CMDLINE) == 0
3215 			  && advance && must_redraw != 0 && !need_wait_return)
3216 		{
3217 		    update_screen(0);
3218 		    setcursor(); // put cursor back where it belongs
3219 		}
3220 
3221 		/*
3222 		 * If we have a partial match (and are going to wait for more
3223 		 * input from the user), show the partially matched characters
3224 		 * to the user with showcmd.
3225 		 */
3226 #ifdef FEAT_CMDL_INFO
3227 		showcmd_idx = 0;
3228 #endif
3229 		c1 = 0;
3230 		if (typebuf.tb_len > 0 && advance && !exmode_active)
3231 		{
3232 		    if (((State & (NORMAL | INSERT)) || State == LANGMAP)
3233 			    && State != HITRETURN)
3234 		    {
3235 			// this looks nice when typing a dead character map
3236 			if (State & INSERT
3237 			    && ptr2cells(typebuf.tb_buf + typebuf.tb_off
3238 						   + typebuf.tb_len - 1) == 1)
3239 			{
3240 			    edit_putchar(typebuf.tb_buf[typebuf.tb_off
3241 						+ typebuf.tb_len - 1], FALSE);
3242 			    setcursor(); // put cursor back where it belongs
3243 			    c1 = 1;
3244 			}
3245 #ifdef FEAT_CMDL_INFO
3246 			// need to use the col and row from above here
3247 			old_wcol = curwin->w_wcol;
3248 			old_wrow = curwin->w_wrow;
3249 			curwin->w_wcol = new_wcol;
3250 			curwin->w_wrow = new_wrow;
3251 			push_showcmd();
3252 			if (typebuf.tb_len > SHOWCMD_COLS)
3253 			    showcmd_idx = typebuf.tb_len - SHOWCMD_COLS;
3254 			while (showcmd_idx < typebuf.tb_len)
3255 			    (void)add_to_showcmd(
3256 			       typebuf.tb_buf[typebuf.tb_off + showcmd_idx++]);
3257 			curwin->w_wcol = old_wcol;
3258 			curwin->w_wrow = old_wrow;
3259 #endif
3260 		    }
3261 
3262 		    // this looks nice when typing a dead character map
3263 		    if ((State & CMDLINE)
3264 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
3265 			    && cmdline_star == 0
3266 #endif
3267 			    && ptr2cells(typebuf.tb_buf + typebuf.tb_off
3268 						   + typebuf.tb_len - 1) == 1)
3269 		    {
3270 			putcmdline(typebuf.tb_buf[typebuf.tb_off
3271 						+ typebuf.tb_len - 1], FALSE);
3272 			c1 = 1;
3273 		    }
3274 		}
3275 
3276 /*
3277  * get a character: 3. from the user - get it
3278  */
3279 		if (typebuf.tb_len == 0)
3280 		    // timedout may have been set while waiting for a mapping
3281 		    // that has a <Nop> RHS.
3282 		    timedout = FALSE;
3283 
3284 		if (advance)
3285 		{
3286 		    if (typebuf.tb_len == 0
3287 			    || !(p_timeout
3288 				 || (p_ttimeout && keylen == KEYLEN_PART_KEY)))
3289 			// blocking wait
3290 			wait_time = -1L;
3291 		    else if (keylen == KEYLEN_PART_KEY && p_ttm >= 0)
3292 			wait_time = p_ttm;
3293 		    else
3294 			wait_time = p_tm;
3295 		}
3296 		else
3297 		    wait_time = 0;
3298 
3299 		wait_tb_len = typebuf.tb_len;
3300 		c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
3301 			typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
3302 			wait_time);
3303 
3304 #ifdef FEAT_CMDL_INFO
3305 		if (showcmd_idx != 0)
3306 		    pop_showcmd();
3307 #endif
3308 		if (c1 == 1)
3309 		{
3310 		    if (State & INSERT)
3311 			edit_unputchar();
3312 		    if (State & CMDLINE)
3313 			unputcmdline();
3314 		    else
3315 			setcursor();	// put cursor back where it belongs
3316 		}
3317 
3318 		if (c < 0)
3319 		    continue;		// end of input script reached
3320 		if (c == NUL)		// no character available
3321 		{
3322 		    if (!advance)
3323 			break;
3324 		    if (wait_tb_len > 0)	// timed out
3325 		    {
3326 			timedout = TRUE;
3327 			continue;
3328 		    }
3329 		}
3330 		else
3331 		{	    // allow mapping for just typed characters
3332 		    while (typebuf.tb_buf[typebuf.tb_off
3333 						     + typebuf.tb_len] != NUL)
3334 			typebuf.tb_noremap[typebuf.tb_off
3335 						 + typebuf.tb_len++] = RM_YES;
3336 #ifdef HAVE_INPUT_METHOD
3337 		    // Get IM status right after getting keys, not after the
3338 		    // timeout for a mapping (focus may be lost by then).
3339 		    vgetc_im_active = im_get_status();
3340 #endif
3341 		}
3342 	    }	    // for (;;)
3343 	}	// if (!character from stuffbuf)
3344 
3345 	// if advance is FALSE don't loop on NULs
3346     } while ((c < 0 && c != K_CANCEL) || (advance && c == NUL));
3347 
3348     /*
3349      * The "INSERT" message is taken care of here:
3350      *	 if we return an ESC to exit insert mode, the message is deleted
3351      *	 if we don't return an ESC but deleted the message before, redisplay it
3352      */
3353     if (advance && p_smd && msg_silent == 0 && (State & INSERT))
3354     {
3355 	if (c == ESC && !mode_deleted && !no_mapping && mode_displayed)
3356 	{
3357 	    if (typebuf.tb_len && !KeyTyped)
3358 		redraw_cmdline = TRUE;	    // delete mode later
3359 	    else
3360 		unshowmode(FALSE);
3361 	}
3362 	else if (c != ESC && mode_deleted)
3363 	{
3364 	    if (typebuf.tb_len && !KeyTyped)
3365 		redraw_cmdline = TRUE;	    // show mode later
3366 	    else
3367 		showmode();
3368 	}
3369     }
3370 #ifdef FEAT_GUI
3371     // may unshow different cursor shape
3372     if (gui.in_use && shape_changed)
3373 	gui_update_cursor(TRUE, FALSE);
3374 #endif
3375     if (timedout && c == ESC)
3376     {
3377 	char_u nop_buf[3];
3378 
3379 	// When recording there will be no timeout.  Add a <Nop> after the ESC
3380 	// to avoid that it forms a key code with following characters.
3381 	nop_buf[0] = K_SPECIAL;
3382 	nop_buf[1] = KS_EXTRA;
3383 	nop_buf[2] = KE_NOP;
3384 	gotchars(nop_buf, 3);
3385     }
3386 
3387     --vgetc_busy;
3388 
3389     return c;
3390 }
3391 
3392 /*
3393  * inchar() - get one character from
3394  *	1. a scriptfile
3395  *	2. the keyboard
3396  *
3397  *  As many characters as we can get (up to 'maxlen') are put in "buf" and
3398  *  NUL terminated (buffer length must be 'maxlen' + 1).
3399  *  Minimum for "maxlen" is 3!!!!
3400  *
3401  *  "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into
3402  *  it.  When typebuf.tb_change_cnt changes (e.g., when a message is received
3403  *  from a remote client) "buf" can no longer be used.  "tb_change_cnt" is 0
3404  *  otherwise.
3405  *
3406  *  If we got an interrupt all input is read until none is available.
3407  *
3408  *  If wait_time == 0  there is no waiting for the char.
3409  *  If wait_time == n  we wait for n msec for a character to arrive.
3410  *  If wait_time == -1 we wait forever for a character to arrive.
3411  *
3412  *  Return the number of obtained characters.
3413  *  Return -1 when end of input script reached.
3414  */
3415     static int
3416 inchar(
3417     char_u	*buf,
3418     int		maxlen,
3419     long	wait_time)	    // milli seconds
3420 {
3421     int		len = 0;	    // init for GCC
3422     int		retesc = FALSE;	    // return ESC with gotint
3423     int		script_char;
3424     int		tb_change_cnt = typebuf.tb_change_cnt;
3425 
3426     if (wait_time == -1L || wait_time > 100L)  // flush output before waiting
3427     {
3428 	cursor_on();
3429 	out_flush_cursor(FALSE, FALSE);
3430 #if defined(FEAT_GUI) && defined(FEAT_MOUSESHAPE)
3431 	if (gui.in_use && postponed_mouseshape)
3432 	    update_mouseshape(-1);
3433 #endif
3434     }
3435 
3436     /*
3437      * Don't reset these when at the hit-return prompt, otherwise a endless
3438      * recursive loop may result (write error in swapfile, hit-return, timeout
3439      * on char wait, flush swapfile, write error....).
3440      */
3441     if (State != HITRETURN)
3442     {
3443 	did_outofmem_msg = FALSE;   // display out of memory message (again)
3444 	did_swapwrite_msg = FALSE;  // display swap file write error again
3445     }
3446     undo_off = FALSE;		    // restart undo now
3447 
3448     /*
3449      * Get a character from a script file if there is one.
3450      * If interrupted: Stop reading script files, close them all.
3451      */
3452     script_char = -1;
3453     while (scriptin[curscript] != NULL && script_char < 0
3454 #ifdef FEAT_EVAL
3455 	    && !ignore_script
3456 #endif
3457 	    )
3458     {
3459 #ifdef MESSAGE_QUEUE
3460 	parse_queued_messages();
3461 #endif
3462 
3463 	if (got_int || (script_char = getc(scriptin[curscript])) < 0)
3464 	{
3465 	    // Reached EOF.
3466 	    // Careful: closescript() frees typebuf.tb_buf[] and buf[] may
3467 	    // point inside typebuf.tb_buf[].  Don't use buf[] after this!
3468 	    closescript();
3469 	    /*
3470 	     * When reading script file is interrupted, return an ESC to get
3471 	     * back to normal mode.
3472 	     * Otherwise return -1, because typebuf.tb_buf[] has changed.
3473 	     */
3474 	    if (got_int)
3475 		retesc = TRUE;
3476 	    else
3477 		return -1;
3478 	}
3479 	else
3480 	{
3481 	    buf[0] = script_char;
3482 	    len = 1;
3483 	}
3484     }
3485 
3486     if (script_char < 0)	// did not get a character from script
3487     {
3488 	/*
3489 	 * If we got an interrupt, skip all previously typed characters and
3490 	 * return TRUE if quit reading script file.
3491 	 * Stop reading typeahead when a single CTRL-C was read,
3492 	 * fill_input_buf() returns this when not able to read from stdin.
3493 	 * Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
3494 	 * and buf may be pointing inside typebuf.tb_buf[].
3495 	 */
3496 	if (got_int)
3497 	{
3498 #define DUM_LEN MAXMAPLEN * 3 + 3
3499 	    char_u	dum[DUM_LEN + 1];
3500 
3501 	    for (;;)
3502 	    {
3503 		len = ui_inchar(dum, DUM_LEN, 0L, 0);
3504 		if (len == 0 || (len == 1 && dum[0] == 3))
3505 		    break;
3506 	    }
3507 	    return retesc;
3508 	}
3509 
3510 	/*
3511 	 * Always flush the output characters when getting input characters
3512 	 * from the user and not just peeking.
3513 	 */
3514 	if (wait_time == -1L || wait_time > 10L)
3515 	    out_flush();
3516 
3517 	/*
3518 	 * Fill up to a third of the buffer, because each character may be
3519 	 * tripled below.
3520 	 */
3521 	len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt);
3522     }
3523 
3524     // If the typebuf was changed further down, it is like nothing was added by
3525     // this call.
3526     if (typebuf_changed(tb_change_cnt))
3527 	return 0;
3528 
3529     // Note the change in the typeahead buffer, this matters for when
3530     // vgetorpeek() is called recursively, e.g. using getchar(1) in a timer
3531     // function.
3532     if (len > 0 && ++typebuf.tb_change_cnt == 0)
3533 	typebuf.tb_change_cnt = 1;
3534 
3535     return fix_input_buffer(buf, len);
3536 }
3537 
3538 /*
3539  * Fix typed characters for use by vgetc() and check_termcode().
3540  * "buf[]" must have room to triple the number of bytes!
3541  * Returns the new length.
3542  */
3543     int
3544 fix_input_buffer(char_u *buf, int len)
3545 {
3546     int		i;
3547     char_u	*p = buf;
3548 
3549     /*
3550      * Two characters are special: NUL and K_SPECIAL.
3551      * When compiled With the GUI CSI is also special.
3552      * Replace	     NUL by K_SPECIAL KS_ZERO	 KE_FILLER
3553      * Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
3554      * Replace       CSI by K_SPECIAL KS_EXTRA   KE_CSI
3555      */
3556     for (i = len; --i >= 0; ++p)
3557     {
3558 #ifdef FEAT_GUI
3559 	// When the GUI is used any character can come after a CSI, don't
3560 	// escape it.
3561 	if (gui.in_use && p[0] == CSI && i >= 2)
3562 	{
3563 	    p += 2;
3564 	    i -= 2;
3565 	}
3566 # ifndef MSWIN
3567 	// When the GUI is not used CSI needs to be escaped.
3568 	else if (!gui.in_use && p[0] == CSI)
3569 	{
3570 	    mch_memmove(p + 3, p + 1, (size_t)i);
3571 	    *p++ = K_SPECIAL;
3572 	    *p++ = KS_EXTRA;
3573 	    *p = (int)KE_CSI;
3574 	    len += 2;
3575 	}
3576 # endif
3577 	else
3578 #endif
3579 	if (p[0] == NUL || (p[0] == K_SPECIAL
3580 		    // timeout may generate K_CURSORHOLD
3581 		    && (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD)
3582 #if defined(MSWIN) && (!defined(FEAT_GUI) || defined(VIMDLL))
3583 		    // Win32 console passes modifiers
3584 		    && (
3585 # ifdef VIMDLL
3586 			gui.in_use ||
3587 # endif
3588 			(i < 2 || p[1] != KS_MODIFIER))
3589 #endif
3590 		    ))
3591 	{
3592 	    mch_memmove(p + 3, p + 1, (size_t)i);
3593 	    p[2] = K_THIRD(p[0]);
3594 	    p[1] = K_SECOND(p[0]);
3595 	    p[0] = K_SPECIAL;
3596 	    p += 2;
3597 	    len += 2;
3598 	}
3599     }
3600     *p = NUL;		// add trailing NUL
3601     return len;
3602 }
3603 
3604 #if defined(USE_INPUT_BUF) || defined(PROTO)
3605 /*
3606  * Return TRUE when bytes are in the input buffer or in the typeahead buffer.
3607  * Normally the input buffer would be sufficient, but the server_to_input_buf()
3608  * or feedkeys() may insert characters in the typeahead buffer while we are
3609  * waiting for input to arrive.
3610  */
3611     int
3612 input_available(void)
3613 {
3614     return (!vim_is_input_buf_empty()
3615 # if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL)
3616 	    || typebuf_was_filled
3617 # endif
3618 	    );
3619 }
3620 #endif
3621 
3622 /*
3623  * Function passed to do_cmdline() to get the command after a <Cmd> key from
3624  * typeahead.
3625  */
3626     char_u *
3627 getcmdkeycmd(
3628 	int		promptc UNUSED,
3629 	void		*cookie UNUSED,
3630 	int		indent UNUSED,
3631 	getline_opt_T	do_concat UNUSED)
3632 {
3633     garray_T	line_ga;
3634     int		c1 = -1;
3635     int		c2;
3636     int		cmod = 0;
3637     int		aborted = FALSE;
3638 
3639     ga_init2(&line_ga, 1, 32);
3640 
3641     // no mapping for these characters
3642     no_mapping++;
3643 
3644     got_int = FALSE;
3645     while (c1 != NUL && !aborted)
3646     {
3647 	if (ga_grow(&line_ga, 32) != OK)
3648 	{
3649 	    aborted = TRUE;
3650 	    break;
3651 	}
3652 
3653 	if (vgetorpeek(FALSE) == NUL)
3654 	{
3655 	    // incomplete <Cmd> is an error, because there is not much the user
3656 	    // could do in this state.
3657 	    emsg(_(e_cmd_mapping_must_end_with_cr));
3658 	    aborted = TRUE;
3659 	    break;
3660 	}
3661 
3662 	// Get one character at a time.
3663 	c1 = vgetorpeek(TRUE);
3664 
3665 	// Get two extra bytes for special keys
3666 	if (c1 == K_SPECIAL)
3667 	{
3668 	    c1 = vgetorpeek(TRUE);
3669 	    c2 = vgetorpeek(TRUE);
3670 	    if (c1 == KS_MODIFIER)
3671 	    {
3672 		cmod = c2;
3673 		continue;
3674 	    }
3675 	    c1 = TO_SPECIAL(c1, c2);
3676 	}
3677 	if (c1 == Ctrl_V)
3678 	{
3679 	    // CTRL-V is followed by octal, hex or other characters, reverses
3680 	    // what AppendToRedobuffLit() does.
3681 	    no_reduce_keys = TRUE;  //  don't merge modifyOtherKeys
3682 	    c1 = get_literal(TRUE);
3683 	    no_reduce_keys = FALSE;
3684 	}
3685 
3686 	if (got_int)
3687 	    aborted = TRUE;
3688 	else if (c1 == '\r' || c1 == '\n')
3689 	    c1 = NUL;  // end the line
3690 	else if (c1 == ESC)
3691 	    aborted = TRUE;
3692 	else if (c1 == K_COMMAND)
3693 	{
3694 	    // give a nicer error message for this special case
3695 	    emsg(_(e_cmd_mapping_must_end_with_cr_before_second_cmd));
3696 	    aborted = TRUE;
3697 	}
3698 	else if (IS_SPECIAL(c1))
3699 	{
3700 	    if (c1 == K_SNR)
3701 		ga_concat(&line_ga, (char_u *)"<SNR>");
3702 	    else
3703 	    {
3704 		semsg(e_cmd_maping_must_not_include_str_key,
3705 					       get_special_key_name(c1, cmod));
3706 		aborted = TRUE;
3707 	    }
3708 	}
3709 	else
3710 	    ga_append(&line_ga, (char)c1);
3711 
3712 	cmod = 0;
3713     }
3714 
3715     no_mapping--;
3716 
3717     if (aborted)
3718 	ga_clear(&line_ga);
3719 
3720     return (char_u *)line_ga.ga_data;
3721 }
3722