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