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