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