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