xref: /vim-8.2.3635/src/message.c (revision f3caeb63)
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  * message.c: functions for displaying messages on the command line
12  */
13 
14 #define MESSAGE_FILE		// don't include prototype for smsg()
15 #define USING_FLOAT_STUFF
16 
17 #include "vim.h"
18 
19 static void add_msg_hist(char_u *s, int len, int attr);
20 static void hit_return_msg(void);
21 static void msg_home_replace_attr(char_u *fname, int attr);
22 static void msg_puts_attr_len(char *str, int maxlen, int attr);
23 static void msg_puts_display(char_u *str, int maxlen, int attr, int recurse);
24 static void msg_scroll_up(void);
25 static void inc_msg_scrolled(void);
26 static void store_sb_text(char_u **sb_str, char_u *s, int attr, int *sb_col, int finish);
27 static void t_puts(int *t_col, char_u *t_s, char_u *s, int attr);
28 static void msg_puts_printf(char_u *str, int maxlen);
29 static int do_more_prompt(int typed_char);
30 static void msg_screen_putchar(int c, int attr);
31 static void msg_moremsg(int full);
32 static int  msg_check_screen(void);
33 static void redir_write(char_u *s, int maxlen);
34 #ifdef FEAT_CON_DIALOG
35 static char_u *msg_show_console_dialog(char_u *message, char_u *buttons, int dfltbutton);
36 static int	confirm_msg_used = FALSE;	// displaying confirm_msg
37 static char_u	*confirm_msg = NULL;		// ":confirm" message
38 static char_u	*confirm_msg_tail;		// tail of confirm_msg
39 static void display_confirm_msg(void);
40 #endif
41 #ifdef FEAT_JOB_CHANNEL
42 static int emsg_to_channel_log = FALSE;
43 #endif
44 
45 struct msg_hist
46 {
47     struct msg_hist	*next;
48     char_u		*msg;
49     int			attr;
50 };
51 
52 static struct msg_hist *first_msg_hist = NULL;
53 static struct msg_hist *last_msg_hist = NULL;
54 static int msg_hist_len = 0;
55 
56 static FILE *verbose_fd = NULL;
57 static int  verbose_did_open = FALSE;
58 
59 /*
60  * When writing messages to the screen, there are many different situations.
61  * A number of variables is used to remember the current state:
62  * msg_didany	    TRUE when messages were written since the last time the
63  *		    user reacted to a prompt.
64  *		    Reset: After hitting a key for the hit-return prompt,
65  *		    hitting <CR> for the command line or input().
66  *		    Set: When any message is written to the screen.
67  * msg_didout	    TRUE when something was written to the current line.
68  *		    Reset: When advancing to the next line, when the current
69  *		    text can be overwritten.
70  *		    Set: When any message is written to the screen.
71  * msg_nowait	    No extra delay for the last drawn message.
72  *		    Used in normal_cmd() before the mode message is drawn.
73  * emsg_on_display  There was an error message recently.  Indicates that there
74  *		    should be a delay before redrawing.
75  * msg_scroll	    The next message should not overwrite the current one.
76  * msg_scrolled	    How many lines the screen has been scrolled (because of
77  *		    messages).  Used in update_screen() to scroll the screen
78  *		    back.  Incremented each time the screen scrolls a line.
79  * msg_scrolled_ign  TRUE when msg_scrolled is non-zero and msg_puts_attr()
80  *		    writes something without scrolling should not make
81  *		    need_wait_return to be set.  This is a hack to make ":ts"
82  *		    work without an extra prompt.
83  * lines_left	    Number of lines available for messages before the
84  *		    more-prompt is to be given.  -1 when not set.
85  * need_wait_return TRUE when the hit-return prompt is needed.
86  *		    Reset: After giving the hit-return prompt, when the user
87  *		    has answered some other prompt.
88  *		    Set: When the ruler or typeahead display is overwritten,
89  *		    scrolling the screen for some message.
90  * keep_msg	    Message to be displayed after redrawing the screen, in
91  *		    main_loop().
92  *		    This is an allocated string or NULL when not used.
93  */
94 
95 /*
96  * msg(s) - displays the string 's' on the status line
97  * When terminal not initialized (yet) mch_errmsg(..) is used.
98  * return TRUE if wait_return not called
99  */
100     int
101 msg(char *s)
102 {
103     return msg_attr_keep(s, 0, FALSE);
104 }
105 
106 /*
107  * Like msg() but keep it silent when 'verbosefile' is set.
108  */
109     int
110 verb_msg(char *s)
111 {
112     int		n;
113 
114     verbose_enter();
115     n = msg_attr_keep(s, 0, FALSE);
116     verbose_leave();
117 
118     return n;
119 }
120 
121     int
122 msg_attr(char *s, int attr)
123 {
124     return msg_attr_keep(s, attr, FALSE);
125 }
126 
127     int
128 msg_attr_keep(
129     char	*s,
130     int		attr,
131     int		keep)	    // TRUE: set keep_msg if it doesn't scroll
132 {
133     static int	entered = 0;
134     int		retval;
135     char_u	*buf = NULL;
136 
137     // Skip messages not matching ":filter pattern".
138     // Don't filter when there is an error.
139     if (!emsg_on_display && message_filtered((char_u *)s))
140 	return TRUE;
141 
142 #ifdef FEAT_EVAL
143     if (attr == 0)
144 	set_vim_var_string(VV_STATUSMSG, (char_u *)s, -1);
145 #endif
146 
147     /*
148      * It is possible that displaying a messages causes a problem (e.g.,
149      * when redrawing the window), which causes another message, etc..	To
150      * break this loop, limit the recursiveness to 3 levels.
151      */
152     if (entered >= 3)
153 	return TRUE;
154     ++entered;
155 
156     // Add message to history (unless it's a repeated kept message or a
157     // truncated message)
158     if ((char_u *)s != keep_msg
159 	    || (*s != '<'
160 		&& last_msg_hist != NULL
161 		&& last_msg_hist->msg != NULL
162 		&& STRCMP(s, last_msg_hist->msg)))
163 	add_msg_hist((char_u *)s, -1, attr);
164 
165 #ifdef FEAT_JOB_CHANNEL
166     if (emsg_to_channel_log)
167 	// Write message in the channel log.
168 	ch_log(NULL, "ERROR: %s", (char *)s);
169 #endif
170 
171     // Truncate the message if needed.
172     msg_start();
173     buf = msg_strtrunc((char_u *)s, FALSE);
174     if (buf != NULL)
175 	s = (char *)buf;
176 
177     msg_outtrans_attr((char_u *)s, attr);
178     msg_clr_eos();
179     retval = msg_end();
180 
181     if (keep && retval && vim_strsize((char_u *)s)
182 			    < (int)(Rows - cmdline_row - 1) * Columns + sc_col)
183 	set_keep_msg((char_u *)s, 0);
184 
185     vim_free(buf);
186     --entered;
187     return retval;
188 }
189 
190 /*
191  * Truncate a string such that it can be printed without causing a scroll.
192  * Returns an allocated string or NULL when no truncating is done.
193  */
194     char_u *
195 msg_strtrunc(
196     char_u	*s,
197     int		force)	    // always truncate
198 {
199     char_u	*buf = NULL;
200     int		len;
201     int		room;
202 
203     // May truncate message to avoid a hit-return prompt
204     if ((!msg_scroll && !need_wait_return && shortmess(SHM_TRUNCALL)
205 			       && !exmode_active && msg_silent == 0) || force)
206     {
207 	len = vim_strsize(s);
208 	if (msg_scrolled != 0)
209 	    // Use all the columns.
210 	    room = (int)(Rows - msg_row) * Columns - 1;
211 	else
212 	    // Use up to 'showcmd' column.
213 	    room = (int)(Rows - msg_row - 1) * Columns + sc_col - 1;
214 	if (len > room && room > 0)
215 	{
216 	    if (enc_utf8)
217 		// may have up to 18 bytes per cell (6 per char, up to two
218 		// composing chars)
219 		len = (room + 2) * 18;
220 	    else if (enc_dbcs == DBCS_JPNU)
221 		// may have up to 2 bytes per cell for euc-jp
222 		len = (room + 2) * 2;
223 	    else
224 		len = room + 2;
225 	    buf = alloc(len);
226 	    if (buf != NULL)
227 		trunc_string(s, buf, room, len);
228 	}
229     }
230     return buf;
231 }
232 
233 /*
234  * Truncate a string "s" to "buf" with cell width "room".
235  * "s" and "buf" may be equal.
236  */
237     void
238 trunc_string(
239     char_u	*s,
240     char_u	*buf,
241     int		room_in,
242     int		buflen)
243 {
244     size_t	room = room_in - 3; // "..." takes 3 chars
245     size_t	half;
246     size_t	len = 0;
247     int		e;
248     int		i;
249     int		n;
250 
251     if (*s == NUL)
252     {
253 	if (buflen > 0)
254 	    *buf = NUL;
255 	return;
256     }
257 
258     if (room_in < 3)
259 	room = 0;
260     half = room / 2;
261 
262     // First part: Start of the string.
263     for (e = 0; len < half && e < buflen; ++e)
264     {
265 	if (s[e] == NUL)
266 	{
267 	    // text fits without truncating!
268 	    buf[e] = NUL;
269 	    return;
270 	}
271 	n = ptr2cells(s + e);
272 	if (len + n > half)
273 	    break;
274 	len += n;
275 	buf[e] = s[e];
276 	if (has_mbyte)
277 	    for (n = (*mb_ptr2len)(s + e); --n > 0; )
278 	    {
279 		if (++e == buflen)
280 		    break;
281 		buf[e] = s[e];
282 	    }
283     }
284 
285     // Last part: End of the string.
286     i = e;
287     if (enc_dbcs != 0)
288     {
289 	// For DBCS going backwards in a string is slow, but
290 	// computing the cell width isn't too slow: go forward
291 	// until the rest fits.
292 	n = vim_strsize(s + i);
293 	while (len + n > room)
294 	{
295 	    n -= ptr2cells(s + i);
296 	    i += (*mb_ptr2len)(s + i);
297 	}
298     }
299     else if (enc_utf8)
300     {
301 	// For UTF-8 we can go backwards easily.
302 	half = i = (int)STRLEN(s);
303 	for (;;)
304 	{
305 	    do
306 		half = half - utf_head_off(s, s + half - 1) - 1;
307 	    while (half > 0 && utf_iscomposing(utf_ptr2char(s + half)));
308 	    n = ptr2cells(s + half);
309 	    if (len + n > room || half == 0)
310 		break;
311 	    len += n;
312 	    i = (int)half;
313 	}
314     }
315     else
316     {
317 	for (i = (int)STRLEN(s);
318 		   i - 1 >= 0 && len + (n = ptr2cells(s + i - 1)) <= room; --i)
319 	    len += n;
320     }
321 
322 
323     if (i <= e + 3)
324     {
325 	// text fits without truncating
326 	if (s != buf)
327 	{
328 	    len = STRLEN(s);
329 	    if (len >= (size_t)buflen)
330 		len = buflen - 1;
331 	    len = len - e + 1;
332 	    if (len < 1)
333 		buf[e - 1] = NUL;
334 	    else
335 		mch_memmove(buf + e, s + e, len);
336 	}
337     }
338     else if (e + 3 < buflen)
339     {
340 	// set the middle and copy the last part
341 	mch_memmove(buf + e, "...", (size_t)3);
342 	len = STRLEN(s + i) + 1;
343 	if (len >= (size_t)buflen - e - 3)
344 	    len = buflen - e - 3 - 1;
345 	mch_memmove(buf + e + 3, s + i, len);
346 	buf[e + 3 + len - 1] = NUL;
347     }
348     else
349     {
350 	// can't fit in the "...", just truncate it
351 	buf[e - 1] = NUL;
352     }
353 }
354 
355 /*
356  * Automatic prototype generation does not understand this function.
357  * Note: Caller of smsg() and smsg_attr() must check the resulting string is
358  * shorter than IOSIZE!!!
359  */
360 #ifndef PROTO
361 
362 int vim_snprintf(char *str, size_t str_m, const char *fmt, ...);
363 
364     int
365 smsg(const char *s, ...)
366 {
367     if (IObuff == NULL)
368     {
369 	// Very early in initialisation and already something wrong, just
370 	// give the raw message so the user at least gets a hint.
371 	return msg((char *)s);
372     }
373     else
374     {
375 	va_list arglist;
376 
377 	va_start(arglist, s);
378 	vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
379 	va_end(arglist);
380 	return msg((char *)IObuff);
381     }
382 }
383 
384     int
385 smsg_attr(int attr, const char *s, ...)
386 {
387     if (IObuff == NULL)
388     {
389 	// Very early in initialisation and already something wrong, just
390 	// give the raw message so the user at least gets a hint.
391 	return msg_attr((char *)s, attr);
392     }
393     else
394     {
395 	va_list arglist;
396 
397 	va_start(arglist, s);
398 	vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
399 	va_end(arglist);
400 	return msg_attr((char *)IObuff, attr);
401     }
402 }
403 
404     int
405 smsg_attr_keep(int attr, const char *s, ...)
406 {
407     if (IObuff == NULL)
408     {
409 	// Very early in initialisation and already something wrong, just
410 	// give the raw message so the user at least gets a hint.
411 	return msg_attr_keep((char *)s, attr, TRUE);
412     }
413     else
414     {
415 	va_list arglist;
416 
417 	va_start(arglist, s);
418 	vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
419 	va_end(arglist);
420 	return msg_attr_keep((char *)IObuff, attr, TRUE);
421     }
422 }
423 
424 #endif
425 
426 /*
427  * Remember the last sourcing name/lnum used in an error message, so that it
428  * isn't printed each time when it didn't change.
429  */
430 static int	last_sourcing_lnum = 0;
431 static char_u   *last_sourcing_name = NULL;
432 
433 /*
434  * Reset the last used sourcing name/lnum.  Makes sure it is displayed again
435  * for the next error message;
436  */
437     void
438 reset_last_sourcing(void)
439 {
440     VIM_CLEAR(last_sourcing_name);
441     last_sourcing_lnum = 0;
442 }
443 
444 /*
445  * Return TRUE if "SOURCING_NAME" differs from "last_sourcing_name".
446  */
447     static int
448 other_sourcing_name(void)
449 {
450     if (SOURCING_NAME != NULL)
451     {
452 	if (last_sourcing_name != NULL)
453 	    return STRCMP(SOURCING_NAME, last_sourcing_name) != 0;
454 	return TRUE;
455     }
456     return FALSE;
457 }
458 
459 /*
460  * Get the message about the source, as used for an error message.
461  * Returns an allocated string with room for one more character.
462  * Returns NULL when no message is to be given.
463  */
464     static char_u *
465 get_emsg_source(void)
466 {
467     char_u	*Buf, *p;
468 
469     if (SOURCING_NAME != NULL && other_sourcing_name())
470     {
471 	char_u	    *sname = estack_sfile(ESTACK_NONE);
472 	char_u	    *tofree = sname;
473 
474 	if (sname == NULL)
475 	    sname = SOURCING_NAME;
476 
477 #ifdef FEAT_EVAL
478 	if (estack_compiling)
479 	    p = (char_u *)_("Error detected while compiling %s:");
480 	else
481 #endif
482 	    p = (char_u *)_("Error detected while processing %s:");
483 	Buf = alloc(STRLEN(sname) + STRLEN(p));
484 	if (Buf != NULL)
485 	    sprintf((char *)Buf, (char *)p, sname);
486 	vim_free(tofree);
487 	return Buf;
488     }
489     return NULL;
490 }
491 
492 /*
493  * Get the message about the source lnum, as used for an error message.
494  * Returns an allocated string with room for one more character.
495  * Returns NULL when no message is to be given.
496  */
497     static char_u *
498 get_emsg_lnum(void)
499 {
500     char_u	*Buf, *p;
501 
502     // lnum is 0 when executing a command from the command line
503     // argument, we don't want a line number then
504     if (SOURCING_NAME != NULL
505 	    && (other_sourcing_name() || SOURCING_LNUM != last_sourcing_lnum)
506 	    && SOURCING_LNUM != 0)
507     {
508 	p = (char_u *)_("line %4ld:");
509 	Buf = alloc(STRLEN(p) + 20);
510 	if (Buf != NULL)
511 	    sprintf((char *)Buf, (char *)p, (long)SOURCING_LNUM);
512 	return Buf;
513     }
514     return NULL;
515 }
516 
517 /*
518  * Display name and line number for the source of an error.
519  * Remember the file name and line number, so that for the next error the info
520  * is only displayed if it changed.
521  */
522     void
523 msg_source(int attr)
524 {
525     char_u	*p;
526 
527     ++no_wait_return;
528     p = get_emsg_source();
529     if (p != NULL)
530     {
531 	msg_attr((char *)p, attr);
532 	vim_free(p);
533     }
534     p = get_emsg_lnum();
535     if (p != NULL)
536     {
537 	msg_attr((char *)p, HL_ATTR(HLF_N));
538 	vim_free(p);
539 	last_sourcing_lnum = SOURCING_LNUM;  // only once for each line
540     }
541 
542     // remember the last sourcing name printed, also when it's empty
543     if (SOURCING_NAME == NULL || other_sourcing_name())
544     {
545 	vim_free(last_sourcing_name);
546 	if (SOURCING_NAME == NULL)
547 	    last_sourcing_name = NULL;
548 	else
549 	    last_sourcing_name = vim_strsave(SOURCING_NAME);
550     }
551     --no_wait_return;
552 }
553 
554 /*
555  * Return TRUE if not giving error messages right now:
556  * If "emsg_off" is set: no error messages at the moment.
557  * If "msg" is in 'debug': do error message but without side effects.
558  * If "emsg_skip" is set: never do error messages.
559  */
560     static int
561 emsg_not_now(void)
562 {
563     if ((emsg_off > 0 && vim_strchr(p_debug, 'm') == NULL
564 					  && vim_strchr(p_debug, 't') == NULL)
565 #ifdef FEAT_EVAL
566 	    || emsg_skip > 0
567 #endif
568 	    )
569 	return TRUE;
570     return FALSE;
571 }
572 
573 #if defined(FEAT_EVAL) || defined(PROTO)
574 static garray_T ignore_error_list = GA_EMPTY;
575 
576     void
577 ignore_error_for_testing(char_u *error)
578 {
579     if (ignore_error_list.ga_itemsize == 0)
580 	ga_init2(&ignore_error_list, sizeof(char_u *), 1);
581 
582     if (STRCMP("RESET", error) == 0)
583 	ga_clear_strings(&ignore_error_list);
584     else
585 	ga_add_string(&ignore_error_list, error);
586 }
587 
588     static int
589 ignore_error(char_u *msg)
590 {
591     int i;
592 
593     for (i = 0; i < ignore_error_list.ga_len; ++i)
594 	if (strstr((char *)msg,
595 		  (char *)((char_u **)(ignore_error_list.ga_data))[i]) != NULL)
596 	    return TRUE;
597     return FALSE;
598 }
599 #endif
600 
601 #if !defined(HAVE_STRERROR) || defined(PROTO)
602 /*
603  * Replacement for perror() that behaves more or less like emsg() was called.
604  * v:errmsg will be set and called_emsg will be incremented.
605  */
606     void
607 do_perror(char *msg)
608 {
609     perror(msg);
610     ++emsg_silent;
611     emsg(msg);
612     --emsg_silent;
613 }
614 #endif
615 
616 /*
617  * emsg_core() - display an error message
618  *
619  * Rings the bell, if appropriate, and calls message() to do the real work
620  * When terminal not initialized (yet) mch_errmsg(..) is used.
621  *
622  * Return TRUE if wait_return not called.
623  * Note: caller must check 'emsg_not_now()' before calling this.
624  */
625     static int
626 emsg_core(char_u *s)
627 {
628     int		attr;
629     char_u	*p;
630     int		r;
631 #ifdef FEAT_EVAL
632     int		ignore = FALSE;
633     int		severe;
634 #endif
635 
636 #ifdef FEAT_EVAL
637     // When testing some errors are turned into a normal message.
638     if (ignore_error(s))
639 	// don't call msg() if it results in a dialog
640 	return msg_use_printf() ? FALSE : msg((char *)s);
641 #endif
642 
643     ++called_emsg;
644 
645 #ifdef FEAT_EVAL
646     // If "emsg_severe" is TRUE: When an error exception is to be thrown,
647     // prefer this message over previous messages for the same command.
648     severe = emsg_severe;
649     emsg_severe = FALSE;
650 #endif
651 
652     if (!emsg_off || vim_strchr(p_debug, 't') != NULL)
653     {
654 #ifdef FEAT_EVAL
655 	/*
656 	 * Cause a throw of an error exception if appropriate.  Don't display
657 	 * the error message in this case.  (If no matching catch clause will
658 	 * be found, the message will be displayed later on.)  "ignore" is set
659 	 * when the message should be ignored completely (used for the
660 	 * interrupt message).
661 	 */
662 	if (cause_errthrow(s, severe, &ignore) == TRUE)
663 	{
664 	    if (!ignore)
665 		++did_emsg;
666 	    return TRUE;
667 	}
668 
669 	if (in_assert_fails && emsg_assert_fails_msg == NULL)
670 	{
671 	    emsg_assert_fails_msg = vim_strsave(s);
672 	    emsg_assert_fails_lnum = SOURCING_LNUM;
673 	    vim_free(emsg_assert_fails_context);
674 	    emsg_assert_fails_context = vim_strsave(
675 			 SOURCING_NAME == NULL ? (char_u *)"" : SOURCING_NAME);
676 	}
677 
678 	// set "v:errmsg", also when using ":silent! cmd"
679 	set_vim_var_string(VV_ERRMSG, s, -1);
680 #endif
681 
682 	/*
683 	 * When using ":silent! cmd" ignore error messages.
684 	 * But do write it to the redirection file.
685 	 */
686 	if (emsg_silent != 0)
687 	{
688 #ifdef FEAT_EVAL
689 	    ++did_emsg_silent;
690 #endif
691 	    if (emsg_noredir == 0)
692 	    {
693 		msg_start();
694 		p = get_emsg_source();
695 		if (p != NULL)
696 		{
697 		    STRCAT(p, "\n");
698 		    redir_write(p, -1);
699 		    vim_free(p);
700 		}
701 		p = get_emsg_lnum();
702 		if (p != NULL)
703 		{
704 		    STRCAT(p, "\n");
705 		    redir_write(p, -1);
706 		    vim_free(p);
707 		}
708 		redir_write(s, -1);
709 	    }
710 #ifdef FEAT_EVAL
711 	    // Only increment did_emsg_def when :silent! wasn't used inside the
712 	    // :def function.
713 	    if (emsg_silent == emsg_silent_def)
714 		++did_emsg_def;
715 #endif
716 #ifdef FEAT_JOB_CHANNEL
717 	    ch_log(NULL, "ERROR silent: %s", (char *)s);
718 #endif
719 	    return TRUE;
720 	}
721 
722 	ex_exitval = 1;
723 
724 	// Reset msg_silent, an error causes messages to be switched back on.
725 	msg_silent = 0;
726 	cmd_silent = FALSE;
727 
728 	if (global_busy)		// break :global command
729 	    ++global_busy;
730 
731 	if (p_eb)
732 	    beep_flush();		// also includes flush_buffers()
733 	else
734 	    flush_buffers(FLUSH_MINIMAL);  // flush internal buffers
735 	++did_emsg;			   // flag for DoOneCmd()
736 #ifdef FEAT_EVAL
737 	did_uncaught_emsg = TRUE;
738 #endif
739     }
740 
741     emsg_on_display = TRUE;	// remember there is an error message
742     ++msg_scroll;		// don't overwrite a previous message
743     attr = HL_ATTR(HLF_E);	// set highlight mode for error messages
744     if (msg_scrolled != 0)
745 	need_wait_return = TRUE;    // needed in case emsg() is called after
746 				    // wait_return has reset need_wait_return
747 				    // and a redraw is expected because
748 				    // msg_scrolled is non-zero
749 
750 #ifdef FEAT_JOB_CHANNEL
751     emsg_to_channel_log = TRUE;
752 #endif
753     /*
754      * Display name and line number for the source of the error.
755      */
756     msg_source(attr);
757 
758     /*
759      * Display the error message itself.
760      */
761     msg_nowait = FALSE;			// wait for this msg
762     r = msg_attr((char *)s, attr);
763 
764 #ifdef FEAT_JOB_CHANNEL
765     emsg_to_channel_log = FALSE;
766 #endif
767     return r;
768 }
769 
770 /*
771  * Print an error message.
772  */
773     int
774 emsg(char *s)
775 {
776     // Skip this if not giving error messages at the moment.
777     if (!emsg_not_now())
778 	return emsg_core((char_u *)s);
779     return TRUE;		// no error messages at the moment
780 }
781 
782 #ifndef PROTO  // manual proto with __attribute__
783 /*
784  * Print an error message with format string and variable arguments.
785  * Note: caller must not pass 'IObuff' as 1st argument.
786  */
787     int
788 semsg(const char *s, ...)
789 {
790     // Skip this if not giving error messages at the moment.
791     if (!emsg_not_now())
792     {
793 	if (IObuff == NULL)
794 	{
795 	    // Very early in initialisation and already something wrong, just
796 	    // give the raw message so the user at least gets a hint.
797 	    return emsg_core((char_u *)s);
798 	}
799 	else
800 	{
801 	    va_list ap;
802 
803 	    va_start(ap, s);
804 	    vim_vsnprintf((char *)IObuff, IOSIZE, s, ap);
805 	    va_end(ap);
806 	    return emsg_core(IObuff);
807 	}
808     }
809     return TRUE;		// no error messages at the moment
810 }
811 #endif
812 
813 /*
814  * Same as emsg(...), but abort on error when ABORT_ON_INTERNAL_ERROR is
815  * defined. It is used for internal errors only, so that they can be
816  * detected when fuzzing vim.
817  */
818     void
819 iemsg(char *s)
820 {
821     if (!emsg_not_now())
822 	emsg_core((char_u *)s);
823 #ifdef ABORT_ON_INTERNAL_ERROR
824     abort();
825 #endif
826 }
827 
828 #ifndef PROTO  // manual proto with __attribute__
829 /*
830  * Same as semsg(...) but abort on error when ABORT_ON_INTERNAL_ERROR is
831  * defined. It is used for internal errors only, so that they can be
832  * detected when fuzzing vim.
833  * Note: caller must not pass 'IObuff' as 1st argument.
834  */
835     void
836 siemsg(const char *s, ...)
837 {
838     if (!emsg_not_now())
839     {
840 	if (IObuff == NULL)
841 	{
842 	    // Very early in initialisation and already something wrong, just
843 	    // give the raw message so the user at least gets a hint.
844 	    emsg_core((char_u *)s);
845 	}
846 	else
847 	{
848 	    va_list ap;
849 
850 	    va_start(ap, s);
851 	    vim_vsnprintf((char *)IObuff, IOSIZE, s, ap);
852 	    va_end(ap);
853 	    emsg_core(IObuff);
854 	}
855     }
856 # ifdef ABORT_ON_INTERNAL_ERROR
857     abort();
858 # endif
859 }
860 #endif
861 
862 /*
863  * Give an "Internal error" message.
864  */
865     void
866 internal_error(char *where)
867 {
868     siemsg(_(e_intern2), where);
869 }
870 
871 /*
872  * Like internal_error() but do not call abort(), to avoid tests using
873  * test_unknown() and test_void() causing Vim to exit.
874  */
875     void
876 internal_error_no_abort(char *where)
877 {
878      semsg(_(e_intern2), where);
879 }
880 
881 // emsg3() and emsgn() are in misc2.c to avoid warnings for the prototypes.
882 
883     void
884 emsg_invreg(int name)
885 {
886     semsg(_("E354: Invalid register name: '%s'"), transchar(name));
887 }
888 
889 /*
890  * Give an error message which contains %s for "name[len]".
891  */
892     void
893 emsg_namelen(char *msg, char_u *name, int len)
894 {
895     char_u *copy = vim_strnsave((char_u *)name, len);
896 
897     semsg(msg, copy == NULL ? "NULL" : (char *)copy);
898     vim_free(copy);
899 }
900 
901 /*
902  * Like msg(), but truncate to a single line if p_shm contains 't', or when
903  * "force" is TRUE.  This truncates in another way as for normal messages.
904  * Careful: The string may be changed by msg_may_trunc()!
905  * Returns a pointer to the printed message, if wait_return() not called.
906  */
907     char *
908 msg_trunc_attr(char *s, int force, int attr)
909 {
910     int		n;
911     char	*ts;
912 
913     // Add message to history before truncating
914     add_msg_hist((char_u *)s, -1, attr);
915 
916     ts = (char *)msg_may_trunc(force, (char_u *)s);
917 
918     msg_hist_off = TRUE;
919     n = msg_attr(ts, attr);
920     msg_hist_off = FALSE;
921 
922     if (n)
923 	return ts;
924     return NULL;
925 }
926 
927 /*
928  * Check if message "s" should be truncated at the start (for filenames).
929  * Return a pointer to where the truncated message starts.
930  * Note: May change the message by replacing a character with '<'.
931  */
932     char_u *
933 msg_may_trunc(int force, char_u *s)
934 {
935     int		n;
936     int		room;
937 
938     room = (int)(Rows - cmdline_row - 1) * Columns + sc_col - 1;
939     if ((force || (shortmess(SHM_TRUNC) && !exmode_active))
940 	    && (n = (int)STRLEN(s) - room) > 0)
941     {
942 	if (has_mbyte)
943 	{
944 	    int	size = vim_strsize(s);
945 
946 	    // There may be room anyway when there are multibyte chars.
947 	    if (size <= room)
948 		return s;
949 
950 	    for (n = 0; size >= room; )
951 	    {
952 		size -= (*mb_ptr2cells)(s + n);
953 		n += (*mb_ptr2len)(s + n);
954 	    }
955 	    --n;
956 	}
957 	s += n;
958 	*s = '<';
959     }
960     return s;
961 }
962 
963     static void
964 add_msg_hist(
965     char_u	*s,
966     int		len,		// -1 for undetermined length
967     int		attr)
968 {
969     struct msg_hist *p;
970 
971     if (msg_hist_off || msg_silent != 0)
972 	return;
973 
974     // Don't let the message history get too big
975     while (msg_hist_len > MAX_MSG_HIST_LEN)
976 	(void)delete_first_msg();
977 
978     // allocate an entry and add the message at the end of the history
979     p = ALLOC_ONE(struct msg_hist);
980     if (p != NULL)
981     {
982 	if (len < 0)
983 	    len = (int)STRLEN(s);
984 	// remove leading and trailing newlines
985 	while (len > 0 && *s == '\n')
986 	{
987 	    ++s;
988 	    --len;
989 	}
990 	while (len > 0 && s[len - 1] == '\n')
991 	    --len;
992 	p->msg = vim_strnsave(s, len);
993 	p->next = NULL;
994 	p->attr = attr;
995 	if (last_msg_hist != NULL)
996 	    last_msg_hist->next = p;
997 	last_msg_hist = p;
998 	if (first_msg_hist == NULL)
999 	    first_msg_hist = last_msg_hist;
1000 	++msg_hist_len;
1001     }
1002 }
1003 
1004 /*
1005  * Delete the first (oldest) message from the history.
1006  * Returns FAIL if there are no messages.
1007  */
1008     int
1009 delete_first_msg(void)
1010 {
1011     struct msg_hist *p;
1012 
1013     if (msg_hist_len <= 0)
1014 	return FAIL;
1015     p = first_msg_hist;
1016     first_msg_hist = p->next;
1017     if (first_msg_hist == NULL)
1018 	last_msg_hist = NULL;  // history is empty
1019     vim_free(p->msg);
1020     vim_free(p);
1021     --msg_hist_len;
1022     return OK;
1023 }
1024 
1025 /*
1026  * ":messages" command.
1027  */
1028     void
1029 ex_messages(exarg_T *eap)
1030 {
1031     struct msg_hist *p;
1032     char_u	    *s;
1033     int		    c = 0;
1034 
1035     if (STRCMP(eap->arg, "clear") == 0)
1036     {
1037 	int keep = eap->addr_count == 0 ? 0 : eap->line2;
1038 
1039 	while (msg_hist_len > keep)
1040 	    (void)delete_first_msg();
1041 	return;
1042     }
1043 
1044     if (*eap->arg != NUL)
1045     {
1046 	emsg(_(e_invarg));
1047 	return;
1048     }
1049 
1050     msg_hist_off = TRUE;
1051 
1052     p = first_msg_hist;
1053     if (eap->addr_count != 0)
1054     {
1055 	// Count total messages
1056 	for (; p != NULL && !got_int; p = p->next)
1057 	    c++;
1058 
1059 	c -= eap->line2;
1060 
1061 	// Skip without number of messages specified
1062 	for (p = first_msg_hist; p != NULL && !got_int && c > 0;
1063 						    p = p->next, c--);
1064     }
1065 
1066     if (p == first_msg_hist)
1067     {
1068 #ifdef FEAT_MULTI_LANG
1069 	s = get_mess_lang();
1070 #else
1071 	s = mch_getenv((char_u *)"LANG");
1072 #endif
1073 	if (s != NULL && *s != NUL)
1074 	    // The next comment is extracted by xgettext and put in po file for
1075 	    // translators to read.
1076 	    msg_attr(
1077 		    // Translator: Please replace the name and email address
1078 		    // with the appropriate text for your translation.
1079 		    _("Messages maintainer: Bram Moolenaar <[email protected]>"),
1080 		    HL_ATTR(HLF_T));
1081     }
1082 
1083     // Display what was not skipped.
1084     for (; p != NULL && !got_int; p = p->next)
1085 	if (p->msg != NULL)
1086 	    msg_attr((char *)p->msg, p->attr);
1087 
1088     msg_hist_off = FALSE;
1089 }
1090 
1091 #if defined(FEAT_CON_DIALOG) || defined(FIND_REPLACE_DIALOG) || defined(PROTO)
1092 /*
1093  * Call this after prompting the user.  This will avoid a hit-return message
1094  * and a delay.
1095  */
1096     void
1097 msg_end_prompt(void)
1098 {
1099     need_wait_return = FALSE;
1100     emsg_on_display = FALSE;
1101     cmdline_row = msg_row;
1102     msg_col = 0;
1103     msg_clr_eos();
1104     lines_left = -1;
1105 }
1106 #endif
1107 
1108 /*
1109  * Wait for the user to hit a key (normally Enter).
1110  * If "redraw" is TRUE, clear and redraw the screen.
1111  * If "redraw" is FALSE, just redraw the screen.
1112  * If "redraw" is -1, don't redraw at all.
1113  */
1114     void
1115 wait_return(int redraw)
1116 {
1117     int		c;
1118     int		oldState;
1119     int		tmpState;
1120     int		had_got_int;
1121     int		save_reg_recording;
1122     FILE	*save_scriptout;
1123 
1124     if (redraw == TRUE)
1125 	must_redraw = CLEAR;
1126 
1127     // If using ":silent cmd", don't wait for a return.  Also don't set
1128     // need_wait_return to do it later.
1129     if (msg_silent != 0)
1130 	return;
1131 
1132     /*
1133      * When inside vgetc(), we can't wait for a typed character at all.
1134      * With the global command (and some others) we only need one return at
1135      * the end. Adjust cmdline_row to avoid the next message overwriting the
1136      * last one.
1137      */
1138     if (vgetc_busy > 0)
1139 	return;
1140     need_wait_return = TRUE;
1141     if (no_wait_return)
1142     {
1143 	if (!exmode_active)
1144 	    cmdline_row = msg_row;
1145 	return;
1146     }
1147 
1148     redir_off = TRUE;		// don't redirect this message
1149     oldState = State;
1150     if (quit_more)
1151     {
1152 	c = CAR;		// just pretend CR was hit
1153 	quit_more = FALSE;
1154 	got_int = FALSE;
1155     }
1156     else if (exmode_active)
1157     {
1158 	msg_puts(" ");		// make sure the cursor is on the right line
1159 	c = CAR;		// no need for a return in ex mode
1160 	got_int = FALSE;
1161     }
1162     else
1163     {
1164 	// Make sure the hit-return prompt is on screen when 'guioptions' was
1165 	// just changed.
1166 	screenalloc(FALSE);
1167 
1168 	State = HITRETURN;
1169 	setmouse();
1170 #ifdef USE_ON_FLY_SCROLL
1171 	dont_scroll = TRUE;		// disallow scrolling here
1172 #endif
1173 	cmdline_row = msg_row;
1174 
1175 	// Avoid the sequence that the user types ":" at the hit-return prompt
1176 	// to start an Ex command, but the file-changed dialog gets in the
1177 	// way.
1178 	if (need_check_timestamps)
1179 	    check_timestamps(FALSE);
1180 
1181 	hit_return_msg();
1182 
1183 	do
1184 	{
1185 	    // Remember "got_int", if it is set vgetc() probably returns a
1186 	    // CTRL-C, but we need to loop then.
1187 	    had_got_int = got_int;
1188 
1189 	    // Don't do mappings here, we put the character back in the
1190 	    // typeahead buffer.
1191 	    ++no_mapping;
1192 	    ++allow_keys;
1193 
1194 	    // Temporarily disable Recording. If Recording is active, the
1195 	    // character will be recorded later, since it will be added to the
1196 	    // typebuf after the loop
1197 	    save_reg_recording = reg_recording;
1198 	    save_scriptout = scriptout;
1199 	    reg_recording = 0;
1200 	    scriptout = NULL;
1201 	    c = safe_vgetc();
1202 	    if (had_got_int && !global_busy)
1203 		got_int = FALSE;
1204 	    --no_mapping;
1205 	    --allow_keys;
1206 	    reg_recording = save_reg_recording;
1207 	    scriptout = save_scriptout;
1208 
1209 #ifdef FEAT_CLIPBOARD
1210 	    // Strange way to allow copying (yanking) a modeless selection at
1211 	    // the hit-enter prompt.  Use CTRL-Y, because the same is used in
1212 	    // Cmdline-mode and it's harmless when there is no selection.
1213 	    if (c == Ctrl_Y && clip_star.state == SELECT_DONE)
1214 	    {
1215 		clip_copy_modeless_selection(TRUE);
1216 		c = K_IGNORE;
1217 	    }
1218 #endif
1219 
1220 	    /*
1221 	     * Allow scrolling back in the messages.
1222 	     * Also accept scroll-down commands when messages fill the screen,
1223 	     * to avoid that typing one 'j' too many makes the messages
1224 	     * disappear.
1225 	     */
1226 	    if (p_more && !p_cp)
1227 	    {
1228 		if (c == 'b' || c == 'k' || c == 'u' || c == 'g'
1229 						|| c == K_UP || c == K_PAGEUP)
1230 		{
1231 		    if (msg_scrolled > Rows)
1232 			// scroll back to show older messages
1233 			do_more_prompt(c);
1234 		    else
1235 		    {
1236 			msg_didout = FALSE;
1237 			c = K_IGNORE;
1238 			msg_col =
1239 #ifdef FEAT_RIGHTLEFT
1240 			    cmdmsg_rl ? Columns - 1 :
1241 #endif
1242 			    0;
1243 		    }
1244 		    if (quit_more)
1245 		    {
1246 			c = CAR;		// just pretend CR was hit
1247 			quit_more = FALSE;
1248 			got_int = FALSE;
1249 		    }
1250 		    else if (c != K_IGNORE)
1251 		    {
1252 			c = K_IGNORE;
1253 			hit_return_msg();
1254 		    }
1255 		}
1256 		else if (msg_scrolled > Rows - 2
1257 			 && (c == 'j' || c == 'd' || c == 'f'
1258 					   || c == K_DOWN || c == K_PAGEDOWN))
1259 		    c = K_IGNORE;
1260 	    }
1261 	} while ((had_got_int && c == Ctrl_C)
1262 				|| c == K_IGNORE
1263 #ifdef FEAT_GUI
1264 				|| c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR
1265 #endif
1266 				|| c == K_LEFTDRAG   || c == K_LEFTRELEASE
1267 				|| c == K_MIDDLEDRAG || c == K_MIDDLERELEASE
1268 				|| c == K_RIGHTDRAG  || c == K_RIGHTRELEASE
1269 				|| c == K_MOUSELEFT  || c == K_MOUSERIGHT
1270 				|| c == K_MOUSEDOWN  || c == K_MOUSEUP
1271 				|| c == K_MOUSEMOVE
1272 				|| (!mouse_has(MOUSE_RETURN)
1273 				    && mouse_row < msg_row
1274 				    && (c == K_LEFTMOUSE
1275 					|| c == K_MIDDLEMOUSE
1276 					|| c == K_RIGHTMOUSE
1277 					|| c == K_X1MOUSE
1278 					|| c == K_X2MOUSE))
1279 				);
1280 	ui_breakcheck();
1281 	/*
1282 	 * Avoid that the mouse-up event causes visual mode to start.
1283 	 */
1284 	if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE
1285 					  || c == K_X1MOUSE || c == K_X2MOUSE)
1286 	    (void)jump_to_mouse(MOUSE_SETPOS, NULL, 0);
1287 	else if (vim_strchr((char_u *)"\r\n ", c) == NULL && c != Ctrl_C)
1288 	{
1289 	    // Put the character back in the typeahead buffer.  Don't use the
1290 	    // stuff buffer, because lmaps wouldn't work.
1291 	    ins_char_typebuf(vgetc_char, vgetc_mod_mask);
1292 	    do_redraw = TRUE;	    // need a redraw even though there is
1293 				    // typeahead
1294 	}
1295     }
1296     redir_off = FALSE;
1297 
1298     /*
1299      * If the user hits ':', '?' or '/' we get a command line from the next
1300      * line.
1301      */
1302     if (c == ':' || c == '?' || c == '/')
1303     {
1304 	if (!exmode_active)
1305 	    cmdline_row = msg_row;
1306 	skip_redraw = TRUE;	    // skip redraw once
1307 	do_redraw = FALSE;
1308 #ifdef FEAT_TERMINAL
1309 	skip_term_loop = TRUE;
1310 #endif
1311     }
1312 
1313     /*
1314      * If the window size changed set_shellsize() will redraw the screen.
1315      * Otherwise the screen is only redrawn if 'redraw' is set and no ':'
1316      * typed.
1317      */
1318     tmpState = State;
1319     State = oldState;		    // restore State before set_shellsize
1320     setmouse();
1321     msg_check();
1322 
1323 #if defined(UNIX) || defined(VMS)
1324     /*
1325      * When switching screens, we need to output an extra newline on exit.
1326      */
1327     if (swapping_screen() && !termcap_active)
1328 	newline_on_exit = TRUE;
1329 #endif
1330 
1331     need_wait_return = FALSE;
1332     did_wait_return = TRUE;
1333     emsg_on_display = FALSE;	// can delete error message now
1334     lines_left = -1;		// reset lines_left at next msg_start()
1335     reset_last_sourcing();
1336     if (keep_msg != NULL && vim_strsize(keep_msg) >=
1337 				  (Rows - cmdline_row - 1) * Columns + sc_col)
1338 	VIM_CLEAR(keep_msg);	    // don't redisplay message, it's too long
1339 
1340     if (tmpState == SETWSIZE)	    // got resize event while in vgetc()
1341     {
1342 	starttermcap();		    // start termcap before redrawing
1343 	shell_resized();
1344     }
1345     else if (!skip_redraw
1346 	    && (redraw == TRUE || (msg_scrolled != 0 && redraw != -1)))
1347     {
1348 	starttermcap();		    // start termcap before redrawing
1349 	redraw_later(VALID);
1350     }
1351 }
1352 
1353 /*
1354  * Write the hit-return prompt.
1355  */
1356     static void
1357 hit_return_msg(void)
1358 {
1359     int		save_p_more = p_more;
1360 
1361     p_more = FALSE;	// don't want see this message when scrolling back
1362     if (msg_didout)	// start on a new line
1363 	msg_putchar('\n');
1364     if (got_int)
1365 	msg_puts(_("Interrupt: "));
1366 
1367     msg_puts_attr(_("Press ENTER or type command to continue"), HL_ATTR(HLF_R));
1368     if (!msg_use_printf())
1369 	msg_clr_eos();
1370     p_more = save_p_more;
1371 }
1372 
1373 /*
1374  * Set "keep_msg" to "s".  Free the old value and check for NULL pointer.
1375  */
1376     void
1377 set_keep_msg(char_u *s, int attr)
1378 {
1379     vim_free(keep_msg);
1380     if (s != NULL && msg_silent == 0)
1381 	keep_msg = vim_strsave(s);
1382     else
1383 	keep_msg = NULL;
1384     keep_msg_more = FALSE;
1385     keep_msg_attr = attr;
1386 }
1387 
1388 #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
1389 /*
1390  * If there currently is a message being displayed, set "keep_msg" to it, so
1391  * that it will be displayed again after redraw.
1392  */
1393     void
1394 set_keep_msg_from_hist(void)
1395 {
1396     if (keep_msg == NULL && last_msg_hist != NULL && msg_scrolled == 0
1397 							  && (State & NORMAL))
1398 	set_keep_msg(last_msg_hist->msg, last_msg_hist->attr);
1399 }
1400 #endif
1401 
1402 /*
1403  * Prepare for outputting characters in the command line.
1404  */
1405     void
1406 msg_start(void)
1407 {
1408     int		did_return = FALSE;
1409 
1410     if (!msg_silent)
1411 	VIM_CLEAR(keep_msg);
1412 
1413 #ifdef FEAT_EVAL
1414     if (need_clr_eos)
1415     {
1416 	// Halfway an ":echo" command and getting an (error) message: clear
1417 	// any text from the command.
1418 	need_clr_eos = FALSE;
1419 	msg_clr_eos();
1420     }
1421 #endif
1422 
1423     if (!msg_scroll && full_screen)	// overwrite last message
1424     {
1425 	msg_row = cmdline_row;
1426 	msg_col =
1427 #ifdef FEAT_RIGHTLEFT
1428 	    cmdmsg_rl ? Columns - 1 :
1429 #endif
1430 	    0;
1431     }
1432     else if (msg_didout)		    // start message on next line
1433     {
1434 	msg_putchar('\n');
1435 	did_return = TRUE;
1436 	if (exmode_active != EXMODE_NORMAL)
1437 	    cmdline_row = msg_row;
1438     }
1439     if (!msg_didany || lines_left < 0)
1440 	msg_starthere();
1441     if (msg_silent == 0)
1442     {
1443 	msg_didout = FALSE;		    // no output on current line yet
1444 	cursor_off();
1445     }
1446 
1447     // when redirecting, may need to start a new line.
1448     if (!did_return)
1449 	redir_write((char_u *)"\n", -1);
1450 }
1451 
1452 /*
1453  * Note that the current msg position is where messages start.
1454  */
1455     void
1456 msg_starthere(void)
1457 {
1458     lines_left = cmdline_row;
1459     msg_didany = FALSE;
1460 }
1461 
1462     void
1463 msg_putchar(int c)
1464 {
1465     msg_putchar_attr(c, 0);
1466 }
1467 
1468     void
1469 msg_putchar_attr(int c, int attr)
1470 {
1471     char_u	buf[MB_MAXBYTES + 1];
1472 
1473     if (IS_SPECIAL(c))
1474     {
1475 	buf[0] = K_SPECIAL;
1476 	buf[1] = K_SECOND(c);
1477 	buf[2] = K_THIRD(c);
1478 	buf[3] = NUL;
1479     }
1480     else
1481 	buf[(*mb_char2bytes)(c, buf)] = NUL;
1482     msg_puts_attr((char *)buf, attr);
1483 }
1484 
1485     void
1486 msg_outnum(long n)
1487 {
1488     char	buf[20];
1489 
1490     sprintf(buf, "%ld", n);
1491     msg_puts(buf);
1492 }
1493 
1494     void
1495 msg_home_replace(char_u *fname)
1496 {
1497     msg_home_replace_attr(fname, 0);
1498 }
1499 
1500 #if defined(FEAT_FIND_ID) || defined(PROTO)
1501     void
1502 msg_home_replace_hl(char_u *fname)
1503 {
1504     msg_home_replace_attr(fname, HL_ATTR(HLF_D));
1505 }
1506 #endif
1507 
1508     static void
1509 msg_home_replace_attr(char_u *fname, int attr)
1510 {
1511     char_u	*name;
1512 
1513     name = home_replace_save(NULL, fname);
1514     if (name != NULL)
1515 	msg_outtrans_attr(name, attr);
1516     vim_free(name);
1517 }
1518 
1519 /*
1520  * Output 'len' characters in 'str' (including NULs) with translation
1521  * if 'len' is -1, output up to a NUL character.
1522  * Use attributes 'attr'.
1523  * Return the number of characters it takes on the screen.
1524  */
1525     int
1526 msg_outtrans(char_u *str)
1527 {
1528     return msg_outtrans_attr(str, 0);
1529 }
1530 
1531     int
1532 msg_outtrans_attr(char_u *str, int attr)
1533 {
1534     return msg_outtrans_len_attr(str, (int)STRLEN(str), attr);
1535 }
1536 
1537     int
1538 msg_outtrans_len(char_u *str, int len)
1539 {
1540     return msg_outtrans_len_attr(str, len, 0);
1541 }
1542 
1543 /*
1544  * Output one character at "p".  Return pointer to the next character.
1545  * Handles multi-byte characters.
1546  */
1547     char_u *
1548 msg_outtrans_one(char_u *p, int attr)
1549 {
1550     int		l;
1551 
1552     if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1553     {
1554 	msg_outtrans_len_attr(p, l, attr);
1555 	return p + l;
1556     }
1557     msg_puts_attr((char *)transchar_byte(*p), attr);
1558     return p + 1;
1559 }
1560 
1561     int
1562 msg_outtrans_len_attr(char_u *msgstr, int len, int attr)
1563 {
1564     int		retval = 0;
1565     char_u	*str = msgstr;
1566     char_u	*plain_start = msgstr;
1567     char_u	*s;
1568     int		mb_l;
1569     int		c;
1570     int		save_got_int = got_int;
1571 
1572     // Only quit when got_int was set in here.
1573     got_int = FALSE;
1574 
1575     // if MSG_HIST flag set, add message to history
1576     if (attr & MSG_HIST)
1577     {
1578 	add_msg_hist(str, len, attr);
1579 	attr &= ~MSG_HIST;
1580     }
1581 
1582     // If the string starts with a composing character first draw a space on
1583     // which the composing char can be drawn.
1584     if (enc_utf8 && utf_iscomposing(utf_ptr2char(msgstr)))
1585 	msg_puts_attr(" ", attr);
1586 
1587     /*
1588      * Go over the string.  Special characters are translated and printed.
1589      * Normal characters are printed several at a time.
1590      */
1591     while (--len >= 0 && !got_int)
1592     {
1593 	if (enc_utf8)
1594 	    // Don't include composing chars after the end.
1595 	    mb_l = utfc_ptr2len_len(str, len + 1);
1596 	else if (has_mbyte)
1597 	    mb_l = (*mb_ptr2len)(str);
1598 	else
1599 	    mb_l = 1;
1600 	if (has_mbyte && mb_l > 1)
1601 	{
1602 	    c = (*mb_ptr2char)(str);
1603 	    if (vim_isprintc(c))
1604 		// printable multi-byte char: count the cells.
1605 		retval += (*mb_ptr2cells)(str);
1606 	    else
1607 	    {
1608 		// unprintable multi-byte char: print the printable chars so
1609 		// far and the translation of the unprintable char.
1610 		if (str > plain_start)
1611 		    msg_puts_attr_len((char *)plain_start,
1612 					       (int)(str - plain_start), attr);
1613 		plain_start = str + mb_l;
1614 		msg_puts_attr((char *)transchar(c),
1615 					    attr == 0 ? HL_ATTR(HLF_8) : attr);
1616 		retval += char2cells(c);
1617 	    }
1618 	    len -= mb_l - 1;
1619 	    str += mb_l;
1620 	}
1621 	else
1622 	{
1623 	    s = transchar_byte(*str);
1624 	    if (s[1] != NUL)
1625 	    {
1626 		// unprintable char: print the printable chars so far and the
1627 		// translation of the unprintable char.
1628 		if (str > plain_start)
1629 		    msg_puts_attr_len((char *)plain_start,
1630 					       (int)(str - plain_start), attr);
1631 		plain_start = str + 1;
1632 		msg_puts_attr((char *)s, attr == 0 ? HL_ATTR(HLF_8) : attr);
1633 		retval += (int)STRLEN(s);
1634 	    }
1635 	    else
1636 		++retval;
1637 	    ++str;
1638 	}
1639     }
1640 
1641     if (str > plain_start && !got_int)
1642 	// print the printable chars at the end
1643 	msg_puts_attr_len((char *)plain_start, (int)(str - plain_start), attr);
1644 
1645     got_int |= save_got_int;
1646 
1647     return retval;
1648 }
1649 
1650 #if defined(FEAT_QUICKFIX) || defined(PROTO)
1651     void
1652 msg_make(char_u *arg)
1653 {
1654     int	    i;
1655     static char_u *str = (char_u *)"eeffoc", *rs = (char_u *)"Plon#dqg#vxjduB";
1656 
1657     arg = skipwhite(arg);
1658     for (i = 5; *arg && i >= 0; --i)
1659 	if (*arg++ != str[i])
1660 	    break;
1661     if (i < 0)
1662     {
1663 	msg_putchar('\n');
1664 	for (i = 0; rs[i]; ++i)
1665 	    msg_putchar(rs[i] - 3);
1666     }
1667 }
1668 #endif
1669 
1670 /*
1671  * Output the string 'str' up to a NUL character.
1672  * Return the number of characters it takes on the screen.
1673  *
1674  * If K_SPECIAL is encountered, then it is taken in conjunction with the
1675  * following character and shown as <F1>, <S-Up> etc.  Any other character
1676  * which is not printable shown in <> form.
1677  * If 'from' is TRUE (lhs of a mapping), a space is shown as <Space>.
1678  * If a character is displayed in one of these special ways, is also
1679  * highlighted (its highlight name is '8' in the p_hl variable).
1680  * Otherwise characters are not highlighted.
1681  * This function is used to show mappings, where we want to see how to type
1682  * the character/string -- webb
1683  */
1684     int
1685 msg_outtrans_special(
1686     char_u	*strstart,
1687     int		from,	// TRUE for lhs of a mapping
1688     int		maxlen) // screen columns, 0 for unlimited
1689 {
1690     char_u	*str = strstart;
1691     int		retval = 0;
1692     char	*text;
1693     int		attr;
1694     int		len;
1695 
1696     attr = HL_ATTR(HLF_8);
1697     while (*str != NUL)
1698     {
1699 	// Leading and trailing spaces need to be displayed in <> form.
1700 	if ((str == strstart || str[1] == NUL) && *str == ' ')
1701 	{
1702 	    text = "<Space>";
1703 	    ++str;
1704 	}
1705 	else
1706 	    text = (char *)str2special(&str, from);
1707 	len = vim_strsize((char_u *)text);
1708 	if (maxlen > 0 && retval + len >= maxlen)
1709 	    break;
1710 	// Highlight special keys
1711 	msg_puts_attr(text, len > 1
1712 		&& (*mb_ptr2len)((char_u *)text) <= 1 ? attr : 0);
1713 	retval += len;
1714     }
1715     return retval;
1716 }
1717 
1718 #if defined(FEAT_EVAL) || defined(PROTO)
1719 /*
1720  * Return the lhs or rhs of a mapping, with the key codes turned into printable
1721  * strings, in an allocated string.
1722  */
1723     char_u *
1724 str2special_save(
1725     char_u  *str,
1726     int	    is_lhs)  // TRUE for lhs, FALSE for rhs
1727 {
1728     garray_T	ga;
1729     char_u	*p = str;
1730 
1731     ga_init2(&ga, 1, 40);
1732     while (*p != NUL)
1733 	ga_concat(&ga, str2special(&p, is_lhs));
1734     ga_append(&ga, NUL);
1735     return (char_u *)ga.ga_data;
1736 }
1737 #endif
1738 
1739 /*
1740  * Return the printable string for the key codes at "*sp".
1741  * Used for translating the lhs or rhs of a mapping to printable chars.
1742  * Advances "sp" to the next code.
1743  */
1744     char_u *
1745 str2special(
1746     char_u	**sp,
1747     int		from)	// TRUE for lhs of mapping
1748 {
1749     int			c;
1750     static char_u	buf[7];
1751     char_u		*str = *sp;
1752     int			modifiers = 0;
1753     int			special = FALSE;
1754 
1755     if (has_mbyte)
1756     {
1757 	char_u	*p;
1758 
1759 	// Try to un-escape a multi-byte character.  Return the un-escaped
1760 	// string if it is a multi-byte character.
1761 	p = mb_unescape(sp);
1762 	if (p != NULL)
1763 	    return p;
1764     }
1765 
1766     c = *str;
1767     if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1768     {
1769 	if (str[1] == KS_MODIFIER)
1770 	{
1771 	    modifiers = str[2];
1772 	    str += 3;
1773 	    c = *str;
1774 	}
1775 	if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
1776 	{
1777 	    c = TO_SPECIAL(str[1], str[2]);
1778 	    str += 2;
1779 	}
1780 	if (IS_SPECIAL(c) || modifiers)	// special key
1781 	    special = TRUE;
1782     }
1783 
1784     if (has_mbyte && !IS_SPECIAL(c))
1785     {
1786 	int len = (*mb_ptr2len)(str);
1787 
1788 	// For multi-byte characters check for an illegal byte.
1789 	if (has_mbyte && MB_BYTE2LEN(*str) > len)
1790 	{
1791 	    transchar_nonprint(curbuf, buf, c);
1792 	    *sp = str + 1;
1793 	    return buf;
1794 	}
1795 	// Since 'special' is TRUE the multi-byte character 'c' will be
1796 	// processed by get_special_key_name()
1797 	c = (*mb_ptr2char)(str);
1798 	*sp = str + len;
1799     }
1800     else
1801 	*sp = str + 1;
1802 
1803     // Make unprintable characters in <> form, also <M-Space> and <Tab>.
1804     // Use <Space> only for lhs of a mapping.
1805     if (special || char2cells(c) > 1 || (from && c == ' '))
1806 	return get_special_key_name(c, modifiers);
1807     buf[0] = c;
1808     buf[1] = NUL;
1809     return buf;
1810 }
1811 
1812 /*
1813  * Translate a key sequence into special key names.
1814  */
1815     void
1816 str2specialbuf(char_u *sp, char_u *buf, int len)
1817 {
1818     char_u	*s;
1819 
1820     *buf = NUL;
1821     while (*sp)
1822     {
1823 	s = str2special(&sp, FALSE);
1824 	if ((int)(STRLEN(s) + STRLEN(buf)) < len)
1825 	    STRCAT(buf, s);
1826     }
1827 }
1828 
1829 /*
1830  * print line for :print or :list command
1831  */
1832     void
1833 msg_prt_line(char_u *s, int list)
1834 {
1835     int		c;
1836     int		col = 0;
1837     int		n_extra = 0;
1838     int		c_extra = 0;
1839     int		c_final = 0;
1840     char_u	*p_extra = NULL;	    // init to make SASC shut up
1841     int		n;
1842     int		attr = 0;
1843     char_u	*trail = NULL;
1844     char_u	*lead = NULL;
1845     int		l;
1846     char_u	buf[MB_MAXBYTES + 1];
1847 
1848     if (curwin->w_p_list)
1849 	list = TRUE;
1850 
1851     if (list)
1852     {
1853 	// find start of trailing whitespace
1854 	if (curwin->w_lcs_chars.trail)
1855 	{
1856 	    trail = s + STRLEN(s);
1857 	    while (trail > s && VIM_ISWHITE(trail[-1]))
1858 		--trail;
1859 	}
1860 	// find end of leading whitespace
1861 	if (curwin->w_lcs_chars.lead)
1862 	{
1863 	    lead = s;
1864 	    while (VIM_ISWHITE(lead[0]))
1865 		lead++;
1866 	    // in a line full of spaces all of them are treated as trailing
1867 	    if (*lead == NUL)
1868 		lead = NULL;
1869 	}
1870     }
1871 
1872     // output a space for an empty line, otherwise the line will be
1873     // overwritten
1874     if (*s == NUL && !(list && curwin->w_lcs_chars.eol != NUL))
1875 	msg_putchar(' ');
1876 
1877     while (!got_int)
1878     {
1879 	if (n_extra > 0)
1880 	{
1881 	    --n_extra;
1882 	    if (n_extra == 0 && c_final)
1883 		c = c_final;
1884 	    else if (c_extra)
1885 		c = c_extra;
1886 	    else
1887 		c = *p_extra++;
1888 	}
1889 	else if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1)
1890 	{
1891 	    col += (*mb_ptr2cells)(s);
1892 	    if (l >= MB_MAXBYTES)
1893 	    {
1894 		STRCPY(buf, "?");
1895 	    }
1896 	    else if (curwin->w_lcs_chars.nbsp != NUL && list
1897 		    && (mb_ptr2char(s) == 160
1898 			|| mb_ptr2char(s) == 0x202f))
1899 	    {
1900 		mb_char2bytes(curwin->w_lcs_chars.nbsp, buf);
1901 		buf[(*mb_ptr2len)(buf)] = NUL;
1902 	    }
1903 	    else
1904 	    {
1905 		mch_memmove(buf, s, (size_t)l);
1906 		buf[l] = NUL;
1907 	    }
1908 	    msg_puts((char *)buf);
1909 	    s += l;
1910 	    continue;
1911 	}
1912 	else
1913 	{
1914 	    attr = 0;
1915 	    c = *s++;
1916 	    if (c == TAB && (!list || curwin->w_lcs_chars.tab1))
1917 	    {
1918 		// tab amount depends on current column
1919 #ifdef FEAT_VARTABS
1920 		n_extra = tabstop_padding(col, curbuf->b_p_ts,
1921 						    curbuf->b_p_vts_array) - 1;
1922 #else
1923 		n_extra = curbuf->b_p_ts - col % curbuf->b_p_ts - 1;
1924 #endif
1925 		if (!list)
1926 		{
1927 		    c = ' ';
1928 		    c_extra = ' ';
1929 		    c_final = NUL;
1930 		}
1931 		else
1932 		{
1933 		    c = (n_extra == 0 && curwin->w_lcs_chars.tab3)
1934 						? curwin->w_lcs_chars.tab3
1935 						: curwin->w_lcs_chars.tab1;
1936 		    c_extra = curwin->w_lcs_chars.tab2;
1937 		    c_final = curwin->w_lcs_chars.tab3;
1938 		    attr = HL_ATTR(HLF_8);
1939 		}
1940 	    }
1941 	    else if (c == 160 && list && curwin->w_lcs_chars.nbsp != NUL)
1942 	    {
1943 		c = curwin->w_lcs_chars.nbsp;
1944 		attr = HL_ATTR(HLF_8);
1945 	    }
1946 	    else if (c == NUL && list && curwin->w_lcs_chars.eol != NUL)
1947 	    {
1948 		p_extra = (char_u *)"";
1949 		c_extra = NUL;
1950 		c_final = NUL;
1951 		n_extra = 1;
1952 		c = curwin->w_lcs_chars.eol;
1953 		attr = HL_ATTR(HLF_AT);
1954 		--s;
1955 	    }
1956 	    else if (c != NUL && (n = byte2cells(c)) > 1)
1957 	    {
1958 		n_extra = n - 1;
1959 		p_extra = transchar_byte(c);
1960 		c_extra = NUL;
1961 		c_final = NUL;
1962 		c = *p_extra++;
1963 		// Use special coloring to be able to distinguish <hex> from
1964 		// the same in plain text.
1965 		attr = HL_ATTR(HLF_8);
1966 	    }
1967 	    else if (c == ' ' && lead != NULL && s <= lead)
1968 	    {
1969 		c = curwin->w_lcs_chars.lead;
1970 		attr = HL_ATTR(HLF_8);
1971 	    }
1972 	    else if (c == ' ' && trail != NULL && s > trail)
1973 	    {
1974 		c = curwin->w_lcs_chars.trail;
1975 		attr = HL_ATTR(HLF_8);
1976 	    }
1977 	    else if (c == ' ' && list && curwin->w_lcs_chars.space != NUL)
1978 	    {
1979 		c = curwin->w_lcs_chars.space;
1980 		attr = HL_ATTR(HLF_8);
1981 	    }
1982 	}
1983 
1984 	if (c == NUL)
1985 	    break;
1986 
1987 	msg_putchar_attr(c, attr);
1988 	col++;
1989     }
1990     msg_clr_eos();
1991 }
1992 
1993 /*
1994  * Use screen_puts() to output one multi-byte character.
1995  * Return the pointer "s" advanced to the next character.
1996  */
1997     static char_u *
1998 screen_puts_mbyte(char_u *s, int l, int attr)
1999 {
2000     int		cw;
2001 
2002     msg_didout = TRUE;		// remember that line is not empty
2003     cw = (*mb_ptr2cells)(s);
2004     if (cw > 1 && (
2005 #ifdef FEAT_RIGHTLEFT
2006 		cmdmsg_rl ? msg_col <= 1 :
2007 #endif
2008 		msg_col == Columns - 1))
2009     {
2010 	// Doesn't fit, print a highlighted '>' to fill it up.
2011 	msg_screen_putchar('>', HL_ATTR(HLF_AT));
2012 	return s;
2013     }
2014 
2015     screen_puts_len(s, l, msg_row, msg_col, attr);
2016 #ifdef FEAT_RIGHTLEFT
2017     if (cmdmsg_rl)
2018     {
2019 	msg_col -= cw;
2020 	if (msg_col == 0)
2021 	{
2022 	    msg_col = Columns;
2023 	    ++msg_row;
2024 	}
2025     }
2026     else
2027 #endif
2028     {
2029 	msg_col += cw;
2030 	if (msg_col >= Columns)
2031 	{
2032 	    msg_col = 0;
2033 	    ++msg_row;
2034 	}
2035     }
2036     return s + l;
2037 }
2038 
2039 /*
2040  * Output a string to the screen at position msg_row, msg_col.
2041  * Update msg_row and msg_col for the next message.
2042  */
2043     void
2044 msg_puts(char *s)
2045 {
2046     msg_puts_attr(s, 0);
2047 }
2048 
2049     void
2050 msg_puts_title(char *s)
2051 {
2052     msg_puts_attr(s, HL_ATTR(HLF_T));
2053 }
2054 
2055 /*
2056  * Show a message in such a way that it always fits in the line.  Cut out a
2057  * part in the middle and replace it with "..." when necessary.
2058  * Does not handle multi-byte characters!
2059  */
2060     static void
2061 msg_outtrans_long_len_attr(char_u *longstr, int len, int attr)
2062 {
2063     int		slen = len;
2064     int		room;
2065 
2066     room = Columns - msg_col;
2067     if (len > room && room >= 20)
2068     {
2069 	slen = (room - 3) / 2;
2070 	msg_outtrans_len_attr(longstr, slen, attr);
2071 	msg_puts_attr("...", HL_ATTR(HLF_8));
2072     }
2073     msg_outtrans_len_attr(longstr + len - slen, slen, attr);
2074 }
2075 
2076     void
2077 msg_outtrans_long_attr(char_u *longstr, int attr)
2078 {
2079     msg_outtrans_long_len_attr(longstr, (int)STRLEN(longstr), attr);
2080 }
2081 
2082 /*
2083  * Basic function for writing a message with highlight attributes.
2084  */
2085     void
2086 msg_puts_attr(char *s, int attr)
2087 {
2088     msg_puts_attr_len(s, -1, attr);
2089 }
2090 
2091 /*
2092  * Like msg_puts_attr(), but with a maximum length "maxlen" (in bytes).
2093  * When "maxlen" is -1 there is no maximum length.
2094  * When "maxlen" is >= 0 the message is not put in the history.
2095  */
2096     static void
2097 msg_puts_attr_len(char *str, int maxlen, int attr)
2098 {
2099     /*
2100      * If redirection is on, also write to the redirection file.
2101      */
2102     redir_write((char_u *)str, maxlen);
2103 
2104     /*
2105      * Don't print anything when using ":silent cmd".
2106      */
2107     if (msg_silent != 0)
2108 	return;
2109 
2110     // if MSG_HIST flag set, add message to history
2111     if ((attr & MSG_HIST) && maxlen < 0)
2112     {
2113 	add_msg_hist((char_u *)str, -1, attr);
2114 	attr &= ~MSG_HIST;
2115     }
2116 
2117     // When writing something to the screen after it has scrolled, requires a
2118     // wait-return prompt later.  Needed when scrolling, resetting
2119     // need_wait_return after some prompt, and then outputting something
2120     // without scrolling
2121     // Not needed when only using CR to move the cursor.
2122     if (msg_scrolled != 0 && !msg_scrolled_ign && STRCMP(str, "\r") != 0)
2123 	need_wait_return = TRUE;
2124     msg_didany = TRUE;		// remember that something was outputted
2125 
2126     /*
2127      * If there is no valid screen, use fprintf so we can see error messages.
2128      * If termcap is not active, we may be writing in an alternate console
2129      * window, cursor positioning may not work correctly (window size may be
2130      * different, e.g. for Win32 console) or we just don't know where the
2131      * cursor is.
2132      */
2133     if (msg_use_printf())
2134 	msg_puts_printf((char_u *)str, maxlen);
2135     else
2136 	msg_puts_display((char_u *)str, maxlen, attr, FALSE);
2137 }
2138 
2139 /*
2140  * The display part of msg_puts_attr_len().
2141  * May be called recursively to display scroll-back text.
2142  */
2143     static void
2144 msg_puts_display(
2145     char_u	*str,
2146     int		maxlen,
2147     int		attr,
2148     int		recurse)
2149 {
2150     char_u	*s = str;
2151     char_u	*t_s = str;	// string from "t_s" to "s" is still todo
2152     int		t_col = 0;	// screen cells todo, 0 when "t_s" not used
2153     int		l;
2154     int		cw;
2155     char_u	*sb_str = str;
2156     int		sb_col = msg_col;
2157     int		wrap;
2158     int		did_last_char;
2159 
2160     did_wait_return = FALSE;
2161     while ((maxlen < 0 || (int)(s - str) < maxlen) && *s != NUL)
2162     {
2163 	/*
2164 	 * We are at the end of the screen line when:
2165 	 * - When outputting a newline.
2166 	 * - When outputting a character in the last column.
2167 	 */
2168 	if (!recurse && msg_row >= Rows - 1 && (*s == '\n' || (
2169 #ifdef FEAT_RIGHTLEFT
2170 		    cmdmsg_rl
2171 		    ? (
2172 			msg_col <= 1
2173 		      || (*s == TAB && msg_col <= 7)
2174 		      || (has_mbyte && (*mb_ptr2cells)(s) > 1 && msg_col <= 2))
2175 		    :
2176 #endif
2177 		      ((*s != '\r' && msg_col + t_col >= Columns - 1)
2178 		       || (*s == TAB && msg_col + t_col >= ((Columns - 1) & ~7))
2179 		       || (has_mbyte && (*mb_ptr2cells)(s) > 1
2180 					 && msg_col + t_col >= Columns - 2)))))
2181 	{
2182 	    /*
2183 	     * The screen is scrolled up when at the last row (some terminals
2184 	     * scroll automatically, some don't.  To avoid problems we scroll
2185 	     * ourselves).
2186 	     */
2187 	    if (t_col > 0)
2188 		// output postponed text
2189 		t_puts(&t_col, t_s, s, attr);
2190 
2191 	    // When no more prompt and no more room, truncate here
2192 	    if (msg_no_more && lines_left == 0)
2193 		break;
2194 
2195 	    // Scroll the screen up one line.
2196 	    msg_scroll_up();
2197 
2198 	    msg_row = Rows - 2;
2199 	    if (msg_col >= Columns)	// can happen after screen resize
2200 		msg_col = Columns - 1;
2201 
2202 	    // Display char in last column before showing more-prompt.
2203 	    if (*s >= ' '
2204 #ifdef FEAT_RIGHTLEFT
2205 		    && !cmdmsg_rl
2206 #endif
2207 	       )
2208 	    {
2209 		if (has_mbyte)
2210 		{
2211 		    if (enc_utf8 && maxlen >= 0)
2212 			// avoid including composing chars after the end
2213 			l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
2214 		    else
2215 			l = (*mb_ptr2len)(s);
2216 		    s = screen_puts_mbyte(s, l, attr);
2217 		}
2218 		else
2219 		    msg_screen_putchar(*s++, attr);
2220 		did_last_char = TRUE;
2221 	    }
2222 	    else
2223 		did_last_char = FALSE;
2224 
2225 	    if (p_more)
2226 		// store text for scrolling back
2227 		store_sb_text(&sb_str, s, attr, &sb_col, TRUE);
2228 
2229 	    inc_msg_scrolled();
2230 	    need_wait_return = TRUE; // may need wait_return in main()
2231 	    redraw_cmdline = TRUE;
2232 	    if (cmdline_row > 0 && !exmode_active)
2233 		--cmdline_row;
2234 
2235 	    /*
2236 	     * If screen is completely filled and 'more' is set then wait
2237 	     * for a character.
2238 	     */
2239 	    if (lines_left > 0)
2240 		--lines_left;
2241 	    if (p_more && lines_left == 0 && State != HITRETURN
2242 					    && !msg_no_more && !exmode_active)
2243 	    {
2244 #ifdef FEAT_CON_DIALOG
2245 		if (do_more_prompt(NUL))
2246 		    s = confirm_msg_tail;
2247 #else
2248 		(void)do_more_prompt(NUL);
2249 #endif
2250 		if (quit_more)
2251 		    return;
2252 	    }
2253 
2254 	    // When we displayed a char in last column need to check if there
2255 	    // is still more.
2256 	    if (did_last_char)
2257 		continue;
2258 	}
2259 
2260 	wrap = *s == '\n'
2261 		    || msg_col + t_col >= Columns
2262 		    || (has_mbyte && (*mb_ptr2cells)(s) > 1
2263 					    && msg_col + t_col >= Columns - 1);
2264 	if (t_col > 0 && (wrap || *s == '\r' || *s == '\b'
2265 						 || *s == '\t' || *s == BELL))
2266 	    // output any postponed text
2267 	    t_puts(&t_col, t_s, s, attr);
2268 
2269 	if (wrap && p_more && !recurse)
2270 	    // store text for scrolling back
2271 	    store_sb_text(&sb_str, s, attr, &sb_col, TRUE);
2272 
2273 	if (*s == '\n')		    // go to next line
2274 	{
2275 	    msg_didout = FALSE;	    // remember that line is empty
2276 #ifdef FEAT_RIGHTLEFT
2277 	    if (cmdmsg_rl)
2278 		msg_col = Columns - 1;
2279 	    else
2280 #endif
2281 		msg_col = 0;
2282 	    if (++msg_row >= Rows)  // safety check
2283 		msg_row = Rows - 1;
2284 	}
2285 	else if (*s == '\r')	    // go to column 0
2286 	{
2287 	    msg_col = 0;
2288 	}
2289 	else if (*s == '\b')	    // go to previous char
2290 	{
2291 	    if (msg_col)
2292 		--msg_col;
2293 	}
2294 	else if (*s == TAB)	    // translate Tab into spaces
2295 	{
2296 	    do
2297 		msg_screen_putchar(' ', attr);
2298 	    while (msg_col & 7);
2299 	}
2300 	else if (*s == BELL)		// beep (from ":sh")
2301 	    vim_beep(BO_SH);
2302 	else
2303 	{
2304 	    if (has_mbyte)
2305 	    {
2306 		cw = (*mb_ptr2cells)(s);
2307 		if (enc_utf8 && maxlen >= 0)
2308 		    // avoid including composing chars after the end
2309 		    l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
2310 		else
2311 		    l = (*mb_ptr2len)(s);
2312 	    }
2313 	    else
2314 	    {
2315 		cw = 1;
2316 		l = 1;
2317 	    }
2318 
2319 	    // When drawing from right to left or when a double-wide character
2320 	    // doesn't fit, draw a single character here.  Otherwise collect
2321 	    // characters and draw them all at once later.
2322 	    if (
2323 # ifdef FEAT_RIGHTLEFT
2324 		    cmdmsg_rl ||
2325 # endif
2326 		    (cw > 1 && msg_col + t_col >= Columns - 1))
2327 	    {
2328 		if (l > 1)
2329 		    s = screen_puts_mbyte(s, l, attr) - 1;
2330 		else
2331 		    msg_screen_putchar(*s, attr);
2332 	    }
2333 	    else
2334 	    {
2335 		// postpone this character until later
2336 		if (t_col == 0)
2337 		    t_s = s;
2338 		t_col += cw;
2339 		s += l - 1;
2340 	    }
2341 	}
2342 	++s;
2343     }
2344 
2345     // output any postponed text
2346     if (t_col > 0)
2347 	t_puts(&t_col, t_s, s, attr);
2348     if (p_more && !recurse)
2349 	store_sb_text(&sb_str, s, attr, &sb_col, FALSE);
2350 
2351     msg_check();
2352 }
2353 
2354 /*
2355  * Return TRUE when ":filter pattern" was used and "msg" does not match
2356  * "pattern".
2357  */
2358     int
2359 message_filtered(char_u *msg)
2360 {
2361     int match;
2362 
2363     if (cmdmod.cmod_filter_regmatch.regprog == NULL)
2364 	return FALSE;
2365     match = vim_regexec(&cmdmod.cmod_filter_regmatch, msg, (colnr_T)0);
2366     return cmdmod.cmod_filter_force ? match : !match;
2367 }
2368 
2369 /*
2370  * Scroll the screen up one line for displaying the next message line.
2371  */
2372     static void
2373 msg_scroll_up(void)
2374 {
2375 #ifdef FEAT_GUI
2376     // Remove the cursor before scrolling, ScreenLines[] is going
2377     // to become invalid.
2378     if (gui.in_use)
2379 	gui_undraw_cursor();
2380 #endif
2381     // scrolling up always works
2382     mch_disable_flush();
2383     screen_del_lines(0, 0, 1, (int)Rows, TRUE, 0, NULL);
2384     mch_enable_flush();
2385 
2386     if (!can_clear((char_u *)" "))
2387     {
2388 	// Scrolling up doesn't result in the right background.  Set the
2389 	// background here.  It's not efficient, but avoids that we have to do
2390 	// it all over the code.
2391 	screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
2392 
2393 	// Also clear the last char of the last but one line if it was not
2394 	// cleared before to avoid a scroll-up.
2395 	if (ScreenAttrs[LineOffset[Rows - 2] + Columns - 1] == (sattr_T)-1)
2396 	    screen_fill((int)Rows - 2, (int)Rows - 1,
2397 				 (int)Columns - 1, (int)Columns, ' ', ' ', 0);
2398     }
2399 }
2400 
2401 /*
2402  * Increment "msg_scrolled".
2403  */
2404     static void
2405 inc_msg_scrolled(void)
2406 {
2407 #ifdef FEAT_EVAL
2408     if (*get_vim_var_str(VV_SCROLLSTART) == NUL)
2409     {
2410 	char_u	    *p = SOURCING_NAME;
2411 	char_u	    *tofree = NULL;
2412 	int	    len;
2413 
2414 	// v:scrollstart is empty, set it to the script/function name and line
2415 	// number
2416 	if (p == NULL)
2417 	    p = (char_u *)_("Unknown");
2418 	else
2419 	{
2420 	    len = (int)STRLEN(p) + 40;
2421 	    tofree = alloc(len);
2422 	    if (tofree != NULL)
2423 	    {
2424 		vim_snprintf((char *)tofree, len, _("%s line %ld"),
2425 						      p, (long)SOURCING_LNUM);
2426 		p = tofree;
2427 	    }
2428 	}
2429 	set_vim_var_string(VV_SCROLLSTART, p, -1);
2430 	vim_free(tofree);
2431     }
2432 #endif
2433     ++msg_scrolled;
2434     if (must_redraw < VALID)
2435 	must_redraw = VALID;
2436 }
2437 
2438 /*
2439  * To be able to scroll back at the "more" and "hit-enter" prompts we need to
2440  * store the displayed text and remember where screen lines start.
2441  */
2442 typedef struct msgchunk_S msgchunk_T;
2443 struct msgchunk_S
2444 {
2445     msgchunk_T	*sb_next;
2446     msgchunk_T	*sb_prev;
2447     char	sb_eol;		// TRUE when line ends after this text
2448     int		sb_msg_col;	// column in which text starts
2449     int		sb_attr;	// text attributes
2450     char_u	sb_text[1];	// text to be displayed, actually longer
2451 };
2452 
2453 static msgchunk_T *last_msgchunk = NULL; // last displayed text
2454 
2455 static msgchunk_T *msg_sb_start(msgchunk_T *mps);
2456 
2457 typedef enum {
2458     SB_CLEAR_NONE = 0,
2459     SB_CLEAR_ALL,
2460     SB_CLEAR_CMDLINE_BUSY,
2461     SB_CLEAR_CMDLINE_DONE
2462 } sb_clear_T;
2463 
2464 // When to clear text on next msg.
2465 static sb_clear_T do_clear_sb_text = SB_CLEAR_NONE;
2466 
2467 /*
2468  * Store part of a printed message for displaying when scrolling back.
2469  */
2470     static void
2471 store_sb_text(
2472     char_u	**sb_str,	// start of string
2473     char_u	*s,		// just after string
2474     int		attr,
2475     int		*sb_col,
2476     int		finish)		// line ends
2477 {
2478     msgchunk_T	*mp;
2479 
2480     if (do_clear_sb_text == SB_CLEAR_ALL
2481 	    || do_clear_sb_text == SB_CLEAR_CMDLINE_DONE)
2482     {
2483 	clear_sb_text(do_clear_sb_text == SB_CLEAR_ALL);
2484 	do_clear_sb_text = SB_CLEAR_NONE;
2485     }
2486 
2487     if (s > *sb_str)
2488     {
2489 	mp = alloc(sizeof(msgchunk_T) + (s - *sb_str));
2490 	if (mp != NULL)
2491 	{
2492 	    mp->sb_eol = finish;
2493 	    mp->sb_msg_col = *sb_col;
2494 	    mp->sb_attr = attr;
2495 	    vim_strncpy(mp->sb_text, *sb_str, s - *sb_str);
2496 
2497 	    if (last_msgchunk == NULL)
2498 	    {
2499 		last_msgchunk = mp;
2500 		mp->sb_prev = NULL;
2501 	    }
2502 	    else
2503 	    {
2504 		mp->sb_prev = last_msgchunk;
2505 		last_msgchunk->sb_next = mp;
2506 		last_msgchunk = mp;
2507 	    }
2508 	    mp->sb_next = NULL;
2509 	}
2510     }
2511     else if (finish && last_msgchunk != NULL)
2512 	last_msgchunk->sb_eol = TRUE;
2513 
2514     *sb_str = s;
2515     *sb_col = 0;
2516 }
2517 
2518 /*
2519  * Finished showing messages, clear the scroll-back text on the next message.
2520  */
2521     void
2522 may_clear_sb_text(void)
2523 {
2524     do_clear_sb_text = SB_CLEAR_ALL;
2525 }
2526 
2527 /*
2528  * Starting to edit the command line, do not clear messages now.
2529  */
2530     void
2531 sb_text_start_cmdline(void)
2532 {
2533     do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY;
2534     msg_sb_eol();
2535 }
2536 
2537 /*
2538  * Ending to edit the command line.  Clear old lines but the last one later.
2539  */
2540     void
2541 sb_text_end_cmdline(void)
2542 {
2543     do_clear_sb_text = SB_CLEAR_CMDLINE_DONE;
2544 }
2545 
2546 /*
2547  * Clear any text remembered for scrolling back.
2548  * When "all" is FALSE keep the last line.
2549  * Called when redrawing the screen.
2550  */
2551     void
2552 clear_sb_text(int all)
2553 {
2554     msgchunk_T	*mp;
2555     msgchunk_T	**lastp;
2556 
2557     if (all)
2558 	lastp = &last_msgchunk;
2559     else
2560     {
2561 	if (last_msgchunk == NULL)
2562 	    return;
2563 	lastp = &last_msgchunk->sb_prev;
2564     }
2565 
2566     while (*lastp != NULL)
2567     {
2568 	mp = (*lastp)->sb_prev;
2569 	vim_free(*lastp);
2570 	*lastp = mp;
2571     }
2572 }
2573 
2574 /*
2575  * "g<" command.
2576  */
2577     void
2578 show_sb_text(void)
2579 {
2580     msgchunk_T	*mp;
2581 
2582     // Only show something if there is more than one line, otherwise it looks
2583     // weird, typing a command without output results in one line.
2584     mp = msg_sb_start(last_msgchunk);
2585     if (mp == NULL || mp->sb_prev == NULL)
2586 	vim_beep(BO_MESS);
2587     else
2588     {
2589 	do_more_prompt('G');
2590 	wait_return(FALSE);
2591     }
2592 }
2593 
2594 /*
2595  * Move to the start of screen line in already displayed text.
2596  */
2597     static msgchunk_T *
2598 msg_sb_start(msgchunk_T *mps)
2599 {
2600     msgchunk_T *mp = mps;
2601 
2602     while (mp != NULL && mp->sb_prev != NULL && !mp->sb_prev->sb_eol)
2603 	mp = mp->sb_prev;
2604     return mp;
2605 }
2606 
2607 /*
2608  * Mark the last message chunk as finishing the line.
2609  */
2610     void
2611 msg_sb_eol(void)
2612 {
2613     if (last_msgchunk != NULL)
2614 	last_msgchunk->sb_eol = TRUE;
2615 }
2616 
2617 /*
2618  * Display a screen line from previously displayed text at row "row".
2619  * Returns a pointer to the text for the next line (can be NULL).
2620  */
2621     static msgchunk_T *
2622 disp_sb_line(int row, msgchunk_T *smp)
2623 {
2624     msgchunk_T	*mp = smp;
2625     char_u	*p;
2626 
2627     for (;;)
2628     {
2629 	msg_row = row;
2630 	msg_col = mp->sb_msg_col;
2631 	p = mp->sb_text;
2632 	if (*p == '\n')	    // don't display the line break
2633 	    ++p;
2634 	msg_puts_display(p, -1, mp->sb_attr, TRUE);
2635 	if (mp->sb_eol || mp->sb_next == NULL)
2636 	    break;
2637 	mp = mp->sb_next;
2638     }
2639     return mp->sb_next;
2640 }
2641 
2642 /*
2643  * Output any postponed text for msg_puts_attr_len().
2644  */
2645     static void
2646 t_puts(
2647     int		*t_col,
2648     char_u	*t_s,
2649     char_u	*s,
2650     int		attr)
2651 {
2652     // output postponed text
2653     msg_didout = TRUE;		// remember that line is not empty
2654     screen_puts_len(t_s, (int)(s - t_s), msg_row, msg_col, attr);
2655     msg_col += *t_col;
2656     *t_col = 0;
2657     // If the string starts with a composing character don't increment the
2658     // column position for it.
2659     if (enc_utf8 && utf_iscomposing(utf_ptr2char(t_s)))
2660 	--msg_col;
2661     if (msg_col >= Columns)
2662     {
2663 	msg_col = 0;
2664 	++msg_row;
2665     }
2666 }
2667 
2668 /*
2669  * Returns TRUE when messages should be printed with mch_errmsg().
2670  * This is used when there is no valid screen, so we can see error messages.
2671  * If termcap is not active, we may be writing in an alternate console
2672  * window, cursor positioning may not work correctly (window size may be
2673  * different, e.g. for Win32 console) or we just don't know where the
2674  * cursor is.
2675  */
2676     int
2677 msg_use_printf(void)
2678 {
2679     return (!msg_check_screen()
2680 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
2681 # ifdef VIMDLL
2682 	    || (!gui.in_use && !termcap_active)
2683 # else
2684 	    || !termcap_active
2685 # endif
2686 #endif
2687 	    || (swapping_screen() && !termcap_active)
2688 	       );
2689 }
2690 
2691 /*
2692  * Print a message when there is no valid screen.
2693  */
2694     static void
2695 msg_puts_printf(char_u *str, int maxlen)
2696 {
2697     char_u	*s = str;
2698     char_u	*buf = NULL;
2699     char_u	*p = s;
2700 
2701 #ifdef MSWIN
2702     if (!(silent_mode && p_verbose == 0))
2703 	mch_settmode(TMODE_COOK);	// handle CR and NL correctly
2704 #endif
2705     while ((maxlen < 0 || (int)(s - str) < maxlen) && *s != NUL)
2706     {
2707 	if (!(silent_mode && p_verbose == 0))
2708 	{
2709 	    // NL --> CR NL translation (for Unix, not for "--version")
2710 	    if (*s == NL)
2711 	    {
2712 		int n = (int)(s - p);
2713 
2714 		buf = alloc(n + 3);
2715 		if (buf != NULL)
2716 		{
2717 		    memcpy(buf, p, n);
2718 		    if (!info_message)
2719 			buf[n++] = CAR;
2720 		    buf[n++] = NL;
2721 		    buf[n++] = NUL;
2722 		    if (info_message)   // informative message, not an error
2723 			mch_msg((char *)buf);
2724 		    else
2725 			mch_errmsg((char *)buf);
2726 		    vim_free(buf);
2727 		}
2728 		p = s + 1;
2729 	    }
2730 	}
2731 
2732 	// primitive way to compute the current column
2733 #ifdef FEAT_RIGHTLEFT
2734 	if (cmdmsg_rl)
2735 	{
2736 	    if (*s == CAR || *s == NL)
2737 		msg_col = Columns - 1;
2738 	    else
2739 		--msg_col;
2740 	}
2741 	else
2742 #endif
2743 	{
2744 	    if (*s == CAR || *s == NL)
2745 		msg_col = 0;
2746 	    else
2747 		++msg_col;
2748 	}
2749 	++s;
2750     }
2751 
2752     if (*p != NUL && !(silent_mode && p_verbose == 0))
2753     {
2754 	char_u *tofree = NULL;
2755 
2756 	if (maxlen > 0 && STRLEN(p) > (size_t)maxlen)
2757 	{
2758 	    tofree = vim_strnsave(p, (size_t)maxlen);
2759 	    p = tofree;
2760 	}
2761 	if (p != NULL)
2762 	{
2763 	    if (info_message)
2764 		mch_msg((char *)p);
2765 	    else
2766 		mch_errmsg((char *)p);
2767 	    vim_free(tofree);
2768 	}
2769     }
2770 
2771     msg_didout = TRUE;	    // assume that line is not empty
2772 
2773 #ifdef MSWIN
2774     if (!(silent_mode && p_verbose == 0))
2775 	mch_settmode(TMODE_RAW);
2776 #endif
2777 }
2778 
2779 /*
2780  * Show the more-prompt and handle the user response.
2781  * This takes care of scrolling back and displaying previously displayed text.
2782  * When at hit-enter prompt "typed_char" is the already typed character,
2783  * otherwise it's NUL.
2784  * Returns TRUE when jumping ahead to "confirm_msg_tail".
2785  */
2786     static int
2787 do_more_prompt(int typed_char)
2788 {
2789     static int	entered = FALSE;
2790     int		used_typed_char = typed_char;
2791     int		oldState = State;
2792     int		c;
2793 #ifdef FEAT_CON_DIALOG
2794     int		retval = FALSE;
2795 #endif
2796     int		toscroll;
2797     msgchunk_T	*mp_last = NULL;
2798     msgchunk_T	*mp;
2799     int		i;
2800 
2801     // We get called recursively when a timer callback outputs a message. In
2802     // that case don't show another prompt. Also when at the hit-Enter prompt
2803     // and nothing was typed.
2804     if (entered || (State == HITRETURN && typed_char == 0))
2805 	return FALSE;
2806     entered = TRUE;
2807 
2808     if (typed_char == 'G')
2809     {
2810 	// "g<": Find first line on the last page.
2811 	mp_last = msg_sb_start(last_msgchunk);
2812 	for (i = 0; i < Rows - 2 && mp_last != NULL
2813 					     && mp_last->sb_prev != NULL; ++i)
2814 	    mp_last = msg_sb_start(mp_last->sb_prev);
2815     }
2816 
2817     State = ASKMORE;
2818     setmouse();
2819     if (typed_char == NUL)
2820 	msg_moremsg(FALSE);
2821     for (;;)
2822     {
2823 	/*
2824 	 * Get a typed character directly from the user.
2825 	 */
2826 	if (used_typed_char != NUL)
2827 	{
2828 	    c = used_typed_char;	// was typed at hit-enter prompt
2829 	    used_typed_char = NUL;
2830 	}
2831 	else
2832 	    c = get_keystroke();
2833 
2834 #if defined(FEAT_MENU) && defined(FEAT_GUI)
2835 	if (c == K_MENU)
2836 	{
2837 	    int idx = get_menu_index(current_menu, ASKMORE);
2838 
2839 	    // Used a menu.  If it starts with CTRL-Y, it must
2840 	    // be a "Copy" for the clipboard.  Otherwise
2841 	    // assume that we end
2842 	    if (idx == MENU_INDEX_INVALID)
2843 		continue;
2844 	    c = *current_menu->strings[idx];
2845 	    if (c != NUL && current_menu->strings[idx][1] != NUL)
2846 		ins_typebuf(current_menu->strings[idx] + 1,
2847 				current_menu->noremap[idx], 0, TRUE,
2848 						   current_menu->silent[idx]);
2849 	}
2850 #endif
2851 
2852 	toscroll = 0;
2853 	switch (c)
2854 	{
2855 	case BS:		// scroll one line back
2856 	case K_BS:
2857 	case 'k':
2858 	case K_UP:
2859 	    toscroll = -1;
2860 	    break;
2861 
2862 	case CAR:		// one extra line
2863 	case NL:
2864 	case 'j':
2865 	case K_DOWN:
2866 	    toscroll = 1;
2867 	    break;
2868 
2869 	case 'u':		// Up half a page
2870 	    toscroll = -(Rows / 2);
2871 	    break;
2872 
2873 	case 'd':		// Down half a page
2874 	    toscroll = Rows / 2;
2875 	    break;
2876 
2877 	case 'b':		// one page back
2878 	case K_PAGEUP:
2879 	    toscroll = -(Rows - 1);
2880 	    break;
2881 
2882 	case ' ':		// one extra page
2883 	case 'f':
2884 	case K_PAGEDOWN:
2885 	case K_LEFTMOUSE:
2886 	    toscroll = Rows - 1;
2887 	    break;
2888 
2889 	case 'g':		// all the way back to the start
2890 	    toscroll = -999999;
2891 	    break;
2892 
2893 	case 'G':		// all the way to the end
2894 	    toscroll = 999999;
2895 	    lines_left = 999999;
2896 	    break;
2897 
2898 	case ':':		// start new command line
2899 #ifdef FEAT_CON_DIALOG
2900 	    if (!confirm_msg_used)
2901 #endif
2902 	    {
2903 		// Since got_int is set all typeahead will be flushed, but we
2904 		// want to keep this ':', remember that in a special way.
2905 		typeahead_noflush(':');
2906 #ifdef FEAT_TERMINAL
2907 		skip_term_loop = TRUE;
2908 #endif
2909 		cmdline_row = Rows - 1;		// put ':' on this line
2910 		skip_redraw = TRUE;		// skip redraw once
2911 		need_wait_return = FALSE;	// don't wait in main()
2912 	    }
2913 	    // FALLTHROUGH
2914 	case 'q':		// quit
2915 	case Ctrl_C:
2916 	case ESC:
2917 #ifdef FEAT_CON_DIALOG
2918 	    if (confirm_msg_used)
2919 	    {
2920 		// Jump to the choices of the dialog.
2921 		retval = TRUE;
2922 	    }
2923 	    else
2924 #endif
2925 	    {
2926 		got_int = TRUE;
2927 		quit_more = TRUE;
2928 	    }
2929 	    // When there is some more output (wrapping line) display that
2930 	    // without another prompt.
2931 	    lines_left = Rows - 1;
2932 	    break;
2933 
2934 #ifdef FEAT_CLIPBOARD
2935 	case Ctrl_Y:
2936 	    // Strange way to allow copying (yanking) a modeless
2937 	    // selection at the more prompt.  Use CTRL-Y,
2938 	    // because the same is used in Cmdline-mode and at the
2939 	    // hit-enter prompt.  However, scrolling one line up
2940 	    // might be expected...
2941 	    if (clip_star.state == SELECT_DONE)
2942 		clip_copy_modeless_selection(TRUE);
2943 	    continue;
2944 #endif
2945 	default:		// no valid response
2946 	    msg_moremsg(TRUE);
2947 	    continue;
2948 	}
2949 
2950 	if (toscroll != 0)
2951 	{
2952 	    if (toscroll < 0)
2953 	    {
2954 		// go to start of last line
2955 		if (mp_last == NULL)
2956 		    mp = msg_sb_start(last_msgchunk);
2957 		else if (mp_last->sb_prev != NULL)
2958 		    mp = msg_sb_start(mp_last->sb_prev);
2959 		else
2960 		    mp = NULL;
2961 
2962 		// go to start of line at top of the screen
2963 		for (i = 0; i < Rows - 2 && mp != NULL && mp->sb_prev != NULL;
2964 									  ++i)
2965 		    mp = msg_sb_start(mp->sb_prev);
2966 
2967 		if (mp != NULL && mp->sb_prev != NULL)
2968 		{
2969 		    // Find line to be displayed at top.
2970 		    for (i = 0; i > toscroll; --i)
2971 		    {
2972 			if (mp == NULL || mp->sb_prev == NULL)
2973 			    break;
2974 			mp = msg_sb_start(mp->sb_prev);
2975 			if (mp_last == NULL)
2976 			    mp_last = msg_sb_start(last_msgchunk);
2977 			else
2978 			    mp_last = msg_sb_start(mp_last->sb_prev);
2979 		    }
2980 
2981 		    if (toscroll == -1 && screen_ins_lines(0, 0, 1,
2982 						     (int)Rows, 0, NULL) == OK)
2983 		    {
2984 			// display line at top
2985 			(void)disp_sb_line(0, mp);
2986 		    }
2987 		    else
2988 		    {
2989 			// redisplay all lines
2990 			screenclear();
2991 			for (i = 0; mp != NULL && i < Rows - 1; ++i)
2992 			{
2993 			    mp = disp_sb_line(i, mp);
2994 			    ++msg_scrolled;
2995 			}
2996 		    }
2997 		    toscroll = 0;
2998 		}
2999 	    }
3000 	    else
3001 	    {
3002 		// First display any text that we scrolled back.
3003 		while (toscroll > 0 && mp_last != NULL)
3004 		{
3005 		    // scroll up, display line at bottom
3006 		    msg_scroll_up();
3007 		    inc_msg_scrolled();
3008 		    screen_fill((int)Rows - 2, (int)Rows - 1, 0,
3009 						   (int)Columns, ' ', ' ', 0);
3010 		    mp_last = disp_sb_line((int)Rows - 2, mp_last);
3011 		    --toscroll;
3012 		}
3013 	    }
3014 
3015 	    if (toscroll <= 0)
3016 	    {
3017 		// displayed the requested text, more prompt again
3018 		screen_fill((int)Rows - 1, (int)Rows, 0,
3019 						   (int)Columns, ' ', ' ', 0);
3020 		msg_moremsg(FALSE);
3021 		continue;
3022 	    }
3023 
3024 	    // display more text, return to caller
3025 	    lines_left = toscroll;
3026 	}
3027 
3028 	break;
3029     }
3030 
3031     // clear the --more-- message
3032     screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
3033     State = oldState;
3034     setmouse();
3035     if (quit_more)
3036     {
3037 	msg_row = Rows - 1;
3038 	msg_col = 0;
3039     }
3040 #ifdef FEAT_RIGHTLEFT
3041     else if (cmdmsg_rl)
3042 	msg_col = Columns - 1;
3043 #endif
3044 
3045     entered = FALSE;
3046 #ifdef FEAT_CON_DIALOG
3047     return retval;
3048 #else
3049     return FALSE;
3050 #endif
3051 }
3052 
3053 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
3054 
3055 #ifdef mch_errmsg
3056 # undef mch_errmsg
3057 #endif
3058 #ifdef mch_msg
3059 # undef mch_msg
3060 #endif
3061 
3062 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3063     static void
3064 mch_errmsg_c(char *str)
3065 {
3066     int	    len = (int)STRLEN(str);
3067     DWORD   nwrite = 0;
3068     DWORD   mode = 0;
3069     HANDLE  h = GetStdHandle(STD_ERROR_HANDLE);
3070 
3071     if (GetConsoleMode(h, &mode) && enc_codepage >= 0
3072 	    && (int)GetConsoleCP() != enc_codepage)
3073     {
3074 	WCHAR	*w = enc_to_utf16((char_u *)str, &len);
3075 
3076 	WriteConsoleW(h, w, len, &nwrite, NULL);
3077 	vim_free(w);
3078     }
3079     else
3080     {
3081 	fprintf(stderr, "%s", str);
3082     }
3083 }
3084 #endif
3085 
3086 /*
3087  * Give an error message.  To be used when the screen hasn't been initialized
3088  * yet.  When stderr can't be used, collect error messages until the GUI has
3089  * started and they can be displayed in a message box.
3090  */
3091     void
3092 mch_errmsg(char *str)
3093 {
3094 #if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
3095     int		len;
3096 #endif
3097 
3098 #if (defined(UNIX) || defined(FEAT_GUI)) && !defined(ALWAYS_USE_GUI) && !defined(VIMDLL)
3099     // On Unix use stderr if it's a tty.
3100     // When not going to start the GUI also use stderr.
3101     // On Mac, when started from Finder, stderr is the console.
3102     if (
3103 # ifdef UNIX
3104 #  ifdef MACOS_X
3105 	    (isatty(2) && strcmp("/dev/console", ttyname(2)) != 0)
3106 #  else
3107 	    isatty(2)
3108 #  endif
3109 #  ifdef FEAT_GUI
3110 	    ||
3111 #  endif
3112 # endif
3113 # ifdef FEAT_GUI
3114 	    !(gui.in_use || gui.starting)
3115 # endif
3116 	    )
3117     {
3118 	fprintf(stderr, "%s", str);
3119 	return;
3120     }
3121 #endif
3122 
3123 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3124 # ifdef VIMDLL
3125     if (!(gui.in_use || gui.starting))
3126 # endif
3127     {
3128 	mch_errmsg_c(str);
3129 	return;
3130     }
3131 #endif
3132 
3133 #if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
3134     // avoid a delay for a message that isn't there
3135     emsg_on_display = FALSE;
3136 
3137     len = (int)STRLEN(str) + 1;
3138     if (error_ga.ga_growsize == 0)
3139     {
3140 	error_ga.ga_growsize = 80;
3141 	error_ga.ga_itemsize = 1;
3142     }
3143     if (ga_grow(&error_ga, len) == OK)
3144     {
3145 	mch_memmove((char_u *)error_ga.ga_data + error_ga.ga_len,
3146 							  (char_u *)str, len);
3147 # ifdef UNIX
3148 	// remove CR characters, they are displayed
3149 	{
3150 	    char_u	*p;
3151 
3152 	    p = (char_u *)error_ga.ga_data + error_ga.ga_len;
3153 	    for (;;)
3154 	    {
3155 		p = vim_strchr(p, '\r');
3156 		if (p == NULL)
3157 		    break;
3158 		*p = ' ';
3159 	    }
3160 	}
3161 # endif
3162 	--len;		// don't count the NUL at the end
3163 	error_ga.ga_len += len;
3164     }
3165 #endif
3166 }
3167 
3168 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3169     static void
3170 mch_msg_c(char *str)
3171 {
3172     int	    len = (int)STRLEN(str);
3173     DWORD   nwrite = 0;
3174     DWORD   mode;
3175     HANDLE  h = GetStdHandle(STD_OUTPUT_HANDLE);
3176 
3177 
3178     if (GetConsoleMode(h, &mode) && enc_codepage >= 0
3179 	    && (int)GetConsoleCP() != enc_codepage)
3180     {
3181 	WCHAR	*w = enc_to_utf16((char_u *)str, &len);
3182 
3183 	WriteConsoleW(h, w, len, &nwrite, NULL);
3184 	vim_free(w);
3185     }
3186     else
3187     {
3188 	printf("%s", str);
3189     }
3190 }
3191 #endif
3192 
3193 /*
3194  * Give a message.  To be used when the screen hasn't been initialized yet.
3195  * When there is no tty, collect messages until the GUI has started and they
3196  * can be displayed in a message box.
3197  */
3198     void
3199 mch_msg(char *str)
3200 {
3201 #if (defined(UNIX) || defined(FEAT_GUI)) && !defined(ALWAYS_USE_GUI) && !defined(VIMDLL)
3202     // On Unix use stdout if we have a tty.  This allows "vim -h | more" and
3203     // uses mch_errmsg() when started from the desktop.
3204     // When not going to start the GUI also use stdout.
3205     // On Mac, when started from Finder, stderr is the console.
3206     if (
3207 # ifdef UNIX
3208 #  ifdef MACOS_X
3209 	    (isatty(2) && strcmp("/dev/console", ttyname(2)) != 0)
3210 #  else
3211 	    isatty(2)
3212 #  endif
3213 #  ifdef FEAT_GUI
3214 	    ||
3215 #  endif
3216 # endif
3217 # ifdef FEAT_GUI
3218 	    !(gui.in_use || gui.starting)
3219 # endif
3220 	    )
3221     {
3222 	printf("%s", str);
3223 	return;
3224     }
3225 #endif
3226 
3227 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3228 # ifdef VIMDLL
3229     if (!(gui.in_use || gui.starting))
3230 # endif
3231     {
3232 	mch_msg_c(str);
3233 	return;
3234     }
3235 #endif
3236 #if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
3237     mch_errmsg(str);
3238 #endif
3239 }
3240 #endif // USE_MCH_ERRMSG
3241 
3242 /*
3243  * Put a character on the screen at the current message position and advance
3244  * to the next position.  Only for printable ASCII!
3245  */
3246     static void
3247 msg_screen_putchar(int c, int attr)
3248 {
3249     msg_didout = TRUE;		// remember that line is not empty
3250     screen_putchar(c, msg_row, msg_col, attr);
3251 #ifdef FEAT_RIGHTLEFT
3252     if (cmdmsg_rl)
3253     {
3254 	if (--msg_col == 0)
3255 	{
3256 	    msg_col = Columns;
3257 	    ++msg_row;
3258 	}
3259     }
3260     else
3261 #endif
3262     {
3263 	if (++msg_col >= Columns)
3264 	{
3265 	    msg_col = 0;
3266 	    ++msg_row;
3267 	}
3268     }
3269 }
3270 
3271     static void
3272 msg_moremsg(int full)
3273 {
3274     int		attr;
3275     char_u	*s = (char_u *)_("-- More --");
3276 
3277     attr = HL_ATTR(HLF_M);
3278     screen_puts(s, (int)Rows - 1, 0, attr);
3279     if (full)
3280 	screen_puts((char_u *)
3281 		_(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "),
3282 		(int)Rows - 1, vim_strsize(s), attr);
3283 }
3284 
3285 /*
3286  * Repeat the message for the current mode: ASKMORE, EXTERNCMD, CONFIRM or
3287  * exmode_active.
3288  */
3289     void
3290 repeat_message(void)
3291 {
3292     if (State == ASKMORE)
3293     {
3294 	msg_moremsg(TRUE);	// display --more-- message again
3295 	msg_row = Rows - 1;
3296     }
3297 #ifdef FEAT_CON_DIALOG
3298     else if (State == CONFIRM)
3299     {
3300 	display_confirm_msg();	// display ":confirm" message again
3301 	msg_row = Rows - 1;
3302     }
3303 #endif
3304     else if (State == EXTERNCMD)
3305     {
3306 	windgoto(msg_row, msg_col); // put cursor back
3307     }
3308     else if (State == HITRETURN || State == SETWSIZE)
3309     {
3310 	if (msg_row == Rows - 1)
3311 	{
3312 	    // Avoid drawing the "hit-enter" prompt below the previous one,
3313 	    // overwrite it.  Esp. useful when regaining focus and a
3314 	    // FocusGained autocmd exists but didn't draw anything.
3315 	    msg_didout = FALSE;
3316 	    msg_col = 0;
3317 	    msg_clr_eos();
3318 	}
3319 	hit_return_msg();
3320 	msg_row = Rows - 1;
3321     }
3322 }
3323 
3324 /*
3325  * msg_check_screen - check if the screen is initialized.
3326  * Also check msg_row and msg_col, if they are too big it may cause a crash.
3327  * While starting the GUI the terminal codes will be set for the GUI, but the
3328  * output goes to the terminal.  Don't use the terminal codes then.
3329  */
3330     static int
3331 msg_check_screen(void)
3332 {
3333     if (!full_screen || !screen_valid(FALSE))
3334 	return FALSE;
3335 
3336     if (msg_row >= Rows)
3337 	msg_row = Rows - 1;
3338     if (msg_col >= Columns)
3339 	msg_col = Columns - 1;
3340     return TRUE;
3341 }
3342 
3343 /*
3344  * Clear from current message position to end of screen.
3345  * Skip this when ":silent" was used, no need to clear for redirection.
3346  */
3347     void
3348 msg_clr_eos(void)
3349 {
3350     if (msg_silent == 0)
3351 	msg_clr_eos_force();
3352 }
3353 
3354 /*
3355  * Clear from current message position to end of screen.
3356  * Note: msg_col is not updated, so we remember the end of the message
3357  * for msg_check().
3358  */
3359     void
3360 msg_clr_eos_force(void)
3361 {
3362     if (msg_use_printf())
3363     {
3364 	if (full_screen)	// only when termcap codes are valid
3365 	{
3366 	    if (*T_CD)
3367 		out_str(T_CD);	// clear to end of display
3368 	    else if (*T_CE)
3369 		out_str(T_CE);	// clear to end of line
3370 	}
3371     }
3372     else
3373     {
3374 #ifdef FEAT_RIGHTLEFT
3375 	if (cmdmsg_rl)
3376 	{
3377 	    screen_fill(msg_row, msg_row + 1, 0, msg_col + 1, ' ', ' ', 0);
3378 	    screen_fill(msg_row + 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
3379 	}
3380 	else
3381 #endif
3382 	{
3383 	    screen_fill(msg_row, msg_row + 1, msg_col, (int)Columns,
3384 								 ' ', ' ', 0);
3385 	    screen_fill(msg_row + 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
3386 	}
3387     }
3388 }
3389 
3390 /*
3391  * Clear the command line.
3392  */
3393     void
3394 msg_clr_cmdline(void)
3395 {
3396     msg_row = cmdline_row;
3397     msg_col = 0;
3398     msg_clr_eos_force();
3399 }
3400 
3401 /*
3402  * end putting a message on the screen
3403  * call wait_return if the message does not fit in the available space
3404  * return TRUE if wait_return not called.
3405  */
3406     int
3407 msg_end(void)
3408 {
3409     /*
3410      * If the string is larger than the window,
3411      * or the ruler option is set and we run into it,
3412      * we have to redraw the window.
3413      * Do not do this if we are abandoning the file or editing the command line.
3414      */
3415     if (!exiting && need_wait_return && !(State & CMDLINE))
3416     {
3417 	wait_return(FALSE);
3418 	return FALSE;
3419     }
3420     out_flush();
3421     return TRUE;
3422 }
3423 
3424 /*
3425  * If the written message runs into the shown command or ruler, we have to
3426  * wait for hit-return and redraw the window later.
3427  */
3428     void
3429 msg_check(void)
3430 {
3431     if (msg_row == Rows - 1 && msg_col >= sc_col)
3432     {
3433 	need_wait_return = TRUE;
3434 	redraw_cmdline = TRUE;
3435     }
3436 }
3437 
3438 /*
3439  * May write a string to the redirection file.
3440  * When "maxlen" is -1 write the whole string, otherwise up to "maxlen" bytes.
3441  */
3442     static void
3443 redir_write(char_u *str, int maxlen)
3444 {
3445     char_u	*s = str;
3446     static int	cur_col = 0;
3447 
3448     // Don't do anything for displaying prompts and the like.
3449     if (redir_off)
3450 	return;
3451 
3452     // If 'verbosefile' is set prepare for writing in that file.
3453     if (*p_vfile != NUL && verbose_fd == NULL)
3454 	verbose_open();
3455 
3456     if (redirecting())
3457     {
3458 	// If the string doesn't start with CR or NL, go to msg_col
3459 	if (*s != '\n' && *s != '\r')
3460 	{
3461 	    while (cur_col < msg_col)
3462 	    {
3463 #ifdef FEAT_EVAL
3464 		if (redir_execute)
3465 		    execute_redir_str((char_u *)" ", -1);
3466 		else if (redir_reg)
3467 		    write_reg_contents(redir_reg, (char_u *)" ", -1, TRUE);
3468 		else if (redir_vname)
3469 		    var_redir_str((char_u *)" ", -1);
3470 		else
3471 #endif
3472 		    if (redir_fd != NULL)
3473 		    fputs(" ", redir_fd);
3474 		if (verbose_fd != NULL)
3475 		    fputs(" ", verbose_fd);
3476 		++cur_col;
3477 	    }
3478 	}
3479 
3480 #ifdef FEAT_EVAL
3481 	if (redir_execute)
3482 	    execute_redir_str(s, maxlen);
3483 	else if (redir_reg)
3484 	    write_reg_contents(redir_reg, s, maxlen, TRUE);
3485 	else if (redir_vname)
3486 	    var_redir_str(s, maxlen);
3487 #endif
3488 
3489 	// Write and adjust the current column.
3490 	while (*s != NUL && (maxlen < 0 || (int)(s - str) < maxlen))
3491 	{
3492 #ifdef FEAT_EVAL
3493 	    if (!redir_reg && !redir_vname && !redir_execute)
3494 #endif
3495 		if (redir_fd != NULL)
3496 		    putc(*s, redir_fd);
3497 	    if (verbose_fd != NULL)
3498 		putc(*s, verbose_fd);
3499 	    if (*s == '\r' || *s == '\n')
3500 		cur_col = 0;
3501 	    else if (*s == '\t')
3502 		cur_col += (8 - cur_col % 8);
3503 	    else
3504 		++cur_col;
3505 	    ++s;
3506 	}
3507 
3508 	if (msg_silent != 0)	// should update msg_col
3509 	    msg_col = cur_col;
3510     }
3511 }
3512 
3513     int
3514 redirecting(void)
3515 {
3516     return redir_fd != NULL || *p_vfile != NUL
3517 #ifdef FEAT_EVAL
3518 			  || redir_reg || redir_vname || redir_execute
3519 #endif
3520 				       ;
3521 }
3522 
3523 /*
3524  * Before giving verbose message.
3525  * Must always be called paired with verbose_leave()!
3526  */
3527     void
3528 verbose_enter(void)
3529 {
3530     if (*p_vfile != NUL)
3531 	++msg_silent;
3532 }
3533 
3534 /*
3535  * After giving verbose message.
3536  * Must always be called paired with verbose_enter()!
3537  */
3538     void
3539 verbose_leave(void)
3540 {
3541     if (*p_vfile != NUL)
3542 	if (--msg_silent < 0)
3543 	    msg_silent = 0;
3544 }
3545 
3546 /*
3547  * Like verbose_enter() and set msg_scroll when displaying the message.
3548  */
3549     void
3550 verbose_enter_scroll(void)
3551 {
3552     if (*p_vfile != NUL)
3553 	++msg_silent;
3554     else
3555 	// always scroll up, don't overwrite
3556 	msg_scroll = TRUE;
3557 }
3558 
3559 /*
3560  * Like verbose_leave() and set cmdline_row when displaying the message.
3561  */
3562     void
3563 verbose_leave_scroll(void)
3564 {
3565     if (*p_vfile != NUL)
3566     {
3567 	if (--msg_silent < 0)
3568 	    msg_silent = 0;
3569     }
3570     else
3571 	cmdline_row = msg_row;
3572 }
3573 
3574 /*
3575  * Called when 'verbosefile' is set: stop writing to the file.
3576  */
3577     void
3578 verbose_stop(void)
3579 {
3580     if (verbose_fd != NULL)
3581     {
3582 	fclose(verbose_fd);
3583 	verbose_fd = NULL;
3584     }
3585     verbose_did_open = FALSE;
3586 }
3587 
3588 /*
3589  * Open the file 'verbosefile'.
3590  * Return FAIL or OK.
3591  */
3592     int
3593 verbose_open(void)
3594 {
3595     if (verbose_fd == NULL && !verbose_did_open)
3596     {
3597 	// Only give the error message once.
3598 	verbose_did_open = TRUE;
3599 
3600 	verbose_fd = mch_fopen((char *)p_vfile, "a");
3601 	if (verbose_fd == NULL)
3602 	{
3603 	    semsg(_(e_notopen), p_vfile);
3604 	    return FAIL;
3605 	}
3606     }
3607     return OK;
3608 }
3609 
3610 /*
3611  * Give a warning message (for searching).
3612  * Use 'w' highlighting and may repeat the message after redrawing
3613  */
3614     void
3615 give_warning(char_u *message, int hl)
3616 {
3617     // Don't do this for ":silent".
3618     if (msg_silent != 0)
3619 	return;
3620 
3621     // Don't want a hit-enter prompt here.
3622     ++no_wait_return;
3623 
3624 #ifdef FEAT_EVAL
3625     set_vim_var_string(VV_WARNINGMSG, message, -1);
3626 #endif
3627     VIM_CLEAR(keep_msg);
3628     if (hl)
3629 	keep_msg_attr = HL_ATTR(HLF_W);
3630     else
3631 	keep_msg_attr = 0;
3632     if (msg_attr((char *)message, keep_msg_attr) && msg_scrolled == 0)
3633 	set_keep_msg(message, keep_msg_attr);
3634     msg_didout = FALSE;	    // overwrite this message
3635     msg_nowait = TRUE;	    // don't wait for this message
3636     msg_col = 0;
3637 
3638     --no_wait_return;
3639 }
3640 
3641 #if defined(FEAT_EVAL) || defined(PROTO)
3642     void
3643 give_warning2(char_u *message, char_u *a1, int hl)
3644 {
3645     if (IObuff == NULL)
3646     {
3647 	// Very early in initialisation and already something wrong, just give
3648 	// the raw message so the user at least gets a hint.
3649 	give_warning((char_u *)message, hl);
3650     }
3651     else
3652     {
3653 	vim_snprintf((char *)IObuff, IOSIZE, (char *)message, a1);
3654 	give_warning(IObuff, hl);
3655     }
3656 }
3657 #endif
3658 
3659 /*
3660  * Advance msg cursor to column "col".
3661  */
3662     void
3663 msg_advance(int col)
3664 {
3665     if (msg_silent != 0)	// nothing to advance to
3666     {
3667 	msg_col = col;		// for redirection, may fill it up later
3668 	return;
3669     }
3670     if (col >= Columns)		// not enough room
3671 	col = Columns - 1;
3672 #ifdef FEAT_RIGHTLEFT
3673     if (cmdmsg_rl)
3674 	while (msg_col > Columns - col)
3675 	    msg_putchar(' ');
3676     else
3677 #endif
3678 	while (msg_col < col)
3679 	    msg_putchar(' ');
3680 }
3681 
3682 #if defined(FEAT_CON_DIALOG) || defined(PROTO)
3683 /*
3684  * Used for "confirm()" function, and the :confirm command prefix.
3685  * Versions which haven't got flexible dialogs yet, and console
3686  * versions, get this generic handler which uses the command line.
3687  *
3688  * type  = one of:
3689  *	   VIM_QUESTION, VIM_INFO, VIM_WARNING, VIM_ERROR or VIM_GENERIC
3690  * title = title string (can be NULL for default)
3691  * (neither used in console dialogs at the moment)
3692  *
3693  * Format of the "buttons" string:
3694  * "Button1Name\nButton2Name\nButton3Name"
3695  * The first button should normally be the default/accept
3696  * The second button should be the 'Cancel' button
3697  * Other buttons- use your imagination!
3698  * A '&' in a button name becomes a shortcut, so each '&' should be before a
3699  * different letter.
3700  */
3701     int
3702 do_dialog(
3703     int		type UNUSED,
3704     char_u	*title UNUSED,
3705     char_u	*message,
3706     char_u	*buttons,
3707     int		dfltbutton,
3708     char_u	*textfield UNUSED,	// IObuff for inputdialog(), NULL
3709 					// otherwise
3710     int		ex_cmd)	    // when TRUE pressing : accepts default and starts
3711 			    // Ex command
3712 {
3713     int		oldState;
3714     int		retval = 0;
3715     char_u	*hotkeys;
3716     int		c;
3717     int		i;
3718     tmode_T	save_tmode;
3719 
3720 #ifndef NO_CONSOLE
3721     // Don't output anything in silent mode ("ex -s")
3722     if (silent_mode)
3723 	return dfltbutton;   // return default option
3724 #endif
3725 
3726 #ifdef FEAT_GUI_DIALOG
3727     // When GUI is running and 'c' not in 'guioptions', use the GUI dialog
3728     if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
3729     {
3730 	c = gui_mch_dialog(type, title, message, buttons, dfltbutton,
3731 							   textfield, ex_cmd);
3732 	// avoid a hit-enter prompt without clearing the cmdline
3733 	need_wait_return = FALSE;
3734 	emsg_on_display = FALSE;
3735 	cmdline_row = msg_row;
3736 
3737 	// Flush output to avoid that further messages and redrawing is done
3738 	// in the wrong order.
3739 	out_flush();
3740 	gui_mch_update();
3741 
3742 	return c;
3743     }
3744 #endif
3745 
3746     oldState = State;
3747     State = CONFIRM;
3748     setmouse();
3749 
3750     // Ensure raw mode here.
3751     save_tmode = cur_tmode;
3752     settmode(TMODE_RAW);
3753 
3754     /*
3755      * Since we wait for a keypress, don't make the
3756      * user press RETURN as well afterwards.
3757      */
3758     ++no_wait_return;
3759     hotkeys = msg_show_console_dialog(message, buttons, dfltbutton);
3760 
3761     if (hotkeys != NULL)
3762     {
3763 	for (;;)
3764 	{
3765 	    // Get a typed character directly from the user.
3766 	    c = get_keystroke();
3767 	    switch (c)
3768 	    {
3769 	    case CAR:		// User accepts default option
3770 	    case NL:
3771 		retval = dfltbutton;
3772 		break;
3773 	    case Ctrl_C:	// User aborts/cancels
3774 	    case ESC:
3775 		retval = 0;
3776 		break;
3777 	    default:		// Could be a hotkey?
3778 		if (c < 0)	// special keys are ignored here
3779 		    continue;
3780 		if (c == ':' && ex_cmd)
3781 		{
3782 		    retval = dfltbutton;
3783 		    ins_char_typebuf(':', 0);
3784 		    break;
3785 		}
3786 
3787 		// Make the character lowercase, as chars in "hotkeys" are.
3788 		c = MB_TOLOWER(c);
3789 		retval = 1;
3790 		for (i = 0; hotkeys[i]; ++i)
3791 		{
3792 		    if (has_mbyte)
3793 		    {
3794 			if ((*mb_ptr2char)(hotkeys + i) == c)
3795 			    break;
3796 			i += (*mb_ptr2len)(hotkeys + i) - 1;
3797 		    }
3798 		    else
3799 			if (hotkeys[i] == c)
3800 			    break;
3801 		    ++retval;
3802 		}
3803 		if (hotkeys[i])
3804 		    break;
3805 		// No hotkey match, so keep waiting
3806 		continue;
3807 	    }
3808 	    break;
3809 	}
3810 
3811 	vim_free(hotkeys);
3812     }
3813 
3814     settmode(save_tmode);
3815     State = oldState;
3816     setmouse();
3817     --no_wait_return;
3818     msg_end_prompt();
3819 
3820     return retval;
3821 }
3822 
3823 /*
3824  * Copy one character from "*from" to "*to", taking care of multi-byte
3825  * characters.  Return the length of the character in bytes.
3826  */
3827     static int
3828 copy_char(
3829     char_u	*from,
3830     char_u	*to,
3831     int		lowercase)	// make character lower case
3832 {
3833     int		len;
3834     int		c;
3835 
3836     if (has_mbyte)
3837     {
3838 	if (lowercase)
3839 	{
3840 	    c = MB_TOLOWER((*mb_ptr2char)(from));
3841 	    return (*mb_char2bytes)(c, to);
3842 	}
3843 	else
3844 	{
3845 	    len = (*mb_ptr2len)(from);
3846 	    mch_memmove(to, from, (size_t)len);
3847 	    return len;
3848 	}
3849     }
3850     else
3851     {
3852 	if (lowercase)
3853 	    *to = (char_u)TOLOWER_LOC(*from);
3854 	else
3855 	    *to = *from;
3856 	return 1;
3857     }
3858 }
3859 
3860 /*
3861  * Format the dialog string, and display it at the bottom of
3862  * the screen. Return a string of hotkey chars (if defined) for
3863  * each 'button'. If a button has no hotkey defined, the first character of
3864  * the button is used.
3865  * The hotkeys can be multi-byte characters, but without combining chars.
3866  *
3867  * Returns an allocated string with hotkeys, or NULL for error.
3868  */
3869     static char_u *
3870 msg_show_console_dialog(
3871     char_u	*message,
3872     char_u	*buttons,
3873     int		dfltbutton)
3874 {
3875     int		len = 0;
3876 #define HOTK_LEN (has_mbyte ? MB_MAXBYTES : 1)
3877     int		lenhotkey = HOTK_LEN;	// count first button
3878     char_u	*hotk = NULL;
3879     char_u	*msgp = NULL;
3880     char_u	*hotkp = NULL;
3881     char_u	*r;
3882     int		copy;
3883 #define HAS_HOTKEY_LEN 30
3884     char_u	has_hotkey[HAS_HOTKEY_LEN];
3885     int		first_hotkey = FALSE;	// first char of button is hotkey
3886     int		idx;
3887 
3888     has_hotkey[0] = FALSE;
3889 
3890     /*
3891      * First loop: compute the size of memory to allocate.
3892      * Second loop: copy to the allocated memory.
3893      */
3894     for (copy = 0; copy <= 1; ++copy)
3895     {
3896 	r = buttons;
3897 	idx = 0;
3898 	while (*r)
3899 	{
3900 	    if (*r == DLG_BUTTON_SEP)
3901 	    {
3902 		if (copy)
3903 		{
3904 		    *msgp++ = ',';
3905 		    *msgp++ = ' ';	    // '\n' -> ', '
3906 
3907 		    // advance to next hotkey and set default hotkey
3908 		    if (has_mbyte)
3909 			hotkp += STRLEN(hotkp);
3910 		    else
3911 			++hotkp;
3912 		    hotkp[copy_char(r + 1, hotkp, TRUE)] = NUL;
3913 		    if (dfltbutton)
3914 			--dfltbutton;
3915 
3916 		    // If no hotkey is specified first char is used.
3917 		    if (idx < HAS_HOTKEY_LEN - 1 && !has_hotkey[++idx])
3918 			first_hotkey = TRUE;
3919 		}
3920 		else
3921 		{
3922 		    len += 3;		    // '\n' -> ', '; 'x' -> '(x)'
3923 		    lenhotkey += HOTK_LEN;  // each button needs a hotkey
3924 		    if (idx < HAS_HOTKEY_LEN - 1)
3925 			has_hotkey[++idx] = FALSE;
3926 		}
3927 	    }
3928 	    else if (*r == DLG_HOTKEY_CHAR || first_hotkey)
3929 	    {
3930 		if (*r == DLG_HOTKEY_CHAR)
3931 		    ++r;
3932 		first_hotkey = FALSE;
3933 		if (copy)
3934 		{
3935 		    if (*r == DLG_HOTKEY_CHAR)		// '&&a' -> '&a'
3936 			*msgp++ = *r;
3937 		    else
3938 		    {
3939 			// '&a' -> '[a]'
3940 			*msgp++ = (dfltbutton == 1) ? '[' : '(';
3941 			msgp += copy_char(r, msgp, FALSE);
3942 			*msgp++ = (dfltbutton == 1) ? ']' : ')';
3943 
3944 			// redefine hotkey
3945 			hotkp[copy_char(r, hotkp, TRUE)] = NUL;
3946 		    }
3947 		}
3948 		else
3949 		{
3950 		    ++len;	    // '&a' -> '[a]'
3951 		    if (idx < HAS_HOTKEY_LEN - 1)
3952 			has_hotkey[idx] = TRUE;
3953 		}
3954 	    }
3955 	    else
3956 	    {
3957 		// everything else copy literally
3958 		if (copy)
3959 		    msgp += copy_char(r, msgp, FALSE);
3960 	    }
3961 
3962 	    // advance to the next character
3963 	    MB_PTR_ADV(r);
3964 	}
3965 
3966 	if (copy)
3967 	{
3968 	    *msgp++ = ':';
3969 	    *msgp++ = ' ';
3970 	    *msgp = NUL;
3971 	}
3972 	else
3973 	{
3974 	    len += (int)(STRLEN(message)
3975 			+ 2			// for the NL's
3976 			+ STRLEN(buttons)
3977 			+ 3);			// for the ": " and NUL
3978 	    lenhotkey++;			// for the NUL
3979 
3980 	    // If no hotkey is specified first char is used.
3981 	    if (!has_hotkey[0])
3982 	    {
3983 		first_hotkey = TRUE;
3984 		len += 2;		// "x" -> "[x]"
3985 	    }
3986 
3987 	    /*
3988 	     * Now allocate and load the strings
3989 	     */
3990 	    vim_free(confirm_msg);
3991 	    confirm_msg = alloc(len);
3992 	    if (confirm_msg == NULL)
3993 		return NULL;
3994 	    *confirm_msg = NUL;
3995 	    hotk = alloc(lenhotkey);
3996 	    if (hotk == NULL)
3997 		return NULL;
3998 
3999 	    *confirm_msg = '\n';
4000 	    STRCPY(confirm_msg + 1, message);
4001 
4002 	    msgp = confirm_msg + 1 + STRLEN(message);
4003 	    hotkp = hotk;
4004 
4005 	    // Define first default hotkey.  Keep the hotkey string NUL
4006 	    // terminated to avoid reading past the end.
4007 	    hotkp[copy_char(buttons, hotkp, TRUE)] = NUL;
4008 
4009 	    // Remember where the choices start, displaying starts here when
4010 	    // "hotkp" typed at the more prompt.
4011 	    confirm_msg_tail = msgp;
4012 	    *msgp++ = '\n';
4013 	}
4014     }
4015 
4016     display_confirm_msg();
4017     return hotk;
4018 }
4019 
4020 /*
4021  * Display the ":confirm" message.  Also called when screen resized.
4022  */
4023     static void
4024 display_confirm_msg(void)
4025 {
4026     // avoid that 'q' at the more prompt truncates the message here
4027     ++confirm_msg_used;
4028     if (confirm_msg != NULL)
4029 	msg_puts_attr((char *)confirm_msg, HL_ATTR(HLF_M));
4030     --confirm_msg_used;
4031 }
4032 
4033 #endif // FEAT_CON_DIALOG
4034 
4035 #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4036 
4037     int
4038 vim_dialog_yesno(
4039     int		type,
4040     char_u	*title,
4041     char_u	*message,
4042     int		dflt)
4043 {
4044     if (do_dialog(type,
4045 		title == NULL ? (char_u *)_("Question") : title,
4046 		message,
4047 		(char_u *)_("&Yes\n&No"), dflt, NULL, FALSE) == 1)
4048 	return VIM_YES;
4049     return VIM_NO;
4050 }
4051 
4052     int
4053 vim_dialog_yesnocancel(
4054     int		type,
4055     char_u	*title,
4056     char_u	*message,
4057     int		dflt)
4058 {
4059     switch (do_dialog(type,
4060 		title == NULL ? (char_u *)_("Question") : title,
4061 		message,
4062 		(char_u *)_("&Yes\n&No\n&Cancel"), dflt, NULL, FALSE))
4063     {
4064 	case 1: return VIM_YES;
4065 	case 2: return VIM_NO;
4066     }
4067     return VIM_CANCEL;
4068 }
4069 
4070     int
4071 vim_dialog_yesnoallcancel(
4072     int		type,
4073     char_u	*title,
4074     char_u	*message,
4075     int		dflt)
4076 {
4077     switch (do_dialog(type,
4078 		title == NULL ? (char_u *)"Question" : title,
4079 		message,
4080 		(char_u *)_("&Yes\n&No\nSave &All\n&Discard All\n&Cancel"),
4081 							   dflt, NULL, FALSE))
4082     {
4083 	case 1: return VIM_YES;
4084 	case 2: return VIM_NO;
4085 	case 3: return VIM_ALL;
4086 	case 4: return VIM_DISCARDALL;
4087     }
4088     return VIM_CANCEL;
4089 }
4090 
4091 #endif // FEAT_GUI_DIALOG || FEAT_CON_DIALOG
4092 
4093 #if defined(FEAT_EVAL)
4094 static char *e_printf = N_("E766: Insufficient arguments for printf()");
4095 
4096 /*
4097  * Get number argument from "idxp" entry in "tvs".  First entry is 1.
4098  */
4099     static varnumber_T
4100 tv_nr(typval_T *tvs, int *idxp)
4101 {
4102     int		idx = *idxp - 1;
4103     varnumber_T	n = 0;
4104     int		err = FALSE;
4105 
4106     if (tvs[idx].v_type == VAR_UNKNOWN)
4107 	emsg(_(e_printf));
4108     else
4109     {
4110 	++*idxp;
4111 	n = tv_get_number_chk(&tvs[idx], &err);
4112 	if (err)
4113 	    n = 0;
4114     }
4115     return n;
4116 }
4117 
4118 /*
4119  * Get string argument from "idxp" entry in "tvs".  First entry is 1.
4120  * If "tofree" is NULL tv_get_string_chk() is used.  Some types (e.g. List)
4121  * are not converted to a string.
4122  * If "tofree" is not NULL echo_string() is used.  All types are converted to
4123  * a string with the same format as ":echo".  The caller must free "*tofree".
4124  * Returns NULL for an error.
4125  */
4126     static char *
4127 tv_str(typval_T *tvs, int *idxp, char_u **tofree)
4128 {
4129     int		    idx = *idxp - 1;
4130     char	    *s = NULL;
4131     static char_u   numbuf[NUMBUFLEN];
4132 
4133     if (tvs[idx].v_type == VAR_UNKNOWN)
4134 	emsg(_(e_printf));
4135     else
4136     {
4137 	++*idxp;
4138 	if (tofree != NULL)
4139 	    s = (char *)echo_string(&tvs[idx], tofree, numbuf, get_copyID());
4140 	else
4141 	    s = (char *)tv_get_string_chk(&tvs[idx]);
4142     }
4143     return s;
4144 }
4145 
4146 # ifdef FEAT_FLOAT
4147 /*
4148  * Get float argument from "idxp" entry in "tvs".  First entry is 1.
4149  */
4150     static double
4151 tv_float(typval_T *tvs, int *idxp)
4152 {
4153     int		idx = *idxp - 1;
4154     double	f = 0;
4155 
4156     if (tvs[idx].v_type == VAR_UNKNOWN)
4157 	emsg(_(e_printf));
4158     else
4159     {
4160 	++*idxp;
4161 	if (tvs[idx].v_type == VAR_FLOAT)
4162 	    f = tvs[idx].vval.v_float;
4163 	else if (tvs[idx].v_type == VAR_NUMBER)
4164 	    f = (double)tvs[idx].vval.v_number;
4165 	else
4166 	    emsg(_("E807: Expected Float argument for printf()"));
4167     }
4168     return f;
4169 }
4170 # endif
4171 #endif
4172 
4173 #ifdef FEAT_FLOAT
4174 /*
4175  * Return the representation of infinity for printf() function:
4176  * "-inf", "inf", "+inf", " inf", "-INF", "INF", "+INF" or " INF".
4177  */
4178     static const char *
4179 infinity_str(int positive,
4180 	     char fmt_spec,
4181 	     int force_sign,
4182 	     int space_for_positive)
4183 {
4184     static const char *table[] =
4185     {
4186 	"-inf", "inf", "+inf", " inf",
4187 	"-INF", "INF", "+INF", " INF"
4188     };
4189     int idx = positive * (1 + force_sign + force_sign * space_for_positive);
4190 
4191     if (ASCII_ISUPPER(fmt_spec))
4192 	idx += 4;
4193     return table[idx];
4194 }
4195 #endif
4196 
4197 /*
4198  * This code was included to provide a portable vsnprintf() and snprintf().
4199  * Some systems may provide their own, but we always use this one for
4200  * consistency.
4201  *
4202  * This code is based on snprintf.c - a portable implementation of snprintf
4203  * by Mark Martinec <[email protected]>, Version 2.2, 2000-10-06.
4204  * Included with permission.  It was heavily modified to fit in Vim.
4205  * The original code, including useful comments, can be found here:
4206  *	http://www.ijs.si/software/snprintf/
4207  *
4208  * This snprintf() only supports the following conversion specifiers:
4209  * s, c, d, u, o, x, X, p  (and synonyms: i, D, U, O - see below)
4210  * with flags: '-', '+', ' ', '0' and '#'.
4211  * An asterisk is supported for field width as well as precision.
4212  *
4213  * Limited support for floating point was added: 'f', 'F', 'e', 'E', 'g', 'G'.
4214  *
4215  * Length modifiers 'h' (short int) and 'l' (long int) and 'll' (long long int)
4216  * are supported.  NOTE: for 'll' the argument is varnumber_T or uvarnumber_T.
4217  *
4218  * The locale is not used, the string is used as a byte string.  This is only
4219  * relevant for double-byte encodings where the second byte may be '%'.
4220  *
4221  * It is permitted for "str_m" to be zero, and it is permitted to specify NULL
4222  * pointer for resulting string argument if "str_m" is zero (as per ISO C99).
4223  *
4224  * The return value is the number of characters which would be generated
4225  * for the given input, excluding the trailing NUL. If this value
4226  * is greater or equal to "str_m", not all characters from the result
4227  * have been stored in str, output bytes beyond the ("str_m"-1) -th character
4228  * are discarded. If "str_m" is greater than zero it is guaranteed
4229  * the resulting string will be NUL-terminated.
4230  */
4231 
4232 /*
4233  * When va_list is not supported we only define vim_snprintf().
4234  *
4235  * vim_vsnprintf_typval() can be invoked with either "va_list" or a list of
4236  * "typval_T".  When the latter is not used it must be NULL.
4237  */
4238 
4239 // When generating prototypes all of this is skipped, cproto doesn't
4240 // understand this.
4241 #ifndef PROTO
4242 
4243 // Like vim_vsnprintf() but append to the string.
4244     int
4245 vim_snprintf_add(char *str, size_t str_m, const char *fmt, ...)
4246 {
4247     va_list	ap;
4248     int		str_l;
4249     size_t	len = STRLEN(str);
4250     size_t	space;
4251 
4252     if (str_m <= len)
4253 	space = 0;
4254     else
4255 	space = str_m - len;
4256     va_start(ap, fmt);
4257     str_l = vim_vsnprintf(str + len, space, fmt, ap);
4258     va_end(ap);
4259     return str_l;
4260 }
4261 
4262     int
4263 vim_snprintf(char *str, size_t str_m, const char *fmt, ...)
4264 {
4265     va_list	ap;
4266     int		str_l;
4267 
4268     va_start(ap, fmt);
4269     str_l = vim_vsnprintf(str, str_m, fmt, ap);
4270     va_end(ap);
4271     return str_l;
4272 }
4273 
4274     int
4275 vim_vsnprintf(
4276     char	*str,
4277     size_t	str_m,
4278     const char	*fmt,
4279     va_list	ap)
4280 {
4281     return vim_vsnprintf_typval(str, str_m, fmt, ap, NULL);
4282 }
4283 
4284     int
4285 vim_vsnprintf_typval(
4286     char	*str,
4287     size_t	str_m,
4288     const char	*fmt,
4289     va_list	ap,
4290     typval_T	*tvs)
4291 {
4292     size_t	str_l = 0;
4293     const char	*p = fmt;
4294     int		arg_idx = 1;
4295 
4296     if (p == NULL)
4297 	p = "";
4298     while (*p != NUL)
4299     {
4300 	if (*p != '%')
4301 	{
4302 	    char    *q = strchr(p + 1, '%');
4303 	    size_t  n = (q == NULL) ? STRLEN(p) : (size_t)(q - p);
4304 
4305 	    // Copy up to the next '%' or NUL without any changes.
4306 	    if (str_l < str_m)
4307 	    {
4308 		size_t avail = str_m - str_l;
4309 
4310 		mch_memmove(str + str_l, p, n > avail ? avail : n);
4311 	    }
4312 	    p += n;
4313 	    str_l += n;
4314 	}
4315 	else
4316 	{
4317 	    size_t  min_field_width = 0, precision = 0;
4318 	    int	    zero_padding = 0, precision_specified = 0, justify_left = 0;
4319 	    int	    alternate_form = 0, force_sign = 0;
4320 
4321 	    // If both the ' ' and '+' flags appear, the ' ' flag should be
4322 	    // ignored.
4323 	    int	    space_for_positive = 1;
4324 
4325 	    // allowed values: \0, h, l, L
4326 	    char    length_modifier = '\0';
4327 
4328 	    // temporary buffer for simple numeric->string conversion
4329 # if defined(FEAT_FLOAT)
4330 #  define TMP_LEN 350	// On my system 1e308 is the biggest number possible.
4331 			// That sounds reasonable to use as the maximum
4332 			// printable.
4333 # else
4334 #  define TMP_LEN 66
4335 # endif
4336 	    char    tmp[TMP_LEN];
4337 
4338 	    // string address in case of string argument
4339 	    const char  *str_arg = NULL;
4340 
4341 	    // natural field width of arg without padding and sign
4342 	    size_t  str_arg_l;
4343 
4344 	    // unsigned char argument value - only defined for c conversion.
4345 	    // N.B. standard explicitly states the char argument for the c
4346 	    // conversion is unsigned
4347 	    unsigned char uchar_arg;
4348 
4349 	    // number of zeros to be inserted for numeric conversions as
4350 	    // required by the precision or minimal field width
4351 	    size_t  number_of_zeros_to_pad = 0;
4352 
4353 	    // index into tmp where zero padding is to be inserted
4354 	    size_t  zero_padding_insertion_ind = 0;
4355 
4356 	    // current conversion specifier character
4357 	    char    fmt_spec = '\0';
4358 
4359 	    // buffer for 's' and 'S' specs
4360 	    char_u  *tofree = NULL;
4361 
4362 
4363 	    p++;  // skip '%'
4364 
4365 	    // parse flags
4366 	    while (*p == '0' || *p == '-' || *p == '+' || *p == ' '
4367 						   || *p == '#' || *p == '\'')
4368 	    {
4369 		switch (*p)
4370 		{
4371 		    case '0': zero_padding = 1; break;
4372 		    case '-': justify_left = 1; break;
4373 		    case '+': force_sign = 1; space_for_positive = 0; break;
4374 		    case ' ': force_sign = 1;
4375 			      // If both the ' ' and '+' flags appear, the ' '
4376 			      // flag should be ignored
4377 			      break;
4378 		    case '#': alternate_form = 1; break;
4379 		    case '\'': break;
4380 		}
4381 		p++;
4382 	    }
4383 	    // If the '0' and '-' flags both appear, the '0' flag should be
4384 	    // ignored.
4385 
4386 	    // parse field width
4387 	    if (*p == '*')
4388 	    {
4389 		int j;
4390 
4391 		p++;
4392 		j =
4393 # if defined(FEAT_EVAL)
4394 		    tvs != NULL ? tv_nr(tvs, &arg_idx) :
4395 # endif
4396 			va_arg(ap, int);
4397 		if (j >= 0)
4398 		    min_field_width = j;
4399 		else
4400 		{
4401 		    min_field_width = -j;
4402 		    justify_left = 1;
4403 		}
4404 	    }
4405 	    else if (VIM_ISDIGIT((int)(*p)))
4406 	    {
4407 		// size_t could be wider than unsigned int; make sure we treat
4408 		// argument like common implementations do
4409 		unsigned int uj = *p++ - '0';
4410 
4411 		while (VIM_ISDIGIT((int)(*p)))
4412 		    uj = 10 * uj + (unsigned int)(*p++ - '0');
4413 		min_field_width = uj;
4414 	    }
4415 
4416 	    // parse precision
4417 	    if (*p == '.')
4418 	    {
4419 		p++;
4420 		precision_specified = 1;
4421 		if (*p == '*')
4422 		{
4423 		    int j;
4424 
4425 		    j =
4426 # if defined(FEAT_EVAL)
4427 			tvs != NULL ? tv_nr(tvs, &arg_idx) :
4428 # endif
4429 			    va_arg(ap, int);
4430 		    p++;
4431 		    if (j >= 0)
4432 			precision = j;
4433 		    else
4434 		    {
4435 			precision_specified = 0;
4436 			precision = 0;
4437 		    }
4438 		}
4439 		else if (VIM_ISDIGIT((int)(*p)))
4440 		{
4441 		    // size_t could be wider than unsigned int; make sure we
4442 		    // treat argument like common implementations do
4443 		    unsigned int uj = *p++ - '0';
4444 
4445 		    while (VIM_ISDIGIT((int)(*p)))
4446 			uj = 10 * uj + (unsigned int)(*p++ - '0');
4447 		    precision = uj;
4448 		}
4449 	    }
4450 
4451 	    // parse 'h', 'l' and 'll' length modifiers
4452 	    if (*p == 'h' || *p == 'l')
4453 	    {
4454 		length_modifier = *p;
4455 		p++;
4456 		if (length_modifier == 'l' && *p == 'l')
4457 		{
4458 		    // double l = __int64 / varnumber_T
4459 		    length_modifier = 'L';
4460 		    p++;
4461 		}
4462 	    }
4463 	    fmt_spec = *p;
4464 
4465 	    // common synonyms:
4466 	    switch (fmt_spec)
4467 	    {
4468 		case 'i': fmt_spec = 'd'; break;
4469 		case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
4470 		case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
4471 		case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
4472 		default: break;
4473 	    }
4474 
4475 # if defined(FEAT_EVAL)
4476 	    switch (fmt_spec)
4477 	    {
4478 		case 'd': case 'u': case 'o': case 'x': case 'X':
4479 		    if (tvs != NULL && length_modifier == '\0')
4480 			length_modifier = 'L';
4481 	    }
4482 # endif
4483 
4484 	    // get parameter value, do initial processing
4485 	    switch (fmt_spec)
4486 	    {
4487 		// '%' and 'c' behave similar to 's' regarding flags and field
4488 		// widths
4489 	    case '%':
4490 	    case 'c':
4491 	    case 's':
4492 	    case 'S':
4493 		str_arg_l = 1;
4494 		switch (fmt_spec)
4495 		{
4496 		case '%':
4497 		    str_arg = p;
4498 		    break;
4499 
4500 		case 'c':
4501 		    {
4502 			int j;
4503 
4504 			j =
4505 # if defined(FEAT_EVAL)
4506 			    tvs != NULL ? tv_nr(tvs, &arg_idx) :
4507 # endif
4508 				va_arg(ap, int);
4509 			// standard demands unsigned char
4510 			uchar_arg = (unsigned char)j;
4511 			str_arg = (char *)&uchar_arg;
4512 			break;
4513 		    }
4514 
4515 		case 's':
4516 		case 'S':
4517 		    str_arg =
4518 # if defined(FEAT_EVAL)
4519 				tvs != NULL ? tv_str(tvs, &arg_idx, &tofree) :
4520 # endif
4521 				    va_arg(ap, char *);
4522 		    if (str_arg == NULL)
4523 		    {
4524 			str_arg = "[NULL]";
4525 			str_arg_l = 6;
4526 		    }
4527 		    // make sure not to address string beyond the specified
4528 		    // precision !!!
4529 		    else if (!precision_specified)
4530 			str_arg_l = strlen(str_arg);
4531 		    // truncate string if necessary as requested by precision
4532 		    else if (precision == 0)
4533 			str_arg_l = 0;
4534 		    else
4535 		    {
4536 			// Don't put the #if inside memchr(), it can be a
4537 			// macro.
4538 			// memchr on HP does not like n > 2^31  !!!
4539 			char *q = memchr(str_arg, '\0',
4540 				  precision <= (size_t)0x7fffffffL ? precision
4541 						       : (size_t)0x7fffffffL);
4542 			str_arg_l = (q == NULL) ? precision
4543 						      : (size_t)(q - str_arg);
4544 		    }
4545 		    if (fmt_spec == 'S')
4546 		    {
4547 			if (min_field_width != 0)
4548 			    min_field_width += STRLEN(str_arg)
4549 				     - mb_string2cells((char_u *)str_arg, -1);
4550 			if (precision)
4551 			{
4552 			    char_u  *p1;
4553 			    size_t  i = 0;
4554 
4555 			    for (p1 = (char_u *)str_arg; *p1;
4556 							  p1 += mb_ptr2len(p1))
4557 			    {
4558 				i += (size_t)mb_ptr2cells(p1);
4559 				if (i > precision)
4560 				    break;
4561 			    }
4562 			    str_arg_l = precision = p1 - (char_u *)str_arg;
4563 			}
4564 		    }
4565 		    break;
4566 
4567 		default:
4568 		    break;
4569 		}
4570 		break;
4571 
4572 	    case 'd': case 'u':
4573 	    case 'b': case 'B':
4574 	    case 'o':
4575 	    case 'x': case 'X':
4576 	    case 'p':
4577 		{
4578 		    // NOTE: the u, b, o, x, X and p conversion specifiers
4579 		    // imply the value is unsigned;  d implies a signed
4580 		    // value
4581 
4582 		    // 0 if numeric argument is zero (or if pointer is
4583 		    // NULL for 'p'), +1 if greater than zero (or nonzero
4584 		    // for unsigned arguments), -1 if negative (unsigned
4585 		    // argument is never negative)
4586 		    int arg_sign = 0;
4587 
4588 		    // only set for length modifier h, or for no length
4589 		    // modifiers
4590 		    int int_arg = 0;
4591 		    unsigned int uint_arg = 0;
4592 
4593 		    // only set for length modifier l
4594 		    long int long_arg = 0;
4595 		    unsigned long int ulong_arg = 0;
4596 
4597 		    // only set for length modifier ll
4598 		    varnumber_T llong_arg = 0;
4599 		    uvarnumber_T ullong_arg = 0;
4600 
4601 		    // only set for b conversion
4602 		    uvarnumber_T bin_arg = 0;
4603 
4604 		    // pointer argument value -only defined for p
4605 		    // conversion
4606 		    void *ptr_arg = NULL;
4607 
4608 		    if (fmt_spec == 'p')
4609 		    {
4610 			length_modifier = '\0';
4611 			ptr_arg =
4612 # if defined(FEAT_EVAL)
4613 				 tvs != NULL ? (void *)tv_str(tvs, &arg_idx,
4614 									NULL) :
4615 # endif
4616 					va_arg(ap, void *);
4617 			if (ptr_arg != NULL)
4618 			    arg_sign = 1;
4619 		    }
4620 		    else if (fmt_spec == 'b' || fmt_spec == 'B')
4621 		    {
4622 			bin_arg =
4623 # if defined(FEAT_EVAL)
4624 				    tvs != NULL ?
4625 					   (uvarnumber_T)tv_nr(tvs, &arg_idx) :
4626 # endif
4627 					va_arg(ap, uvarnumber_T);
4628 			if (bin_arg != 0)
4629 			    arg_sign = 1;
4630 		    }
4631 		    else if (fmt_spec == 'd')
4632 		    {
4633 			// signed
4634 			switch (length_modifier)
4635 			{
4636 			case '\0':
4637 			case 'h':
4638 			    // char and short arguments are passed as int.
4639 			    int_arg =
4640 # if defined(FEAT_EVAL)
4641 					tvs != NULL ? tv_nr(tvs, &arg_idx) :
4642 # endif
4643 					    va_arg(ap, int);
4644 			    if (int_arg > 0)
4645 				arg_sign =  1;
4646 			    else if (int_arg < 0)
4647 				arg_sign = -1;
4648 			    break;
4649 			case 'l':
4650 			    long_arg =
4651 # if defined(FEAT_EVAL)
4652 					tvs != NULL ? tv_nr(tvs, &arg_idx) :
4653 # endif
4654 					    va_arg(ap, long int);
4655 			    if (long_arg > 0)
4656 				arg_sign =  1;
4657 			    else if (long_arg < 0)
4658 				arg_sign = -1;
4659 			    break;
4660 			case 'L':
4661 			    llong_arg =
4662 # if defined(FEAT_EVAL)
4663 					tvs != NULL ? tv_nr(tvs, &arg_idx) :
4664 # endif
4665 					    va_arg(ap, varnumber_T);
4666 			    if (llong_arg > 0)
4667 				arg_sign =  1;
4668 			    else if (llong_arg < 0)
4669 				arg_sign = -1;
4670 			    break;
4671 			}
4672 		    }
4673 		    else
4674 		    {
4675 			// unsigned
4676 			switch (length_modifier)
4677 			{
4678 			    case '\0':
4679 			    case 'h':
4680 				uint_arg =
4681 # if defined(FEAT_EVAL)
4682 					    tvs != NULL ? (unsigned)
4683 							tv_nr(tvs, &arg_idx) :
4684 # endif
4685 						va_arg(ap, unsigned int);
4686 				if (uint_arg != 0)
4687 				    arg_sign = 1;
4688 				break;
4689 			    case 'l':
4690 				ulong_arg =
4691 # if defined(FEAT_EVAL)
4692 					    tvs != NULL ? (unsigned long)
4693 							tv_nr(tvs, &arg_idx) :
4694 # endif
4695 						va_arg(ap, unsigned long int);
4696 				if (ulong_arg != 0)
4697 				    arg_sign = 1;
4698 				break;
4699 			    case 'L':
4700 				ullong_arg =
4701 # if defined(FEAT_EVAL)
4702 					    tvs != NULL ? (uvarnumber_T)
4703 							tv_nr(tvs, &arg_idx) :
4704 # endif
4705 						va_arg(ap, uvarnumber_T);
4706 				if (ullong_arg != 0)
4707 				    arg_sign = 1;
4708 				break;
4709 			}
4710 		    }
4711 
4712 		    str_arg = tmp;
4713 		    str_arg_l = 0;
4714 
4715 		    // NOTE:
4716 		    //   For d, i, u, o, x, and X conversions, if precision is
4717 		    //   specified, the '0' flag should be ignored. This is so
4718 		    //   with Solaris 2.6, Digital UNIX 4.0, HPUX 10, Linux,
4719 		    //   FreeBSD, NetBSD; but not with Perl.
4720 		    if (precision_specified)
4721 			zero_padding = 0;
4722 		    if (fmt_spec == 'd')
4723 		    {
4724 			if (force_sign && arg_sign >= 0)
4725 			    tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
4726 			// leave negative numbers for sprintf to handle, to
4727 			// avoid handling tricky cases like (short int)-32768
4728 		    }
4729 		    else if (alternate_form)
4730 		    {
4731 			if (arg_sign != 0
4732 				     && (fmt_spec == 'b' || fmt_spec == 'B'
4733 				      || fmt_spec == 'x' || fmt_spec == 'X') )
4734 			{
4735 			    tmp[str_arg_l++] = '0';
4736 			    tmp[str_arg_l++] = fmt_spec;
4737 			}
4738 			// alternate form should have no effect for p
4739 			// conversion, but ...
4740 		    }
4741 
4742 		    zero_padding_insertion_ind = str_arg_l;
4743 		    if (!precision_specified)
4744 			precision = 1;   // default precision is 1
4745 		    if (precision == 0 && arg_sign == 0)
4746 		    {
4747 			// When zero value is formatted with an explicit
4748 			// precision 0, the resulting formatted string is
4749 			// empty (d, i, u, b, B, o, x, X, p).
4750 		    }
4751 		    else
4752 		    {
4753 			char	f[6];
4754 			int	f_l = 0;
4755 
4756 			// construct a simple format string for sprintf
4757 			f[f_l++] = '%';
4758 			if (!length_modifier)
4759 			    ;
4760 			else if (length_modifier == 'L')
4761 			{
4762 # ifdef MSWIN
4763 			    f[f_l++] = 'I';
4764 			    f[f_l++] = '6';
4765 			    f[f_l++] = '4';
4766 # else
4767 			    f[f_l++] = 'l';
4768 			    f[f_l++] = 'l';
4769 # endif
4770 			}
4771 			else
4772 			    f[f_l++] = length_modifier;
4773 			f[f_l++] = fmt_spec;
4774 			f[f_l++] = '\0';
4775 
4776 			if (fmt_spec == 'p')
4777 			    str_arg_l += sprintf(tmp + str_arg_l, f, ptr_arg);
4778 			else if (fmt_spec == 'b' || fmt_spec == 'B')
4779 			{
4780 			    char	    b[8 * sizeof(uvarnumber_T)];
4781 			    size_t	    b_l = 0;
4782 			    uvarnumber_T    bn = bin_arg;
4783 
4784 			    do
4785 			    {
4786 				b[sizeof(b) - ++b_l] = '0' + (bn & 0x1);
4787 				bn >>= 1;
4788 			    }
4789 			    while (bn != 0);
4790 
4791 			    memcpy(tmp + str_arg_l, b + sizeof(b) - b_l, b_l);
4792 			    str_arg_l += b_l;
4793 			}
4794 			else if (fmt_spec == 'd')
4795 			{
4796 			    // signed
4797 			    switch (length_modifier)
4798 			    {
4799 			    case '\0': str_arg_l += sprintf(
4800 						 tmp + str_arg_l, f,
4801 						 int_arg);
4802 				       break;
4803 			    case 'h': str_arg_l += sprintf(
4804 						 tmp + str_arg_l, f,
4805 						 (short)int_arg);
4806 				      break;
4807 			    case 'l': str_arg_l += sprintf(
4808 						tmp + str_arg_l, f, long_arg);
4809 				      break;
4810 			    case 'L': str_arg_l += sprintf(
4811 					       tmp + str_arg_l, f, llong_arg);
4812 				      break;
4813 			    }
4814 			}
4815 			else
4816 			{
4817 			    // unsigned
4818 			    switch (length_modifier)
4819 			    {
4820 			    case '\0': str_arg_l += sprintf(
4821 						tmp + str_arg_l, f,
4822 						uint_arg);
4823 				       break;
4824 			    case 'h': str_arg_l += sprintf(
4825 						tmp + str_arg_l, f,
4826 						(unsigned short)uint_arg);
4827 				      break;
4828 			    case 'l': str_arg_l += sprintf(
4829 					       tmp + str_arg_l, f, ulong_arg);
4830 				      break;
4831 			    case 'L': str_arg_l += sprintf(
4832 					      tmp + str_arg_l, f, ullong_arg);
4833 				      break;
4834 			    }
4835 			}
4836 
4837 			// include the optional minus sign and possible
4838 			// "0x" in the region before the zero padding
4839 			// insertion point
4840 			if (zero_padding_insertion_ind < str_arg_l
4841 				&& tmp[zero_padding_insertion_ind] == '-')
4842 			    zero_padding_insertion_ind++;
4843 			if (zero_padding_insertion_ind + 1 < str_arg_l
4844 				&& tmp[zero_padding_insertion_ind]   == '0'
4845 				&& (tmp[zero_padding_insertion_ind + 1] == 'x'
4846 				 || tmp[zero_padding_insertion_ind + 1] == 'X'))
4847 			    zero_padding_insertion_ind += 2;
4848 		    }
4849 
4850 		    {
4851 			size_t num_of_digits = str_arg_l
4852 						 - zero_padding_insertion_ind;
4853 
4854 			if (alternate_form && fmt_spec == 'o'
4855 				// unless zero is already the first
4856 				// character
4857 				&& !(zero_padding_insertion_ind < str_arg_l
4858 				    && tmp[zero_padding_insertion_ind] == '0'))
4859 			{
4860 			    // assure leading zero for alternate-form
4861 			    // octal numbers
4862 			    if (!precision_specified
4863 					     || precision < num_of_digits + 1)
4864 			    {
4865 				// precision is increased to force the
4866 				// first character to be zero, except if a
4867 				// zero value is formatted with an
4868 				// explicit precision of zero
4869 				precision = num_of_digits + 1;
4870 			    }
4871 			}
4872 			// zero padding to specified precision?
4873 			if (num_of_digits < precision)
4874 			    number_of_zeros_to_pad = precision - num_of_digits;
4875 		    }
4876 		    // zero padding to specified minimal field width?
4877 		    if (!justify_left && zero_padding)
4878 		    {
4879 			int n = (int)(min_field_width - (str_arg_l
4880 						    + number_of_zeros_to_pad));
4881 			if (n > 0)
4882 			    number_of_zeros_to_pad += n;
4883 		    }
4884 		    break;
4885 		}
4886 
4887 # ifdef FEAT_FLOAT
4888 	    case 'f':
4889 	    case 'F':
4890 	    case 'e':
4891 	    case 'E':
4892 	    case 'g':
4893 	    case 'G':
4894 		{
4895 		    // Floating point.
4896 		    double	f;
4897 		    double	abs_f;
4898 		    char	format[40];
4899 		    int		l;
4900 		    int		remove_trailing_zeroes = FALSE;
4901 
4902 		    f =
4903 #  if defined(FEAT_EVAL)
4904 			tvs != NULL ? tv_float(tvs, &arg_idx) :
4905 #  endif
4906 			    va_arg(ap, double);
4907 		    abs_f = f < 0 ? -f : f;
4908 
4909 		    if (fmt_spec == 'g' || fmt_spec == 'G')
4910 		    {
4911 			// Would be nice to use %g directly, but it prints
4912 			// "1.0" as "1", we don't want that.
4913 			if ((abs_f >= 0.001 && abs_f < 10000000.0)
4914 							      || abs_f == 0.0)
4915 			    fmt_spec = ASCII_ISUPPER(fmt_spec) ? 'F' : 'f';
4916 			else
4917 			    fmt_spec = fmt_spec == 'g' ? 'e' : 'E';
4918 			remove_trailing_zeroes = TRUE;
4919 		    }
4920 
4921 		    if ((fmt_spec == 'f' || fmt_spec == 'F') &&
4922 #  ifdef VAX
4923 			    abs_f > 1.0e38
4924 #  else
4925 			    abs_f > 1.0e307
4926 #  endif
4927 			    )
4928 		    {
4929 			// Avoid a buffer overflow
4930 			STRCPY(tmp, infinity_str(f > 0.0, fmt_spec,
4931 					      force_sign, space_for_positive));
4932 			str_arg_l = STRLEN(tmp);
4933 			zero_padding = 0;
4934 		    }
4935 		    else
4936 		    {
4937 			if (isnan(f))
4938 			{
4939 			    // Not a number: nan or NAN
4940 			    STRCPY(tmp, ASCII_ISUPPER(fmt_spec) ? "NAN"
4941 								      : "nan");
4942 			    str_arg_l = 3;
4943 			    zero_padding = 0;
4944 			}
4945 			else if (isinf(f))
4946 			{
4947 			    STRCPY(tmp, infinity_str(f > 0.0, fmt_spec,
4948 					      force_sign, space_for_positive));
4949 			    str_arg_l = STRLEN(tmp);
4950 			    zero_padding = 0;
4951 			}
4952 			else
4953 			{
4954 			    // Regular float number
4955 			    format[0] = '%';
4956 			    l = 1;
4957 			    if (force_sign)
4958 				format[l++] = space_for_positive ? ' ' : '+';
4959 			    if (precision_specified)
4960 			    {
4961 				size_t max_prec = TMP_LEN - 10;
4962 
4963 				// Make sure we don't get more digits than we
4964 				// have room for.
4965 				if ((fmt_spec == 'f' || fmt_spec == 'F')
4966 								&& abs_f > 1.0)
4967 				    max_prec -= (size_t)log10(abs_f);
4968 				if (precision > max_prec)
4969 				    precision = max_prec;
4970 				l += sprintf(format + l, ".%d", (int)precision);
4971 			    }
4972 			    format[l] = fmt_spec == 'F' ? 'f' : fmt_spec;
4973 			    format[l + 1] = NUL;
4974 
4975 			    str_arg_l = sprintf(tmp, format, f);
4976 			}
4977 
4978 			if (remove_trailing_zeroes)
4979 			{
4980 			    int i;
4981 			    char *tp;
4982 
4983 			    // Using %g or %G: remove superfluous zeroes.
4984 			    if (fmt_spec == 'f' || fmt_spec == 'F')
4985 				tp = tmp + str_arg_l - 1;
4986 			    else
4987 			    {
4988 				tp = (char *)vim_strchr((char_u *)tmp,
4989 						 fmt_spec == 'e' ? 'e' : 'E');
4990 				if (tp != NULL)
4991 				{
4992 				    // Remove superfluous '+' and leading
4993 				    // zeroes from the exponent.
4994 				    if (tp[1] == '+')
4995 				    {
4996 					// Change "1.0e+07" to "1.0e07"
4997 					STRMOVE(tp + 1, tp + 2);
4998 					--str_arg_l;
4999 				    }
5000 				    i = (tp[1] == '-') ? 2 : 1;
5001 				    while (tp[i] == '0')
5002 				    {
5003 					// Change "1.0e07" to "1.0e7"
5004 					STRMOVE(tp + i, tp + i + 1);
5005 					--str_arg_l;
5006 				    }
5007 				    --tp;
5008 				}
5009 			    }
5010 
5011 			    if (tp != NULL && !precision_specified)
5012 				// Remove trailing zeroes, but keep the one
5013 				// just after a dot.
5014 				while (tp > tmp + 2 && *tp == '0'
5015 							     && tp[-1] != '.')
5016 				{
5017 				    STRMOVE(tp, tp + 1);
5018 				    --tp;
5019 				    --str_arg_l;
5020 				}
5021 			}
5022 			else
5023 			{
5024 			    char *tp;
5025 
5026 			    // Be consistent: some printf("%e") use 1.0e+12
5027 			    // and some 1.0e+012.  Remove one zero in the last
5028 			    // case.
5029 			    tp = (char *)vim_strchr((char_u *)tmp,
5030 						 fmt_spec == 'e' ? 'e' : 'E');
5031 			    if (tp != NULL && (tp[1] == '+' || tp[1] == '-')
5032 					  && tp[2] == '0'
5033 					  && vim_isdigit(tp[3])
5034 					  && vim_isdigit(tp[4]))
5035 			    {
5036 				STRMOVE(tp + 2, tp + 3);
5037 				--str_arg_l;
5038 			    }
5039 			}
5040 		    }
5041 		    if (zero_padding && min_field_width > str_arg_l
5042 					      && (tmp[0] == '-' || force_sign))
5043 		    {
5044 			// padding 0's should be inserted after the sign
5045 			number_of_zeros_to_pad = min_field_width - str_arg_l;
5046 			zero_padding_insertion_ind = 1;
5047 		    }
5048 		    str_arg = tmp;
5049 		    break;
5050 		}
5051 # endif
5052 
5053 	    default:
5054 		// unrecognized conversion specifier, keep format string
5055 		// as-is
5056 		zero_padding = 0;  // turn zero padding off for non-numeric
5057 				   // conversion
5058 		justify_left = 1;
5059 		min_field_width = 0;		    // reset flags
5060 
5061 		// discard the unrecognized conversion, just keep *
5062 		// the unrecognized conversion character
5063 		str_arg = p;
5064 		str_arg_l = 0;
5065 		if (*p != NUL)
5066 		    str_arg_l++;  // include invalid conversion specifier
5067 				  // unchanged if not at end-of-string
5068 		break;
5069 	    }
5070 
5071 	    if (*p != NUL)
5072 		p++;     // step over the just processed conversion specifier
5073 
5074 	    // insert padding to the left as requested by min_field_width;
5075 	    // this does not include the zero padding in case of numerical
5076 	    // conversions
5077 	    if (!justify_left)
5078 	    {
5079 		// left padding with blank or zero
5080 		int pn = (int)(min_field_width - (str_arg_l + number_of_zeros_to_pad));
5081 
5082 		if (pn > 0)
5083 		{
5084 		    if (str_l < str_m)
5085 		    {
5086 			size_t avail = str_m - str_l;
5087 
5088 			vim_memset(str + str_l, zero_padding ? '0' : ' ',
5089 					     (size_t)pn > avail ? avail
5090 								: (size_t)pn);
5091 		    }
5092 		    str_l += pn;
5093 		}
5094 	    }
5095 
5096 	    // zero padding as requested by the precision or by the minimal
5097 	    // field width for numeric conversions required?
5098 	    if (number_of_zeros_to_pad == 0)
5099 	    {
5100 		// will not copy first part of numeric right now, *
5101 		// force it to be copied later in its entirety
5102 		zero_padding_insertion_ind = 0;
5103 	    }
5104 	    else
5105 	    {
5106 		// insert first part of numerics (sign or '0x') before zero
5107 		// padding
5108 		int zn = (int)zero_padding_insertion_ind;
5109 
5110 		if (zn > 0)
5111 		{
5112 		    if (str_l < str_m)
5113 		    {
5114 			size_t avail = str_m - str_l;
5115 
5116 			mch_memmove(str + str_l, str_arg,
5117 					     (size_t)zn > avail ? avail
5118 								: (size_t)zn);
5119 		    }
5120 		    str_l += zn;
5121 		}
5122 
5123 		// insert zero padding as requested by the precision or min
5124 		// field width
5125 		zn = (int)number_of_zeros_to_pad;
5126 		if (zn > 0)
5127 		{
5128 		    if (str_l < str_m)
5129 		    {
5130 			size_t avail = str_m - str_l;
5131 
5132 			vim_memset(str + str_l, '0',
5133 					     (size_t)zn > avail ? avail
5134 								: (size_t)zn);
5135 		    }
5136 		    str_l += zn;
5137 		}
5138 	    }
5139 
5140 	    // insert formatted string
5141 	    // (or as-is conversion specifier for unknown conversions)
5142 	    {
5143 		int sn = (int)(str_arg_l - zero_padding_insertion_ind);
5144 
5145 		if (sn > 0)
5146 		{
5147 		    if (str_l < str_m)
5148 		    {
5149 			size_t avail = str_m - str_l;
5150 
5151 			mch_memmove(str + str_l,
5152 				str_arg + zero_padding_insertion_ind,
5153 				(size_t)sn > avail ? avail : (size_t)sn);
5154 		    }
5155 		    str_l += sn;
5156 		}
5157 	    }
5158 
5159 	    // insert right padding
5160 	    if (justify_left)
5161 	    {
5162 		// right blank padding to the field width
5163 		int pn = (int)(min_field_width
5164 				      - (str_arg_l + number_of_zeros_to_pad));
5165 
5166 		if (pn > 0)
5167 		{
5168 		    if (str_l < str_m)
5169 		    {
5170 			size_t avail = str_m - str_l;
5171 
5172 			vim_memset(str + str_l, ' ',
5173 					     (size_t)pn > avail ? avail
5174 								: (size_t)pn);
5175 		    }
5176 		    str_l += pn;
5177 		}
5178 	    }
5179 	    vim_free(tofree);
5180 	}
5181     }
5182 
5183     if (str_m > 0)
5184     {
5185 	// make sure the string is nul-terminated even at the expense of
5186 	// overwriting the last character (shouldn't happen, but just in case)
5187 	//
5188 	str[str_l <= str_m - 1 ? str_l : str_m - 1] = '\0';
5189     }
5190 
5191     if (tvs != NULL && tvs[arg_idx - 1].v_type != VAR_UNKNOWN)
5192 	emsg(_("E767: Too many arguments to printf()"));
5193 
5194     // Return the number of characters formatted (excluding trailing nul
5195     // character), that is, the number of characters that would have been
5196     // written to the buffer if it were large enough.
5197     return (int)str_l;
5198 }
5199 
5200 #endif // PROTO
5201