robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
106.4 KiB3738 linesraw
1// message.c: functions for displaying messages on the command line
2
3#include <assert.h>
4#include <inttypes.h>
5#include <limits.h>
6#include <stdarg.h>
7#include <stdbool.h>
8#include <stddef.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <uv.h>
13
14#include "klib/kvec.h"
15#include "nvim/api/private/defs.h"
16#include "nvim/api/private/helpers.h"
17#include "nvim/api/vim.h"
18#include "nvim/ascii_defs.h"
19#include "nvim/autocmd.h"
20#include "nvim/buffer_defs.h"
21#include "nvim/channel.h"
22#include "nvim/charset.h"
23#include "nvim/dialog.h"
24#include "nvim/drawscreen.h"
25#include "nvim/errors.h"
26#include "nvim/eval.h"
27#include "nvim/eval/typval.h"
28#include "nvim/eval/typval_defs.h"
29#include "nvim/eval/vars.h"
30#include "nvim/event/defs.h"
31#include "nvim/event/loop.h"
32#include "nvim/event/multiqueue.h"
33#include "nvim/ex_cmds_defs.h"
34#include "nvim/ex_docmd.h"
35#include "nvim/ex_eval.h"
36#include "nvim/ex_getln.h"
37#include "nvim/fileio.h"
38#include "nvim/garray.h"
39#include "nvim/garray_defs.h"
40#include "nvim/gettext_defs.h"
41#include "nvim/globals.h"
42#include "nvim/grid.h"
43#include "nvim/highlight.h"
44#include "nvim/highlight_defs.h"
45#include "nvim/highlight_group.h"
46#include "nvim/indent.h"
47#include "nvim/input.h"
48#include "nvim/keycodes.h"
49#include "nvim/log.h"
50#include "nvim/main.h"
51#include "nvim/mbyte.h"
52#include "nvim/mbyte_defs.h"
53#include "nvim/memory.h"
54#include "nvim/memory_defs.h"
55#include "nvim/message.h"
56#include "nvim/message_defs.h"
57#include "nvim/mouse.h"
58#include "nvim/option.h"
59#include "nvim/option_vars.h"
60#include "nvim/optionstr.h"
61#include "nvim/os/fs.h"
62#include "nvim/os/input.h"
63#include "nvim/os/os.h"
64#include "nvim/os/time.h"
65#include "nvim/pos_defs.h"
66#include "nvim/regexp.h"
67#include "nvim/register.h"
68#include "nvim/runtime.h"
69#include "nvim/runtime_defs.h"
70#include "nvim/state_defs.h"
71#include "nvim/strings.h"
72#include "nvim/types_defs.h"
73#include "nvim/ui.h"
74#include "nvim/ui_compositor.h"
75#include "nvim/ui_defs.h"
76#include "nvim/vim_defs.h"
77
78#include "options_keysets.generated.h"
79
80// To be able to scroll back at the "more" and "hit-enter" prompts we need to
81// store the displayed text and remember where screen lines start.
82typedef struct msgchunk_S msgchunk_T;
83struct msgchunk_S {
84  msgchunk_T *sb_next;
85  msgchunk_T *sb_prev;
86  char sb_eol;                  // true when line ends after this text
87  int sb_msg_col;               // column in which text starts
88  int sb_hl_id;                 // text highlight id
89  char sb_text[];               // text to be displayed
90};
91
92static int confirm_msg_used = false;            // displaying confirm_msg
93#include "message.c.generated.h"
94
95MessageHistoryEntry *msg_hist_last = NULL;          // Last message (extern for unittest)
96static MessageHistoryEntry *msg_hist_first = NULL;  // First message
97static MessageHistoryEntry *msg_hist_temp = NULL;   // First potentially temporary message
98static int msg_hist_len = 0;
99static int msg_hist_max = 500;  // The default max value is 500
100
101#define PROGRESS_TARGET_CMD          0x01
102
103// 'messagesopt' items. Default: "hit-enter,history:500,progress:c".
104static bool msg_hit_enter = true;
105static int msg_wait = 0;
106static int progress_msg_target = PROGRESS_TARGET_CMD;
107
108static FILE *verbose_fd = NULL;
109static bool verbose_did_open = false;
110
111static bool keep_msg_more = false;    // keep_msg was set by msgmore()
112
113// When writing messages to the screen, there are many different situations.
114// A number of variables is used to remember the current state:
115// msg_didany       true when messages were written since the last time the
116//                  user reacted to a prompt.
117//                  Reset: After hitting a key for the hit-return prompt,
118//                  hitting <CR> for the command line or input().
119//                  Set: When any message is written to the screen.
120// msg_didout       true when something was written to the current line.
121//                  Reset: When advancing to the next line, when the current
122//                  text can be overwritten.
123//                  Set: When any message is written to the screen.
124// msg_nowait       No extra delay for the last drawn message.
125//                  Used in normal_cmd() before the mode message is drawn.
126// emsg_on_display  There was an error message recently.  Indicates that there
127//                  should be a delay before redrawing.
128// msg_scroll       The next message should not overwrite the current one.
129// msg_scrolled     How many lines the screen has been scrolled (because of
130//                  messages).  Used in update_screen() to scroll the screen
131//                  back.  Incremented each time the screen scrolls a line.
132// msg_scrolled_ign  true when msg_scrolled is non-zero and msg_puts_hl()
133//                  writes something without scrolling should not make
134//                  need_wait_return to be set.  This is a hack to make ":ts"
135//                  work without an extra prompt.
136// lines_left       Number of lines available for messages before the
137//                  more-prompt is to be given.  -1 when not set.
138// need_wait_return true when the hit-return prompt is needed.
139//                  Reset: After giving the hit-return prompt, when the user
140//                  has answered some other prompt.
141//                  Set: When the ruler or typeahead display is overwritten,
142//                  scrolling the screen for some message.
143// keep_msg         Message to be displayed after redrawing the screen, in
144//                  Normal mode main loop.
145//                  This is an allocated string or NULL when not used.
146
147// Extended msg state, currently used for external UIs with ext_messages
148static const char *msg_ext_kind = NULL;
149static const char *msg_ext_trigger = NULL;
150static MsgID msg_ext_id = { .type = kObjectTypeInteger, .data.integer = 1 };
151static Array *msg_ext_chunks = NULL;
152static garray_T msg_ext_last_chunk = GA_INIT(sizeof(char), 40);
153static sattr_T msg_ext_last_attr = -1;
154static int msg_ext_last_hl_id;
155
156static bool msg_ext_history = false;  ///< message was added to history
157static bool msg_ext_append = false;  ///< message appended to previous message line
158
159static int msg_grid_pos_at_flush = 0;
160
161static int64_t msg_id_next = 1;           ///< message id to be allocated to next message
162
163/// Returns true if the given integer message-id was previously generated.
164bool msg_id_exists(int64_t id)
165{
166  return id > 0 && id < msg_id_next;
167}
168
169static void ui_ext_msg_set_pos(int row, bool scrolled)
170{
171  char buf[MAX_SCHAR_SIZE];
172  size_t size = schar_get(buf, curwin->w_p_fcs_chars.msgsep);
173  ui_call_msg_set_pos(msg_grid.handle, row, scrolled,
174                      (String){ .data = buf, .size = size }, msg_grid.zindex,
175                      (int)msg_grid.comp_index);
176  msg_grid.pending_comp_index_update = false;
177}
178
179void msg_grid_set_pos(int row, bool scrolled)
180{
181  if (!msg_grid.throttled) {
182    ui_ext_msg_set_pos(row, scrolled);
183    msg_grid_pos_at_flush = row;
184  }
185  msg_grid_pos = row;
186  if (msg_grid.chars) {
187    msg_grid_adj.row_offset = -row;
188  }
189}
190
191bool msg_use_grid(void)
192{
193  return default_grid.chars && !ui_has(kUIMessages);
194}
195
196void msg_grid_validate(void)
197{
198  grid_assign_handle(&msg_grid);
199  bool should_alloc = msg_use_grid();
200  int max_rows = Rows - (int)p_ch;
201  if (should_alloc && (msg_grid.rows != Rows || msg_grid.cols != Columns
202                       || !msg_grid.chars)) {
203    // TODO(bfredl): eventually should be set to "invalid". I e all callers
204    // will use the grid including clear to EOS if necessary.
205    grid_alloc(&msg_grid, Rows, Columns, false, true);
206    msg_grid.zindex = kZIndexMessages;
207
208    xfree(msg_grid.dirty_col);
209    msg_grid.dirty_col = xcalloc((size_t)Rows, sizeof(*msg_grid.dirty_col));
210
211    // Tricky: allow resize while pager or ex mode is active
212    int pos = (State & MODE_ASKMORE) ? 0 : MAX(max_rows - msg_scrolled, 0);
213    msg_grid.throttled = false;  // don't throttle in 'cmdheight' area
214    msg_grid_set_pos(pos, msg_scrolled);
215    ui_comp_put_grid(&msg_grid, pos, 0, msg_grid.rows, msg_grid.cols,
216                     false, true);
217    ui_call_grid_resize(msg_grid.handle, msg_grid.cols, msg_grid.rows);
218
219    msg_scrolled_at_flush = msg_scrolled;
220    msg_grid.mouse_enabled = false;
221    msg_grid_adj.target = &msg_grid;
222  } else if (!should_alloc && msg_grid.chars) {
223    ui_comp_remove_grid(&msg_grid);
224    grid_free(&msg_grid);
225    XFREE_CLEAR(msg_grid.dirty_col);
226    ui_call_grid_destroy(msg_grid.handle);
227    msg_grid.throttled = false;
228    msg_grid_adj.row_offset = 0;
229    msg_grid_adj.target = &default_grid;
230    redraw_cmdline = true;
231  } else if (msg_grid.chars && !msg_scrolled && msg_grid_pos != max_rows) {
232    int diff = msg_grid_pos - max_rows;
233    msg_grid_set_pos(max_rows, false);
234    if (diff > 0) {
235      grid_clear(&msg_grid_adj, Rows - diff, Rows, 0, Columns, HL_ATTR(HLF_MSG));
236    }
237  }
238
239  if (msg_grid.chars && !msg_scrolled && cmdline_row < msg_grid_pos) {
240    // TODO(bfredl): this should already be the case, but fails in some
241    // "batched" executions where compute_cmdrow() use stale positions or
242    // something.
243    cmdline_row = msg_grid_pos;
244  }
245}
246
247/// Like msg() but keep it silent when 'verbosefile' is set.
248int verb_msg(const char *s)
249{
250  verbose_enter();
251  int n = msg_keep(s, 0, false, false);
252  verbose_leave();
253
254  return n;
255}
256
257/// Displays the string 's' on the status line
258/// When terminal not initialized (yet) printf("%s", ..) is used.
259///
260/// @return  true if wait_return() not called
261bool msg(const char *s, const int hl_id)
262  FUNC_ATTR_NONNULL_ARG(1)
263{
264  return msg_keep(s, hl_id, false, false);
265}
266
267/// Similar to msg_outtrans_len, but support newlines and tabs.
268void msg_multiline(String str, int hl_id, bool check_int, bool hist, bool *need_clear)
269  FUNC_ATTR_NONNULL_ALL
270{
271  const char *s = str.data;
272  const char *chunk = s;
273  while ((size_t)(s - str.data) < str.size) {
274    if (check_int && got_int) {
275      return;
276    }
277    if (*s == '\n' || *s == TAB || *s == '\r' || *s == BELL) {
278      // Print all chars before the delimiter
279      msg_outtrans_len(chunk, (int)(s - chunk), hl_id, hist);
280
281      if (*s != TAB && *need_clear) {
282        msg_clr_eos();
283        *need_clear = false;
284      }
285      if (*s == BELL) {
286        vim_beep(kOptBoFlagShell);
287      } else {
288        msg_putchar_hl((uint8_t)(*s), hl_id);
289      }
290      chunk = s + 1;
291    }
292    s++;
293  }
294
295  // Print the remainder or emit empty event if entire message is empty.
296  if (*chunk != NUL || chunk == str.data) {
297    msg_outtrans_len(chunk, (int)(str.size - (size_t)(chunk - str.data)), hl_id, hist);
298  }
299}
300
301// Ensure a single msg_show event, msg_list and history entry for entire multihl message.
302static int is_multihl = 0;
303
304/// Format a progress message, adding title and percent if given.
305///
306/// @param hl_msg Message chunks
307/// @param msg_data Additional data for progress messages
308static bool format_progress_message(HlMessage *hl_msg, MessageData *msg_data)
309{
310  HlMessage updated_msg = KV_INITIAL_VALUE;
311  // progress messages are special. displayed as "title: percent% msg"
312  if (msg_data->title.size != 0) {
313    // this block draws the "title:" before the progress-message
314    int hl_id = 0;
315    if (msg_data->status.data == NULL) {
316      hl_id = 0;
317    } else if (strequal(msg_data->status.data, "success")) {
318      hl_id = syn_check_group("OkMsg", STRLEN_LITERAL("OkMsg"));
319    } else if (strequal(msg_data->status.data, "failed")) {
320      hl_id = syn_check_group("ErrorMsg", STRLEN_LITERAL("ErrorMsg"));
321    } else if (strequal(msg_data->status.data, "running")) {
322      hl_id = syn_check_group("MoreMsg", STRLEN_LITERAL("MoreMsg"));
323    } else if (strequal(msg_data->status.data, "cancel")) {
324      hl_id = syn_check_group("WarningMsg", STRLEN_LITERAL("WarningMsg"));
325    }
326    kv_push(updated_msg, ((HlMessageChunk){ copy_string(msg_data->title, NULL), hl_id }));
327    kv_push(updated_msg, ((HlMessageChunk){ cstr_to_string(": "), 0 }));
328  }
329  if (msg_data->percent >= 0) {
330    char percent_buf[10];
331    vim_snprintf(percent_buf, sizeof(percent_buf), "%3ld%% ", (long)msg_data->percent);
332    String percent = cstr_to_string(percent_buf);
333    int hl_id = syn_check_group("WarningMsg", STRLEN_LITERAL("WarningMsg"));
334    kv_push(updated_msg, ((HlMessageChunk){ percent, hl_id }));
335  }
336
337  if (kv_size(updated_msg) != 0) {
338    for (uint32_t i = 0; i < kv_size(*hl_msg); i++) {
339      HlMessageChunk chunk = kv_A(*hl_msg, i);
340      kv_push(updated_msg, ((HlMessageChunk){ copy_string(chunk.text, NULL), chunk.hl_id }));
341    }
342    *hl_msg = updated_msg;
343    return true;
344  }
345  return false;
346}
347
348/// Print message chunks, each with their own highlight ID.
349///
350/// @param hl_msg Message chunks
351/// @param kind Message kind (can be NULL to avoid setting kind)
352/// @param history Whether to add message to history
353/// @param err Whether to print message as an error
354/// @param msg_data Progress-message data
355MsgID msg_multihl(MsgID id, HlMessage hl_msg, const char *kind, bool history, bool err,
356                  MessageData *msg_data, bool *needs_msg_clear)
357{
358  // Message `id`:
359  // - Nil: Generate a new Integer id.
360  // - Integer: Existing id.
361  // - String: User-defined id (new or existing).
362  if (id.type == kObjectTypeNil) {
363    id = INTEGER_OBJ(msg_id_next++);
364  } else if (id.type == kObjectTypeInteger && !msg_id_exists(id.data.integer)) {
365    abort();
366  }
367
368  bool hl_msg_updated = false;
369  // don't display progress message in cmd when target doesn't have cmd
370  if (strequal(kind, "progress")) {
371    do_autocmd_progress(id, hl_msg, msg_data);
372    if ((progress_msg_target & PROGRESS_TARGET_CMD) == 0) {
373      *needs_msg_clear = true;
374      return id;
375    }
376    if (msg_data && format_progress_message(&hl_msg, msg_data)) {
377      *needs_msg_clear = true;
378      hl_msg_updated = true;
379    }
380  }
381
382  no_wait_return++;
383  msg_start();
384  msg_clr_eos();
385  bool need_clear = false;
386  if (kind != NULL) {
387    msg_ext_set_kind(kind);
388  }
389  msg_ext_skip_flush = true;
390  msg_ext_id = id;
391
392  for (uint32_t i = 0; i < kv_size(hl_msg); i++) {
393    HlMessageChunk chunk = kv_A(hl_msg, i);
394    is_multihl++;
395    if (err) {
396      emsg_multiline(chunk.text.data, kind, chunk.hl_id, true);
397    } else {
398      msg_multiline(chunk.text, chunk.hl_id, true, false, &need_clear);
399    }
400    assert(!ui_has(kUIMessages) || kind == NULL || msg_ext_kind == kind);
401  }
402
403  if (history && kv_size(hl_msg)) {
404    msg_hist_add_multihl(hl_msg, false);
405  }
406
407  msg_ext_skip_flush = false;
408  is_multihl = 0;
409  no_wait_return--;
410  msg_end();
411
412  if (hl_msg_updated && !(history && kv_size(hl_msg))) {
413    hl_msg_free(hl_msg);
414  }
415  // Release the id: it belongs to this message, and a String id only borrows the caller's storage
416  // (often a stack buffer). Redundant unless nothing was emitted (e.g. 'msg_silent').
417  msg_ext_id = INTEGER_OBJ(msg_id_next);
418  return id;
419}
420
421/// @param keep set keep_msg if it doesn't scroll
422bool msg_keep(const char *s, int hl_id, bool keep, bool multiline)
423  FUNC_ATTR_NONNULL_ALL
424{
425  static int entered = 0;
426
427  if (keep && multiline) {
428    // Not implemented. 'multiline' is only used by nvim-added messages,
429    // which should avoid 'keep' behavior (just show the message at
430    // the correct time already).
431    abort();
432  }
433
434  // Skip messages not match ":filter pattern".
435  // Don't filter when there is an error.
436  if (!emsg_on_display && message_filtered(s)) {
437    return true;
438  }
439
440  if (hl_id == 0) {
441    set_vim_var_string(VV_STATUSMSG, s, -1);
442  }
443
444  // It is possible that displaying a messages causes a problem (e.g.,
445  // when redrawing the window), which causes another message, etc..    To
446  // break this loop, limit the recursiveness to 3 levels.
447  if (entered >= 3) {
448    return true;
449  }
450  entered++;
451
452  // Add message to history unless it's a multihl, repeated kept or truncated message.
453  if (!is_multihl
454      && (s != keep_msg
455          || (*s != '<' && msg_hist_last != NULL
456              && strcmp(s, msg_hist_last->msg.items[0].text.data) != 0))) {
457    msg_hist_add(s, -1, hl_id);
458  }
459
460  if (!is_multihl) {
461    msg_start();
462  }
463  // Truncate the message if needed.
464  char *buf = msg_strtrunc(s, false);
465  if (buf != NULL) {
466    s = buf;
467  }
468
469  bool need_clear = true;
470  if (multiline) {
471    msg_multiline(cstr_as_string(s), hl_id, false, false, &need_clear);
472  } else {
473    msg_outtrans(s, hl_id, false);
474  }
475  if (need_clear) {
476    msg_clr_eos();
477  }
478  bool retval = true;
479  if (!is_multihl) {
480    retval = msg_end();
481  }
482
483  if (keep && retval && vim_strsize(s) < (Rows - cmdline_row - 1) * Columns + sc_col) {
484    set_keep_msg(s, 0);
485  }
486
487  need_fileinfo = false;
488
489  xfree(buf);
490  entered--;
491  return retval;
492}
493
494/// Truncate a string such that it can be printed without causing a scroll.
495///
496/// @return  an allocated string or NULL when no truncating is done.
497///
498/// @param force  always truncate
499char *msg_strtrunc(const char *s, int force)
500{
501  char *buf = NULL;
502
503  // May truncate message to avoid a hit-return prompt
504  if ((!msg_scroll && !need_wait_return && shortmess(kShmTruncall)
505       && msg_silent == 0 && !ui_has(kUIMessages))
506      || force) {
507    int room;
508    int len = vim_strsize(s);
509    if (msg_scrolled != 0) {
510      // Use all the columns.
511      room = (Rows - msg_row) * Columns - 1;
512    } else {
513      // Use up to 'showcmd' column.
514      // In the case of ui2, we no longer need to avoid the "Press ENTER" prompt, but the message is
515      // still kept under 1 line to avoid glitches. For example, when a long search term is
516      // displayed that expands the cmdline, it will be immediately collapsed again when the search
517      // count is displayed, which leads to flickering on each hit.
518      int last_row = ui_has(kUIMessages) ? Columns : sc_col - 1;
519      room = (Rows - msg_row - 1) * Columns + last_row;
520    }
521    if (len > room && room > 0) {
522      // may have up to 18 bytes per cell (6 per char, up to two
523      // composing chars)
524      len = (room + 2) * 18;
525      buf = xmalloc((size_t)len);
526      trunc_string(s, buf, room, len);
527    }
528  }
529  return buf;
530}
531
532/// Truncate a string "s" to "buf" with cell width "room".
533/// "s" and "buf" may be equal.
534void trunc_string(const char *s, char *buf, int room_in, int buflen)
535{
536  int room = room_in - 3;  // "..." takes 3 chars
537  int len = 0;
538  int e;
539  int i;
540  int n;
541
542  if (*s == NUL) {
543    if (buflen > 0) {
544      *buf = NUL;
545    }
546    return;
547  }
548
549  if (room_in < 3) {
550    room = 0;
551  }
552  int half = room / 2;
553
554  // First part: Start of the string.
555  for (e = 0; len < half && e < buflen; e++) {
556    if (s[e] == NUL) {
557      // text fits without truncating!
558      buf[e] = NUL;
559      return;
560    }
561    n = ptr2cells(s + e);
562    if (len + n > half) {
563      break;
564    }
565    len += n;
566    buf[e] = s[e];
567    for (n = utfc_ptr2len(s + e); --n > 0;) {
568      if (++e == buflen) {
569        break;
570      }
571      buf[e] = s[e];
572    }
573  }
574
575  // Last part: End of the string.
576  half = i = (int)strlen(s);
577  while (true) {
578    half = half - utf_head_off(s, s + half - 1) - 1;
579    n = ptr2cells(s + half);
580    if (len + n > room || half == 0) {
581      break;
582    }
583    len += n;
584    i = half;
585  }
586
587  if (i <= e + 3) {
588    // text fits without truncating
589    if (s != buf) {
590      len = (int)strlen(s);
591      if (len >= buflen) {
592        len = buflen - 1;
593      }
594      len = len - e + 1;
595      if (len < 1) {
596        buf[e - 1] = NUL;
597      } else {
598        memmove(buf + e, s + e, (size_t)len);
599      }
600    }
601  } else if (e + 3 < buflen) {
602    // set the middle and copy the last part
603    memmove(buf + e, "...", 3);
604    len = (int)strlen(s + i) + 1;
605    if (len >= buflen - e - 3) {
606      len = buflen - e - 3 - 1;
607    }
608    memmove(buf + e + 3, s + i, (size_t)len);
609    buf[e + 3 + len - 1] = NUL;
610  } else {
611    // can't fit in the "...", just truncate it
612    buf[buflen - 1] = NUL;
613  }
614}
615
616/// Shows a printf-style message with highlight id.
617///
618/// Note: Caller must check the resulting string is shorter than IOSIZE!!!
619///
620/// @see semsg
621/// @see swmsg
622///
623/// @param s printf-style format message
624int smsg(int hl_id, const char *s, ...)
625  FUNC_ATTR_PRINTF(2, 3)
626{
627  va_list arglist;
628
629  va_start(arglist, s);
630  vim_vsnprintf(IObuff, IOSIZE, s, arglist);
631  va_end(arglist);
632  return msg(IObuff, hl_id);
633}
634
635int smsg_keep(int hl_id, const char *s, ...)
636  FUNC_ATTR_PRINTF(2, 3)
637{
638  va_list arglist;
639
640  va_start(arglist, s);
641  vim_vsnprintf(IObuff, IOSIZE, s, arglist);
642  va_end(arglist);
643  return msg_keep(IObuff, hl_id, true, false);
644}
645
646// Remember the last sourcing name/lnum used in an error message, so that it
647// isn't printed each time when it didn't change.
648static int last_sourcing_lnum = 0;
649static char *last_sourcing_name = NULL;
650
651/// Reset the last used sourcing name/lnum.  Makes sure it is displayed again
652/// for the next error message;
653void reset_last_sourcing(void)
654{
655  XFREE_CLEAR(last_sourcing_name);
656  last_sourcing_lnum = 0;
657}
658
659/// @return  true if "SOURCING_NAME" differs from "last_sourcing_name".
660static bool other_sourcing_name(void)
661{
662  if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL) {
663    if (last_sourcing_name != NULL) {
664      return strcmp(SOURCING_NAME, last_sourcing_name) != 0;
665    }
666    return true;
667  }
668  return false;
669}
670
671/// Get the message about the source, as used for an error message
672///
673/// @return [allocated] String with room for one more character. NULL when no
674///                     message is to be given.
675static char *get_emsg_source(void)
676  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT
677{
678  if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL && other_sourcing_name()) {
679    char *sname = estack_sfile(ESTACK_NONE);
680    char *tofree = sname;
681
682    if (sname == NULL) {
683      sname = SOURCING_NAME;
684    }
685
686    const char *const p = _("Error in %s:");
687    const size_t buf_len = strlen(sname) + strlen(p) + 1;
688    char *const buf = xmalloc(buf_len);
689    snprintf(buf, buf_len, p, sname);
690    xfree(tofree);
691    return buf;
692  }
693  return NULL;
694}
695
696/// Get the message about the source lnum, as used for an error message.
697///
698/// @return [allocated] String with room for one more character. NULL when no
699///                     message is to be given.
700static char *get_emsg_lnum(void)
701  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT
702{
703  // lnum is 0 when executing a command from the command line
704  // argument, we don't want a line number then
705  if (SOURCING_NAME != NULL
706      && (other_sourcing_name() || SOURCING_LNUM != last_sourcing_lnum)
707      && SOURCING_LNUM != 0) {
708    const char *const p = _("line %4" PRIdLINENR ":");
709    const size_t buf_len = 20 + strlen(p);
710    char *const buf = xmalloc(buf_len);
711    snprintf(buf, buf_len, p, SOURCING_LNUM);
712    return buf;
713  }
714  return NULL;
715}
716
717/// Display name and line number for the source of an error.
718/// Remember the file name and line number, so that for the next error the info
719/// is only displayed if it changed.
720void msg_source(int hl_id)
721{
722  static bool recursive = false;
723
724  // Bail out if something called here causes an error.
725  if (recursive) {
726    return;
727  }
728  recursive = true;
729
730  no_wait_return++;
731  char *p = get_emsg_source();
732  if (p != NULL) {
733    msg_scroll = true;  // this will take more than one line
734    msg(p, hl_id);
735    xfree(p);
736  }
737  p = get_emsg_lnum();
738  if (p != NULL) {
739    msg(p, HLF_N);
740    xfree(p);
741    last_sourcing_lnum = SOURCING_LNUM;      // only once for each line
742  }
743
744  // remember the last sourcing name printed, also when it's empty
745  if (SOURCING_NAME == NULL || other_sourcing_name()) {
746    XFREE_CLEAR(last_sourcing_name);
747    if (SOURCING_NAME != NULL) {
748      last_sourcing_name = xstrdup(SOURCING_NAME);
749      if (!redirecting()) {
750        msg_putchar_hl('\n', hl_id);
751      }
752    }
753  }
754  no_wait_return--;
755
756  recursive = false;
757}
758
759/// @return  true if not giving error messages right now:
760///            If "emsg_off" is set: no error messages at the moment.
761///            If "msg" is in 'debug': do error message but without side effects.
762///            If "emsg_skip" is set: never do error messages.
763static int emsg_not_now(void)
764{
765  if ((emsg_off > 0 && vim_strchr(p_debug, 'm') == NULL
766       && vim_strchr(p_debug, 't') == NULL)
767      || emsg_skip > 0) {
768    return true;
769  }
770  return false;
771}
772
773bool emsg_multiline(const char *s, const char *kind, int hl_id, bool multiline)
774{
775  bool ignore = false;
776
777  // Skip this if not giving error messages at the moment.
778  if (emsg_not_now()) {
779    return true;
780  }
781
782  called_emsg++;
783
784  // If "emsg_severe" is true: When an error exception is to be thrown,
785  // prefer this message over previous messages for the same command.
786  bool severe = emsg_severe;
787  emsg_severe = false;
788
789  if (!emsg_off || vim_strchr(p_debug, 't') != NULL) {
790    // Cause a throw of an error exception if appropriate.  Don't display
791    // the error message in this case.  (If no matching catch clause will
792    // be found, the message will be displayed later on.)  "ignore" is set
793    // when the message should be ignored completely (used for the
794    // interrupt message).
795    if (cause_errthrow(s, multiline, is_multihl > 1, severe, &ignore)) {
796      if (!ignore) {
797        did_emsg++;
798      }
799      return true;
800    }
801
802    if (in_assert_fails && emsg_assert_fails_msg == NULL) {
803      emsg_assert_fails_msg = xstrdup(s);
804      emsg_assert_fails_lnum = SOURCING_LNUM;
805      xfree(emsg_assert_fails_context);
806      emsg_assert_fails_context = xstrdup(SOURCING_NAME == NULL ? "" : SOURCING_NAME);
807    }
808
809    // set "v:errmsg", also when using ":silent! cmd"
810    set_vim_var_string(VV_ERRMSG, s, -1);
811
812    // When using ":silent! cmd" ignore error messages.
813    // But do write it to the redirection file.
814    if (emsg_silent != 0) {
815      if (!emsg_noredir) {
816        msg_start();
817        char *p = get_emsg_source();
818        if (p != NULL) {
819          const size_t p_len = strlen(p);
820          p[p_len] = '\n';
821          redir_write(p, (ptrdiff_t)p_len + 1);
822          xfree(p);
823        }
824        p = get_emsg_lnum();
825        if (p != NULL) {
826          const size_t p_len = strlen(p);
827          p[p_len] = '\n';
828          redir_write(p, (ptrdiff_t)p_len + 1);
829          xfree(p);
830        }
831        redir_write(s, (ptrdiff_t)strlen(s));
832      }
833
834      // Log (silent) errors as debug messages.
835      if (SOURCING_NAME != NULL && SOURCING_LNUM != 0) {
836        DLOG("(:silent) %s (%s (line %" PRIdLINENR "))",
837             s, SOURCING_NAME, SOURCING_LNUM);
838      } else {
839        DLOG("(:silent) %s", s);
840      }
841
842      return true;
843    }
844
845    // Log editor errors as INFO.
846    if (SOURCING_NAME != NULL && SOURCING_LNUM != 0) {
847      ILOG("%s (%s (line %" PRIdLINENR "))", s, SOURCING_NAME, SOURCING_LNUM);
848    } else {
849      ILOG("%s", s);
850    }
851
852    ex_exitval = 1;
853
854    // Reset msg_silent, an error causes messages to be switched back on.
855    msg_silent = 0;
856    cmd_silent = false;
857
858    if (global_busy) {        // break :global command
859      global_busy++;
860    }
861
862    if (p_eb) {
863      beep_flush();           // also includes flush_buffers()
864    } else {
865      flush_buffers(FLUSH_MINIMAL);  // flush internal buffers
866    }
867    did_emsg++;               // flag for DoOneCmd()
868  }
869
870  emsg_on_display = true;     // remember there is an error message
871  if (msg_scrolled != 0) {
872    need_wait_return = true;  // needed in case emsg() is called after
873  }                           // wait_return() has reset need_wait_return
874                              // and a redraw is expected because
875                              // msg_scrolled is non-zero
876  msg_ext_set_kind(kind);
877
878  // Display name and line number for the source of the error.
879  msg_scroll = true;
880  bool save_msg_skip_flush = msg_ext_skip_flush;
881  msg_ext_skip_flush = true;
882  msg_source(hl_id);
883
884  // Display the error message itself.
885  msg_nowait = false;  // Wait for this msg.
886  int rv = msg_keep(s, hl_id, false, multiline);
887  msg_ext_skip_flush = save_msg_skip_flush;
888  return rv;
889}
890
891/// emsg() - display an error message
892///
893/// Rings the bell, if appropriate, and calls message() to do the real work
894/// When terminal not initialized (yet) fprintf(stderr, "%s", ..) is used.
895///
896/// @return true if wait_return() not called
897bool emsg(const char *s)
898{
899  return emsg_multiline(s, "emsg", HLF_E, false);
900}
901
902void emsg_invreg(int name)
903{
904  semsg(_("E354: Invalid register name: '%s'"), transchar_buf(NULL, name));
905}
906
907/// Print an error message with unknown number of arguments
908///
909/// @return whether the message was displayed
910bool semsg(const char *const fmt, ...)
911  FUNC_ATTR_PRINTF(1, 2)
912{
913  bool ret;
914
915  va_list ap;
916  va_start(ap, fmt);
917  ret = semsgv(fmt, ap);
918  va_end(ap);
919
920  return ret;
921}
922
923#define MULTILINE_BUFSIZE 8192
924
925bool semsg_multiline(const char *kind, const char *const fmt, ...)
926{
927  bool ret;
928  va_list ap;
929
930  static char errbuf[MULTILINE_BUFSIZE];
931  if (emsg_not_now()) {
932    return true;
933  }
934
935  va_start(ap, fmt);
936  vim_vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
937  va_end(ap);
938
939  ret = emsg_multiline(errbuf, kind, HLF_E, true);
940
941  return ret;
942}
943
944/// Print an error message with unknown number of arguments
945static bool semsgv(const char *fmt, va_list ap)
946{
947  static char errbuf[IOSIZE];
948  if (emsg_not_now()) {
949    return true;
950  }
951
952  vim_vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
953
954  return emsg(errbuf);
955}
956
957/// Same as emsg(...), but abort on error when ABORT_ON_INTERNAL_ERROR is
958/// defined. It is used for internal errors only, so that they can be
959/// detected when fuzzing vim.
960void iemsg(const char *s)
961{
962  if (emsg_not_now()) {
963    return;
964  }
965
966  emsg(s);
967#ifdef ABORT_ON_INTERNAL_ERROR
968  set_vim_var_string(VV_ERRMSG, s, -1);
969  msg_putchar('\n');  // avoid overwriting the error message
970  ui_flush();
971  abort();
972#endif
973}
974
975/// Same as semsg(...) but abort on error when ABORT_ON_INTERNAL_ERROR is
976/// defined. It is used for internal errors only, so that they can be
977/// detected when fuzzing vim.
978void siemsg(const char *s, ...)
979{
980  if (emsg_not_now()) {
981    return;
982  }
983
984  va_list ap;
985  va_start(ap, s);
986  semsgv(s, ap);
987  va_end(ap);
988#ifdef ABORT_ON_INTERNAL_ERROR
989  msg_putchar('\n');  // avoid overwriting the error message
990  ui_flush();
991  abort();
992#endif
993}
994
995/// Give an "Internal error" message.
996void internal_error(const char *where)
997{
998  siemsg(_(e_intern2), where);
999}
1000
1001static void msg_semsg_event(void **argv)
1002{
1003  char *s = argv[0];
1004  emsg(s);
1005  xfree(s);
1006}
1007
1008void msg_schedule_semsg(const char *const fmt, ...)
1009  FUNC_ATTR_PRINTF(1, 2)
1010{
1011  va_list ap;
1012  va_start(ap, fmt);
1013  vim_vsnprintf(IObuff, IOSIZE, fmt, ap);
1014  va_end(ap);
1015
1016  char *s = xstrdup(IObuff);
1017  loop_schedule_deferred(&main_loop, event_create(msg_semsg_event, s));
1018}
1019
1020static void msg_semsg_multiline_event(void **argv)
1021{
1022  char *s = argv[0];
1023  emsg_multiline(s, "emsg", HLF_E, true);
1024  xfree(s);
1025}
1026
1027void msg_schedule_semsg_multiline(const char *const fmt, ...)
1028{
1029  va_list ap;
1030  va_start(ap, fmt);
1031  vim_vsnprintf(IObuff, IOSIZE, fmt, ap);
1032  va_end(ap);
1033
1034  char *s = xstrdup(IObuff);
1035  loop_schedule_deferred(&main_loop, event_create(msg_semsg_multiline_event, s));
1036}
1037
1038/// Like msg(), but truncate to a single line if p_shm contains 't', or when
1039/// "force" is true.  This truncates in another way as for normal messages.
1040/// Careful: The string may be changed by msg_may_trunc()!
1041///
1042/// @return  a pointer to the printed message, if wait_return() not called.
1043char *msg_trunc(char *s, bool force, int hl_id)
1044{
1045  // Add message to history before truncating.
1046  msg_hist_add(s, -1, hl_id);
1047
1048  char *ts = msg_may_trunc(force, s);
1049
1050  msg_hist_off = true;
1051  bool n = msg(ts, hl_id);
1052  msg_hist_off = false;
1053
1054  if (n) {
1055    return ts;
1056  }
1057  return NULL;
1058}
1059
1060/// Check if message "s" should be truncated at the start (for filenames).
1061///
1062/// @return  a pointer to where the truncated message starts.
1063///
1064/// @note: May change the message by replacing a character with '<'.
1065char *msg_may_trunc(bool force, char *s)
1066{
1067  if (ui_has(kUIMessages)) {
1068    return s;
1069  }
1070
1071  // If something unexpected happened "room" may be negative, check for that
1072  // just in case.
1073  int room = (Rows - cmdline_row - 1) * Columns + sc_col - 1;
1074  if (room > 0
1075      && (force || shortmess(kShmTrunc))
1076      && (int)strlen(s) - room > 0) {
1077    int size = vim_strsize(s);
1078
1079    // There may be room anyway when there are multibyte chars.
1080    if (size <= room) {
1081      return s;
1082    }
1083    int n;
1084    for (n = 0; size >= room;) {
1085      size -= utf_ptr2cells(s + n);
1086      n += utfc_ptr2len(s + n);
1087    }
1088    n--;
1089    s += n;
1090    *s = '<';
1091  }
1092  return s;
1093}
1094
1095/// Shows a progress-message.  A non-"running" `status` ends the message and announces the
1096/// progress task as "done".
1097///
1098/// @param s    Message text.  NULL ends the message without showing anything.
1099/// @param err  Show as an error message.
1100char *msg_progress(char *s, char *id, char *status, int hl_id, bool hist, bool trunc, bool err)
1101{
1102  bool clear = false;
1103  MessageData data = {
1104    .source = cstr_as_string("nvim"),
1105    .status = cstr_as_string(status),
1106    .percent = -1,
1107  };
1108  HlMessage chunks = KV_INITIAL_VALUE;
1109  if (s != NULL) {
1110    if (hist && (!trunc || ui_has(kUIMessages))) {
1111      msg_hist_add(s, -1, 0);
1112    }
1113    if (trunc) {
1114      s = msg_may_trunc(false, s);
1115    }
1116    kv_push(chunks, ((HlMessageChunk){ cstr_as_string(s), hl_id }));
1117  }
1118  msg_ext_no_fast();
1119  msg_multihl(CSTR_AS_OBJ(id), chunks, "progress", false, err, &data, &clear);
1120  kv_destroy(chunks);
1121  ui_flush();
1122  return s;
1123}
1124
1125void hl_msg_free(HlMessage hl_msg)
1126{
1127  for (size_t i = 0; i < kv_size(hl_msg); i++) {
1128    xfree(kv_A(hl_msg, i).text.data);
1129  }
1130  kv_destroy(hl_msg);
1131}
1132
1133/// Add the message at the end of the history
1134///
1135/// @param[in]  len  Length of s or -1.
1136static void msg_hist_add(const char *s, int len, int hl_id)
1137{
1138  String text = { .size = len < 0 ? strlen(s) : (size_t)len };
1139  // Remove leading and trailing newlines.
1140  while (text.size > 0 && *s == '\n') {
1141    text.size--;
1142    s++;
1143  }
1144  while (text.size > 0 && s[text.size - 1] == '\n') {
1145    text.size--;
1146  }
1147  if (text.size == 0) {
1148    return;
1149  }
1150  text.data = xmemdupz(s, text.size);
1151
1152  HlMessage msg = KV_INITIAL_VALUE;
1153  kv_push(msg, ((HlMessageChunk){ text, hl_id }));
1154  msg_hist_add_multihl(msg, false);
1155}
1156
1157static bool do_clear_hist_temp = true;
1158
1159void do_autocmd_progress(MsgID msg_id, HlMessage msg, MessageData *msg_data)
1160{
1161  if (!has_event(EVENT_PROGRESS)) {
1162    return;
1163  }
1164
1165  MAXSIZE_TEMP_DICT(data, 7);
1166  ArrayOf(String) messages = ARRAY_DICT_INIT;
1167  for (size_t i = 0; i < msg.size; i++) {
1168    ADD(messages, STRING_OBJ(msg.items[i].text));
1169  }
1170
1171  PUT_C(data, "id", OBJECT_OBJ(msg_id));
1172  PUT_C(data, "text", ARRAY_OBJ(messages));
1173  if (msg_data != NULL) {
1174    if (msg_data->percent >= 0) {
1175      // If percent=nil we omit it, it means "indeterminate progress". #39029
1176      PUT_C(data, "percent", INTEGER_OBJ(msg_data->percent));
1177    }
1178    PUT_C(data, "source", STRING_OBJ(msg_data->source));
1179    PUT_C(data, "status", STRING_OBJ(msg_data->status));
1180    PUT_C(data, "title", STRING_OBJ(msg_data->title));
1181    PUT_C(data, "data", DICT_OBJ(msg_data->data));
1182  }
1183
1184  apply_autocmds_group(EVENT_PROGRESS,
1185                       (msg_data && msg_data->source.size > 0) ? msg_data->source.data : "", NULL,
1186                       true,
1187                       AUGROUP_ALL, NULL, curwin, NULL, &DICT_OBJ(data), false);
1188  kv_destroy(messages);
1189}
1190
1191static void msg_hist_add_multihl(HlMessage msg, bool temp)
1192{
1193  if (do_clear_hist_temp) {
1194    msg_hist_clear_temp();
1195    do_clear_hist_temp = false;
1196  }
1197
1198  if (msg_hist_off || msg_silent != 0) {
1199    hl_msg_free(msg);
1200    return;
1201  }
1202
1203  // Allocate an entry and add the message at the end of the history.
1204  MessageHistoryEntry *entry = xmalloc(sizeof(MessageHistoryEntry));
1205  entry->msg = msg;
1206  entry->temp = temp;
1207  entry->kind = msg_ext_kind ? xstrdup(msg_ext_kind) : NULL;
1208  entry->prev = msg_hist_last;
1209  entry->next = NULL;
1210  // NOTE: this does not encode if the message was actually appended to the
1211  // previous entry in the message history. However append is currently only
1212  // true for :echon, which is stored in the history as a temporary entry for
1213  // "g<" where it is guaranteed to be after the entry it was appended to.
1214  entry->append = msg_ext_append;
1215
1216  if (msg_hist_first == NULL) {
1217    msg_hist_first = entry;
1218  }
1219  if (msg_hist_last != NULL) {
1220    msg_hist_last->next = entry;
1221  }
1222  if (msg_hist_temp == NULL) {
1223    msg_hist_temp = entry;
1224  }
1225
1226  msg_hist_len += !temp;
1227  msg_hist_last = entry;
1228  msg_ext_history = true;
1229
1230  msg_hist_clear(msg_hist_max);
1231}
1232
1233static void msg_hist_free_msg(MessageHistoryEntry *entry)
1234{
1235  if (entry->next == NULL) {
1236    msg_hist_last = entry->prev;
1237  } else {
1238    entry->next->prev = entry->prev;
1239  }
1240  if (entry->prev == NULL) {
1241    msg_hist_first = entry->next;
1242  } else {
1243    entry->prev->next = entry->next;
1244  }
1245  if (entry == msg_hist_temp) {
1246    msg_hist_temp = entry->next;
1247  }
1248  hl_msg_free(entry->msg);
1249  xfree(entry->kind);
1250  xfree(entry);
1251}
1252
1253/// Delete oldest messages from the history until there are "keep" messages.
1254void msg_hist_clear(int keep)
1255{
1256  while (msg_hist_len > keep || (keep == 0 && msg_hist_first != NULL)) {
1257    msg_hist_len -= !msg_hist_first->temp;
1258    msg_hist_free_msg(msg_hist_first);
1259  }
1260}
1261
1262void msg_hist_clear_temp(void)
1263{
1264  while (msg_hist_temp != NULL) {
1265    MessageHistoryEntry *next = msg_hist_temp->next;
1266    if (msg_hist_temp->temp) {
1267      msg_hist_free_msg(msg_hist_temp);
1268    }
1269    msg_hist_temp = next;
1270  }
1271}
1272
1273int messagesopt_changed(void)
1274{
1275  OptKeyDict_mopt *v = opt_keyset(p_mopt, kOptMessagesopt, NULL);
1276
1277  // Either "wait" or "hit-enter" is required; "history" always.
1278  if ((!v->hit_enter && !HAS_KEY(v, mopt, wait)) || !HAS_KEY(v, mopt, history)) {
1279    return FAIL;
1280  }
1281  // "history" and "wait" must be <= 10000; "maxheight" is a percentage.
1282  if (v->history > 10000 || v->wait > 10000 || v->maxheight > 100) {
1283    return FAIL;
1284  }
1285
1286  msg_hit_enter = v->hit_enter;
1287  msg_wait = (int)v->wait;
1288  progress_msg_target = strequal(v->progress, "c") ? PROGRESS_TARGET_CMD : 0;
1289  msg_hist_max = (int)v->history;
1290  msg_hist_clear(msg_hist_max);
1291
1292  return OK;
1293}
1294
1295/// :messages command implementation
1296void ex_messages(exarg_T *eap)
1297  FUNC_ATTR_NONNULL_ALL
1298{
1299  if (strcmp(eap->arg, "clear") == 0) {
1300    msg_hist_clear(eap->addr_count ? eap->line2 : 0);
1301    return;
1302  }
1303
1304  if (*eap->arg != NUL) {
1305    emsg(_(e_invarg));
1306    return;
1307  }
1308
1309  Array entries = ARRAY_DICT_INIT;
1310  MessageHistoryEntry *p = eap->skip ? msg_hist_temp : msg_hist_first;
1311  int skip = eap->addr_count ? (msg_hist_len - eap->line2) : 0;
1312  for (; p != NULL; p = p->next) {
1313    // Skip over count or temporary "g<" messages.
1314    if ((p->temp && !eap->skip) || skip-- > 0) {
1315      continue;
1316    }
1317    if (ui_has(kUIMessages) && !msg_silent) {
1318      Array entry = ARRAY_DICT_INIT;
1319      ADD(entry, CSTR_TO_OBJ(p->kind));
1320      Array content = ARRAY_DICT_INIT;
1321      for (uint32_t i = 0; i < kv_size(p->msg); i++) {
1322        HlMessageChunk chunk = kv_A(p->msg, i);
1323        Array content_entry = ARRAY_DICT_INIT;
1324        ADD(content_entry, INTEGER_OBJ(chunk.hl_id ? syn_id2attr(chunk.hl_id) : 0));
1325        ADD(content_entry, STRING_OBJ(copy_string(chunk.text, NULL)));
1326        ADD(content_entry, INTEGER_OBJ(chunk.hl_id));
1327        ADD(content, ARRAY_OBJ(content_entry));
1328      }
1329      ADD(entry, ARRAY_OBJ(content));
1330      ADD(entry, BOOLEAN_OBJ(p->append));
1331      ADD(entries, ARRAY_OBJ(entry));
1332    }
1333    if (redirecting() || !ui_has(kUIMessages)) {
1334      msg_silent += ui_has(kUIMessages);
1335      bool needs_clear = false;
1336      msg_multihl(NIL, p->msg, p->kind, false, false, NULL, &needs_clear);
1337      msg_silent -= ui_has(kUIMessages);
1338    }
1339  }
1340  if (kv_size(entries) > 0) {
1341    ui_call_msg_history_show(entries, eap->skip != 0);
1342    api_free_array(entries);
1343  }
1344}
1345
1346/// Call this after prompting the user.  This will avoid a hit-return message
1347/// and a delay.
1348void msg_end_prompt(void)
1349{
1350  need_wait_return = false;
1351  emsg_on_display = false;
1352  cmdline_row = msg_row;
1353  msg_col = 0;
1354  msg_clr_eos();
1355  lines_left = -1;
1356}
1357
1358/// Wait for the user to hit a key (normally Enter)
1359///
1360/// @param redraw  if true, redraw the entire screen UPD_NOT_VALID
1361///                if false, do a normal redraw
1362///                if -1, don't redraw at all
1363void wait_return(int redraw)
1364{
1365  int c;
1366  int had_got_int;
1367  FILE *save_scriptout;
1368
1369  if (redraw == true) {
1370    redraw_all_later(UPD_NOT_VALID);
1371  }
1372
1373  if (ui_has(kUIMessages)) {
1374    prompt_for_input("Press any key to continue", HLF_M, true, NULL);
1375    return;
1376  }
1377
1378  // If using ":silent cmd", don't wait for a return.  Also don't set
1379  // need_wait_return to do it later.
1380  if (msg_silent != 0) {
1381    return;
1382  }
1383
1384  if (headless_mode && !ui_active()) {
1385    return;
1386  }
1387
1388  // When inside vgetc(), we can't wait for a typed character at all.
1389  // With the global command (and some others) we only need one return at
1390  // the end. Adjust cmdline_row to avoid the next message overwriting the
1391  // last one.
1392  if (vgetc_busy > 0) {
1393    return;
1394  }
1395  need_wait_return = true;
1396  if (no_wait_return) {
1397    cmdline_row = msg_row;
1398    return;
1399  }
1400
1401  redir_off = true;             // don't redirect this message
1402  int oldState = State;
1403  if (quit_more) {
1404    c = CAR;                    // just pretend CR was hit
1405    quit_more = false;
1406    got_int = false;
1407  } else if (!stuff_empty()) {
1408    // When there are stuffed characters, the next stuffed character will
1409    // dismiss the hit-enter prompt immediately and have to be put back, so
1410    // instead just don't show the hit-enter prompt at all.
1411    c = CAR;
1412  } else {
1413    State = MODE_HITRETURN;
1414    setmouse();
1415    cmdline_row = msg_row;
1416    // Avoid the sequence that the user types ":" at the hit-return prompt
1417    // to start an Ex command, but the file-changed dialog gets in the
1418    // way.
1419    if (need_check_timestamps) {
1420      check_timestamps(false);
1421    }
1422
1423    // if cmdheight=0, we need to scroll in the first line of msg_grid upon the screen
1424    if (p_ch == 0 && !ui_has(kUIMessages) && !msg_scrolled) {
1425      msg_grid_validate();
1426      msg_scroll_up(false, true);
1427      msg_scrolled++;
1428      cmdline_row = Rows - 1;
1429    }
1430
1431    if (msg_hit_enter) {
1432      hit_return_msg(true);
1433
1434      do {
1435        // Remember "got_int", if it is set vgetc() probably returns a
1436        // CTRL-C, but we need to loop then.
1437        had_got_int = got_int;
1438
1439        // Don't do mappings here, we put the character back in the
1440        // typeahead buffer.
1441        no_mapping++;
1442        allow_keys++;
1443
1444        // Temporarily disable Recording. If Recording is active, the
1445        // character will be recorded later, since it will be added to the
1446        // typebuf after the loop
1447        const int save_reg_recording = reg_recording;
1448        save_scriptout = scriptout;
1449        reg_recording = 0;
1450        scriptout = NULL;
1451        c = safe_vgetc();
1452        if (had_got_int && !global_busy) {
1453          got_int = false;
1454        }
1455        no_mapping--;
1456        allow_keys--;
1457        reg_recording = save_reg_recording;
1458        scriptout = save_scriptout;
1459
1460        // Allow scrolling back in the messages.
1461        // Also accept scroll-down commands when messages fill the screen,
1462        // to avoid that typing one 'j' too many makes the messages
1463        // disappear.
1464        if (KeyTyped && p_more) {
1465          if (c == 'b' || c == Ctrl_B || c == 'k' || c == 'u' || c == 'g'
1466              || c == K_UP || c == K_PAGEUP) {
1467            if (msg_scrolled > Rows) {
1468              // scroll back to show older messages
1469              do_more_prompt(c);
1470            } else {
1471              msg_didout = false;
1472              c = K_IGNORE;
1473              msg_col = 0;
1474            }
1475            if (quit_more) {
1476              c = CAR;  // just pretend CR was hit
1477              quit_more = false;
1478              got_int = false;
1479            } else if (c != K_IGNORE) {
1480              c = K_IGNORE;
1481              hit_return_msg(false);
1482            }
1483          } else if (msg_scrolled > Rows - 2
1484                     && (c == 'j' || c == 'd' || c == 'f' || c == Ctrl_F
1485                         || c == K_DOWN || c == K_PAGEDOWN)) {
1486            c = K_IGNORE;
1487          }
1488        }
1489      } while ((had_got_int && c == Ctrl_C)
1490               || c == K_IGNORE
1491               || c == K_LEFTDRAG || c == K_LEFTRELEASE
1492               || c == K_MIDDLEDRAG || c == K_MIDDLERELEASE
1493               || c == K_RIGHTDRAG || c == K_RIGHTRELEASE
1494               || c == K_MOUSELEFT || c == K_MOUSERIGHT
1495               || c == K_MOUSEDOWN || c == K_MOUSEUP
1496               || c == K_MOUSEMOVE);
1497      os_breakcheck();
1498
1499      // Avoid that the mouse-up event causes visual mode to start.
1500      if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE
1501          || c == K_X1MOUSE || c == K_X2MOUSE) {
1502        jump_to_mouse(MOUSE_SETPOS, NULL, 0);
1503      } else if (!KeyTyped
1504                 || (vim_strchr("\r\n ", c) == NULL && c != Ctrl_C && c != 'q')) {
1505        // Put the character back in the typeahead buffer.  Don't use the
1506        // stuff buffer, because lmaps wouldn't work.
1507        requeue_key(vgetc_char, vgetc_mod_mask, 0,
1508                    // Recording was suppressed around safe_vgetc() above.
1509                    false);
1510        do_redraw = true;  // need a redraw even though there is typeahead
1511      }
1512    } else {
1513      c = CAR;
1514      // Wait to allow the user to verify the output.
1515      do_sleep(msg_wait, true);
1516    }
1517  }
1518  redir_off = false;
1519
1520  // If the user hits ':', '?' or '/' we get a command line from the next
1521  // line.
1522  if (c == ':' || c == '?' || c == '/') {
1523    cmdline_row = msg_row;
1524    skip_redraw = true;  // skip redraw once
1525    do_redraw = false;
1526  }
1527
1528  // If the screen size changed screen_resize() will redraw the screen.
1529  // Otherwise the screen is only redrawn if 'redraw' is set and no ':'
1530  // typed.
1531  int tmpState = State;
1532  State = oldState;  // restore State before screen_resize()
1533  setmouse();
1534  msg_check();
1535  need_wait_return = false;
1536  did_wait_return = true;
1537  emsg_on_display = false;      // can delete error message now
1538  lines_left = -1;              // reset lines_left at next msg_start()
1539  reset_last_sourcing();
1540  if (keep_msg != NULL && vim_strsize(keep_msg) >=
1541      (Rows - cmdline_row - 1) * Columns + sc_col) {
1542    XFREE_CLEAR(keep_msg);          // don't redisplay message, it's too long
1543  }
1544
1545  if (tmpState == MODE_SETWSIZE) {       // got resize event while in vgetc()
1546    ui_refresh();
1547  } else if (!skip_redraw) {
1548    if (redraw == true || (msg_scrolled != 0 && redraw != -1)) {
1549      redraw_later(curwin, UPD_VALID);
1550    }
1551  }
1552}
1553
1554/// Write the hit-return prompt.
1555///
1556/// @param newline_sb  if starting a new line, add it to the scrollback.
1557static void hit_return_msg(bool newline_sb)
1558{
1559  int save_p_more = p_more;
1560
1561  if (!newline_sb) {
1562    p_more = false;
1563  }
1564  if (msg_didout) {     // start on a new line
1565    msg_putchar('\n');
1566  }
1567  p_more = false;       // don't want to see this message when scrolling back
1568  if (got_int) {
1569    msg_puts(_("Interrupt: "));
1570  }
1571
1572  msg_puts_hl(_("Press ENTER or type command to continue"), HLF_R, false);
1573  if (!msg_use_printf()) {
1574    msg_clr_eos();
1575  }
1576  p_more = save_p_more;
1577}
1578
1579/// Set "keep_msg" to "s".  Free the old value and check for NULL pointer.
1580void set_keep_msg(const char *s, int hl_id)
1581{
1582  // Kept message is not cleared and re-emitted with ext_messages: #20416.
1583  if (ui_has(kUIMessages)) {
1584    return;
1585  }
1586
1587  xfree(keep_msg);
1588  if (s != NULL && msg_silent == 0) {
1589    keep_msg = xstrdup(s);
1590  } else {
1591    keep_msg = NULL;
1592  }
1593  keep_msg_more = false;
1594  keep_msg_hl_id = hl_id;
1595}
1596
1597/// Return true if printing messages should currently be done.
1598bool messaging(void)
1599{
1600  // TODO(bfredl): with general support for "async" messages with p_ch,
1601  // this should be re-enabled.
1602  return !(p_lz && char_avail() && !KeyTyped) && (p_ch > 0 || ui_has(kUIMessages));
1603}
1604
1605void msgmore(int n)
1606{
1607  int pn;
1608
1609  if (global_busy           // no messages now, wait until global is finished
1610      || !messaging()) {      // 'lazyredraw' set, don't do messages now
1611    return;
1612  }
1613
1614  // We don't want to overwrite another important message, but do overwrite
1615  // a previous "more lines" or "fewer lines" message, so that "5dd" and
1616  // then "put" reports the last action.
1617  if (keep_msg != NULL && !keep_msg_more) {
1618    return;
1619  }
1620
1621  pn = abs(n);
1622
1623  if (pn > p_report) {
1624    if (n > 0) {
1625      vim_snprintf(msg_buf, MSG_BUF_LEN,
1626                   NGETTEXT("%d more line", "%d more lines", pn),
1627                   pn);
1628    } else {
1629      vim_snprintf(msg_buf, MSG_BUF_LEN,
1630                   NGETTEXT("%d line less", "%d fewer lines", pn),
1631                   pn);
1632    }
1633    if (got_int) {
1634      xstrlcat(msg_buf, _(" (Interrupted)"), MSG_BUF_LEN);
1635    }
1636    if (msg(msg_buf, 0)) {
1637      set_keep_msg(msg_buf, 0);
1638      keep_msg_more = true;
1639    }
1640  }
1641}
1642
1643static int redir_col = 0;  // Message column used in redir_write().
1644void msg_ext_set_kind(const char *msg_kind)
1645{
1646  // Don't change the label of an existing batch:
1647  msg_ext_ui_flush();
1648
1649  // TODO(bfredl): would be nice to avoid dynamic scoping, but that would
1650  // need refactoring the msg_ interface to not be "please pretend nvim is
1651  // a terminal for a moment"
1652  msg_ext_kind = msg_kind;
1653
1654  // Need to reset the redirection column at the start of a message, for which
1655  // leading newlines are responsible without kUIMessages. Unrelated to setting
1656  // the kind but this is called more consistently at the start of a message
1657  // than msg_start() at this point.
1658  redir_col = msg_ext_append ? redir_col : 0;
1659
1660  if (strcmp("list_cmd", msg_kind) == 0) {
1661    msg_ext_no_fast();
1662  }
1663}
1664
1665void msg_ext_set_append(bool append)
1666{
1667  msg_ext_ui_flush();
1668  msg_ext_append = append;
1669}
1670
1671void msg_ext_set_trigger(const char *trigger)
1672{
1673  msg_ext_ui_flush();
1674  msg_ext_trigger = trigger;
1675}
1676
1677// Should be executed at all callsites emitting non-internal messages.
1678void msg_ext_no_fast(void)
1679{
1680  msg_ext_ui_flush();
1681  msg_ext_fast = false;
1682}
1683
1684/// Prepare for outputting characters in the command line.
1685void msg_start(void)
1686{
1687  bool did_return = false;
1688
1689  msg_row = MAX(msg_row, cmdline_row);
1690
1691  if (!msg_silent) {
1692    XFREE_CLEAR(keep_msg);              // don't display old message now
1693    need_fileinfo = false;
1694  }
1695
1696  if (need_highlight_changed) {
1697    highlight_changed();
1698  }
1699
1700  if (need_clr_eos || (p_ch == 0 && redrawing_cmdline)) {
1701    // Halfway an ":echo" command and getting an (error) message: clear
1702    // any text from the command.
1703    need_clr_eos = false;
1704    msg_clr_eos();
1705  }
1706
1707  // if cmdheight=0, we need to scroll in the first line of msg_grid upon the screen
1708  if (p_ch == 0 && !ui_has(kUIMessages) && !msg_scrolled) {
1709    msg_grid_validate();
1710    msg_scroll_up(false, true);
1711    msg_scrolled++;
1712    cmdline_row = Rows - 1;
1713  }
1714
1715  if (!msg_scroll && full_screen) {     // overwrite last message
1716    msg_row = cmdline_row;
1717    msg_col = 0;
1718  } else if ((msg_didout || p_ch == 0) && !ui_has(kUIMessages)) {  // start message on next line
1719    if (p_ch == 0 && !msg_didout && msg_use_printf()) {
1720      msg_puts_display("\n", 1, 0, false);
1721    } else {
1722      msg_putchar('\n');
1723    }
1724    did_return = true;
1725    cmdline_row = msg_row;
1726  }
1727  if (!msg_didany || lines_left < 0) {
1728    msg_starthere();
1729  }
1730  if (msg_silent == 0) {
1731    msg_didout = false;                     // no output on current line yet
1732  }
1733
1734  if (ui_has(kUIMessages)) {
1735    msg_ext_ui_flush();
1736  }
1737
1738  // When redirecting, may need to start a new line.
1739  if (!did_return) {
1740    redir_write("\n", 1);
1741  }
1742}
1743
1744/// Note that the current msg position is where messages start.
1745void msg_starthere(void)
1746{
1747  lines_left = cmdline_row;
1748  msg_didany = false;
1749}
1750
1751void msg_putchar(int c)
1752{
1753  msg_putchar_hl(c, 0);
1754}
1755
1756void msg_putchar_hl(int c, int hl_id)
1757{
1758  char buf[MB_MAXCHAR + 1];
1759
1760  if (IS_SPECIAL(c)) {
1761    buf[0] = (char)K_SPECIAL;
1762    buf[1] = (char)K_SECOND(c);
1763    buf[2] = (char)K_THIRD(c);
1764    buf[3] = NUL;
1765  } else {
1766    buf[utf_char2bytes(c, buf)] = NUL;
1767  }
1768  msg_puts_hl(buf, hl_id, false);
1769}
1770
1771void msg_outnum(int n)
1772{
1773  char buf[20];
1774
1775  snprintf(buf, sizeof(buf), "%d", n);
1776  msg_puts(buf);
1777}
1778
1779void msg_home_replace(const char *fname)
1780{
1781  msg_home_replace_hl(fname, 0);
1782}
1783
1784static void msg_home_replace_hl(const char *fname, int hl_id)
1785{
1786  char *name = home_replace_save(NULL, fname);
1787  msg_outtrans(name, hl_id, false);
1788  xfree(name);
1789}
1790
1791/// Output "len" characters in "str" (including NULs) with translation
1792/// if "len" is -1, output up to a NUL character. Use highlight "hl_id".
1793///
1794/// @return  the number of characters it takes on the screen.
1795int msg_outtrans(const char *str, int hl_id, bool hist)
1796{
1797  return msg_outtrans_len(str, (int)strlen(str), hl_id, hist);
1798}
1799
1800/// Output one character at "p".
1801/// Handles multi-byte characters.
1802///
1803/// @return  pointer to the next character.
1804const char *msg_outtrans_one(const char *p, int hl_id, bool hist)
1805{
1806  int l;
1807
1808  if ((l = utfc_ptr2len(p)) > 1) {
1809    msg_outtrans_len(p, l, hl_id, hist);
1810    return p + l;
1811  }
1812  msg_puts_hl(transchar_byte_buf(NULL, (uint8_t)(*p)), hl_id, hist);
1813  return p + 1;
1814}
1815
1816int msg_outtrans_len(const char *msgstr, int len, int hl_id, bool hist)
1817{
1818  int retval = 0;
1819  const char *str = msgstr;
1820  const char *plain_start = msgstr;
1821  char *s;
1822  int c;
1823  int save_got_int = got_int;
1824
1825  // Only quit when got_int was set in here.
1826  got_int = false;
1827
1828  if (hist) {
1829    msg_hist_add(str, len, hl_id);
1830  }
1831
1832  // When drawing over the command line no need to clear it later or remove
1833  // the mode message.
1834  if (msg_silent == 0 && len > 0 && msg_row >= cmdline_row && msg_col == 0) {
1835    clear_cmdline = false;
1836    mode_displayed = false;
1837  }
1838
1839  // Go over the string.  Special characters are translated and printed.
1840  // Normal characters are printed several at a time.
1841  while (--len >= 0 && !got_int) {
1842    // Don't include composing chars after the end.
1843    int mb_l = utfc_ptr2len_len(str, len + 1);
1844    if (mb_l > 1) {
1845      c = utf_ptr2char(str);
1846      if (vim_isprintc(c)) {
1847        // Printable multi-byte char: count the cells.
1848        retval += utf_ptr2cells(str);
1849      } else {
1850        // Unprintable multi-byte char: print the printable chars so
1851        // far and the translation of the unprintable char.
1852        if (str > plain_start) {
1853          msg_puts_len(plain_start, str - plain_start, hl_id, hist);
1854        }
1855        plain_start = str + mb_l;
1856        msg_puts_hl(transchar_buf(NULL, c), hl_id == 0 ? HLF_8 : hl_id, false);
1857        retval += char2cells(c);
1858      }
1859      len -= mb_l - 1;
1860      str += mb_l;
1861    } else {
1862      s = transchar_byte_buf(NULL, (uint8_t)(*str));
1863      if (s[1] != NUL) {
1864        // Unprintable char: print the printable chars so far and the
1865        // translation of the unprintable char.
1866        if (str > plain_start) {
1867          msg_puts_len(plain_start, str - plain_start, hl_id, hist);
1868        }
1869        plain_start = str + 1;
1870        msg_puts_hl(s, hl_id == 0 ? HLF_8 : hl_id, false);
1871        retval += (int)strlen(s);
1872      } else {
1873        retval++;
1874      }
1875      str++;
1876    }
1877  }
1878
1879  if ((str > plain_start || plain_start == msgstr) && !got_int) {
1880    // Print the printable chars at the end (or emit empty string).
1881    msg_puts_len(plain_start, str - plain_start, hl_id, hist);
1882  }
1883
1884  got_int |= save_got_int;
1885
1886  return retval;
1887}
1888
1889void msg_make(const char *arg)
1890{
1891  int i;
1892  static const char *str = "eeffoc";
1893  static const char *rs = "Plon#dqg#vxjduB";
1894
1895  arg = skipwhite(arg);
1896  for (i = 5; *arg && i >= 0; i--) {
1897    if (*arg++ != str[i]) {
1898      break;
1899    }
1900  }
1901  if (i < 0) {
1902    msg_putchar('\n');
1903    for (i = 0; rs[i]; i++) {
1904      msg_putchar(rs[i] - 3);
1905    }
1906  }
1907}
1908
1909/// Output the string 'str' up to a NUL character.
1910/// Return the number of characters it takes on the screen.
1911///
1912/// If K_SPECIAL is encountered, then it is taken in conjunction with the
1913/// following character and shown as <F1>, <S-Up> etc.  Any other character
1914/// which is not printable shown in <> form.
1915/// If 'from' is true (lhs of a mapping), a space is shown as <Space>.
1916/// If a character is displayed in one of these special ways, is also
1917/// highlighted (its highlight name is '8' in the p_hl variable).
1918/// Otherwise characters are not highlighted.
1919/// This function is used to show mappings, where we want to see how to type
1920/// the character/string -- webb
1921///
1922/// @param from  true for LHS of a mapping
1923/// @param maxlen  screen columns, 0 for unlimited
1924int msg_outtrans_special(const char *strstart, bool from, int maxlen)
1925{
1926  if (strstart == NULL) {
1927    return 0;  // Do nothing.
1928  }
1929  const char *str = strstart;
1930  int retval = 0;
1931  int hl_id = HLF_8;
1932
1933  while (*str != NUL) {
1934    const char *text;
1935    // Leading and trailing spaces need to be displayed in <> form.
1936    if ((str == strstart || str[1] == NUL) && *str == ' ') {
1937      text = "<Space>";
1938      str++;
1939    } else {
1940      text = str2special(&str, from, false, NULL);
1941    }
1942    if (text[0] != NUL && text[1] == NUL) {
1943      // single-byte character or illegal byte
1944      text = transchar_byte_buf(NULL, (uint8_t)text[0]);
1945    }
1946    const int len = vim_strsize(text);
1947    if (maxlen > 0 && retval + len >= maxlen) {
1948      break;
1949    }
1950    // Highlight special keys
1951    msg_puts_hl(text, (len > 1 && utfc_ptr2len(text) <= 1 ? hl_id : 0), false);
1952    retval += len;
1953  }
1954  return retval;
1955}
1956
1957/// Convert string, replacing key codes with printables
1958///
1959/// Used for lhs or rhs of mappings.
1960///
1961/// @param[in]  str  String to convert.
1962/// @param[in]  replace_spaces  Convert spaces into `<Space>`, normally used for
1963///                             lhs of mapping and keytrans(), but not rhs.
1964/// @param[in]  replace_others  kTrue/kNone: Convert `<` into `<lt>`.
1965///                             kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`.
1966///
1967/// @return [allocated] Converted string.
1968char *str2special_save(const char *const str, const bool replace_spaces,
1969                       const TriState replace_others)
1970  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
1971  FUNC_ATTR_NONNULL_RET
1972{
1973  garray_T ga;
1974  ga_init(&ga, 1, 40);
1975
1976  const char *p = str;
1977  while (*p != NUL) {
1978    ga_concat(&ga, str2special(&p, replace_spaces, replace_others, NULL));
1979  }
1980  ga_append(&ga, NUL);
1981  return (char *)ga.ga_data;
1982}
1983
1984/// Convert string, replacing key codes with printables
1985///
1986/// Used for lhs or rhs of mappings.
1987///
1988/// @param[in]  str  String to convert.
1989/// @param[in]  replace_spaces  Convert spaces into `<Space>`, normally used for
1990///                             lhs of mapping and keytrans(), but not rhs.
1991/// @param[in]  replace_others  kTrue/kNone: Convert `<` into `<lt>`.
1992///                             kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`.
1993///
1994/// @return [allocated] Converted string.
1995char *str2special_arena(const char *const str, const bool replace_spaces,
1996                        const TriState replace_others, Arena *const arena)
1997  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
1998  FUNC_ATTR_NONNULL_RET
1999{
2000  const char *p = str;
2001  size_t len = 0;
2002  while (*p) {
2003    len += strlen(str2special(&p, replace_spaces, replace_others, NULL));
2004  }
2005
2006  char *buf = arena_alloc(arena, len + 1, false);
2007  size_t pos = 0;
2008  p = str;
2009  while (*p) {
2010    const char *s = str2special(&p, replace_spaces, replace_others, NULL);
2011    size_t s_len = strlen(s);
2012    memcpy(buf + pos, s, s_len);
2013    pos += s_len;
2014  }
2015  buf[pos] = NUL;
2016  return buf;
2017}
2018
2019/// Convert character, replacing key with printable representation.
2020///
2021/// @param[in,out]  sp  String to convert. Is advanced to the next key code.
2022/// @param[in]  replace_spaces  Convert spaces into `<Space>`, normally used for
2023///                             lhs of mapping and keytrans(), but not rhs.
2024/// @param[in]  replace_others  kTrue/kNone: Convert `<` into `<lt>`.
2025///                             kTrue: Convert `|` into `<Bar>`, `\` into `<Bslash>`.
2026/// @param[out]  data  If non-NULL, gets structured info about the key chord.
2027///
2028/// @return Converted key code, in a static buffer. Buffer is always one and the
2029///         same, so save converted string somewhere before running str2special
2030///         for the second time.
2031///         On illegal byte return a string with only that byte.
2032const char *str2special(const char **const sp, const bool replace_spaces,
2033                        const TriState replace_others, struct keychord *data)
2034  FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET
2035{
2036  static char buf[7];
2037
2038  {
2039    // Try to un-escape a multi-byte character.  Return the un-escaped
2040    // string if it is a multi-byte character.
2041    const char *const p = mb_unescape(sp);
2042    if (p != NULL) {
2043      if (data) {
2044        data->mods = 0;
2045        data->key = (String){ (char *)p, strlen(p) };
2046        data->key_alt = (String){ NULL, 0 };
2047      }
2048
2049      return p;
2050    }
2051  }
2052
2053  const char *str = *sp;
2054  int c = (uint8_t)(*str);
2055  int modifiers = 0;
2056  bool special = false;
2057  if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) {
2058    if ((uint8_t)str[1] == KS_MODIFIER) {
2059      modifiers = (uint8_t)str[2];
2060      str += 3;
2061      c = (uint8_t)(*str);
2062    }
2063    if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) {
2064      c = TO_SPECIAL((uint8_t)str[1], (uint8_t)str[2]);
2065      str += 2;
2066    }
2067    if (IS_SPECIAL(c) || modifiers) {  // Special key.
2068      special = true;
2069    }
2070  }
2071
2072  if (!IS_SPECIAL(c) && MB_BYTE2LEN(c) > 1) {
2073    *sp = str;
2074    // Try to un-escape a multi-byte character after modifiers.
2075    const char *p = mb_unescape(sp);
2076    if (p != NULL) {
2077      // Since 'special' is true the multi-byte character 'c' will be
2078      // processed by get_special_key_name().
2079      c = utf_ptr2char(p);
2080    } else {
2081      // illegal byte
2082      *sp = str + 1;
2083    }
2084  } else {
2085    // single-byte character, NUL or illegal byte
2086    *sp = str + (*str == NUL ? 0 : 1);
2087  }
2088
2089  // Make special keys and C0 control characters in <> form, also <M-Space>.
2090  if (special
2091      || c < ' '
2092      || (replace_spaces && c == ' ')
2093      || (replace_others != kFalse && c == '<')
2094      || (replace_others == kTrue && (c == '|' || c == '\\'))) {
2095    return get_special_key(c, modifiers, data);
2096  }
2097
2098  if (data) {
2099    data->mods = 0;
2100    if ('A' <= c && c <= 'Z') {
2101      data->key_mem = (char)c + 32;
2102      data->key = (String){ &data->key_mem, 1 };
2103      data->mods |= MOD_MASK_SHIFT;
2104      data->key_alt = (String){ buf, 1 };
2105    } else {
2106      data->key = (String){ buf, 1 };
2107      data->key_alt = (String){ NULL, 0 };
2108    }
2109  }
2110
2111  buf[0] = (char)c;
2112  buf[1] = NUL;
2113  return buf;
2114}
2115
2116/// Convert string, replacing key codes with printables
2117///
2118/// @param[in]  str  String to convert.
2119/// @param[out]  buf  Buffer to save results to.
2120/// @param[in]  len  Buffer length.
2121void str2specialbuf(const char *sp, char *buf, size_t len)
2122  FUNC_ATTR_NONNULL_ALL
2123{
2124  while (*sp) {
2125    const char *s = str2special(&sp, false, false, NULL);
2126    const size_t s_len = strlen(s);
2127    if (len <= s_len) {
2128      break;
2129    }
2130    memcpy(buf, s, s_len);
2131    buf += s_len;
2132    len -= s_len;
2133  }
2134  *buf = NUL;
2135}
2136
2137/// print line for :print or :list command
2138void msg_prt_line(const char *s, bool list)
2139{
2140  schar_T sc;
2141  int col = 0;
2142  int n_extra = 0;
2143  schar_T sc_extra = 0;
2144  schar_T sc_final = 0;
2145  const char *p_extra = NULL;  // init to make SASC shut up. ASCII only!
2146  int n;
2147  int hl_id = 0;
2148  const char *lead = NULL;
2149  bool in_multispace = false;
2150  int multispace_pos = 0;
2151  const char *trail = NULL;
2152  int l;
2153
2154  if (curwin->w_p_list) {
2155    list = true;
2156  }
2157
2158  if (list) {
2159    // find start of trailing whitespace
2160    if (curwin->w_p_lcs_chars.trail) {
2161      trail = s + strlen(s);
2162      while (trail > s && ascii_iswhite(trail[-1])) {
2163        trail--;
2164      }
2165    }
2166    // find end of leading whitespace
2167    if (curwin->w_p_lcs_chars.lead
2168        || curwin->w_p_lcs_chars.leadmultispace != NULL
2169        || curwin->w_p_lcs_chars.leadtab1 != NUL) {
2170      lead = s;
2171      while (ascii_iswhite(lead[0])) {
2172        lead++;
2173      }
2174      // in a line full of spaces all of them are treated as trailing
2175      if (*lead == NUL) {
2176        lead = NULL;
2177      }
2178    }
2179  }
2180
2181  // output a space for an empty line, otherwise the line will be overwritten
2182  if (*s == NUL && !(list && curwin->w_p_lcs_chars.eol != NUL)) {
2183    msg_putchar(' ');
2184  }
2185
2186  while (!got_int) {
2187    if (n_extra > 0) {
2188      n_extra--;
2189      if (n_extra == 0 && sc_final) {
2190        sc = sc_final;
2191      } else if (sc_extra) {
2192        sc = sc_extra;
2193      } else {
2194        assert(p_extra != NULL);
2195        sc = schar_from_ascii((unsigned char)(*p_extra++));
2196      }
2197    } else if ((l = utfc_ptr2len(s)) > 1) {
2198      col += utf_ptr2cells(s);
2199      char buf[MB_MAXBYTES + 1];
2200      if (l >= MB_MAXBYTES) {
2201        xstrlcpy(buf, "?", sizeof(buf));
2202      } else if (curwin->w_p_lcs_chars.nbsp != NUL && list
2203                 && (utf_ptr2char(s) == 160 || utf_ptr2char(s) == 0x202f)) {
2204        schar_get(buf, curwin->w_p_lcs_chars.nbsp);
2205      } else {
2206        memmove(buf, s, (size_t)l);
2207        buf[l] = NUL;
2208      }
2209      msg_puts(buf);
2210      s += l;
2211      continue;
2212    } else {
2213      hl_id = 0;
2214      int c = (uint8_t)(*s++);
2215      if (c >= 0x80) {  // Illegal byte
2216        col += utf_char2cells(c);
2217        msg_putchar(c);
2218        continue;
2219      }
2220      sc_extra = NUL;
2221      sc_final = NUL;
2222      if (list) {
2223        in_multispace = c == ' ' && (*s == ' '
2224                                     || (col > 0 && s[-2] == ' '));
2225        if (!in_multispace) {
2226          multispace_pos = 0;
2227        }
2228      }
2229      if (c == TAB && (!list || curwin->w_p_lcs_chars.tab1)) {
2230        // tab amount depends on current column
2231        n_extra = tabstop_padding(col, curbuf->b_p_ts,
2232                                  curbuf->b_p_vts_array) - 1;
2233        if (!list) {
2234          sc = schar_from_ascii(' ');
2235          sc_extra = schar_from_ascii(' ');
2236        } else {
2237          schar_T lcs_tab1 = curwin->w_p_lcs_chars.tab1;
2238          schar_T lcs_tab2 = curwin->w_p_lcs_chars.tab2;
2239          schar_T lcs_tab3 = curwin->w_p_lcs_chars.tab3;
2240          // check if leadtab is set in 'listchars'
2241          if (lead != NULL && s <= lead && curwin->w_p_lcs_chars.leadtab1 != NUL) {
2242            lcs_tab1 = curwin->w_p_lcs_chars.leadtab1;
2243            lcs_tab2 = curwin->w_p_lcs_chars.leadtab2;
2244            lcs_tab3 = curwin->w_p_lcs_chars.leadtab3;
2245          }
2246          sc = (n_extra == 0 && lcs_tab3) ? lcs_tab3 : lcs_tab1;
2247          sc_extra = lcs_tab2;
2248          sc_final = lcs_tab3;
2249          hl_id = HLF_0;
2250        }
2251      } else if (c == NUL && list && curwin->w_p_lcs_chars.eol != NUL) {
2252        p_extra = "";
2253        n_extra = 1;
2254        sc = curwin->w_p_lcs_chars.eol;
2255        hl_id = HLF_AT;
2256        s--;
2257      } else if (c != NUL && (n = ascii2cells(c)) > 1) {
2258        n_extra = n - 1;
2259        p_extra = transchar_byte_buf(NULL, c);
2260        sc = schar_from_ascii(*p_extra++);
2261        // Use special coloring to be able to distinguish <hex> from
2262        // the same in plain text.
2263        hl_id = HLF_0;
2264      } else if (c == ' ') {
2265        if (lead != NULL && s <= lead && in_multispace
2266            && curwin->w_p_lcs_chars.leadmultispace != NULL) {
2267          sc = curwin->w_p_lcs_chars.leadmultispace[multispace_pos++];
2268          if (curwin->w_p_lcs_chars.leadmultispace[multispace_pos] == NUL) {
2269            multispace_pos = 0;
2270          }
2271          hl_id = HLF_0;
2272        } else if (lead != NULL && s <= lead && curwin->w_p_lcs_chars.lead != NUL) {
2273          sc = curwin->w_p_lcs_chars.lead;
2274          hl_id = HLF_0;
2275        } else if (trail != NULL && s > trail) {
2276          sc = curwin->w_p_lcs_chars.trail;
2277          hl_id = HLF_0;
2278        } else if (in_multispace
2279                   && curwin->w_p_lcs_chars.multispace != NULL) {
2280          sc = curwin->w_p_lcs_chars.multispace[multispace_pos++];
2281          if (curwin->w_p_lcs_chars.multispace[multispace_pos] == NUL) {
2282            multispace_pos = 0;
2283          }
2284          hl_id = HLF_0;
2285        } else if (list && curwin->w_p_lcs_chars.space != NUL) {
2286          sc = curwin->w_p_lcs_chars.space;
2287          hl_id = HLF_0;
2288        } else {
2289          sc = schar_from_ascii(' ');  // SPACE!
2290        }
2291      } else {
2292        sc = schar_from_ascii(c);
2293      }
2294    }
2295
2296    if (sc == NUL) {
2297      break;
2298    }
2299
2300    // TODO(bfredl): this is such baloney. need msg_put_schar
2301    char buf[MAX_SCHAR_SIZE];
2302    schar_get(buf, sc);
2303    msg_puts_hl(buf, hl_id, false);
2304    col++;
2305  }
2306  msg_clr_eos();
2307}
2308
2309/// Output a string to the screen at position msg_row, msg_col.
2310/// Update msg_row and msg_col for the next message.
2311void msg_puts(const char *s)
2312{
2313  msg_puts_hl(s, 0, false);
2314}
2315
2316void msg_puts_title(const char *s)
2317{
2318  s += (ui_has(kUIMessages) && *s == '\n');
2319  msg_puts_hl(s, HLF_T, false);
2320}
2321
2322/// Show a message in such a way that it always fits in the line.  Cut out a
2323/// part in the middle and replace it with "..." when necessary.
2324/// Does not handle multi-byte characters!
2325void msg_outtrans_long(const char *longstr, int hl_id)
2326{
2327  int len = (int)strlen(longstr);
2328  int slen = len;
2329  int room = Columns - msg_col;
2330  if (!ui_has(kUIMessages) && len > room && room >= 20) {
2331    slen = (room - 3) / 2;
2332    msg_outtrans_len(longstr, slen, hl_id, false);
2333    msg_puts_hl("...", HLF_8, false);
2334  }
2335  msg_outtrans_len(longstr + len - slen, slen, hl_id, false);
2336}
2337
2338/// Basic function for writing a message with highlight id.
2339void msg_puts_hl(const char *const s, const int hl_id, const bool hist)
2340{
2341  msg_puts_len(s, -1, hl_id, hist);
2342}
2343
2344/// Write a message with highlight id.
2345///
2346/// @param[in]  str  NUL-terminated message string.
2347/// @param[in]  len  Length of the string or -1.
2348/// @param[in]  hl_id  Highlight id.
2349void msg_puts_len(const char *const str, const ptrdiff_t len, int hl_id, bool hist)
2350  FUNC_ATTR_NONNULL_ALL
2351{
2352  assert(len < 0 || memchr(str, 0, (size_t)len) == NULL);
2353  // If redirection is on, also write to the redirection file.
2354  redir_write(str, len);
2355
2356  // Don't print anything when using ":silent cmd" or empty message.
2357  if (msg_silent != 0 || *str == NUL) {
2358    if (*str == NUL && ui_has(kUIMessages)) {
2359      msg_ext_no_fast();
2360      ui_call_msg_show(cstr_as_string("empty"), (Array)ARRAY_DICT_INIT, false, false, false,
2361                       INTEGER_OBJ(-1), (String)STRING_INIT);
2362      cmdline_was_last_drawn = false;
2363    }
2364    return;
2365  }
2366
2367  if (hist) {
2368    msg_hist_add(str, (int)len, hl_id);
2369  }
2370
2371  // When writing something to the screen after it has scrolled, requires a
2372  // wait-return prompt later.  Needed when scrolling, resetting
2373  // need_wait_return after some prompt, and then outputting something
2374  // without scrolling
2375  // Not needed when only using CR to move the cursor.
2376  bool overflow = !ui_has(kUIMessages) && msg_scrolled > (p_ch == 0 ? 1 : 0);
2377
2378  if (overflow && !msg_scrolled_ign && strcmp(str, "\r") != 0) {
2379    need_wait_return = true;
2380  }
2381  msg_didany = true;  // remember that something was outputted
2382
2383  // If there is no valid screen, use fprintf so we can see error messages.
2384  // If termcap is not active, we may be writing in an alternate console
2385  // window, cursor positioning may not work correctly (window size may be
2386  // different, e.g. for Win32 console) or we just don't know where the
2387  // cursor is.
2388  if (msg_use_printf()) {
2389    int saved_msg_col = msg_col;
2390    msg_puts_printf(str, len);
2391    if (headless_mode) {
2392      msg_col = saved_msg_col;
2393    }
2394  }
2395  if (!msg_use_printf() || (headless_mode && default_grid.chars)) {
2396    msg_puts_display(str, (int)len, hl_id, false);
2397  }
2398
2399  need_fileinfo = false;
2400}
2401
2402static void msg_ext_emit_chunk(void)
2403{
2404  if (msg_ext_chunks == NULL) {
2405    msg_ext_init_chunks();
2406  }
2407  // Color was changed or a message flushed, end current chunk.
2408  if (msg_ext_last_attr == -1) {
2409    return;  // no chunk
2410  }
2411  Array chunk = ARRAY_DICT_INIT;
2412  ADD(chunk, INTEGER_OBJ(msg_ext_last_attr));
2413  msg_ext_last_attr = -1;
2414  String text = ga_take_string(&msg_ext_last_chunk);
2415  ADD(chunk, STRING_OBJ(text));
2416  ADD(chunk, INTEGER_OBJ(msg_ext_last_hl_id));
2417  ADD(*msg_ext_chunks, ARRAY_OBJ(chunk));
2418}
2419
2420/// The display part of msg_puts_len().
2421/// May be called recursively to display scroll-back text.
2422static void msg_puts_display(const char *str, int maxlen, int hl_id, int recurse)
2423{
2424  const char *s = str;
2425  const char *sb_str = str;
2426  int sb_col = msg_col;
2427  int attr = hl_id ? syn_id2attr(hl_id) : 0;
2428
2429  did_wait_return = false;
2430
2431  if (ui_has(kUIMessages)) {
2432    if (attr != msg_ext_last_attr) {
2433      msg_ext_emit_chunk();
2434      msg_ext_last_attr = attr;
2435      msg_ext_last_hl_id = hl_id;
2436    }
2437    // Concat pieces with the same highlight
2438    size_t len = maxlen < 0 ? strlen(str) : strnlen(str, (size_t)maxlen);
2439    ga_concat_len(&msg_ext_last_chunk, str, len);
2440
2441    // Find last newline in the message and calculate the current message column
2442    const char *lastline = xmemrchr(str, '\n', len);
2443    maxlen -= (int)(lastline ? (lastline - str) : 0);
2444    const char *p = lastline ? lastline + 1 : str;
2445    int col = (int)(maxlen < 0 ? mb_string2cells(p) : mb_string2cells_len(p, (size_t)maxlen));
2446    msg_col = (lastline ? 0 : msg_col) + col;
2447
2448    return;
2449  }
2450
2451  int print_attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr);
2452  msg_grid_validate();
2453
2454  cmdline_was_last_drawn = redrawing_cmdline;
2455
2456  int msg_row_pending = -1;
2457
2458  while (true) {
2459    if (msg_col >= Columns) {
2460      if (p_more && !recurse) {
2461        // Store text for scrolling back.
2462        store_sb_text(&sb_str, s, hl_id, &sb_col, true);
2463      }
2464      if (msg_no_more && lines_left == 0) {
2465        break;
2466      }
2467
2468      msg_col = 0;
2469      msg_row++;
2470      msg_didout = false;
2471    }
2472
2473    if (msg_row >= Rows) {
2474      msg_row = Rows - 1;
2475
2476      // When no more prompt and no more room, truncate here
2477      if (msg_no_more && lines_left == 0) {
2478        break;
2479      }
2480
2481      if (!recurse) {
2482        if (msg_row_pending >= 0) {
2483          msg_line_flush();
2484          msg_row_pending = -1;
2485        }
2486
2487        // Scroll the screen up one line.
2488        msg_scroll_up(true, false);
2489
2490        inc_msg_scrolled();
2491        need_wait_return = true;       // may need wait_return() in main()
2492        redraw_cmdline = true;
2493        if (cmdline_row > 0) {
2494          cmdline_row--;
2495        }
2496
2497        // If screen is completely filled and 'more' is set then wait
2498        // for a character.
2499        if (lines_left > 0) {
2500          lines_left--;
2501        }
2502
2503        if (p_more && lines_left == 0 && State != MODE_HITRETURN
2504            && !msg_no_more) {
2505          if (do_more_prompt(NUL)) {
2506            s = confirm_buttons;
2507          }
2508          if (quit_more) {
2509            return;
2510          }
2511        }
2512      }
2513    }
2514
2515    if (!((maxlen < 0 || (int)(s - str) < maxlen) && *s != NUL)) {
2516      break;
2517    }
2518
2519    if (msg_row != msg_row_pending && ((uint8_t)(*s) >= 0x20 || *s == TAB)) {
2520      // TODO(bfredl): this logic is messier that it has to be. What
2521      // messages really want is its own private linebuf_char buffer.
2522      if (msg_row_pending >= 0) {
2523        msg_line_flush();
2524      }
2525      grid_line_start(&msg_grid_adj, msg_row);
2526      msg_row_pending = msg_row;
2527    }
2528
2529    if ((uint8_t)(*s) >= 0x20) {  // printable char
2530      int cw = utf_ptr2cells(s);
2531      // avoid including composing chars after the end
2532      int l = (maxlen >= 0) ? utfc_ptr2len_len(s, (int)((str + maxlen) - s)) : utfc_ptr2len(s);
2533
2534      if (cw > 1 && (msg_col == Columns - 1)) {
2535        // Doesn't fit, print a highlighted '>' to fill it up.
2536        grid_line_puts(msg_col, ">", 1, HL_ATTR(HLF_AT));
2537        cw = 1;
2538      } else {
2539        grid_line_puts(msg_col, s, l, print_attr);
2540        s += l;
2541      }
2542      msg_didout = true;  // remember that line is not empty
2543      msg_col += cw;
2544    } else {
2545      char c = *s++;
2546      if (c == '\n') {  // go to next line
2547        msg_didout = false;  // remember that line is empty
2548        msg_col = 0;
2549        msg_row++;
2550        if (p_more && !recurse) {
2551          // Store text for scrolling back.
2552          store_sb_text(&sb_str, s, hl_id, &sb_col, true);
2553        }
2554      } else if (c == '\r') {  // go to column 0
2555        msg_col = 0;
2556      } else if (c == '\b') {  // go to previous char
2557        if (msg_col) {
2558          msg_col--;
2559        }
2560      } else if (c == TAB) {  // translate Tab into spaces
2561        do {
2562          grid_line_puts(msg_col, " ", 1, print_attr);
2563          msg_col += 1;
2564
2565          if (msg_col == Columns) {
2566            break;
2567          }
2568        } while (msg_col & 7);
2569      } else if (c == BELL) {  // beep (from ":sh")
2570        vim_beep(kOptBoFlagShell);
2571      }
2572    }
2573  }
2574
2575  if (msg_row_pending >= 0) {
2576    msg_line_flush();
2577  }
2578  msg_cursor_goto(msg_row, msg_col);
2579
2580  if (p_more && !recurse) {
2581    store_sb_text(&sb_str, s, hl_id, &sb_col, false);
2582  }
2583
2584  msg_check();
2585}
2586
2587void msg_line_flush(void)
2588{
2589  if (cmdmsg_rl) {
2590    grid_line_mirror(msg_grid.cols);
2591  }
2592  grid_line_flush_if_valid_row();
2593}
2594
2595void msg_cursor_goto(int row, int col)
2596{
2597  if (cmdmsg_rl) {
2598    col = Columns - 1 - col;
2599  }
2600  ScreenGrid *grid = grid_adjust(&msg_grid_adj, &row, &col);
2601  ui_grid_cursor_goto(grid->handle, row, col);
2602}
2603
2604/// @return  true when ":filter pattern" was used and "msg" does not match
2605///          "pattern".
2606bool message_filtered(const char *msg)
2607{
2608  if (cmdmod.cmod_filter_regmatch.regprog == NULL) {
2609    return false;
2610  }
2611
2612  bool match = vim_regexec(&cmdmod.cmod_filter_regmatch, msg, 0);
2613  return cmdmod.cmod_filter_force ? match : !match;
2614}
2615
2616/// including horizontal separator
2617int msg_scrollsize(void)
2618{
2619  return msg_scrolled + (int)p_ch + ((p_ch > 0 || msg_scrolled > 1) ? 1 : 0);
2620}
2621
2622bool msg_do_throttle(void)
2623{
2624  return msg_use_grid() && !(rdb_flags & kOptRdbFlagNothrottle);
2625}
2626
2627/// Scroll the screen up one line for displaying the next message line.
2628void msg_scroll_up(bool may_throttle, bool zerocmd)
2629{
2630  if (may_throttle && msg_do_throttle()) {
2631    msg_grid.throttled = true;
2632  }
2633  msg_did_scroll = true;
2634  if (msg_grid_pos > 0) {
2635    msg_grid_set_pos(msg_grid_pos - 1, !zerocmd);
2636
2637    // When displaying the first line with cmdheight=0, we need to draw over
2638    // the existing last line of the screen.
2639    if (zerocmd && msg_grid.chars) {
2640      grid_clear_line(&msg_grid, msg_grid.line_offset[0], msg_grid.cols, false);
2641    }
2642  } else {
2643    grid_del_lines(&msg_grid, 0, 1, msg_grid.rows, 0, msg_grid.cols);
2644    memmove(msg_grid.dirty_col, msg_grid.dirty_col + 1,
2645            (size_t)(msg_grid.rows - 1) * sizeof(*msg_grid.dirty_col));
2646    msg_grid.dirty_col[msg_grid.rows - 1] = 0;
2647  }
2648
2649  grid_clear(&msg_grid_adj, Rows - 1, Rows, 0, Columns, HL_ATTR(HLF_MSG));
2650}
2651
2652/// Send throttled message output to UI clients
2653///
2654/// The way message.c uses the grid_xx family of functions is quite inefficient
2655/// relative to the "gridline" UI protocol used by TUI and modern clients.
2656/// For instance scrolling is done one line at a time. By throttling drawing
2657/// on the message grid, we can coalesce scrolling to a single grid_scroll
2658/// per screen update.
2659///
2660/// NB: The bookkeeping is quite messy, and rests on a bunch of poorly
2661/// documented assumptions. For instance that the message area always grows
2662/// while being throttled, messages are only being output on the last line
2663/// etc.
2664///
2665/// Probably message scrollback storage should be reimplemented as a
2666/// file_buffer, and message scrolling in TUI be reimplemented as a modal
2667/// floating window. Then we get throttling "for free" using standard
2668/// redraw_later code paths.
2669void msg_scroll_flush(void)
2670{
2671  if (msg_grid.throttled) {
2672    msg_grid.throttled = false;
2673    int pos_delta = msg_grid_pos_at_flush - msg_grid_pos;
2674    assert(pos_delta >= 0);
2675    int delta = MIN(msg_scrolled - msg_scrolled_at_flush, msg_grid.rows);
2676
2677    if (pos_delta > 0) {
2678      ui_ext_msg_set_pos(msg_grid_pos, true);
2679    }
2680
2681    int to_scroll = delta - pos_delta - msg_grid_scroll_discount;
2682    assert(to_scroll >= 0);
2683
2684    // TODO(bfredl): msg_grid_pos should be 0 already when starting scrolling
2685    // but this sometimes fails in "headless" message printing.
2686    if (to_scroll > 0 && msg_grid_pos == 0) {
2687      ui_call_grid_scroll(msg_grid.handle, 0, Rows, 0, Columns, to_scroll, 0);
2688    }
2689
2690    for (int i = MAX(Rows - MAX(delta, 1), 0); i < Rows; i++) {
2691      int row = i - msg_grid_pos;
2692      assert(row >= 0);
2693      ui_line(&msg_grid, row, false, 0, msg_grid.dirty_col[row], msg_grid.cols,
2694              HL_ATTR(HLF_MSG), false);
2695      msg_grid.dirty_col[row] = 0;
2696    }
2697  }
2698  msg_scrolled_at_flush = msg_scrolled;
2699  msg_grid_scroll_discount = 0;
2700  msg_grid_pos_at_flush = msg_grid_pos;
2701}
2702
2703void msg_reset_scroll(void)
2704{
2705  if (ui_has(kUIMessages)) {
2706    return;
2707  }
2708  // TODO(bfredl): some duplicate logic with update_screen(). Later on
2709  // we should properly disentangle message clear with full screen redraw.
2710  msg_grid.throttled = false;
2711  // TODO(bfredl): risk for extra flicker i e with
2712  // "nvim -o has_swap also_has_swap"
2713  msg_grid_set_pos(Rows - (int)p_ch, false);
2714  clear_cmdline = true;
2715  if (msg_grid.chars) {
2716    // non-displayed part of msg_grid is considered invalid.
2717    for (int i = 0; i < MIN(msg_scrollsize(), msg_grid.rows); i++) {
2718      grid_clear_line(&msg_grid, msg_grid.line_offset[i],
2719                      msg_grid.cols, false);
2720    }
2721  }
2722  msg_scrolled = 0;
2723  msg_scrolled_at_flush = 0;
2724  msg_grid_scroll_discount = 0;
2725}
2726
2727void msg_ui_refresh(void)
2728{
2729  if (ui_has(kUIMultigrid) && msg_grid.chars) {
2730    ui_call_grid_resize(msg_grid.handle, msg_grid.cols, msg_grid.rows);
2731    ui_ext_msg_set_pos(msg_grid_pos, msg_scrolled);
2732  }
2733}
2734
2735void msg_ui_flush(void)
2736{
2737  if (ui_has(kUIMultigrid) && msg_grid.chars && msg_grid.pending_comp_index_update) {
2738    ui_ext_msg_set_pos(msg_grid_pos, msg_scrolled);
2739  }
2740}
2741
2742/// Increment "msg_scrolled".
2743static void inc_msg_scrolled(void)
2744{
2745  if (*get_vim_var_str(VV_SCROLLSTART) == NUL) {
2746    String p = { .data = SOURCING_NAME };
2747    char *tofree = NULL;
2748
2749    // v:scrollstart is empty, set it to the script/function name and line
2750    // number
2751    if (p.data == NULL) {
2752      p = cstr_as_string(_("Unknown"));
2753    } else {
2754      size_t tofreesize = strlen(p.data) + 40;
2755      tofree = xmalloc(tofreesize);
2756      p.size = vim_snprintf_safelen(tofree, tofreesize, _("%s line %" PRId64),
2757                                    p.data, (int64_t)SOURCING_LNUM);
2758      p.data = tofree;
2759    }
2760    set_vim_var_string(VV_SCROLLSTART, p.data, (ptrdiff_t)p.size);
2761    xfree(tofree);
2762  }
2763  msg_scrolled++;
2764  set_must_redraw(UPD_VALID);
2765}
2766
2767static msgchunk_T *last_msgchunk = NULL;  // last displayed text
2768
2769typedef enum {
2770  SB_CLEAR_NONE = 0,
2771  SB_CLEAR_ALL,
2772  SB_CLEAR_CMDLINE_BUSY,
2773  SB_CLEAR_CMDLINE_DONE,
2774} sb_clear_T;
2775
2776// When to clear text on next msg.
2777static sb_clear_T do_clear_sb_text = SB_CLEAR_NONE;
2778
2779/// Store part of a printed message for displaying when scrolling back.
2780///
2781/// @param sb_str  start of string
2782/// @param s  just after string
2783/// @param finish  line ends
2784static void store_sb_text(const char **sb_str, const char *s, int hl_id, int *sb_col, int finish)
2785{
2786  msgchunk_T *mp;
2787
2788  if (do_clear_sb_text == SB_CLEAR_ALL
2789      || do_clear_sb_text == SB_CLEAR_CMDLINE_DONE) {
2790    clear_sb_text(do_clear_sb_text == SB_CLEAR_ALL);
2791    msg_sb_eol();  // prevent messages from overlapping
2792    if (do_clear_sb_text == SB_CLEAR_CMDLINE_DONE && s > *sb_str && **sb_str == '\n') {
2793      (*sb_str)++;
2794    }
2795    do_clear_sb_text = SB_CLEAR_NONE;
2796  }
2797
2798  if (s > *sb_str) {
2799    mp = xmalloc(offsetof(msgchunk_T, sb_text) + (size_t)(s - *sb_str) + 1);
2800    mp->sb_eol = (char)finish;
2801    mp->sb_msg_col = *sb_col;
2802    mp->sb_hl_id = hl_id;
2803    memcpy(mp->sb_text, *sb_str, (size_t)(s - *sb_str));
2804    mp->sb_text[s - *sb_str] = NUL;
2805
2806    if (last_msgchunk == NULL) {
2807      last_msgchunk = mp;
2808      mp->sb_prev = NULL;
2809    } else {
2810      mp->sb_prev = last_msgchunk;
2811      last_msgchunk->sb_next = mp;
2812      last_msgchunk = mp;
2813    }
2814    mp->sb_next = NULL;
2815  } else if (finish && last_msgchunk != NULL) {
2816    last_msgchunk->sb_eol = true;
2817  }
2818
2819  *sb_str = s;
2820  *sb_col = 0;
2821}
2822
2823/// Finished showing messages, clear the scroll-back text on the next message.
2824void may_clear_sb_text(void)
2825{
2826  msg_ext_ui_flush();  // ensure messages until now are emitted
2827  do_clear_sb_text = SB_CLEAR_ALL;
2828  do_clear_hist_temp = true;
2829}
2830
2831/// Starting to edit the command line: do not clear messages now.
2832void sb_text_start_cmdline(void)
2833{
2834  if (do_clear_sb_text == SB_CLEAR_CMDLINE_BUSY) {
2835    // Invoking command line recursively: the previous-level command line
2836    // doesn't need to be remembered as it will be redrawn when returning
2837    // to that level.
2838    sb_text_restart_cmdline();
2839  } else {
2840    msg_sb_eol();
2841    do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY;
2842  }
2843}
2844
2845/// Redrawing the command line: clear the last unfinished line.
2846void sb_text_restart_cmdline(void)
2847{
2848  // Needed when returning from nested command line.
2849  do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY;
2850
2851  if (last_msgchunk == NULL || last_msgchunk->sb_eol) {
2852    // No unfinished line: don't clear anything.
2853    return;
2854  }
2855
2856  msgchunk_T *tofree = msg_sb_start(last_msgchunk);
2857  last_msgchunk = tofree->sb_prev;
2858  if (last_msgchunk != NULL) {
2859    last_msgchunk->sb_next = NULL;
2860  }
2861  while (tofree != NULL) {
2862    msgchunk_T *tofree_next = tofree->sb_next;
2863    xfree(tofree);
2864    tofree = tofree_next;
2865  }
2866}
2867
2868/// Ending to edit the command line: clear old lines but the last one later.
2869void sb_text_end_cmdline(void)
2870{
2871  do_clear_sb_text = SB_CLEAR_CMDLINE_DONE;
2872}
2873
2874/// Clear any text remembered for scrolling back.
2875/// When "all" is false keep the last line.
2876/// Called when redrawing the screen.
2877void clear_sb_text(bool all)
2878{
2879  msgchunk_T *mp;
2880  msgchunk_T **lastp;
2881
2882  if (all) {
2883    lastp = &last_msgchunk;
2884  } else {
2885    if (last_msgchunk == NULL) {
2886      return;
2887    }
2888    lastp = &msg_sb_start(last_msgchunk)->sb_prev;
2889  }
2890
2891  while (*lastp != NULL) {
2892    mp = (*lastp)->sb_prev;
2893    xfree(*lastp);
2894    *lastp = mp;
2895  }
2896}
2897
2898/// "g<" command.
2899void show_sb_text(void)
2900{
2901  if (ui_has(kUIMessages)) {
2902    exarg_T ea = { .arg = "", .skip = true };
2903    ex_messages(&ea);
2904    return;
2905  }
2906  // Only show something if there is more than one line, otherwise it looks
2907  // weird, typing a command without output results in one line.
2908  msgchunk_T *mp = msg_sb_start(last_msgchunk);
2909  if (mp == NULL || mp->sb_prev == NULL) {
2910    vim_beep(kOptBoFlagMess);
2911  } else {
2912    do_more_prompt('G');
2913    wait_return(false);
2914  }
2915}
2916
2917/// Move to the start of screen line in already displayed text.
2918static msgchunk_T *msg_sb_start(msgchunk_T *mps)
2919{
2920  msgchunk_T *mp = mps;
2921
2922  while (mp != NULL && mp->sb_prev != NULL && !mp->sb_prev->sb_eol) {
2923    mp = mp->sb_prev;
2924  }
2925  return mp;
2926}
2927
2928/// Mark the last message chunk as finishing the line.
2929void msg_sb_eol(void)
2930{
2931  if (last_msgchunk != NULL) {
2932    last_msgchunk->sb_eol = true;
2933  }
2934}
2935
2936/// Display a screen line from previously displayed text at row "row".
2937///
2938/// @return  a pointer to the text for the next line (can be NULL).
2939static msgchunk_T *disp_sb_line(int row, msgchunk_T *smp)
2940{
2941  msgchunk_T *mp = smp;
2942
2943  while (true) {
2944    msg_row = row;
2945    msg_col = mp->sb_msg_col;
2946    char *p = mp->sb_text;
2947    msg_puts_display(p, -1, mp->sb_hl_id, true);
2948    if (mp->sb_eol || mp->sb_next == NULL) {
2949      break;
2950    }
2951    mp = mp->sb_next;
2952  }
2953
2954  return mp->sb_next;
2955}
2956
2957/// @return  true when messages should be printed to stdout/stderr:
2958///          - "batch mode" ("silent mode", -es/-Es/-l)
2959///          - no UI and not embedded
2960///          - no ext_messages
2961int msg_use_printf(void)
2962{
2963  return !embedded_mode && !ui_active() && !ui_has(kUIMessages);
2964}
2965
2966/// Print a message when there is no valid screen.
2967static void msg_puts_printf(const char *str, const ptrdiff_t maxlen)
2968{
2969  const char *s = str;
2970  char buf[7];
2971  char *p;
2972
2973  if (on_print.type != kCallbackNone) {
2974    typval_T argv[1];
2975    argv[0].v_type = VAR_STRING;
2976    argv[0].v_lock = VAR_UNLOCKED;
2977    argv[0].vval.v_string = (char *)str;
2978    typval_T rettv = TV_INITIAL_VALUE;
2979    callback_call(&on_print, 1, argv, &rettv);
2980    tv_clear(&rettv);
2981    return;
2982  }
2983
2984  while ((maxlen < 0 || s - str < maxlen) && *s != NUL) {
2985    int len = utf_ptr2len(s);
2986    if (!(silent_mode && p_verbose == 0)) {
2987      // NL --> CR NL translation (for Unix, not for "--version")
2988      p = &buf[0];
2989      if (*s == '\n' && !info_message && !silent_mode && !headless_mode) {
2990        *p++ = '\r';
2991      }
2992      memcpy(p, s, (size_t)len);
2993      *(p + len) = NUL;
2994      if (info_message) {
2995        printf("%s", buf);
2996      } else {
2997        fprintf(stderr, "%s", buf);
2998      }
2999    }
3000
3001    int cw = utf_char2cells(utf_ptr2char(s));
3002    // primitive way to compute the current column
3003    if (*s == '\r' || *s == '\n') {
3004      msg_col = 0;
3005      msg_didout = false;
3006    } else {
3007      msg_col += cw;
3008      msg_didout = true;
3009    }
3010    s += len;
3011  }
3012}
3013
3014/// Show the more-prompt and handle the user response.
3015/// This takes care of scrolling back and displaying previously displayed text.
3016/// When at hit-enter prompt "typed_char" is the already typed character,
3017/// otherwise it's NUL.
3018///
3019/// @return  true when jumping ahead to "confirm_buttons".
3020static bool do_more_prompt(int typed_char)
3021{
3022  static bool entered = false;
3023  int used_typed_char = typed_char;
3024  int oldState = State;
3025  int c;
3026  bool retval = false;
3027  bool to_redraw = false;
3028  msgchunk_T *mp_last = NULL;
3029  msgchunk_T *mp;
3030
3031  // If headless mode is enabled and no input is required, this variable
3032  // will be true. However If server mode is enabled, the message "--more--"
3033  // should be displayed.
3034  bool no_need_more = headless_mode && !embedded_mode && !ui_active();
3035
3036  // We get called recursively when a timer callback outputs a message. In
3037  // that case don't show another prompt. Also when at the hit-Enter prompt
3038  // and nothing was typed.
3039  if (no_need_more || entered || (State == MODE_HITRETURN && typed_char == 0)) {
3040    return false;
3041  }
3042  entered = true;
3043
3044  if (typed_char == 'G') {
3045    // "g<": Find first line on the last page.
3046    mp_last = msg_sb_start(last_msgchunk);
3047    for (int i = 0; i < Rows - 2 && mp_last != NULL
3048         && mp_last->sb_prev != NULL; i++) {
3049      mp_last = msg_sb_start(mp_last->sb_prev);
3050    }
3051  }
3052
3053  State = MODE_ASKMORE;
3054  setmouse();
3055  if (typed_char == NUL) {
3056    msg_moremsg(false);
3057  }
3058  while (true) {
3059    // Get a typed character directly from the user.
3060    if (used_typed_char != NUL) {
3061      c = used_typed_char;              // was typed at hit-enter prompt
3062      used_typed_char = NUL;
3063    } else {
3064      c = get_keystroke(resize_events);
3065    }
3066
3067    int toscroll = 0;
3068    switch (c) {
3069    case BS:                    // scroll one line back
3070    case K_BS:
3071    case 'k':
3072    case K_UP:
3073      toscroll = -1;
3074      break;
3075
3076    case CAR:                   // one extra line
3077    case NL:
3078    case 'j':
3079    case K_DOWN:
3080      toscroll = 1;
3081      break;
3082
3083    case 'u':                   // Up half a page
3084      toscroll = -(Rows / 2);
3085      break;
3086
3087    case 'd':                   // Down half a page
3088      toscroll = Rows / 2;
3089      break;
3090
3091    case 'b':                   // one page back
3092    case Ctrl_B:
3093    case K_PAGEUP:
3094      toscroll = -(Rows - 1);
3095      break;
3096
3097    case ' ':                   // one extra page
3098    case 'f':
3099    case Ctrl_F:
3100    case K_PAGEDOWN:
3101    case K_LEFTMOUSE:
3102      toscroll = Rows - 1;
3103      break;
3104
3105    case 'g':                   // all the way back to the start
3106      toscroll = -999999;
3107      break;
3108
3109    case 'G':                   // all the way to the end
3110      toscroll = 999999;
3111      lines_left = 999999;
3112      break;
3113
3114    case ':':                   // start new command line
3115      if (!confirm_msg_used) {
3116        // Since got_int is set all typeahead will be flushed, but we
3117        // want to keep this ':', remember that in a special way.
3118        typeahead_noflush(':');
3119        cmdline_row = Rows - 1;                 // put ':' on this line
3120        skip_redraw = true;                     // skip redraw once
3121        need_wait_return = false;               // don't wait in main()
3122      }
3123      FALLTHROUGH;
3124    case 'q':                   // quit
3125    case Ctrl_C:
3126    case ESC:
3127      if (confirm_msg_used) {
3128        // Jump to the choices of the dialog.
3129        retval = true;
3130      } else {
3131        got_int = true;
3132        quit_more = true;
3133      }
3134      // When there is some more output (wrapping line) display that
3135      // without another prompt.
3136      lines_left = Rows - 1;
3137      break;
3138
3139    case K_EVENT:
3140      // only resize_events are processed here
3141      // Attempt to redraw the screen. sb_text doesn't support reflow
3142      // so this only really works for vertical resize.
3143      multiqueue_process_events(resize_events);
3144      to_redraw = true;
3145      break;
3146
3147    default:                    // no valid response
3148      msg_moremsg(true);
3149      continue;
3150    }
3151
3152    // code assumes we only do one at a time
3153    assert((toscroll == 0) || !to_redraw);
3154
3155    if (toscroll != 0 || to_redraw) {
3156      if (toscroll < 0 || to_redraw) {
3157        // go to start of last line
3158        if (mp_last == NULL) {
3159          mp = msg_sb_start(last_msgchunk);
3160        } else if (mp_last->sb_prev != NULL) {
3161          mp = msg_sb_start(mp_last->sb_prev);
3162        } else {
3163          mp = NULL;
3164        }
3165
3166        // go to start of line at top of the screen
3167        for (int i = 0; i < Rows - 2 && mp != NULL && mp->sb_prev != NULL; i++) {
3168          mp = msg_sb_start(mp->sb_prev);
3169        }
3170
3171        if (mp != NULL && (mp->sb_prev != NULL || to_redraw)) {
3172          // Find line to be displayed at top
3173          for (int i = 0; i > toscroll; i--) {
3174            if (mp == NULL || mp->sb_prev == NULL) {
3175              break;
3176            }
3177            mp = msg_sb_start(mp->sb_prev);
3178            if (mp_last == NULL) {
3179              mp_last = msg_sb_start(last_msgchunk);
3180            } else {
3181              mp_last = msg_sb_start(mp_last->sb_prev);
3182            }
3183          }
3184
3185          if (toscroll == -1 && !to_redraw) {
3186            grid_ins_lines(&msg_grid, 0, 1, Rows, 0, Columns);
3187            grid_clear(&msg_grid_adj, 0, 1, 0, Columns, HL_ATTR(HLF_MSG));
3188            // display line at top
3189            disp_sb_line(0, mp);
3190          } else {
3191            // redisplay all lines
3192            // TODO(bfredl): this case is not optimized (though only concerns
3193            // event fragmentation, not unnecessary scroll events).
3194            grid_clear(&msg_grid_adj, 0, Rows, 0, Columns, HL_ATTR(HLF_MSG));
3195            for (int i = 0; mp != NULL && i < Rows - 1; i++) {
3196              mp = disp_sb_line(i, mp);
3197              msg_scrolled++;
3198            }
3199            to_redraw = false;
3200          }
3201          toscroll = 0;
3202        }
3203      } else {
3204        // First display any text that we scrolled back.
3205        // if p_ch=0 we need to allocate a line for "press enter" messages!
3206        if (cmdline_row >= Rows && !ui_has(kUIMessages)) {
3207          msg_scroll_up(true, false);
3208          msg_scrolled++;
3209        }
3210        while (toscroll > 0 && mp_last != NULL) {
3211          if (msg_do_throttle() && !msg_grid.throttled) {
3212            // Tricky: we redraw at one line higher than usual. Therefore
3213            // the non-flushed area is one line larger.
3214            msg_scrolled_at_flush--;
3215            msg_grid_scroll_discount++;
3216          }
3217          // scroll up, display line at bottom
3218          msg_scroll_up(true, false);
3219          inc_msg_scrolled();
3220          grid_clear(&msg_grid_adj, Rows - 2, Rows - 1, 0, Columns, HL_ATTR(HLF_MSG));
3221          mp_last = disp_sb_line(Rows - 2, mp_last);
3222          toscroll--;
3223        }
3224      }
3225
3226      if (toscroll <= 0) {
3227        // displayed the requested text, more prompt again
3228        grid_clear(&msg_grid_adj, Rows - 1, Rows, 0, Columns, HL_ATTR(HLF_MSG));
3229        msg_moremsg(false);
3230        continue;
3231      }
3232
3233      // display more text, return to caller
3234      lines_left = toscroll;
3235    }
3236
3237    break;
3238  }
3239
3240  // clear the --more-- message
3241  grid_clear(&msg_grid_adj, Rows - 1, Rows, 0, Columns, HL_ATTR(HLF_MSG));
3242  redraw_cmdline = true;
3243  clear_cmdline = false;
3244  mode_displayed = false;
3245
3246  State = oldState;
3247  setmouse();
3248  if (quit_more) {
3249    msg_row = Rows - 1;
3250    msg_col = 0;
3251  }
3252
3253  entered = false;
3254  return retval;
3255}
3256
3257static void msg_moremsg(bool full)
3258{
3259  int attr = hl_combine_attr(HL_ATTR(HLF_MSG), HL_ATTR(HLF_M));
3260  grid_line_start(&msg_grid_adj, Rows - 1);
3261  int len = grid_line_puts(0, _("-- More --"), -1, attr);
3262  if (full) {
3263    len += grid_line_puts(len, _(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "),
3264                          -1, attr);
3265  }
3266  grid_line_cursor_goto(len);
3267  grid_line_flush();
3268}
3269
3270/// Repeat the message for the current mode: MODE_ASKMORE, MODE_EXTERNCMD,
3271/// or confirm() prompt.
3272void repeat_message(void)
3273{
3274  if (ui_has(kUIMessages)) {
3275    return;
3276  }
3277
3278  if (State == MODE_ASKMORE) {
3279    msg_moremsg(true);          // display --more-- message again
3280    msg_row = Rows - 1;
3281  } else if ((State & MODE_CMDLINE) && confirm_msg != NULL) {
3282    display_confirm_msg();      // display ":confirm" message again
3283    msg_row = Rows - 1;
3284  } else if (State == MODE_EXTERNCMD) {
3285    ui_cursor_goto(msg_row, msg_col);     // put cursor back
3286  } else if (State == MODE_HITRETURN || State == MODE_SETWSIZE) {
3287    if (msg_row == Rows - 1) {
3288      // Avoid drawing the "hit-enter" prompt below the previous one,
3289      // overwrite it.  Esp. useful when regaining focus and a
3290      // FocusGained autocmd exists but didn't draw anything.
3291      msg_didout = false;
3292      msg_col = 0;
3293      msg_clr_eos();
3294    }
3295    hit_return_msg(false);
3296    msg_row = Rows - 1;
3297  }
3298}
3299
3300/// Clear from current message position to end of screen.
3301/// Skip this when ":silent" was used, no need to clear for redirection.
3302void msg_clr_eos(void)
3303{
3304  if (msg_silent == 0) {
3305    msg_clr_eos_force();
3306  }
3307}
3308
3309/// Clear from current message position to end of screen.
3310/// Note: msg_col is not updated, so we remember the end of the message
3311/// for msg_check().
3312void msg_clr_eos_force(void)
3313{
3314  if (ui_has(kUIMessages)) {
3315    return;
3316  }
3317  int msg_startcol = cmdmsg_rl ? 0 : msg_col;
3318  int msg_endcol = cmdmsg_rl ? Columns - msg_col : Columns;
3319
3320  // TODO(bfredl): ugly, this state should already been validated at this
3321  // point. But msg_clr_eos() is called in a lot of places.
3322  if (msg_grid.chars && msg_row < msg_grid_pos) {
3323    msg_grid_validate();
3324    if (msg_row < msg_grid_pos) {
3325      msg_row = msg_grid_pos;
3326    }
3327  }
3328
3329  grid_clear(&msg_grid_adj, msg_row, msg_row + 1, msg_startcol, msg_endcol, HL_ATTR(HLF_MSG));
3330  grid_clear(&msg_grid_adj, msg_row + 1, Rows, 0, Columns, HL_ATTR(HLF_MSG));
3331
3332  redraw_cmdline = true;  // overwritten the command line
3333  if (msg_row < Rows - 1 || msg_col == 0) {
3334    clear_cmdline = false;  // command line has been cleared
3335    mode_displayed = false;  // mode cleared or overwritten
3336    cmdline_was_last_drawn = false;
3337  }
3338}
3339
3340/// Clear the command line.
3341void msg_clr_cmdline(void)
3342{
3343  msg_row = cmdline_row;
3344  msg_col = 0;
3345  msg_clr_eos_force();
3346}
3347
3348/// end putting a message on the screen
3349/// call wait_return() if the message does not fit in the available space
3350///
3351/// @return  true if wait_return() not called.
3352bool msg_end(void)
3353{
3354  // If the string is larger than the window,
3355  // or the ruler option is set and we run into it,
3356  // we have to redraw the window.
3357  // Do not do this if we are abandoning the file or editing the command line.
3358  if (!exiting && need_wait_return && !(State & MODE_CMDLINE)) {
3359    wait_return(false);
3360    return false;
3361  }
3362
3363  // NOTE: ui_flush() used to be called here. This had to be removed, as it
3364  // inhibited substantial performance improvements. It is assumed that relevant
3365  // callers invoke ui_flush() before going into CPU busywork, or restricted
3366  // event processing after displaying a message to the user.
3367  msg_ext_ui_flush();
3368  return true;
3369}
3370
3371/// Clear "msg_ext_chunks" before flushing so that ui_flush() does not re-emit
3372/// the same message recursively.
3373static Array *msg_ext_init_chunks(void)
3374{
3375  Array *tofree = msg_ext_chunks;
3376  msg_ext_chunks = xcalloc(1, sizeof(*msg_ext_chunks));
3377  msg_col = 0;
3378  return tofree;
3379}
3380
3381void msg_ext_ui_flush(void)
3382{
3383  if (!ui_has(kUIMessages)) {
3384    msg_ext_kind = NULL;
3385    return;
3386  } else if (msg_ext_skip_flush) {
3387    return;
3388  }
3389
3390  msg_ext_emit_chunk();
3391  if (msg_ext_chunks->size > 0) {
3392    Array *tofree = msg_ext_init_chunks();
3393
3394    ui_call_msg_show(cstr_as_string(msg_ext_kind), *tofree, msg_ext_overwrite, msg_ext_history,
3395                     msg_ext_append, msg_ext_id, cstr_as_string(msg_ext_trigger));
3396    // clear info after emitting message.
3397    if (msg_ext_history) {
3398      api_free_array(*tofree);
3399    } else {
3400      // Add to history as temporary message for "g<".
3401      HlMessage msg = KV_INITIAL_VALUE;
3402      for (size_t i = 0; i < kv_size(*tofree); i++) {
3403        Object *chunk = kv_A(*tofree, i).data.array.items;
3404        kv_push(msg, ((HlMessageChunk){ chunk[1].data.string, (int)chunk[2].data.integer }));
3405        xfree(chunk);
3406      }
3407      xfree(tofree->items);
3408      msg_hist_add_multihl(msg, true);
3409    }
3410    xfree(tofree);
3411    msg_ext_overwrite = false;
3412    msg_ext_history = false;
3413    msg_ext_append = false;
3414    msg_ext_fast = true;
3415    msg_ext_kind = NULL;
3416    // Consume the pre-allocated id, if the message did not get one from msg_multihl().
3417    if (msg_ext_id.type == kObjectTypeInteger && msg_ext_id.data.integer == msg_id_next) {
3418      msg_id_next++;
3419    }
3420    msg_ext_id = INTEGER_OBJ(msg_id_next);
3421  }
3422}
3423
3424void msg_ext_flush_showmode(void)
3425{
3426  // Showmode messages doesn't interrupt normal message flow, so we use
3427  // separate event. Still reuse the same chunking logic, for simplicity.
3428  // This is called unconditionally; check if we are emitting, or have
3429  // emitted non-empty "content".
3430  static bool clear = false;
3431  if (ui_has(kUIMessages) && (msg_ext_last_attr != -1 || clear)) {
3432    clear = msg_ext_last_attr != -1;
3433    msg_ext_emit_chunk();
3434    Array *tofree = msg_ext_init_chunks();
3435    ui_call_msg_showmode(*tofree);
3436    api_free_array(*tofree);
3437    xfree(tofree);
3438  }
3439}
3440
3441/// If the written message runs into the shown command or ruler, we have to
3442/// wait for hit-return and redraw the window later.
3443void msg_check(void)
3444{
3445  if (ui_has(kUIMessages)) {
3446    return;
3447  }
3448  if (msg_row == Rows - 1 && msg_col >= sc_col) {
3449    need_wait_return = true;
3450    redraw_cmdline = true;
3451  }
3452}
3453
3454/// May write a string to the redirection file.
3455///
3456/// @param maxlen  if -1, write the whole string, otherwise up to "maxlen" bytes.
3457static void redir_write(const char *const str, const ptrdiff_t maxlen)
3458{
3459  const char *s = str;
3460
3461  if (maxlen == 0) {
3462    return;
3463  }
3464
3465  // Don't do anything for displaying prompts and the like.
3466  if (redir_off) {
3467    return;
3468  }
3469
3470  // If 'verbosefile' is set prepare for writing in that file.
3471  if (*p_vfile != NUL && verbose_fd == NULL) {
3472    verbose_open();
3473  }
3474
3475  if (redirecting()) {
3476    // If the string doesn't start with CR or NL, go to msg_col
3477    if (*s != '\n' && *s != '\r') {
3478      while (redir_col < msg_col) {
3479        if (capture_ga) {
3480          ga_concat_len(capture_ga, " ", 1);
3481        }
3482        if (redir_reg) {
3483          write_reg_contents(redir_reg, " ", 1, true);
3484        } else if (redir_vname) {
3485          var_redir_str(" ", -1);
3486        } else if (redir_fd != NULL) {
3487          fputs(" ", redir_fd);
3488        }
3489        if (verbose_fd != NULL) {
3490          fputs(" ", verbose_fd);
3491        }
3492        redir_col++;
3493      }
3494    }
3495
3496    size_t len = maxlen == -1 ? strlen(s) : (size_t)maxlen;
3497    if (capture_ga) {
3498      ga_concat_len(capture_ga, str, len);
3499    }
3500    if (redir_reg) {
3501      write_reg_contents(redir_reg, s, (ssize_t)len, true);
3502    }
3503    if (redir_vname) {
3504      var_redir_str(s, (int)maxlen);
3505    }
3506
3507    // Write and adjust the current column.
3508    while (*s != NUL
3509           && (maxlen < 0 || (int)(s - str) < maxlen)) {
3510      if (!redir_reg && !redir_vname && !capture_ga) {
3511        if (redir_fd != NULL) {
3512          putc(*s, redir_fd);
3513        }
3514      }
3515      if (verbose_fd != NULL) {
3516        putc(*s, verbose_fd);
3517      }
3518      if (*s == '\r' || *s == '\n') {
3519        redir_col = 0;
3520      } else if (*s == '\t') {
3521        redir_col += (8 - redir_col % 8);
3522      } else {
3523        redir_col++;
3524      }
3525      s++;
3526    }
3527
3528    if (msg_silent != 0) {      // should update msg_col
3529      msg_col = redir_col;
3530    }
3531  }
3532}
3533
3534int redirecting(void)
3535{
3536  return redir_fd != NULL || *p_vfile != NUL
3537         || redir_reg || redir_vname || capture_ga != NULL;
3538}
3539
3540// Save and restore message kind when emitting a verbose message.
3541static const char *pre_verbose_kind = NULL;
3542static const char *verbose_kind = "verbose";
3543
3544/// Before giving verbose message.
3545/// Must always be called paired with verbose_leave()!
3546void verbose_enter(void)
3547{
3548  if (*p_vfile != NUL) {
3549    msg_silent++;
3550  }
3551  // Don't set the verbose kind if message continuity is wanted like with last_set_msg().
3552  if (!msg_ext_skip_verbose) {
3553    if (msg_ext_kind != verbose_kind) {
3554      pre_verbose_kind = msg_ext_kind;
3555    }
3556    msg_ext_set_kind("verbose");
3557  }
3558  msg_ext_skip_verbose = false;
3559}
3560
3561/// After giving verbose message.
3562/// Must always be called paired with verbose_enter()!
3563void verbose_leave(void)
3564{
3565  if (*p_vfile != NUL) {
3566    if (--msg_silent < 0) {
3567      msg_silent = 0;
3568    }
3569  }
3570  if (pre_verbose_kind != NULL) {
3571    msg_ext_set_kind(pre_verbose_kind);
3572    pre_verbose_kind = NULL;
3573  }
3574}
3575
3576/// Like verbose_enter() and set msg_scroll when displaying the message.
3577void verbose_enter_scroll(void)
3578{
3579  verbose_enter();
3580  if (*p_vfile == NUL) {
3581    // always scroll up, don't overwrite
3582    msg_scroll = true;
3583  }
3584}
3585
3586/// Like verbose_leave() and set cmdline_row when displaying the message.
3587void verbose_leave_scroll(void)
3588{
3589  verbose_leave();
3590  if (*p_vfile == NUL) {
3591    cmdline_row = msg_row;
3592  }
3593}
3594
3595/// Called when 'verbosefile' is set: stop writing to the file.
3596void verbose_stop(void)
3597{
3598  if (verbose_fd != NULL) {
3599    fclose(verbose_fd);
3600    verbose_fd = NULL;
3601  }
3602  verbose_did_open = false;
3603}
3604
3605/// Open the file 'verbosefile'.
3606///
3607/// @return  FAIL or OK.
3608int verbose_open(void)
3609{
3610  if (verbose_fd == NULL && !verbose_did_open) {
3611    // Only give the error message once.
3612    verbose_did_open = true;
3613
3614    verbose_fd = os_fopen(p_vfile, "a");
3615    if (verbose_fd == NULL) {
3616      semsg(_(e_notopen), p_vfile);
3617      return FAIL;
3618    }
3619  }
3620  return OK;
3621}
3622
3623/// Give a warning message (for searching).
3624/// Use 'w' highlighting and may repeat the message after redrawing
3625void give_warning(const char *message, bool hl, bool hist)
3626  FUNC_ATTR_NONNULL_ARG(1)
3627{
3628  // Don't do this for ":silent".
3629  if (msg_silent != 0) {
3630    return;
3631  }
3632
3633  bool save_msg_hist_off = msg_hist_off;
3634  msg_hist_off = !hist;
3635
3636  // Don't want a hit-enter prompt here.
3637  no_wait_return++;
3638
3639  set_vim_var_string(VV_WARNINGMSG, message, -1);
3640  XFREE_CLEAR(keep_msg);
3641  if (hl) {
3642    keep_msg_hl_id = HLF_W;
3643  } else {
3644    keep_msg_hl_id = 0;
3645  }
3646
3647  if (msg_ext_kind == NULL) {
3648    msg_ext_set_kind("wmsg");
3649  }
3650
3651  if (msg(message, keep_msg_hl_id) && msg_scrolled == 0) {
3652    set_keep_msg(message, keep_msg_hl_id);
3653  }
3654  msg_didout = false;  // Overwrite this message.
3655  msg_nowait = true;   // Don't wait for this message.
3656  msg_col = 0;
3657
3658  no_wait_return--;
3659  msg_hist_off = save_msg_hist_off;
3660}
3661
3662/// Shows a warning, with optional highlighting.
3663///
3664/// @param hl enable highlighting
3665/// @param fmt printf-style format message
3666///
3667/// @see smsg
3668/// @see semsg
3669void swmsg(bool hl, const char *const fmt, ...)
3670  FUNC_ATTR_PRINTF(2, 3)
3671{
3672  va_list args;
3673
3674  va_start(args, fmt);
3675  vim_vsnprintf(IObuff, IOSIZE, fmt, args);
3676  va_end(args);
3677
3678  give_warning(IObuff, hl, true);
3679}
3680
3681/// Advance msg cursor to column "col".
3682void msg_advance(int col)
3683{
3684  if (msg_silent != 0) {        // nothing to advance to
3685    msg_col = col;              // for redirection, may fill it up later
3686    return;
3687  }
3688  col = MIN(col, Columns - 1);  // not enough room
3689  while (msg_col < col) {
3690    msg_putchar(' ');
3691  }
3692}
3693
3694/// Display the ":confirm" message.  Also called from do_dialog() and when screen resized.
3695void display_confirm_msg(void)
3696{
3697  // Avoid that 'q' at the more prompt truncates the message here.
3698  confirm_msg_used++;
3699  if (confirm_msg != NULL) {
3700    msg_ext_set_kind("confirm");
3701    msg_puts_hl(confirm_msg, HLF_M, false);
3702  }
3703  confirm_msg_used--;
3704}
3705
3706/// Only for legacy UI (`!ui_has(kUIMessages)`): Pause to display a message for `ms` milliseconds.
3707///
3708/// TODO(justinmk): Most of these cases may not be needed after "ui2"...
3709void msg_delay(uint64_t ms, bool ignoreinput)
3710{
3711  if (ui_has(kUIMessages)) {
3712    return;
3713  }
3714
3715  if (nvim_testing) {
3716    // XXX: Reduce non-functional (UI only) delay in tests/CI.
3717    ms = 100;
3718  }
3719
3720  DLOG("%" PRIu64 " ms%s", ms, nvim_testing ? " (skipped by NVIM_TEST)" : "");
3721  ui_flush();
3722  os_delay(ms, ignoreinput);
3723}
3724
3725/// Check if there should be a delay to allow the user to see a message.
3726///
3727/// Used before clearing or redrawing the screen or the command line.
3728void msg_check_for_delay(bool check_msg_scroll)
3729{
3730  if ((emsg_on_display || (check_msg_scroll && msg_scroll))
3731      && !did_wait_return && emsg_silent == 0 && !in_assert_fails && !ui_has(kUIMessages)) {
3732    msg_delay(1006, true);
3733    emsg_on_display = false;
3734    if (check_msg_scroll) {
3735      msg_scroll = false;
3736    }
3737  }
3738}