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