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