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