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