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