robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
67.6 KiB2177 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <stdbool.h>
4#include <stddef.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8
9#include "nvim/api/private/defs.h"
10#include "nvim/api/private/helpers.h"
11#include "nvim/ascii_defs.h"
12#include "nvim/autocmd.h"
13#include "nvim/buffer.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/context.h"
17#include "nvim/digraph.h"
18#include "nvim/drawline.h"
19#include "nvim/drawscreen.h"
20#include "nvim/eval.h"
21#include "nvim/eval/typval_defs.h"
22#include "nvim/eval/vars.h"
23#include "nvim/eval_defs.h"
24#include "nvim/gettext_defs.h"
25#include "nvim/globals.h"
26#include "nvim/grid.h"
27#include "nvim/grid_defs.h"
28#include "nvim/highlight.h"
29#include "nvim/highlight_defs.h"
30#include "nvim/highlight_group.h"
31#include "nvim/macros_defs.h"
32#include "nvim/mbyte.h"
33#include "nvim/memline.h"
34#include "nvim/memline_defs.h"
35#include "nvim/memory.h"
36#include "nvim/memory_defs.h"
37#include "nvim/message.h"
38#include "nvim/normal.h"
39#include "nvim/option.h"
40#include "nvim/option_vars.h"
41#include "nvim/os/os.h"
42#include "nvim/os/os_defs.h"
43#include "nvim/path.h"
44#include "nvim/plines.h"
45#include "nvim/pos_defs.h"
46#include "nvim/sign.h"
47#include "nvim/sign_defs.h"
48#include "nvim/state_defs.h"
49#include "nvim/statusline.h"
50#include "nvim/strings.h"
51#include "nvim/types_defs.h"
52#include "nvim/ui.h"
53#include "nvim/ui_defs.h"
54#include "nvim/undo.h"
55#include "nvim/window.h"
56
57// Specifies whether/where to add padding to reach target width.
58typedef enum {
59  kPaddingNone,
60  kPaddingLeft,
61  kPaddingRight,
62} StlPadding;
63
64#include "statusline.c.generated.h"
65
66// Determines how deeply nested %{} blocks will be evaluated in statusline.
67#define MAX_STL_EVAL_DEPTH 100
68
69/// Enumeration specifying the valid numeric bases that can
70/// be used when printing numbers in the status line.
71typedef enum {
72  kNumBaseDecimal = 10,
73  kNumBaseHexadecimal = 16,
74} NumberBase;
75
76/// Redraw the status line of window `wp`.
77///
78/// If inversion is possible we use it. Else '=' characters are used.
79void win_redr_status(win_T *wp)
80{
81  bool is_stl_global = global_stl_height() > 0;
82  static bool busy = false;
83
84  // May get here recursively when 'statusline' (indirectly)
85  // invokes ":redrawstatus".  Simply ignore the call then.
86  if (busy
87      // Also ignore if wildmenu is showing.
88      || (wild_menu_showing != 0 && !ui_has(kUIWildmenu))) {
89    return;
90  }
91
92  busy = true;
93  wp->w_redr_status = false;
94
95  // curwin may be temporarily switched during autocmds (ctx_switch).
96  win_T *stl_curwin = ctx_saved_curwin();
97  if (stl_curwin == NULL) {
98    stl_curwin = curwin;
99  }
100  bool is_stl_curwin = wp == stl_curwin;
101
102  if (wp->w_status_height == 0 && !(is_stl_global && is_stl_curwin)) {
103    // no status line, either global statusline is enabled or the window is a last window
104    redraw_cmdline = true;
105  } else if (!redrawing()) {
106    // Don't redraw right now, do it later. Don't update status line when
107    // popup menu is visible and may be drawn over it
108    wp->w_redr_status = true;
109  } else if (*wp->w_p_stl != NUL || !wp->w_floating || (is_stl_global && is_stl_curwin)) {
110    win_redr_stl_expr(wp, false, false, false);
111  }
112
113  hlf_T group = HLF_C;
114  // May need to draw the character below the vertical separator.
115  if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing()) {
116    schar_T fillchar;
117    if (stl_connected(wp)) {
118      fillchar = fillchar_status(&group, wp);
119    } else {
120      fillchar = wp->w_p_fcs_chars.vert;
121    }
122    int attr = win_hl_attr(wp, (int)group);
123    grid_line_start(&default_gridview, W_ENDROW(wp));
124    grid_line_put_schar(W_ENDCOL(wp), fillchar, attr);
125    grid_line_flush();
126  }
127  busy = false;
128}
129
130void get_trans_bufname(buf_T *buf)
131{
132  if (buf_spname(buf) != NULL) {
133    xstrlcpy(NameBuff, buf_spname(buf), MAXPATHL);
134  } else {
135    home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, true);
136  }
137  trans_characters(NameBuff, MAXPATHL);
138}
139
140/// Only call if (wp->w_vsep_width != 0).
141///
142/// @return  true if the status line of window "wp" is connected to the status
143/// line of the window right of it.  If not, then it's a vertical separator.
144bool stl_connected(win_T *wp)
145{
146  frame_T *fr = wp->w_frame;
147  while (fr->fr_parent != NULL) {
148    if (fr->fr_parent->fr_layout == FR_COL) {
149      if (fr->fr_next != NULL) {
150        break;
151      }
152    } else {
153      if (fr->fr_next != NULL) {
154        return true;
155      }
156    }
157    fr = fr->fr_parent;
158  }
159  return false;
160}
161
162/// Clear status line, window bar or tab page line click definition table
163///
164/// @param[out]  tpcd  Table to clear.
165/// @param[in]  tpcd_size  Size of the table.
166void stl_clear_click_defs(StlClickDefinition *const click_defs, const size_t click_defs_size)
167{
168  if (click_defs != NULL) {
169    for (size_t i = 0; i < click_defs_size; i++) {
170      if (i == 0 || click_defs[i].func != click_defs[i - 1].func) {
171        xfree(click_defs[i].func);
172      }
173    }
174    memset(click_defs, 0, click_defs_size * sizeof(click_defs[0]));
175  }
176}
177
178/// Allocate or resize the click definitions array if needed.
179StlClickDefinition *stl_alloc_click_defs(StlClickDefinition *cdp, int width, size_t *size)
180{
181  if (*size < (size_t)width) {
182    xfree(cdp);
183    *size = (size_t)width;
184    cdp = xcalloc(*size, sizeof(StlClickDefinition));
185  }
186  return cdp;
187}
188
189/// Fill the click definitions array if needed.
190void stl_fill_click_defs(StlClickDefinition *click_defs, StlClickRecord *click_recs,
191                         const char *buf, int width, bool tabline)
192{
193  if (click_defs == NULL) {
194    return;
195  }
196
197  int col = 0;
198  int len = 0;
199
200  StlClickDefinition cur_click_def = {
201    .type = kStlClickDisabled,
202  };
203  for (int i = 0; click_recs[i].start != NULL; i++) {
204    len += vim_strnsize(buf, (int)(click_recs[i].start - buf));
205    assert(len <= width);
206    if (col < len) {
207      while (col < len) {
208        click_defs[col++] = cur_click_def;
209      }
210    } else {
211      xfree(cur_click_def.func);
212    }
213    buf = click_recs[i].start;
214    cur_click_def = click_recs[i].def;
215    if (!tabline && !(cur_click_def.type == kStlClickDisabled
216                      || cur_click_def.type == kStlClickFuncRun)) {
217      // window bar and status line only support click functions
218      cur_click_def.type = kStlClickDisabled;
219    }
220  }
221  if (col < width) {
222    while (col < width) {
223      click_defs[col++] = cur_click_def;
224    }
225  } else {
226    xfree(cur_click_def.func);
227  }
228}
229
230static bool did_show_ext_ruler = false;
231/// Redraws the statusline, winbar, ruler or tabline.
232///
233/// @param wp  target window, NULL for 'tabline'
234/// @param draw_winbar  redraw 'winbar'
235/// @param draw_ruler  redraw 'rulerformat'
236/// @param ui_event  emit UI-event instead of drawing
237static void win_redr_stl_expr(win_T *wp, bool draw_winbar, bool draw_ruler, bool ui_event)
238{
239  static bool entered = false;
240  int col = 0;
241  int attr, row, maxwidth;
242  hlf_T group;
243  schar_T fillchar;
244  char buf[MAXPATHL];
245  char transbuf[MAXPATHL];
246  char *stl;
247  OptIndex opt_idx = kOptInvalid;
248  int opt_scope = 0;
249  stl_hlrec_t *hltab;
250  StlClickDefinition *click_defs;
251  bool is_stl_global = global_stl_height() > 0;
252
253  ScreenGrid *grid = wp && wp->w_floating && !is_stl_global ? &wp->w_grid_alloc : &default_grid;
254
255  if (!is_stl_global && wp != NULL && wp->w_config.hide) {
256    return;  // unnecessary
257  }
258
259  // There is a tiny chance that this gets called recursively: When
260  // redrawing a status line triggers redrawing the ruler or tabline.
261  // Avoid trouble by not allowing recursion.
262  if (entered) {
263    return;
264  }
265  entered = true;
266
267  // Restore actual curwin before redrawing.
268  win_T *save_curwin = ctx_saved_curwin();
269  win_T *restore_curwin = save_curwin != NULL ? curwin : NULL;
270  if (save_curwin != NULL) {
271    curwin = save_curwin;
272    curbuf = curwin->w_buffer;
273  }
274
275  // setup environment for the task at hand
276  if (wp == NULL) {
277    // Use 'tabline'.  Always at the first line of the screen.
278    stl = p_tal;
279    row = 0;
280    fillchar = schar_from_ascii(' ');
281    group = HLF_TPF;
282    attr = HL_ATTR(group);
283    maxwidth = Columns;
284    opt_idx = kOptTabline;
285    click_defs = tab_page_click_defs;
286  } else if (draw_winbar) {
287    opt_idx = kOptWinbar;
288    stl = ((*wp->w_p_wbr != NUL) ? wp->w_p_wbr : p_wbr);
289    opt_scope = ((*wp->w_p_wbr != NUL) ? OPT_LOCAL : 0);
290    row = -1;  // row zero is first row of text
291    col = 0;
292    grid = grid_adjust(&wp->w_grid, &row, &col);
293
294    if (row < 0) {
295      goto theend;
296    }
297
298    fillchar = wp->w_p_fcs_chars.wbr;
299    group = (wp == curwin) ? HLF_WBR : HLF_WBRNC;
300    attr = win_hl_attr(wp, (int)group);
301    maxwidth = wp->w_view_width;
302    stl_clear_click_defs(wp->w_winbar_click_defs, wp->w_winbar_click_defs_size);
303    wp->w_winbar_click_defs = stl_alloc_click_defs(wp->w_winbar_click_defs, maxwidth,
304                                                   &wp->w_winbar_click_defs_size);
305    click_defs = wp->w_winbar_click_defs;
306  } else if (draw_ruler && ui_event) {
307    stl = p_ruf;
308    opt_idx = kOptRulerformat;
309    maxwidth = Columns / 2;
310    fillchar = schar_from_ascii(' ');
311    group = HLF_MSG;
312    attr = HL_ATTR(group);
313    click_defs = NULL;
314  } else if (draw_ruler) {
315    stl = p_ruf;
316    opt_idx = kOptRulerformat;
317    // advance past any leading group spec - implicit in ru_col
318    if (*stl == '%') {
319      if (*++stl == '-') {
320        stl++;
321      }
322      if (atoi(stl)) {
323        while (ascii_isdigit(*stl)) {
324          stl++;
325        }
326      }
327      if (*stl++ != '(') {
328        stl = p_ruf;
329      }
330    }
331    row = Rows - 1;
332    col = MAX(ru_col, Columns / 2);
333    grid = grid_adjust(&msg_grid_adj, &row, &col);
334    maxwidth = Columns - col;
335    fillchar = schar_from_ascii(' ');
336    group = HLF_MSG;
337    attr = HL_ATTR(group);
338    click_defs = NULL;
339  } else {
340    // statusline
341    stl = ((*wp->w_p_stl != NUL) ? wp->w_p_stl : p_stl);
342    opt_idx = kOptStatusline;
343    opt_scope = ((*wp->w_p_stl != NUL) ? OPT_LOCAL : 0);
344    if (is_stl_global) {
345      row = Rows - (int)p_ch - 1;
346      col = 0;
347      maxwidth = Columns;
348    } else if (wp->w_status_height == 0) {
349      goto theend;
350    } else if (wp->w_floating) {
351      row = wp->w_winrow_off + wp->w_view_height;
352      col = wp->w_wincol_off;
353      maxwidth = wp->w_view_width;
354    } else {
355      row = W_ENDROW(wp);
356      col = wp->w_wincol;
357      maxwidth = wp->w_width;
358    }
359    fillchar = fillchar_status(&group, wp);
360    attr = win_hl_attr(wp, (int)group);
361    stl_clear_click_defs(wp->w_status_click_defs, wp->w_status_click_defs_size);
362    wp->w_status_click_defs = stl_alloc_click_defs(wp->w_status_click_defs, maxwidth,
363                                                   &wp->w_status_click_defs_size);
364    click_defs = wp->w_status_click_defs;
365  }
366
367  if (maxwidth <= 0) {
368    goto theend;
369  }
370
371  // Temporarily reset 'cursorbind', we don't want a side effect from moving
372  // the cursor away and back.
373  win_T *ewp = wp == NULL ? curwin : wp;
374  int p_crb_save = ewp->w_p_crb;
375  ewp->w_p_crb = false;
376
377  // Make a copy, because the statusline may include a function call that
378  // might change the option value and free the memory.
379  stl = xstrdup(stl);
380
381  StlClickRecord *tabtab = NULL;
382  build_stl_str_hl(ewp, (CharBuf){ buf, sizeof(buf) }, stl, opt_idx, opt_scope,
383                   fillchar, maxwidth, &hltab, NULL, click_defs ? &tabtab : NULL, NULL);
384  stl_fill_click_defs(click_defs, tabtab, buf, maxwidth, wp == NULL);
385
386  xfree(stl);
387  ewp->w_p_crb = p_crb_save;
388
389  int len = (int)strlen(buf);
390  int start_col = col;
391
392  if (!ui_event) {
393    // Draw each snippet with the specified highlighting.
394    screengrid_line_start(grid, row, 0);
395  }
396
397  char *p = buf;
398  int curattr = attr;
399  int curgroup = (int)group;
400  Array content = ARRAY_DICT_INIT;
401  for (stl_hlrec_t *sp = hltab;; sp++) {
402    int textlen = (int)(sp->start ? sp->start - p : buf + len - p);
403    // Make all characters printable. Use an empty string instead of p, if p is beyond buf + len.
404    size_t tsize = transstr_buf(p >= buf + len ? "" : p, textlen, transbuf, sizeof transbuf, true);
405    if (!ui_event) {
406      col += grid_line_puts(col, transbuf, (int)tsize, curattr);
407    } else {
408      Array chunk = ARRAY_DICT_INIT;
409      ADD(chunk, INTEGER_OBJ(curattr));
410      ADD(chunk, STRING_OBJ(cbuf_as_string(xmemdupz(transbuf, tsize), tsize)));
411      ADD(chunk, INTEGER_OBJ(curgroup));
412      ADD(content, ARRAY_OBJ(chunk));
413    }
414    p = sp->start;
415
416    if (p == NULL) {
417      break;
418    } else if (sp->userhl == 0) {
419      curattr = attr;
420      curgroup = (int)group;
421    } else if (sp->userhl < 0) {
422      int new_attr = syn_id2attr(-sp->userhl);
423      if (sp->item == STL_HIGHLIGHT_COMB) {
424        curattr = hl_combine_attr(curattr, new_attr);
425      } else {
426        curattr = new_attr;
427      }
428      curgroup = -sp->userhl;
429    } else {
430      int *userhl = (wp != NULL && wp != curwin && wp->w_status_height != 0)
431                    ? highlight_stlnc : highlight_user;
432      char userbuf[5] = "User";
433      userbuf[4] = (char)sp->userhl + '0';
434      curattr = userhl[sp->userhl - 1];
435      curgroup = syn_name2id_len(userbuf, 5);
436    }
437    if (curattr != attr) {
438      curattr = hl_combine_attr(attr, curattr);
439    }
440  }
441
442  if (p_sc && find_option(p_sloc) == opt_idx) {
443    showcmd_update_clear_state();
444  }
445
446  if (ui_event) {
447    ui_call_msg_ruler(content);
448    did_show_ext_ruler = true;
449    api_free_array(content);
450    goto theend;
451  }
452
453  int maxcol = start_col + maxwidth;
454
455  // fill up with "fillchar"
456  grid_line_fill(col, maxcol, fillchar, curattr);
457  grid_line_flush();
458
459theend:
460  entered = false;
461
462  // Restore temporary autocmd curwin.
463  if (restore_curwin != NULL) {
464    curwin = restore_curwin;
465    curbuf = restore_curwin->w_buffer;
466  }
467}
468
469void win_redr_winbar(win_T *wp)
470{
471  static bool entered = false;
472
473  // Return when called recursively. This can happen when the winbar contains an expression
474  // that triggers a redraw.
475  if (entered) {
476    return;
477  }
478  entered = true;
479
480  if (wp->w_winbar_height == 0 || !redrawing()) {
481    // Do nothing.
482  } else if (*p_wbr != NUL || *wp->w_p_wbr != NUL) {
483    win_redr_stl_expr(wp, true, false, false);
484  }
485  entered = false;
486}
487
488void redraw_ruler(void)
489{
490  static bool did_show_ruler = false;
491  win_T *wp = !curwin->w_config.hide
492              && curwin->w_status_height == 0 ? curwin : lastwin_nofloating(NULL);
493  bool is_stl_global = global_stl_height() > 0;
494
495  // Check if ruler should be drawn, clear if it was drawn before.
496  bool part_of_status = wp->w_status_height != 0 || is_stl_global;
497  if (!p_ru || part_of_status || (p_ch == 0 && !ui_has(kUIMessages))) {
498    if (did_show_ext_ruler && ui_has(kUIMessages)) {
499      ui_call_msg_ruler((Array)ARRAY_DICT_INIT);
500      did_show_ext_ruler = false;
501    } else if (did_show_ruler && !ui_has(kUIMessages)) {
502      msg_clr_eos();
503    }
504    did_show_ruler = false;
505    return;
506  }
507
508  // Check if cursor.lnum is valid, since redraw_ruler() may be called
509  // after deleting lines, before cursor.lnum is corrected.
510  if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) {
511    return;
512  }
513
514  // Don't draw the ruler while doing insert-completion, it might overwrite
515  // the (long) mode message.
516  if (wp->w_status_height == 0 && !is_stl_global && edit_submode != NULL) {
517    return;
518  }
519
520  win_redr_stl_expr(wp, false, true, ui_has(kUIMessages));
521  did_show_ruler = !ui_has(kUIMessages);
522}
523
524/// Get the character to use in a status line.  Get its attributes in "*attr".
525schar_T fillchar_status(hlf_T *group, win_T *wp)
526{
527  if (wp == curwin) {
528    *group = HLF_S;
529    return wp->w_p_fcs_chars.stl;
530  } else {
531    *group = HLF_SNC;
532    return wp->w_p_fcs_chars.stlnc;
533  }
534}
535
536static void ui_ext_tabline_update(void)
537{
538  Arena arena = ARENA_EMPTY;
539
540  size_t n_tabs = 0;
541  FOR_ALL_TABS(tp) {
542    n_tabs++;
543  }
544
545  Array tabs = arena_array(&arena, n_tabs);
546  FOR_ALL_TABS(tp) {
547    Dict tab_info = arena_dict(&arena, 2);
548    PUT_C(tab_info, "tab", TABPAGE_OBJ(tp->handle));
549
550    win_T *cwp = (tp == curtab) ? curwin : tp->tp_curwin;
551    get_trans_bufname(cwp->w_buffer);
552    PUT_C(tab_info, "name", CSTR_TO_ARENA_OBJ(&arena, NameBuff));
553
554    ADD_C(tabs, DICT_OBJ(tab_info));
555  }
556
557  size_t n_buffers = 0;
558  FOR_ALL_BUFFERS(buf) {
559    n_buffers += buf->b_p_bl ? 1 : 0;
560  }
561
562  Array buffers = arena_array(&arena, n_buffers);
563  FOR_ALL_BUFFERS(buf) {
564    // Do not include unlisted buffers
565    if (!buf->b_p_bl) {
566      continue;
567    }
568
569    Dict buffer_info = arena_dict(&arena, 2);
570    PUT_C(buffer_info, "buffer", BUFFER_OBJ(buf->handle));
571
572    get_trans_bufname(buf);
573    PUT_C(buffer_info, "name", CSTR_TO_ARENA_OBJ(&arena, NameBuff));
574
575    ADD_C(buffers, DICT_OBJ(buffer_info));
576  }
577
578  ui_call_tabline_update(curtab->handle, tabs, curbuf->handle, buffers);
579  arena_mem_free(arena_finish(&arena));
580}
581
582/// Draw the tab pages line at the top of the Vim window.
583void draw_tabline(void)
584{
585  win_T *wp;
586  int attr_nosel = HL_ATTR(HLF_TP);
587  int attr_fill = HL_ATTR(HLF_TPF);
588  bool use_sep_chars = (t_colors < 8);
589
590  if (default_grid.chars == NULL) {
591    return;
592  }
593  redraw_tabline = false;
594
595  if (ui_has(kUITabline)) {
596    ui_ext_tabline_update();
597    return;
598  }
599
600  if (tabline_height() < 1) {
601    return;
602  }
603
604  // Clear tab_page_click_defs: Clicking outside of tabs has no effect.
605  assert(tab_page_click_defs_size >= (size_t)Columns);
606  stl_clear_click_defs(tab_page_click_defs, tab_page_click_defs_size);
607
608  // Use the 'tabline' option if it's set.
609  if (*p_tal != NUL) {
610    win_redr_stl_expr(NULL, false, false, false);
611  } else {
612    int tabcount = 0;
613    int col = 0;
614    win_T *cwp;
615    int wincount;
616    grid_line_start(&default_gridview, 0);
617    FOR_ALL_TABS(tp) {
618      tabcount++;
619    }
620
621    int tabwidth = MAX(tabcount > 0 ? (Columns - 1 + tabcount / 2) / tabcount : 0, 6);
622
623    int attr = attr_nosel;
624    tabcount = 0;
625
626    FOR_ALL_TABS(tp) {
627      if (col >= Columns - 4) {
628        break;
629      }
630
631      int scol = col;
632
633      if (tp == curtab) {
634        cwp = curwin;
635        wp = firstwin;
636      } else {
637        cwp = tp->tp_curwin;
638        wp = tp->tp_firstwin;
639      }
640
641      if (tp->tp_topframe == topframe) {
642        attr = win_hl_attr(cwp, HLF_TPS);
643      }
644      if (use_sep_chars && col > 0) {
645        grid_line_put_schar(col++, schar_from_ascii('|'), attr);
646      }
647
648      if (tp->tp_topframe != topframe) {
649        attr = win_hl_attr(cwp, HLF_TP);
650      }
651
652      grid_line_put_schar(col++, schar_from_ascii(' '), attr);
653
654      bool modified = false;
655
656      for (wincount = 0; wp != NULL; wp = wp->w_next, wincount++) {
657        if (!wp->w_config.focusable || wp->w_config.hide) {
658          wincount--;
659        } else if (bufIsChanged(wp->w_buffer)) {
660          modified = true;
661        }
662      }
663
664      if (modified || wincount > 1) {
665        if (wincount > 1) {
666          int len = vim_snprintf(NameBuff, MAXPATHL, "%d", wincount);
667          if (col + len >= Columns - 3) {
668            break;
669          }
670          grid_line_puts(col, NameBuff, len,
671                         hl_combine_attr(attr, win_hl_attr(cwp, HLF_T)));
672          col += len;
673        }
674        if (modified) {
675          grid_line_put_schar(col++, schar_from_ascii('+'), attr);
676        }
677        grid_line_put_schar(col++, schar_from_ascii(' '), attr);
678      }
679
680      int room = scol - col + tabwidth - 1;
681      if (room > 0) {
682        // Get buffer name in NameBuff[]
683        get_trans_bufname(cwp->w_buffer);
684        shorten_dir(NameBuff);
685        int len = vim_strsize(NameBuff);
686        char *p = NameBuff;
687        while (len > room) {
688          len -= ptr2cells(p);
689          MB_PTR_ADV(p);
690        }
691        int n = Columns - col - 1;
692        len = MIN(len, n);
693
694        grid_line_puts(col, p, -1, attr);
695        col += len;
696      }
697      grid_line_put_schar(col++, schar_from_ascii(' '), attr);
698
699      // Store the tab page number in tab_page_click_defs[], so that
700      // jump_to_mouse() knows where each one is.
701      tabcount++;
702      while (scol < col) {
703        tab_page_click_defs[scol++] = (StlClickDefinition) {
704          .type = kStlClickTabSwitch,
705          .tabnr = tabcount,
706          .func = NULL,
707        };
708      }
709    }
710
711    for (int scol = col; scol < Columns; scol++) {
712      // Use 0 as tabpage number here, so that double-click opens a tabpage
713      // after the last one, and single-click goes to the next tabpage.
714      tab_page_click_defs[scol] = (StlClickDefinition) {
715        .type = kStlClickTabSwitch,
716        .tabnr = 0,
717        .func = NULL,
718      };
719    }
720
721    char c = use_sep_chars ? '_' : ' ';
722    grid_line_fill(col, Columns, schar_from_ascii(c), attr_fill);
723
724    // Draw the 'showcmd' information if 'showcmdloc' == "tabline".
725    if (p_sc && *p_sloc == 't') {
726      int n = Columns - col - (tabcount > 1) * 3;
727      const int sc_width = MIN(10, n);
728
729      if (sc_width > 0) {
730        grid_line_puts(Columns - sc_width - (tabcount > 1) * 2,
731                       showcmd_buf, sc_width, attr_nosel);
732      }
733      showcmd_update_clear_state();
734    }
735
736    // Put an "X" for closing the current tab if there are several.
737    if (tabcount > 1) {
738      grid_line_put_schar(Columns - 1, schar_from_ascii('X'), attr_nosel);
739      tab_page_click_defs[Columns - 1] = (StlClickDefinition) {
740        .type = kStlClickTabClose,
741        .tabnr = 999,
742        .func = NULL,
743      };
744    }
745
746    grid_line_flush();
747  }
748
749  // Reset the flag here again, in case evaluating 'tabline' causes it to be
750  // set.
751  redraw_tabline = false;
752}
753
754/// Build the 'statuscolumn' string for line "lnum". When "relnum" == -1,
755/// the v:lnum and v:relnum variables don't have to be updated.
756///
757/// @return  The width of the built status column string for line "lnum"
758int build_statuscol_str(win_T *wp, linenr_T lnum, int relnum, int virtnum, CharBuf buf,
759                        statuscol_T *stcp)
760{
761  if (relnum >= 0) {
762    set_vim_var_nr(VV_LNUM, lnum);
763    set_vim_var_nr(VV_RELNUM, relnum);
764  }
765  set_vim_var_nr(VV_VIRTNUM, virtnum);
766
767  StlClickRecord *clickrec;
768  char *stc = xstrdup(wp->w_p_stc);
769  int width = build_stl_str_hl(wp, buf, stc, kOptStatuscolumn, OPT_LOCAL, 0,
770                               stcp->width, &stcp->hlrec, NULL, &clickrec, stcp);
771  xfree(stc);
772
773  if (clickrec[0].start != NULL) {
774    StcClicks *clicks = map_put_ref(int, StcClicks)(wp->w_statuscol_click_defs, lnum, NULL, NULL);
775    StcClick *click_defs = map_put_ref(int, StcClick)(clicks, virtnum, NULL, NULL);
776    stl_clear_click_defs(click_defs->def, click_defs->size);
777    click_defs->def = stl_alloc_click_defs(click_defs->def, width, &click_defs->size);
778    stl_fill_click_defs(click_defs->def, clickrec, buf.data, width, false);
779  }
780
781  return width;
782}
783
784/// Truncates the statusline at the first truncation marker (%<) if present,
785/// or alternatively at the first item, or otherwise at the beginning.
786///
787/// @param width  Current width in cells (will be adjusted if truncation took place)
788/// @param minwid  Minimum width in cells
789/// @param maxwid  Maximum width in cells
790/// @param fillchar  Fillchar
791/// @param stl_items  Items
792/// @param startitem  Start item index (inclusive)
793/// @param curitem  End item index (exclusive)
794/// @param start_p  Start position in the output buffer
795/// @param out_p  Current output buffer position (will be adjusted if truncation took place)
796static void stl_truncate(int *width, int minwid, int maxwid, schar_T fillchar,
797                         stl_item_t *stl_items, int startitem, int *curitem, char *start_p,
798                         char **out_p)
799{
800  minwid = MIN(minwid, maxwid);
801
802  int item_idx = startitem;
803  char *trunc_p;
804
805  // If there are no items, truncate from beginning
806  if (startitem == *curitem) {
807    trunc_p = start_p;
808
809    // Otherwise, look for the truncation item
810  } else {
811    // Default to truncating at the first item
812    trunc_p = stl_items[item_idx].start;
813
814    for (int i = startitem; i < *curitem; i++) {
815      if (stl_items[i].type == Trunc) {
816        // Truncate at %< stl_items.
817        trunc_p = stl_items[i].start;
818        item_idx = i;
819        break;
820      }
821    }
822  }
823
824  // If the truncation point we found is beyond the maximum
825  // length of the string, truncate the end of the string.
826  if (*width - vim_strsize(trunc_p) >= maxwid) {
827    // Walk from the beginning of the
828    // string to find the last character that will fit.
829    trunc_p = start_p;
830    *width = 0;
831    while (true) {
832      int char_cells = ptr2cells(trunc_p);
833      if (*width + char_cells >= maxwid) {
834        break;
835      }
836
837      // Note: Only advance the pointer if the next
838      //       character will fit in the available output space
839      *width += char_cells;
840      trunc_p += utfc_ptr2len(trunc_p);
841    }
842
843    // Ignore any items in the statusline that occur after
844    // the truncation point
845    for (int i = startitem; i < *curitem; i++) {
846      if (stl_items[i].start > trunc_p) {
847        for (int j = i; j < *curitem; j++) {
848          if (stl_items[j].type == ClickFunc) {
849            XFREE_CLEAR(stl_items[j].cmd);
850          }
851        }
852        *curitem = i;
853        break;
854      }
855    }
856
857    // Truncate the output
858    *trunc_p++ = '>';
859    *out_p = trunc_p;
860
861    // Truncate at the truncation point we found
862  } else {
863    // { Determine how many bytes to remove
864    int trunc_len = 0;
865    while (*width >= maxwid) {
866      *width -= ptr2cells(trunc_p + trunc_len);
867      trunc_len += utfc_ptr2len(trunc_p + trunc_len);
868    }
869    // }
870
871    // { Truncate the string
872    char *trunc_end_p = trunc_p + trunc_len;
873    memmove(trunc_p + 1, trunc_end_p, (size_t)(*out_p - trunc_end_p) + 1);  // +1 for NUL
874    *out_p -= (size_t)(trunc_end_p - (trunc_p + 1));
875
876    // Put a `<` to mark where we truncated at
877    *trunc_p = '<';
878    // }
879
880    // { Change the start point for items based on
881    //  their position relative to our truncation point
882
883    // Note: The offset is one less than the truncation length because
884    //       the truncation marker `<` is not counted.
885    int item_offset = trunc_len - 1;
886
887    for (int i = item_idx; i < *curitem; i++) {
888      // Items starting at or after the end of the truncated section need
889      // to be moved backwards.
890      if (stl_items[i].start >= trunc_end_p) {
891        stl_items[i].start -= item_offset;
892      } else {
893        // Anything inside the truncated area is set to start
894        // at the `<` truncation character.
895        stl_items[i].start = trunc_p;
896      }
897    }
898    // }
899  }
900
901  // Fill up for half a double-wide character.
902  while (++*width < minwid) {
903    schar_get_adv(out_p, fillchar);
904  }
905  **out_p = NUL;
906}
907
908/// Expands the statusline at separation markers (%=) if present,
909/// or otherwise according to padding choice.
910///
911/// @param width  Current width in cells (will be adjusted if expansion took place)
912/// @param target_width  Target width in cells
913/// @param padding  Padding to add until target width is reached, if there are no separation markers
914/// @param remaining_capacity  Remaining output buffer capacity in bytes
915/// @param fillchar  Fillchar
916/// @param stl_items  Items
917/// @param startitem  Start item index (inclusive)
918/// @param curitem  End item index (exclusive)
919/// @param start_p  Start position in the output buffer
920/// @param out_p  Current output buffer position (will be adjusted if expansion took place)
921static void stl_expand(int *width, int target_width, StlPadding padding, int remaining_capacity,
922                       schar_T fillchar, stl_item_t *stl_items, int startitem, int curitem,
923                       char *start_p, char **out_p)
924{
925  int fillchar_bytes = (int)schar_len(fillchar);
926  int added_cells = MIN(target_width - *width, remaining_capacity / fillchar_bytes);
927  int added_bytes = added_cells * fillchar_bytes;
928
929  // First, try to expand at separation markers %=.
930  int num_separators = 0;
931  for (int i = startitem; i < curitem; i++) {
932    if (stl_items[i].type == Separate) {
933      num_separators += 1;
934    }
935  }
936  if (num_separators > 0) {
937    int standard_spaces = added_cells / num_separators;
938    int final_spaces = added_cells - standard_spaces * (num_separators - 1);
939    int cumulated_dislocation = 0;
940
941    for (int i = startitem; i < curitem; i++) {
942      stl_items[i].start += cumulated_dislocation;
943
944      if (stl_items[i].type == Separate) {
945        int dislocation = --num_separators > 0 ? standard_spaces : final_spaces;
946        dislocation *= fillchar_bytes;
947        cumulated_dislocation += dislocation;
948
949        char *start = stl_items[i].start;
950        char *seploc = start + dislocation;
951        STRMOVE(seploc, start);
952        for (char *s = start; s < seploc;) {
953          schar_get_adv(&s, fillchar);
954        }
955      }
956    }
957
958    *width += added_cells;
959    *out_p += added_bytes;
960
961    // Add filler characters to the right.
962  } else if (padding == kPaddingRight) {
963    for (; added_cells > 0; added_cells--) {
964      schar_get_adv(out_p, fillchar);
965    }
966
967    *width += added_cells;
968
969    // Shift everything to the right and prepend with filler characters.
970  } else if (padding == kPaddingLeft) {
971    // Move the group to the right
972    memmove(start_p + added_bytes, start_p, (size_t)(*out_p - start_p));
973
974    // Prepend the fill characters
975    for (; added_cells > 0; added_cells--) {
976      schar_get_adv(&start_p, fillchar);
977    }
978
979    // Adjust item start positions
980    for (int n = startitem; n < curitem; n++) {
981      stl_items[n].start += added_bytes;
982    }
983
984    *width += added_cells;
985    *out_p += added_bytes;
986  }
987}
988
989/// Build a string from the status line items in "fmt".
990/// Return length of string in screen cells.
991///
992/// Normally works for window "wp", except when working for 'tabline' then it
993/// is "curwin".
994///
995/// Items are drawn interspersed with the text that surrounds it
996/// Specials: %-<wid>(xxx%) => group, %= => separation marker, %< => truncation
997/// Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional
998///
999/// If maxwidth is not zero, the string will be filled at any middle marker
1000/// or truncated if too long, fillchar is used for all whitespace.
1001///
1002/// @param wp  The window to build a statusline for
1003/// @param out  The output buffer to write the statusline to
1004///             Note: This should not be NameBuff
1005/// @param fmt  The statusline format string
1006/// @param opt_idx  Index of the option corresponding to "fmt"
1007/// @param opt_scope  The scope corresponding to "opt_idx"
1008/// @param fillchar  Character to use when filling empty space in the statusline
1009/// @param maxwidth  The maximum width to make the statusline
1010/// @param hltab  HL attributes (can be NULL)
1011/// @param tabtab  Tab clicks definition (can be NULL)
1012/// @param stcp  Status column attributes (can be NULL)
1013///
1014/// @return  The final width of the statusline
1015int build_stl_str_hl(win_T *wp, CharBuf out, char *fmt, OptIndex opt_idx, int opt_scope,
1016                     schar_T fillchar, int maxwidth, stl_hlrec_t **hltab, size_t *hltab_len,
1017                     StlClickRecord **tabtab, statuscol_T *stcp)
1018{
1019  static size_t stl_items_len = 20;  // Initial value, grows as needed.
1020  static stl_item_t *stl_items = NULL;
1021  static int *stl_groupitems = NULL;
1022  static stl_hlrec_t *stl_hltab = NULL;
1023  static StlClickRecord *stl_tabtab = NULL;
1024  static int curitem = 0;
1025
1026#define TMPLEN 70
1027  char buf_tmp[TMPLEN];
1028  char *usefmt = fmt;
1029  const bool save_redraw_not_allowed = redraw_not_allowed;
1030  const bool save_KeyTyped = KeyTyped;
1031  // TODO(Bram): find out why using called_emsg_before makes tests fail, does it
1032  // matter?
1033  // const int called_emsg_before = called_emsg;
1034  const int did_emsg_before = did_emsg;
1035
1036  // When inside update_screen() we do not want redrawing a statusline,
1037  // ruler, title, etc. to trigger another redraw, it may cause an endless
1038  // loop.
1039  if (updating_screen) {
1040    redraw_not_allowed = true;
1041  }
1042
1043  if (stl_items == NULL) {
1044    stl_items = xmalloc(sizeof(stl_item_t) * stl_items_len);
1045    stl_groupitems = xmalloc(sizeof(int) * stl_items_len);
1046
1047    // Allocate one more, because the last element is used to indicate the
1048    // end of the list.
1049    stl_hltab = xmalloc(sizeof(stl_hlrec_t) * (stl_items_len + 1));
1050    stl_tabtab = xmalloc(sizeof(StlClickRecord) * (stl_items_len + 1));
1051  }
1052
1053  // If "fmt" was set insecurely it needs to be evaluated in the sandbox.
1054  // "opt_idx" will be kOptInvalid when caller is nvim_eval_statusline().
1055  const bool use_sandbox = (opt_idx != kOptInvalid) ? was_set_insecurely(wp, opt_idx, opt_scope)
1056                                                    : false;
1057
1058  // When the format starts with "%!" then evaluate it as an expression and
1059  // use the result as the actual format string.
1060  if (fmt[0] == '%' && fmt[1] == '!') {
1061    typval_T tv = {
1062      .v_type = VAR_NUMBER,
1063      .vval.v_number = wp->handle,
1064    };
1065    set_var(S_LEN("g:statusline_winid"), &tv, false);
1066
1067    usefmt = eval_to_string_safe(fmt + 2, use_sandbox, false);
1068    if (usefmt == NULL) {
1069      usefmt = fmt;
1070    }
1071
1072    do_unlet(S_LEN("g:statusline_winid"), true);
1073  }
1074
1075  if (fillchar == 0) {
1076    fillchar = schar_from_ascii(' ');
1077  }
1078
1079  // The cursor in windows other than the current one isn't always
1080  // up-to-date, esp. because of autocommands and timers.
1081  linenr_T lnum = wp->w_cursor.lnum;
1082  if (lnum > wp->w_buffer->b_ml.ml_line_count) {
1083    lnum = wp->w_buffer->b_ml.ml_line_count;
1084    wp->w_cursor.lnum = lnum;
1085  }
1086
1087  // Get line & check if empty (cursorpos will show "0-1").
1088  const char *line_ptr = ml_get_buf(wp->w_buffer, lnum);
1089  bool empty_line = (*line_ptr == NUL);
1090
1091  // Get the byte value now, in case we need it below. This is more
1092  // efficient than making a copy of the line.
1093  int byteval;
1094  const colnr_T len = ml_get_buf_len(wp->w_buffer, lnum);
1095  if (wp->w_cursor.col > len) {
1096    // Line may have changed since checking the cursor column, or the lnum
1097    // was adjusted above.
1098    wp->w_cursor.col = len;
1099    wp->w_cursor.coladd = 0;
1100    byteval = 0;
1101  } else {
1102    byteval = utf_ptr2char(line_ptr + wp->w_cursor.col);
1103  }
1104
1105  int groupdepth = 0;
1106  int evaldepth = 0;
1107
1108  int curr_hl_pos = -1;
1109
1110  // nvim_eval_statusline() can be called from inside a {-expression item so
1111  // this may be a recursive call. Keep track of the start index into "stl_items".
1112  // During post-processing only treat items filled in a certain recursion level.
1113  int evalstart = curitem;
1114
1115  bool prevchar_isflag = true;
1116  bool prevchar_isitem = false;
1117
1118  // out_p is the current position in the output buffer
1119  char *out_p = out.data;
1120
1121  // out_end_p is the last valid character in the output buffer
1122  // Note: The null termination character must occur here or earlier,
1123  //       so any user-visible characters must occur before here.
1124  char *out_end_p = (out.data + out.size) - 1;
1125
1126#define MAY_GROW_STL_ITEMS_LEN() \
1127  do { \
1128    if (curitem == (int)stl_items_len) { \
1129      size_t new_len = stl_items_len * 3 / 2; \
1130      stl_items = xrealloc(stl_items, sizeof(stl_item_t) * new_len); \
1131      stl_groupitems = xrealloc(stl_groupitems, sizeof(int) * new_len); \
1132      stl_hltab = xrealloc(stl_hltab, sizeof(stl_hlrec_t) * (new_len + 1)); \
1133      stl_tabtab = xrealloc(stl_tabtab, sizeof(StlClickRecord) * (new_len + 1)); \
1134      stl_items_len = new_len; \
1135    } \
1136  } while (0)
1137
1138  // Proceed character by character through the statusline format string
1139  // fmt_p is the current position in the input buffer
1140  for (char *fmt_p = usefmt; *fmt_p != NUL;) {
1141    MAY_GROW_STL_ITEMS_LEN();
1142
1143    if (*fmt_p != '%') {
1144      prevchar_isflag = prevchar_isitem = false;
1145    }
1146
1147    // Copy the formatting verbatim until we reach the end of the string
1148    // or find a formatting item (denoted by `%`)
1149    // or run out of room in our output buffer.
1150    while (*fmt_p != NUL && *fmt_p != '%' && out_p < out_end_p) {
1151      *out_p++ = *fmt_p++;
1152    }
1153
1154    // If we have processed the entire format string or run out of
1155    // room in our output buffer, exit the loop.
1156    if (*fmt_p == NUL || out_p >= out_end_p) {
1157      break;
1158    }
1159
1160    // The rest of this loop will handle a single `%` item.
1161    // Note: We increment here to skip over the `%` character we are currently
1162    //       on so we can process the item's contents.
1163    fmt_p++;
1164
1165    // Ignore `%` at the end of the format string
1166    if (*fmt_p == NUL) {
1167      break;
1168    }
1169
1170    // Two `%` in a row is the escape sequence to print a
1171    // single `%` in the output buffer.
1172    if (*fmt_p == '%') {
1173      *out_p++ = *fmt_p++;
1174      prevchar_isflag = prevchar_isitem = false;
1175      continue;
1176    }
1177
1178    // STL_SEPARATE: Separation between items, filled with fillchars.
1179    if (*fmt_p == STL_SEPARATE) {
1180      fmt_p++;
1181      stl_items[curitem].type = Separate;
1182      stl_items[curitem++].start = out_p;
1183      continue;
1184    }
1185
1186    // STL_TRUNCMARK: Where to begin truncating if the statusline is too long.
1187    if (*fmt_p == STL_TRUNCMARK) {
1188      fmt_p++;
1189      stl_items[curitem].type = Trunc;
1190      stl_items[curitem++].start = out_p;
1191      continue;
1192    }
1193
1194    // The end of a grouping
1195    if (*fmt_p == ')') {
1196      fmt_p++;
1197      // Ignore if we are not actually inside a group currently
1198      if (groupdepth < 1) {
1199        continue;
1200      }
1201      groupdepth--;
1202      if (stl_items[stl_groupitems[groupdepth]].type != Group) {
1203        // it's possible to break assumptions with %{%...%}, which doesn't check syntax
1204        continue;
1205      }
1206
1207      // Determine how long the group is.
1208      // Note: We set the current output position to null
1209      //       so `vim_strsize` will work.
1210      char *t = stl_items[stl_groupitems[groupdepth]].start;
1211      *out_p = NUL;
1212      int group_len = vim_strsize(t);
1213
1214      // If the group contained internal items
1215      // and the group did not have a minimum width,
1216      // and if there were no normal items in the group,
1217      // move the output pointer back to where the group started.
1218      // Note: This erases any non-item characters that were in the group.
1219      //       Otherwise there would be no reason to do this step.
1220      if (curitem > stl_groupitems[groupdepth] + 1
1221          && stl_items[stl_groupitems[groupdepth]].minwid == 0) {
1222        int group_start_userhl = 0;
1223        int group_end_userhl = 0;
1224        int n;
1225        // remove group if all items are empty and highlight group
1226        // doesn't change
1227        for (n = stl_groupitems[groupdepth] - 1; n >= 0; n--) {
1228          if (stl_items[n].type == Highlight || stl_items[n].type == HighlightCombining) {
1229            group_start_userhl = group_end_userhl = stl_items[n].minwid;
1230            break;
1231          }
1232        }
1233        for (n = stl_groupitems[groupdepth] + 1; n < curitem; n++) {
1234          if (stl_items[n].type == Normal) {
1235            break;
1236          }
1237          if (stl_items[n].type == Highlight || stl_items[n].type == HighlightCombining) {
1238            group_end_userhl = stl_items[n].minwid;
1239          }
1240        }
1241        if (n == curitem && group_start_userhl == group_end_userhl) {
1242          // empty group
1243          out_p = t;
1244          group_len = 0;
1245          for (n = stl_groupitems[groupdepth] + 1; n < curitem; n++) {
1246            // do not use the highlighting from the removed group
1247            if (stl_items[n].type == Highlight || stl_items[n].type == HighlightCombining) {
1248              stl_items[n].type = Disabled;
1249            }
1250            // adjust the start position of TabPage to the next
1251            // item position
1252            if (stl_items[n].type == TabPage) {
1253              stl_items[n].start = out_p;
1254            }
1255          }
1256        }
1257      }
1258
1259      int maxwid = stl_items[stl_groupitems[groupdepth]].maxwid;
1260      int minwid = stl_items[stl_groupitems[groupdepth]].minwid;
1261      StlPadding padding = minwid < 0 ? kPaddingRight : kPaddingLeft;
1262      minwid = abs(minwid);
1263
1264      // If the group is longer than it is allowed to be truncate by removing
1265      // bytes from the start of the group text. Don't truncate when item is a
1266      // 'statuscolumn' fold item to ensure correctness of the mouse clicks.
1267      if (group_len > maxwid && stl_items[stl_groupitems[groupdepth]].type != HighlightFold) {
1268        stl_truncate(&group_len, minwid, maxwid, fillchar, stl_items,
1269                     stl_groupitems[groupdepth] + 1, &curitem, t, &out_p);
1270
1271        // If the group is shorter than the minimum width, add padding characters.
1272      } else if (minwid > group_len) {
1273        stl_expand(&group_len, minwid, padding, (int)(out_end_p - out_p), fillchar, stl_items,
1274                   stl_groupitems[groupdepth] + 1, curitem, t, &out_p);
1275      }
1276
1277      // Deactivate separation/truncation markers for wrapping item groups and top-level.
1278      for (int n = stl_groupitems[groupdepth] + 1; n < curitem; n++) {
1279        if (stl_items[n].type == Separate || stl_items[n].type == Trunc) {
1280          stl_items[n].type = Disabled;
1281        }
1282      }
1283
1284      continue;
1285    }
1286
1287    int minwid = 0;
1288    int maxwid = 9999;
1289    int foldsignitem = -1;        // Start of fold or sign item
1290    bool left_align_num = false;  // Number item for should be left-aligned
1291    bool left_align = false;
1292
1293    // Denotes that numbers should be left-padded with zeros
1294    bool zeropad = (*fmt_p == '0');
1295    if (zeropad) {
1296      fmt_p++;
1297    }
1298
1299    // Denotes that the item should be left-aligned.
1300    // This is tracked by using a negative length.
1301    if (*fmt_p == '-') {
1302      fmt_p++;
1303      left_align = true;
1304    }
1305
1306    // The first digit group is the item's min width
1307    if (ascii_isdigit(*fmt_p)) {
1308      minwid = getdigits_int(&fmt_p, false, 0);
1309    }
1310
1311    // User highlight groups override the min width field
1312    // to denote the styling to use.
1313    if (*fmt_p == STL_USER_HL) {
1314      curr_hl_pos = curitem;
1315      stl_items[curitem].type = Highlight;
1316      stl_items[curitem].start = out_p;
1317      stl_items[curitem].minwid = minwid > 9 ? 1 : minwid;
1318      fmt_p++;
1319      curitem++;
1320      continue;
1321    }
1322
1323    // TABPAGE pairs are used to denote a region that when clicked will
1324    // either switch to or close a tab.
1325    //
1326    // Ex: tabline=%1Ttab\ one%X
1327    //   This tabline has a TABPAGENR item with minwid `1`,
1328    //   which is then closed with a TABCLOSENR item.
1329    //   Clicking on this region with mouse enabled will switch to tab 1.
1330    //   Setting the minwid to a different value will switch
1331    //   to that tab, if it exists
1332    //
1333    // Ex: tabline=%1Xtab\ one%X
1334    //   This tabline has a TABCLOSENR item with minwid `1`,
1335    //   which is then closed with a TABCLOSENR item.
1336    //   Clicking on this region with mouse enabled will close tab 1.
1337    //
1338    // Note: These options are only valid when creating a tabline.
1339    if (*fmt_p == STL_TABPAGENR || *fmt_p == STL_TABCLOSENR) {
1340      if (*fmt_p == STL_TABCLOSENR) {
1341        if (minwid == 0) {
1342          // %X ends the close label, go back to the previous tab label nr.
1343          for (int n = curitem - 1; n >= 0; n--) {
1344            if (stl_items[n].type == TabPage && stl_items[n].minwid >= 0) {
1345              minwid = stl_items[n].minwid;
1346              break;
1347            }
1348          }
1349        } else {
1350          // close nrs are stored as negative values
1351          minwid = -minwid;
1352        }
1353      }
1354      stl_items[curitem].type = TabPage;
1355      stl_items[curitem].start = out_p;
1356      stl_items[curitem].minwid = minwid;
1357      fmt_p++;
1358      curitem++;
1359      continue;
1360    }
1361
1362    if (*fmt_p == STL_CLICK_FUNC) {
1363      fmt_p++;
1364      char *t = fmt_p;
1365      while (*fmt_p != STL_CLICK_FUNC && *fmt_p) {
1366        fmt_p++;
1367      }
1368      if (*fmt_p != STL_CLICK_FUNC) {
1369        break;
1370      }
1371      stl_items[curitem].type = ClickFunc;
1372      stl_items[curitem].start = out_p;
1373      stl_items[curitem].cmd = tabtab ? xmemdupz(t, (size_t)(fmt_p - t)) : NULL;
1374      stl_items[curitem].minwid = minwid;
1375      fmt_p++;
1376      curitem++;
1377      continue;
1378    }
1379
1380    // Denotes the end of the minwid
1381    // the maxwid may follow immediately after
1382    if (*fmt_p == '.') {
1383      fmt_p++;
1384      if (ascii_isdigit(*fmt_p)) {
1385        maxwid = getdigits_int(&fmt_p, false, 50);
1386        if (maxwid <= 0) {  // overflow or an explicit zero
1387          maxwid = 50;
1388        }
1389      }
1390    }
1391
1392    // Make the number negative to denote left alignment of the item
1393    minwid *= left_align ? -1 : 1;
1394
1395    // Denotes the start of a new group
1396    if (*fmt_p == '(') {
1397      stl_groupitems[groupdepth++] = curitem;
1398      stl_items[curitem].type = Group;
1399      stl_items[curitem].start = out_p;
1400      stl_items[curitem].minwid = minwid;
1401      stl_items[curitem].maxwid = maxwid;
1402      fmt_p++;
1403      curitem++;
1404      continue;
1405    }
1406
1407    // Denotes end of an expanded %{%...%} block
1408    if (*fmt_p == '}' && evaldepth > 0) {
1409      fmt_p++;
1410      evaldepth--;
1411      if (groupdepth > 0) {
1412        // Look for normal items since the last %{%.
1413        // If we find a %{% before any normal item, it must be the start of the current block, since
1414        // a nested block would have been marked normal unless it contained normal items itself.
1415        bool normal_items = false;
1416        for (int i = curitem - 1; i >= evalstart && stl_items[i].type != Expression; i--) {
1417          if (stl_items[i].type == Normal || stl_items[i].type == NormalEmpty) {
1418            normal_items = true;
1419            break;
1420          }
1421        }
1422        if (!normal_items) {
1423          // If the expression result contained no normal items, treat the whole result as one.
1424          // This prevents a surrounding auto-hiding item group from being hidden.
1425          stl_items[curitem].type = Normal;
1426          stl_items[curitem].start = out_p;
1427          curitem++;
1428        }
1429      }
1430      continue;
1431    }
1432
1433    // Denotes a highlight scope
1434    if (*fmt_p == STL_HIGHLIGHT) {
1435      switch (*(fmt_p + 1)) {
1436      case '(':
1437        fmt_p += 2;
1438        stl_groupitems[groupdepth++] = curitem;
1439        stl_items[curitem].type = HighlightScope;
1440        stl_items[curitem].start = out_p;
1441        stl_items[curitem].minwid = curr_hl_pos;
1442        curitem++;
1443        continue;
1444      case ')':
1445        fmt_p += 2;
1446        if (groupdepth < 1) {
1447          continue;
1448        }
1449        int scope_start = stl_groupitems[--groupdepth];
1450        if (stl_items[scope_start].type != HighlightScope) {
1451          // it's possible to break assumptions with %{%...%}, which doesn't check syntax
1452          continue;
1453        }
1454        int hl_pos = stl_items[scope_start].minwid;
1455        curr_hl_pos = curitem;
1456        stl_items[curitem].type = Highlight;
1457        stl_items[curitem].start = out_p;
1458        stl_items[curitem].minwid = hl_pos == -1 ? 0 : stl_items[hl_pos].minwid;
1459        curitem++;
1460        for (int i = hl_pos == -1 ? evalstart : hl_pos + 1; i < scope_start; i++) {
1461          MAY_GROW_STL_ITEMS_LEN();
1462          if (stl_items[i].type == HighlightCombining) {
1463            stl_items[curitem].type = HighlightCombining;
1464            stl_items[curitem].start = out_p;
1465            stl_items[curitem].minwid = stl_items[i].minwid;
1466            curitem++;
1467          }
1468        }
1469        continue;
1470      }
1471    }
1472
1473    // An invalid item was specified.
1474    // Continue processing on the next character of the format string.
1475    if (vim_strchr(STL_ALL, (uint8_t)(*fmt_p)) == NULL) {
1476      if (*fmt_p == NUL) {  // can happen with "%0"
1477        break;
1478      }
1479      fmt_p++;
1480      continue;
1481    }
1482
1483    // The status line item type
1484    char opt = *fmt_p++;
1485
1486    // OK - now for the real work
1487    NumberBase base = kNumBaseDecimal;
1488    bool itemisflag = false;
1489    bool fillable = true;
1490    int num = -1;
1491    char *str = NULL;
1492    switch (opt) {
1493    case STL_FILEPATH:
1494    case STL_FULLPATH:
1495    case STL_FILENAME: {
1496      // Set fillable to false so that ' ' in the filename will not
1497      // get replaced with the fillchar
1498      fillable = false;
1499      char *name = buf_spname(wp->w_buffer);
1500      if (name != NULL) {
1501        xstrlcpy(NameBuff, name, MAXPATHL);
1502      } else {
1503        char *t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname
1504                                        : wp->w_buffer->b_fname;
1505        home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, true);
1506      }
1507      trans_characters(NameBuff, MAXPATHL);
1508      if (opt != STL_FILENAME) {
1509        str = NameBuff;
1510      } else {
1511        str = path_tail(NameBuff);
1512      }
1513      break;
1514    }
1515
1516    case STL_VIM_EXPR:     // '{'
1517    {
1518      char *block_start = fmt_p - 1;
1519      bool reevaluate = (*fmt_p == '%');
1520
1521      if (reevaluate) {
1522        fmt_p++;
1523      }
1524      // %0{} keeps the result verbatim
1525      itemisflag = zeropad ? false : true;
1526
1527      // Attempt to copy the expression to evaluate into
1528      // the output buffer as a null-terminated string.
1529      char *t = out_p;
1530      while ((*fmt_p != '}' || (reevaluate && fmt_p[-1] != '%'))
1531             && *fmt_p != NUL && out_p < out_end_p) {
1532        *out_p++ = *fmt_p++;
1533      }
1534      if (*fmt_p != '}') {          // missing '}' or out of space
1535        break;
1536      }
1537      fmt_p++;
1538      if (reevaluate && out_p > out.data) {
1539        out_p[-1] = NUL;  // remove the % at the end of %{% expr %}
1540      } else {
1541        *out_p = NUL;
1542      }
1543
1544      // Move our position in the output buffer
1545      // to the beginning of the expression
1546      out_p = t;
1547
1548      // { Evaluate the expression
1549
1550      // Store the current buffer number as a string variable
1551      vim_snprintf(buf_tmp, sizeof(buf_tmp), "%d", curbuf->b_fnum);
1552      set_internal_string_var("g:actual_curbuf", buf_tmp);
1553      vim_snprintf(buf_tmp, sizeof(buf_tmp), "%d", curwin->handle);
1554      set_internal_string_var("g:actual_curwin", buf_tmp);
1555
1556      buf_T *const save_curbuf = curbuf;
1557      win_T *const save_curwin = curwin;
1558      const int save_VIsual_active = Visual.active;
1559      curwin = wp;
1560      curbuf = wp->w_buffer;
1561      // Visual mode is only valid in the current window.
1562      if (curwin != save_curwin) {
1563        Visual.active = false;
1564      }
1565
1566      // Note: The result stored in `t` is unused.
1567      str = eval_to_string_safe(out_p, use_sandbox, false);
1568
1569      curwin = save_curwin;
1570      curbuf = save_curbuf;
1571      Visual.active = save_VIsual_active;
1572
1573      // Remove the variable we just stored
1574      do_unlet(S_LEN("g:actual_curbuf"), true);
1575      do_unlet(S_LEN("g:actual_curwin"), true);
1576
1577      // }
1578
1579      // Check if the evaluated result is a number.
1580      // If so, convert the number to an int and free the string.
1581      if (!zeropad && str != NULL && *str != NUL) {
1582        if (*skipdigits(str) == NUL) {
1583          num = atoi(str);
1584          XFREE_CLEAR(str);
1585          itemisflag = false;
1586        }
1587      }
1588
1589      // If the output of the expression needs to be evaluated
1590      // replace the %{} block with the result of evaluation
1591      if (reevaluate && str != NULL && *str != NUL
1592          && strchr(str, '%') != NULL
1593          && evaldepth < MAX_STL_EVAL_DEPTH) {
1594        size_t parsed_usefmt = (size_t)(block_start - usefmt);
1595        size_t str_length = strlen(str);
1596        size_t fmt_length = strlen(fmt_p);
1597        size_t new_fmt_len = parsed_usefmt + str_length + fmt_length + 3;
1598        char *new_fmt = xmalloc(new_fmt_len * sizeof(char));
1599        char *new_fmt_p = new_fmt;
1600
1601        new_fmt_p = (char *)memcpy(new_fmt_p, usefmt, parsed_usefmt) + parsed_usefmt;
1602        new_fmt_p = (char *)memcpy(new_fmt_p, str, str_length) + str_length;
1603        new_fmt_p = (char *)memcpy(new_fmt_p, "%}", 2) + 2;
1604        new_fmt_p = (char *)memcpy(new_fmt_p, fmt_p, fmt_length) + fmt_length;
1605        *new_fmt_p = 0;
1606        new_fmt_p = NULL;
1607
1608        if (usefmt != fmt) {
1609          xfree(usefmt);
1610        }
1611        XFREE_CLEAR(str);
1612        usefmt = new_fmt;
1613        fmt_p = usefmt + parsed_usefmt;
1614        evaldepth++;
1615        stl_items[curitem].type = Expression;
1616        stl_items[curitem].start = out_p;
1617        curitem++;
1618        continue;
1619      }
1620      break;
1621    }
1622
1623    case STL_LINE:
1624      // Overload %l with v:(re)lnum for 'statuscolumn'. Place a sign when 'signcolumn'
1625      // is set to "number". Take care of alignment for 'number' + 'relativenumber'.
1626      if (stcp != NULL && (wp->w_p_nu || wp->w_p_rnu) && get_vim_var_nr(VV_VIRTNUM) == 0) {
1627        if (wp->w_maxscwidth == SCL_NUM && stcp->sattrs[0].text[0]) {
1628          goto stcsign;
1629        }
1630        int relnum = (int)get_vim_var_nr(VV_RELNUM);
1631        num = (!wp->w_p_rnu || (wp->w_p_nu && relnum == 0)) ? (int)get_vim_var_nr(VV_LNUM) : relnum;
1632        left_align_num = wp->w_p_rnu && wp->w_p_nu && relnum == 0;
1633        if (!left_align_num) {
1634          stl_items[curitem].type = Separate;
1635          stl_items[curitem++].start = out_p;
1636          MAY_GROW_STL_ITEMS_LEN();
1637        }
1638      } else if (stcp == NULL) {
1639        num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0 : wp->w_cursor.lnum;
1640      }
1641      break;
1642
1643    case STL_NUMLINES:
1644      num = wp->w_buffer->b_ml.ml_line_count;
1645      break;
1646
1647    case STL_COLUMN:
1648      num = (State & MODE_INSERT) == 0 && empty_line ? 0 : (int)wp->w_cursor.col + 1;
1649      break;
1650
1651    case STL_VIRTCOL:
1652    case STL_VIRTCOL_ALT: {
1653      colnr_T virtcol = wp->w_virtcol + 1;
1654      // Don't display %V if it's the same as %c.
1655      if (opt == STL_VIRTCOL_ALT
1656          && (virtcol == (colnr_T)((State & MODE_INSERT) == 0 && empty_line
1657                                   ? 0 : (int)wp->w_cursor.col + 1))) {
1658        break;
1659      }
1660      num = virtcol;
1661      break;
1662    }
1663
1664    case STL_PERCENTAGE:
1665      num = calc_percentage(wp->w_cursor.lnum, wp->w_buffer->b_ml.ml_line_count);
1666      break;
1667
1668    case STL_ALTPERCENT:
1669      // Store the position percentage in our temporary buffer.
1670      // Note: We cannot store the value in `num` because
1671      //       `get_rel_pos` can return a named position. Ex: "Top"
1672      (void)get_rel_pos(wp, buf_tmp, TMPLEN);
1673      str = buf_tmp;
1674      break;
1675
1676    case STL_SHOWCMD:
1677      if (p_sc && (opt_idx == kOptInvalid || find_option(p_sloc) == opt_idx)) {
1678        str = showcmd_buf;
1679      }
1680      break;
1681
1682    case STL_ARGLISTSTAT:
1683      fillable = false;
1684      buf_tmp[0] = NUL;
1685      if (append_arg_number(wp, buf_tmp, sizeof(buf_tmp)) > 0) {
1686        str = buf_tmp;
1687      }
1688      break;
1689
1690    case STL_KEYMAP:
1691      fillable = false;
1692      if (get_keymap_str(wp, "<%s>", buf_tmp, TMPLEN) > 0) {
1693        str = buf_tmp;
1694      }
1695      break;
1696    case STL_PAGENUM:
1697      num = 0;
1698      break;
1699
1700    case STL_BUFNO:
1701      num = wp->w_buffer->b_fnum;
1702      break;
1703
1704    case STL_OFFSET_X:
1705      base = kNumBaseHexadecimal;
1706      FALLTHROUGH;
1707    case STL_OFFSET: {
1708      int l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL,
1709                                     false);
1710      num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0
1711            ? 0 : l + 1 + ((State & MODE_INSERT) == 0 && empty_line
1712                           ? 0 : (int)wp->w_cursor.col);
1713      break;
1714    }
1715    case STL_BYTEVAL_X:
1716      base = kNumBaseHexadecimal;
1717      FALLTHROUGH;
1718    case STL_BYTEVAL:
1719      num = byteval;
1720      if (num == NL) {
1721        num = 0;
1722      } else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC) {
1723        num = NL;
1724      }
1725      break;
1726
1727    case STL_ROFLAG:
1728    case STL_ROFLAG_ALT:
1729      itemisflag = true;
1730      if (wp->w_buffer->b_p_ro) {
1731        str = (opt == STL_ROFLAG_ALT) ? ",RO" : _("[RO]");
1732      }
1733      break;
1734
1735    case STL_HELPFLAG:
1736    case STL_HELPFLAG_ALT:
1737      itemisflag = true;
1738      if (wp->w_buffer->b_help) {
1739        str = (opt == STL_HELPFLAG_ALT) ? ",HLP" : _("[Help]");
1740      }
1741      break;
1742
1743    case STL_FOLDCOL:    // 'C' for 'statuscolumn'
1744    case STL_SIGNCOL: {  // 's' for 'statuscolumn'
1745stcsign:
1746      if (stcp == NULL) {
1747        break;
1748      }
1749      int fdc = opt == STL_FOLDCOL ? compute_foldcolumn(wp, 0) : 0;
1750      int width = opt == STL_FOLDCOL ? fdc > 0 : opt == STL_SIGNCOL ? wp->w_scwidth : 1;
1751
1752      if (width <= 0) {
1753        break;
1754      }
1755      foldsignitem = curitem;
1756      lnum = (linenr_T)get_vim_var_nr(VV_LNUM);
1757
1758      if (fdc > 0) {
1759        schar_T fold_buf[9];
1760        fill_foldcolumn(wp, stcp->foldinfo, stcp->lnum, 0, fdc, get_vim_var_nr(VV_VIRTNUM) < 0,
1761                        NULL, stcp->fold_vcol, fold_buf);
1762        stl_items[curitem].minwid = -(use_cursor_line_highlight(wp, lnum) ? HLF_CLF : HLF_FC);
1763        size_t buflen = 0;
1764        // TODO(bfredl): this is very backwards. we must support schar_T
1765        // being used directly in 'statuscolumn'
1766        for (int i = 0; i < fdc; i++) {
1767          buflen += schar_get(buf_tmp + buflen, fold_buf[i]);
1768        }
1769      }
1770
1771      size_t signlen = 0;
1772      for (int i = 0; i < width; i++) {
1773        stl_items[curitem].start = out_p + signlen;
1774        if (fdc == 0) {
1775          SignTextAttrs sattr = stcp->sattrs[i];
1776          if (sattr.text[0] && get_vim_var_nr(VV_VIRTNUM) == 0) {
1777            signlen += describe_sign_text(buf_tmp + signlen, sattr.text);
1778            stl_items[curitem].minwid = -(stcp->sign_cul_id ? stcp->sign_cul_id : sattr.hl_id);
1779          } else {
1780            buf_tmp[signlen++] = ' ';
1781            buf_tmp[signlen++] = ' ';
1782            buf_tmp[signlen] = NUL;
1783            stl_items[curitem].minwid = 0;
1784          }
1785        }
1786        stl_items[curitem++].type = fdc > 0 ? HighlightFold : HighlightSign;
1787        MAY_GROW_STL_ITEMS_LEN();
1788      }
1789      str = buf_tmp;
1790      break;
1791    }
1792
1793    case STL_FILETYPE:
1794      // Copy the filetype if it is not null and the formatted string will fit
1795      // in the temporary buffer
1796      // (including the brackets and null terminating character)
1797      if (*wp->w_buffer->b_p_ft != NUL
1798          && strlen(wp->w_buffer->b_p_ft) < TMPLEN - 3) {
1799        vim_snprintf(buf_tmp, sizeof(buf_tmp), "[%s]",
1800                     wp->w_buffer->b_p_ft);
1801        str = buf_tmp;
1802      }
1803      break;
1804
1805    case STL_FILETYPE_ALT:
1806      itemisflag = true;
1807      // Copy the filetype if it is not null and the formatted string will fit
1808      // in the temporary buffer
1809      // (including the comma and null terminating character)
1810      if (*wp->w_buffer->b_p_ft != NUL
1811          && strlen(wp->w_buffer->b_p_ft) < TMPLEN - 2) {
1812        vim_snprintf(buf_tmp, sizeof(buf_tmp), ",%s", wp->w_buffer->b_p_ft);
1813        // Uppercase the file extension
1814        for (char *t = buf_tmp; *t != 0; t++) {
1815          *t = (char)TOUPPER_LOC((uint8_t)(*t));
1816        }
1817        str = buf_tmp;
1818      }
1819      break;
1820    case STL_PREVIEWFLAG:
1821    case STL_PREVIEWFLAG_ALT:
1822      itemisflag = true;
1823      if (wp->w_p_pvw) {
1824        str = (opt == STL_PREVIEWFLAG_ALT) ? ",PRV" : _("[Preview]");
1825      }
1826      break;
1827
1828    case STL_QUICKFIX:
1829      if (bt_quickfix(wp->w_buffer)) {
1830        str = wp->w_llist_ref ? _(msg_loclist) : _(msg_qflist);
1831      }
1832      break;
1833
1834    case STL_MODIFIED:
1835    case STL_MODIFIED_ALT:
1836      itemisflag = true;
1837      switch ((opt == STL_MODIFIED_ALT)
1838              + bufIsChanged(wp->w_buffer) * 2
1839              + (!MODIFIABLE(wp->w_buffer)) * 4) {
1840      case 2:
1841        str = "[+]"; break;
1842      case 3:
1843        str = ",+"; break;
1844      case 4:
1845        str = "[-]"; break;
1846      case 5:
1847        str = ",-"; break;
1848      case 6:
1849        str = "[+-]"; break;
1850      case 7:
1851        str = ",+-"; break;
1852      }
1853      break;
1854
1855    case STL_HIGHLIGHT_COMB:
1856    case STL_HIGHLIGHT: {
1857      // { The name of the highlight is surrounded by `#` or `$`
1858      char *t = fmt_p;
1859      while (*fmt_p != opt && *fmt_p != NUL) {
1860        fmt_p++;
1861      }
1862      // }
1863
1864      // Create a highlight item based on the name
1865      if (*fmt_p == opt) {
1866        if (opt == STL_HIGHLIGHT) {
1867          curr_hl_pos = curitem;
1868          stl_items[curitem].type = Highlight;
1869        } else {
1870          stl_items[curitem].type = HighlightCombining;
1871        }
1872        stl_items[curitem].start = out_p;
1873        stl_items[curitem].minwid = -syn_name2id_len(t, (size_t)(fmt_p - t));
1874        curitem++;
1875        fmt_p++;
1876      }
1877      continue;
1878    }
1879    }
1880
1881    // If we made it this far, the item is normal and starts at
1882    // our current position in the output buffer.
1883    // Non-normal items would have `continued`.
1884    assert(curitem < (int)stl_items_len);
1885    stl_items[curitem].start = out_p;
1886    stl_items[curitem].type = Normal;
1887
1888    // Copy the item string into the output buffer
1889    if (str != NULL && *str) {
1890      // { Skip the leading `,` or ` ` if the item is a flag
1891      //  and the proper conditions are met
1892      char *t = str;
1893      if (itemisflag) {
1894        if ((t[0] && t[1])
1895            && ((!prevchar_isitem && *t == ',')
1896                || (prevchar_isflag && *t == ' '))) {
1897          t++;
1898        }
1899        prevchar_isflag = true;
1900      }
1901      // }
1902
1903      int l = vim_strsize(t);
1904
1905      // If this item is non-empty, record that the last thing
1906      // we put in the output buffer was an item
1907      if (l > 0) {
1908        prevchar_isitem = true;
1909      }
1910
1911      // If the item is too wide, truncate it from the beginning
1912      if (l > maxwid) {
1913        while (l >= maxwid) {
1914          l -= ptr2cells(t);
1915          t += utfc_ptr2len(t);
1916        }
1917
1918        // Early out if there isn't enough room for the truncation marker
1919        if (out_p >= out_end_p) {
1920          break;
1921        }
1922
1923        // Add the truncation marker
1924        *out_p++ = '<';
1925      }
1926
1927      // If the item is right aligned and not wide enough,
1928      // pad with fill characters.
1929      if (minwid > 0) {
1930        for (; l < minwid && out_p < out_end_p; l++) {
1931          // Don't put a "-" in front of a digit.
1932          if (l + 1 == minwid && fillchar == '-' && ascii_isdigit(*t)) {
1933            *out_p++ = ' ';
1934          } else {
1935            schar_get_adv(&out_p, fillchar);
1936          }
1937        }
1938        minwid = 0;
1939        // For a 'statuscolumn' sign or fold item, shift the added items
1940        if (foldsignitem >= 0) {
1941          ptrdiff_t offset = out_p - stl_items[foldsignitem].start;
1942          for (int i = foldsignitem; i < curitem; i++) {
1943            stl_items[i].start += offset;
1944          }
1945        }
1946      } else {
1947        // Note: The negative value denotes a left aligned item.
1948        //       Here we switch the minimum width back to a positive value.
1949        minwid *= -1;
1950      }
1951
1952      // { Copy the string text into the output buffer
1953      for (; *t && out_p < out_end_p; t++) {
1954        // Change a space by fillchar, unless fillchar is '-' and a
1955        // digit follows.
1956        if (fillable && *t == ' '
1957            && (!ascii_isdigit(*(t + 1)) || fillchar != '-')) {
1958          schar_get_adv(&out_p, fillchar);
1959        } else {
1960          *out_p++ = *t;
1961        }
1962      }
1963      // }
1964
1965      // For a 'statuscolumn' sign or fold item, add an item to reset the highlight group
1966      if (foldsignitem >= 0) {
1967        stl_items[curitem].type = Highlight;
1968        stl_items[curitem].start = out_p;
1969        stl_items[curitem].minwid = 0;
1970      }
1971
1972      // For left-aligned items, fill any remaining space with the fillchar
1973      for (; l < minwid && out_p < out_end_p; l++) {
1974        schar_get_adv(&out_p, fillchar);
1975      }
1976
1977      // Otherwise if the item is a number, copy that to the output buffer.
1978    } else if (num >= 0) {
1979      if (out_p + 20 > out_end_p) {
1980        break;                  // not sufficient space
1981      }
1982      prevchar_isitem = true;
1983
1984      // { Build the formatting string
1985      char nstr[20];
1986      char *t = nstr;
1987      if (opt == STL_VIRTCOL_ALT) {
1988        *t++ = '-';
1989        minwid--;
1990      }
1991      *t++ = '%';
1992      if (zeropad) {
1993        *t++ = '0';
1994      }
1995
1996      // Note: The `*` means we take the width as one of the arguments
1997      *t++ = '*';
1998      *t++ = base == kNumBaseHexadecimal ? 'X' : 'd';
1999      *t = NUL;
2000      // }
2001
2002      // { Determine how many characters the number will take up when printed
2003      //  Note: We have to cast the base because the compiler uses
2004      //        unsigned ints for the enum values.
2005      int num_chars = 1;
2006      for (int n = num; n >= (int)base; n /= (int)base) {
2007        num_chars++;
2008      }
2009
2010      // VIRTCOL_ALT takes up an extra character because
2011      // of the `-` we added above.
2012      if (opt == STL_VIRTCOL_ALT) {
2013        num_chars++;
2014      }
2015      // }
2016
2017      assert(out_end_p >= out_p);
2018      size_t remaining_buf_len = (size_t)(out_end_p - out_p) + 1;
2019
2020      // If the number is going to take up too much room
2021      // Figure out the approximate number in "scientific" type notation.
2022      // Ex: 14532 with maxwid of 4 -> '14>3'
2023      if (num_chars > maxwid) {
2024        // Add two to the width because the power piece will take
2025        // two extra characters
2026        num_chars += 2;
2027
2028        // How many extra characters there are
2029        int n = num_chars - maxwid;
2030
2031        // { Reduce the number by base^n
2032        while (num_chars-- > maxwid) {
2033          num /= (int)base;
2034        }
2035        // }
2036
2037        // { Add the format string for the exponent bit
2038        *t++ = '>';
2039        *t++ = '%';
2040        // Use the same base as the first number
2041        *t = t[-3];
2042        *++t = NUL;
2043        // }
2044
2045        out_p += vim_snprintf_safelen(out_p, remaining_buf_len, nstr, 0, num, n);
2046      } else {
2047        out_p += vim_snprintf_safelen(out_p, remaining_buf_len, nstr, minwid, num);
2048      }
2049
2050      // Otherwise, there was nothing to print so mark the item as empty
2051    } else {
2052      stl_items[curitem].type = NormalEmpty;
2053    }
2054
2055    if (num >= 0 || (!itemisflag && str && *str)) {
2056      prevchar_isflag = false;              // Item not NULL, but not a flag
2057    }
2058
2059    // Only free the string buffer if we allocated it.
2060    // Note: This is not needed if `str` is pointing at `tmp`
2061    if (opt == STL_VIM_EXPR) {
2062      XFREE_CLEAR(str);
2063    }
2064
2065    // Item processed, move to the next
2066    curitem++;
2067    // For a 'statuscolumn' number item that is left aligned, add a separator item.
2068    if (left_align_num) {
2069      MAY_GROW_STL_ITEMS_LEN();
2070      stl_items[curitem].type = Separate;
2071      stl_items[curitem++].start = out_p;
2072    }
2073  }
2074#undef MAY_GROW_STL_ITEMS_LEN
2075
2076  *out_p = NUL;
2077
2078  // Free the format buffer if we allocated it internally
2079  if (usefmt != fmt) {
2080    xfree(usefmt);
2081  }
2082
2083  // We have now processed the entire statusline format string.
2084  // What follows is post-processing to handle alignment and highlighting.
2085
2086  int width = vim_strsize(out.data);
2087  if (maxwidth > 0 && width > maxwidth && (!stcp || width > MAX_STCWIDTH)) {
2088    // Result is too long, must truncate somewhere.
2089    stl_truncate(&width, 0, maxwidth, fillchar, stl_items, evalstart, &curitem, out.data, &out_p);
2090
2091    // If there is room left in our statusline, and room left in our buffer,
2092    // add characters at the separation markers (if there are any) to fill up the available space.
2093  } else if (width < maxwidth) {
2094    stl_expand(&width, maxwidth, kPaddingNone, (int)(out_end_p - out_p), fillchar, stl_items,
2095               evalstart, curitem, out.data, &out_p);
2096  }
2097
2098  // Store the info about highlighting.
2099  if (hltab != NULL) {
2100    *hltab = stl_hltab;
2101    stl_hlrec_t *sp = stl_hltab;
2102    for (int l = evalstart; l < curitem; l++) {
2103      if (stl_items[l].type == Highlight || stl_items[l].type == HighlightCombining
2104          || stl_items[l].type == HighlightFold || stl_items[l].type == HighlightSign) {
2105        sp->start = stl_items[l].start;
2106        sp->userhl = stl_items[l].minwid;
2107        unsigned type = stl_items[l].type;
2108        sp->item = type == HighlightSign ? STL_SIGNCOL : type ==
2109                   HighlightFold ? STL_FOLDCOL : type ==
2110                   HighlightCombining ? STL_HIGHLIGHT_COMB : 0;
2111        sp++;
2112      }
2113    }
2114    sp->start = NULL;
2115    sp->userhl = 0;
2116  }
2117  if (hltab_len) {
2118    *hltab_len = (size_t)(curitem - evalstart);
2119  }
2120
2121  // Store the info about tab pages labels.
2122  if (tabtab != NULL) {
2123    *tabtab = stl_tabtab;
2124    StlClickRecord *cur_tab_rec = stl_tabtab;
2125    for (int l = evalstart; l < curitem; l++) {
2126      if (stl_items[l].type == TabPage) {
2127        cur_tab_rec->start = stl_items[l].start;
2128        if (stl_items[l].minwid == 0) {
2129          cur_tab_rec->def.type = kStlClickDisabled;
2130          cur_tab_rec->def.tabnr = 0;
2131        } else {
2132          int tabnr = stl_items[l].minwid;
2133          if (stl_items[l].minwid > 0) {
2134            cur_tab_rec->def.type = kStlClickTabSwitch;
2135          } else {
2136            cur_tab_rec->def.type = kStlClickTabClose;
2137            tabnr = -tabnr;
2138          }
2139          cur_tab_rec->def.tabnr = tabnr;
2140        }
2141        cur_tab_rec->def.func = NULL;
2142        cur_tab_rec++;
2143      } else if (stl_items[l].type == ClickFunc) {
2144        cur_tab_rec->start = stl_items[l].start;
2145        cur_tab_rec->def.type = kStlClickFuncRun;
2146        cur_tab_rec->def.tabnr = stl_items[l].minwid;
2147        cur_tab_rec->def.func = stl_items[l].cmd;
2148        cur_tab_rec++;
2149      }
2150    }
2151    cur_tab_rec->start = NULL;
2152    cur_tab_rec->def.type = kStlClickDisabled;
2153    cur_tab_rec->def.tabnr = 0;
2154    cur_tab_rec->def.func = NULL;
2155  }
2156
2157  // Restore `curitem` to previous recursion level.
2158  curitem = evalstart;
2159
2160  redraw_not_allowed = save_redraw_not_allowed;
2161
2162  // Check for an error.  If there is one the display will be messed up and
2163  // might loop redrawing.  Avoid that by setting the option to its default.
2164  // TODO(Bram): find out why using called_emsg_before makes tests fail, does it
2165  // matter?
2166  // if (called_emsg > called_emsg_before)
2167  if (opt_idx != kOptInvalid && did_emsg > did_emsg_before) {
2168    Object def = get_option_default(opt_idx, opt_scope);
2169    set_option_direct(opt_idx, def, opt_scope, SID_ERROR);
2170    optval_free_read(opt_idx, def);
2171  }
2172
2173  // A user function may reset KeyTyped, restore it.
2174  KeyTyped = save_KeyTyped;
2175
2176  return width;
2177}