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