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