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