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