robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
124.6 KiB3388 linesraw
1// drawline.c: Functions for drawing window lines on the screen.
2// This is the middle level, drawscreen.c is the top and grid.c the lower level.
3
4#include <assert.h>
5#include <limits.h>
6#include <stdbool.h>
7#include <stddef.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include "nvim/ascii_defs.h"
13#include "nvim/buffer.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/cursor.h"
17#include "nvim/cursor_shape.h"
18#include "nvim/decoration.h"
19#include "nvim/decoration_defs.h"
20#include "nvim/decoration_provider.h"
21#include "nvim/diff.h"
22#include "nvim/drawline.h"
23#include "nvim/drawscreen.h"
24#include "nvim/eval/vars.h"
25#include "nvim/fold.h"
26#include "nvim/fold_defs.h"
27#include "nvim/globals.h"
28#include "nvim/grid.h"
29#include "nvim/grid_defs.h"
30#include "nvim/highlight.h"
31#include "nvim/highlight_defs.h"
32#include "nvim/highlight_group.h"
33#include "nvim/indent.h"
34#include "nvim/insexpand.h"
35#include "nvim/mark_defs.h"
36#include "nvim/marktree_defs.h"
37#include "nvim/match.h"
38#include "nvim/mbyte.h"
39#include "nvim/mbyte_defs.h"
40#include "nvim/memline.h"
41#include "nvim/memory.h"
42#include "nvim/move.h"
43#include "nvim/option.h"
44#include "nvim/option_vars.h"
45#include "nvim/os/os_defs.h"
46#include "nvim/plines.h"
47#include "nvim/pos_defs.h"
48#include "nvim/quickfix.h"
49#include "nvim/sign_defs.h"
50#include "nvim/spell.h"
51#include "nvim/state.h"
52#include "nvim/state_defs.h"
53#include "nvim/statusline.h"
54#include "nvim/statusline_defs.h"
55#include "nvim/strings.h"
56#include "nvim/syntax.h"
57#include "nvim/terminal.h"
58#include "nvim/types_defs.h"
59#include "nvim/ui.h"
60#include "nvim/ui_defs.h"
61#include "nvim/vim_defs.h"
62
63#define MB_FILLER_CHAR '<'  // character used when a double-width character doesn't fit.
64
65/// structure with variables passed between win_line() and other functions
66typedef struct {
67  const linenr_T lnum;       ///< line number to be drawn
68  const foldinfo_T foldinfo;  ///< fold info for this line
69
70  const int startrow;        ///< first row in the window to be drawn
71  int row;                   ///< row in the window, excl w_winrow
72
73  colnr_T vcol;              ///< virtual column, before wrapping
74  int col;                   ///< visual column on screen, after wrapping
75  int boguscols;             ///< nonexistent columns added to "col" to force wrapping
76  int old_boguscols;         ///< bogus boguscols
77  int vcol_off_co;           ///< offset for concealed characters
78
79  int off;                   ///< offset relative start of line
80
81  int cul_attr;              ///< set when 'cursorline' active
82  int line_attr;             ///< attribute for the whole line
83  int line_attr_lowprio;     ///< low-priority attribute for the line
84  int sign_num_attr;         ///< line number attribute (sign numhl)
85  int prev_num_attr;         ///< previous line's number attribute (sign numhl)
86  int sign_cul_attr;         ///< cursorline sign attribute (sign culhl)
87
88  int fromcol;               ///< start of inverting
89  int tocol;                 ///< end of inverting
90
91  colnr_T vcol_sbr;          ///< virtual column after showbreak
92  bool need_showbreak;       ///< overlong line, skipping first x chars
93
94  int char_attr;             ///< attributes for next character
95
96  int n_extra;               ///< number of extra bytes
97  int n_attr;                ///< chars with special attr
98  char *p_extra;             ///< string of extra chars, plus NUL, only used
99                             ///< when sc_extra and sc_final are NUL
100  int extra_attr;            ///< attributes for p_extra
101  schar_T sc_extra;          ///< extra chars, all the same
102  schar_T sc_final;          ///< final char, mandatory if set
103
104  bool extra_for_extmark;    ///< n_extra set for inline virtual text
105
106  char extra[11];            ///< must be as large as transchar_charbuf[] in charset.c
107
108  hlf_T diff_hlf;            ///< type of diff highlighting
109
110  int n_virt_lines;          ///< nr of virtual lines
111  int n_virt_below;          ///< nr of virtual lines belonging to previous line
112  int filler_lines;          ///< nr of filler lines to be drawn
113  int filler_todo;           ///< nr of filler lines still to do + 1
114  int virt_below_skip;       ///< nr of below filler skipped to satisfy w_topfill
115  int filler_lines_skip;     ///< nr of filler lines skipped to satisfy w_topfill
116  SignTextAttrs sattrs[SIGN_SHOW_MAX];  ///< sign attributes for the sign column
117  /// do consider wrapping in linebreak mode only after encountering
118  /// a non whitespace char
119  bool need_lbr;
120
121  VirtText virt_inline;
122  size_t virt_inline_i;
123  HlMode virt_inline_hl_mode;
124
125  bool reset_extra_attr;
126
127  int skip_cells;            ///< nr of cells to skip for w_leftcol
128                             ///< or w_skipcol or concealing
129  int skipped_cells;         ///< nr of skipped cells for virtual text
130                             ///< to be added to wlv.vcol later
131
132  int *color_cols;           ///< if not NULL, highlight colorcolumn using according columns array
133} winlinevars_T;
134
135#include "drawline.c.generated.h"
136
137static char *extra_buf = NULL;
138static size_t extra_buf_size = 0;
139
140static char *get_extra_buf(size_t size)
141{
142  size = MAX(size, 64);
143  if (extra_buf_size < size) {
144    xfree(extra_buf);
145    extra_buf = xmalloc(size);
146    extra_buf_size = size;
147  }
148  return extra_buf;
149}
150
151#ifdef EXITFREE
152void drawline_free_all_mem(void)
153{
154  xfree(extra_buf);
155}
156#endif
157
158/// Get the 'listchars' "extends" characters to use for "wp", or NUL if it
159/// shouldn't be used.
160static schar_T get_lcs_ext(win_T *wp)
161{
162  if (wp->w_p_wrap) {
163    // Line never continues beyond the right of the screen with 'wrap'.
164    return NUL;
165  }
166  if (wp->w_p_wrap_flags & kOptFlagInsecure) {
167    // If 'nowrap' was set from a modeline, forcibly use '>'.
168    return schar_from_ascii('>');
169  }
170  return wp->w_p_list ? wp->w_p_lcs_chars.ext : NUL;
171}
172
173/// Advance wlv->color_cols if not NULL
174static void advance_color_col(winlinevars_T *wlv, int vcol)
175{
176  if (wlv->color_cols) {
177    while (*wlv->color_cols >= 0 && vcol > *wlv->color_cols) {
178      wlv->color_cols++;
179    }
180    if (*wlv->color_cols < 0) {
181      wlv->color_cols = NULL;
182    }
183  }
184}
185
186/// Used when 'cursorlineopt' contains "screenline": compute the margins between
187/// which the highlighting is used.
188static void margin_columns_win(win_T *wp, int *left_col, int *right_col)
189{
190  // cache previous calculations depending on w_virtcol
191  static int saved_w_virtcol;
192  static win_T *prev_wp;
193  static int prev_width1;
194  static int prev_width2;
195  static int prev_left_col;
196  static int prev_right_col;
197
198  int cur_col_off = win_col_off(wp);
199  int width1 = wp->w_view_width - cur_col_off;
200  int width2 = width1 + win_col_off2(wp);
201
202  if (saved_w_virtcol == wp->w_virtcol && prev_wp == wp
203      && prev_width1 == width1 && prev_width2 == width2) {
204    *right_col = prev_right_col;
205    *left_col = prev_left_col;
206    return;
207  }
208
209  *left_col = 0;
210  *right_col = width1;
211
212  if (wp->w_virtcol >= (colnr_T)width1 && width2 > 0) {
213    *right_col = width1 + ((wp->w_virtcol - width1) / width2 + 1) * width2;
214  }
215  if (wp->w_virtcol >= (colnr_T)width1 && width2 > 0) {
216    *left_col = (wp->w_virtcol - width1) / width2 * width2 + width1;
217  }
218
219  // cache values
220  prev_left_col = *left_col;
221  prev_right_col = *right_col;
222  prev_wp = wp;
223  prev_width1 = width1;
224  prev_width2 = width2;
225  saved_w_virtcol = wp->w_virtcol;
226}
227
228/// Put a single char from an UTF-8 buffer into a line buffer.
229///
230/// If `*pp` is a double-width char and only one cell is left, emit a space,
231/// and don't advance *pp
232///
233/// Handles composing chars
234static int line_putchar(buf_T *buf, const char **pp, schar_T *dest, int maxcells, int vcol)
235{
236  // Caller should handle overwriting the right half of a double-width char.
237  assert(dest[0] != 0);
238
239  const char *p = *pp;
240  int cells = utf_ptr2cells(p);
241  int c_len = utfc_ptr2len(p);
242  assert(maxcells > 0);
243  if (cells > maxcells) {
244    dest[0] = schar_from_ascii(' ');
245    return 1;
246  }
247
248  if (*p == TAB) {
249    cells = tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array);
250    cells = MIN(cells, maxcells);
251  }
252
253  // When overwriting the left half of a double-width char, clear the right half.
254  if (cells < maxcells && dest[cells] == 0) {
255    dest[cells] = schar_from_ascii(' ');
256  }
257  if (*p == TAB) {
258    for (int c = 0; c < cells; c++) {
259      dest[c] = schar_from_ascii(' ');
260    }
261  } else {
262    int u8c;
263    dest[0] = utfc_ptr2schar(p, &u8c);
264    if (cells > 1) {
265      dest[1] = 0;
266    }
267  }
268
269  *pp += c_len;
270  return cells;
271}
272
273static void draw_virt_text(win_T *wp, buf_T *buf, int col_off, int *end_col, int win_row)
274{
275  DecorState *const state = &decor_state;
276  int const max_col = wp->w_view_width;
277  int right_pos = max_col;
278  bool const do_eol = state->eol_col > -1;
279
280  int const end = state->current_end;
281  int *const indices = state->ranges_i.items;
282  DecorRangeSlot *const slots = state->slots.items;
283
284  /// Total width of all virtual text with "eol_right_align" alignment
285  int totalWidthOfEolRightAlignedVirtText = 0;
286
287  for (int i = 0; i < end; i++) {
288    DecorRange *item = &slots[indices[i]].range;
289    if (!(item->start_row == state->row && decor_virt_pos(item))) {
290      continue;
291    }
292
293    DecorVirtText *vt = NULL;
294    if (item->kind == kDecorKindVirtText) {
295      assert(item->data.vt);
296      vt = item->data.vt;
297    }
298    if (decor_virt_pos(item) && item->draw_col == -1) {
299      bool updated = true;
300      VirtTextPos pos = decor_virt_pos_kind(item);
301
302      if (do_eol && pos == kVPosEndOfLineRightAlign) {
303        int eolOffset = 0;
304        if (totalWidthOfEolRightAlignedVirtText == 0) {
305          // Look ahead to the remaining decor items
306          for (int j = i; j < end; j++) {
307            /// A future decor to be handled in this function's call
308            DecorRange *lookaheadItem = &slots[indices[j]].range;
309
310            if (lookaheadItem->start_row != state->row
311                || !decor_virt_pos(lookaheadItem)
312                || lookaheadItem->draw_col != -1) {
313              continue;
314            }
315
316            /// The Virtual Text of the decor item we're looking ahead to
317            DecorVirtText *lookaheadVt = NULL;
318            if (lookaheadItem->kind == kDecorKindVirtText) {
319              assert(lookaheadItem->data.vt);
320              lookaheadVt = lookaheadItem->data.vt;
321            }
322
323            if (decor_virt_pos_kind(lookaheadItem) == kVPosEndOfLineRightAlign) {
324              // An extra space is added for single character spacing in EOL alignment
325              totalWidthOfEolRightAlignedVirtText += (lookaheadVt->width + 1);
326            }
327          }
328
329          // Remove one space from the total width since there's no single space after the last entry
330          totalWidthOfEolRightAlignedVirtText--;
331
332          if (totalWidthOfEolRightAlignedVirtText <= (right_pos - state->eol_col)) {
333            eolOffset = right_pos - totalWidthOfEolRightAlignedVirtText - state->eol_col;
334          }
335        }
336
337        item->draw_col = state->eol_col + eolOffset;
338      } else if (pos == kVPosRightAlign) {
339        right_pos -= vt->width;
340        item->draw_col = right_pos;
341      } else if (pos == kVPosEndOfLine && do_eol) {
342        item->draw_col = state->eol_col;
343      } else if (pos == kVPosWinCol) {
344        item->draw_col = MAX(col_off + vt->col, 0);
345      } else {
346        updated = false;
347      }
348      if (updated && (item->draw_col < 0 || item->draw_col >= wp->w_view_width)) {
349        // Out of window, don't draw at all.
350        item->draw_col = INT_MIN;
351      }
352    }
353    if (item->draw_col < 0) {
354      continue;
355    }
356    if (item->kind == kDecorKindUIWatched) {
357      // send mark position to UI
358      WinExtmark m = { (NS)item->data.ui.ns_id, item->data.ui.mark_id, win_row, item->draw_col };
359      kv_push(win_extmark_arr, m);
360    }
361    if (vt) {
362      int vcol = item->draw_col - col_off;
363      int col = draw_virt_text_item(buf, item->draw_col, vt->data.virt_text,
364                                    vt->hl_mode, max_col, vcol, 0, false);
365      if (do_eol && ((vt->pos == kVPosEndOfLine) || (vt->pos == kVPosEndOfLineRightAlign))) {
366        state->eol_col = col + 1;
367      }
368      *end_col = MAX(*end_col, col);
369    }
370    if (!vt || !(vt->flags & kVTRepeatLinebreak)) {
371      item->draw_col = INT_MIN;  // deactivate
372    }
373  }
374}
375
376/// @param eol_hl Extend highlight to EOL.
377static int draw_virt_text_item(buf_T *buf, int col, VirtText vt, HlMode hl_mode, int max_col,
378                               int vcol, int skip_cells, bool eol_hl)
379{
380  const char *virt_str = "";
381  int virt_attr = 0;
382  size_t virt_pos = 0;
383  eol_hl &= kv_size(vt) && *kv_A(vt, kv_size(vt) - 1).text == NUL;
384
385  while (col < max_col) {
386    // extending last highlight till the end of line
387    if (eol_hl && *virt_str == NUL && virt_pos == kv_size(vt)) {
388      virt_str = " ";
389    }
390    if (skip_cells >= 0 && *virt_str == NUL) {
391      if (virt_pos >= kv_size(vt)) {
392        break;
393      }
394      virt_attr = 0;
395      virt_str = next_virt_text_chunk(vt, &virt_pos, &virt_attr);
396      if (virt_str == NULL) {
397        break;
398      }
399    }
400    // Skip cells in the text.
401    while (skip_cells > 0 && *virt_str != NUL) {
402      int c_len = utfc_ptr2len(virt_str);
403      int cells = *virt_str == TAB
404                  ? tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array)
405                  : utf_ptr2cells(virt_str);
406      skip_cells -= cells;
407      vcol += cells;
408      virt_str += c_len;
409    }
410    // If a double-width char or TAB doesn't fit, pad with spaces.
411    const char *draw_str = skip_cells < 0 ? " " : virt_str;
412    if (*draw_str == NUL) {
413      continue;
414    }
415    assert(skip_cells <= 0);
416    int attr;
417    bool through = false;
418    if (hl_mode == kHlModeCombine) {
419      attr = hl_combine_attr(linebuf_attr[col], virt_attr);
420    } else if (hl_mode == kHlModeBlend) {
421      through = (*draw_str == ' ');
422      attr = hl_blend_attrs(linebuf_attr[col], virt_attr, &through);
423    } else {
424      attr = virt_attr;
425    }
426    schar_T dummy[2] = { schar_from_ascii(' '), schar_from_ascii(' ') };
427    int maxcells = max_col - col;
428    // When overwriting the right half of a double-width char, clear the left half.
429    if (!through && linebuf_char[col] == 0) {
430      assert(col > 0);
431      linebuf_char[col - 1] = schar_from_ascii(' ');
432      // Clear the right half as well for the assertion in line_putchar().
433      linebuf_char[col] = schar_from_ascii(' ');
434    }
435    int cells = line_putchar(buf, &draw_str, through ? dummy : &linebuf_char[col],
436                             maxcells, vcol);
437    for (int c = 0; c < cells; c++) {
438      linebuf_attr[col] = attr;
439      col++;
440    }
441    if (skip_cells < 0) {
442      skip_cells++;
443    } else {
444      vcol += cells;
445      virt_str = draw_str;
446    }
447  }
448  return col;
449}
450
451// TODO(bfredl): integrate with grid.c linebuf code? madness?
452static void draw_col_buf(win_T *wp, winlinevars_T *wlv, const char *text, size_t len, int attr,
453                         const colnr_T *fold_vcol, bool inc_vcol)
454{
455  const char *ptr = text;
456  while (ptr < text + len && wlv->off < wp->w_view_width) {
457    int cells = line_putchar(wp->w_buffer, &ptr, &linebuf_char[wlv->off],
458                             wp->w_view_width - wlv->off, wlv->off);
459    int myattr = attr;
460    if (inc_vcol) {
461      advance_color_col(wlv, wlv->vcol);
462      if (wlv->color_cols && wlv->vcol == *wlv->color_cols) {
463        myattr = hl_combine_attr(win_hl_attr(wp, HLF_MC), myattr);
464      }
465    }
466    for (int c = 0; c < cells; c++) {
467      linebuf_attr[wlv->off] = myattr;
468      linebuf_vcol[wlv->off] = inc_vcol ? wlv->vcol++ : fold_vcol ? *(fold_vcol++) : -1;
469      wlv->off++;
470    }
471  }
472}
473
474static void draw_col_fill(winlinevars_T *wlv, schar_T fillchar, int width, int attr)
475{
476  for (int i = 0; i < width; i++) {
477    linebuf_char[wlv->off] = fillchar;
478    linebuf_attr[wlv->off] = attr;
479    wlv->off++;
480  }
481}
482
483/// Return true if CursorLineSign / CursorLineFold highlight is to be used.
484/// This depends only on 'cursorline', not on 'cursorlineopt'.
485bool use_cursor_line_highlight(win_T *wp, linenr_T lnum)
486{
487  return wp->w_p_cul && lnum == wp->w_cursorline;
488}
489
490/// Setup for drawing the 'foldcolumn', if there is one.
491static void draw_foldcolumn(win_T *wp, winlinevars_T *wlv)
492{
493  int fdc = compute_foldcolumn(wp, 0);
494  if (fdc > 0) {
495    int attr = win_hl_attr(wp, use_cursor_line_highlight(wp, wlv->lnum) ? HLF_CLF : HLF_FC);
496    bool is_virt = wlv->filler_todo > 0;
497    fill_foldcolumn(wp, wlv->foldinfo, wlv->lnum, attr, fdc, is_virt, &wlv->off, NULL, NULL);
498  }
499}
500
501/// Get foldcolumn char based on line fold level and column, either `foldsep`, `foldinner`,
502/// or an overflow indicator. `foldopen` and `foldclosed` are set in `fill_foldcolumn`.
503/// @param first_level Lowest fold level displayed on line
504/// @param i Column index
505static inline schar_T foldcolumn_sep_char(int first_level, int i, win_T *wp)
506{
507  if (first_level == 1) {
508    return wp->w_p_fcs_chars.foldsep;
509  } else if (wp->w_p_fcs_chars.foldinner != NUL) {
510    return wp->w_p_fcs_chars.foldinner;
511  } else if (first_level + i <= 9) {
512    return schar_from_ascii('0' + first_level + i);
513  } else {
514    return schar_from_ascii('>');
515  }
516}
517
518/// Draw the foldcolumn or fill "out_buffer". Assume monocell characters.
519///
520/// @param fdc  Current width of the foldcolumn
521/// @param is_virt Whether the line is a filler line (diff or virtual)
522/// @param[out] wlv_off  Pointer to linebuf offset, incremented for default column
523/// @param[out] out_buffer  Char array to fill, only used for 'statuscolumn'
524/// @param[out] out_vcol  vcol array to fill, only used for 'statuscolumn'
525void fill_foldcolumn(win_T *wp, foldinfo_T foldinfo, linenr_T lnum, int attr, int fdc, bool is_virt,
526                     int *wlv_off, colnr_T *out_vcol, schar_T *out_buffer)
527{
528  bool closed = foldinfo.fi_level != 0 && foldinfo.fi_lines > 0;
529  int level = foldinfo.fi_level;
530
531  // If the column is too narrow, we start at the lowest level that
532  // fits and use numbers to indicate the depth.
533  int first_level = MAX(level - fdc - closed + 1, 1);
534  int closedcol = MIN(fdc, level);
535
536  for (int i = 0; i < fdc; i++) {
537    schar_T symbol = 0;
538    if (i >= level) {
539      symbol = schar_from_ascii(' ');
540    } else if (i == closedcol - 1 && closed) {
541      symbol = wp->w_p_fcs_chars.foldclosed;
542    } else if (foldinfo.fi_lnum == lnum && first_level + i >= foldinfo.fi_low_level) {
543      symbol = wp->w_p_fcs_chars.foldopen;
544    } else {
545      symbol = foldcolumn_sep_char(first_level, i, wp);
546    }
547
548    // We don't want to show `foldopen` or `foldclose` twice, so we compute
549    // the fold level of `lnum - 1` and reuse the logic from above.
550    if (is_virt && foldinfo.fi_level != 0 && foldinfo.fi_lnum == lnum) {
551      int outer_level = MAX(foldinfo.fi_low_level - 1, 0);
552      int outer_first_level = MAX(outer_level - fdc + 1, 1);
553      if (i >= outer_level) {
554        symbol = schar_from_ascii(' ');
555      } else {
556        symbol = foldcolumn_sep_char(outer_first_level, i, wp);
557      }
558    }
559
560    int vcol = i >= level ? -1 : (i == closedcol - 1 && closed) ? -2 : -3;
561    if (out_buffer) {
562      out_vcol[i] = vcol;
563      out_buffer[i] = symbol;
564    } else {
565      linebuf_vcol[*wlv_off] = vcol;
566      linebuf_attr[*wlv_off] = attr;
567      linebuf_char[(*wlv_off)++] = symbol;
568    }
569  }
570}
571
572/// Get information needed to display the sign in line "wlv->lnum" in window "wp".
573/// If "nrcol" is true, the sign is going to be displayed in the number column.
574/// Otherwise the sign is going to be displayed in the sign column. If there is no
575/// sign, draw blank cells instead.
576static void draw_sign(bool nrcol, win_T *wp, winlinevars_T *wlv, int sign_idx)
577{
578  SignTextAttrs sattr = wlv->sattrs[sign_idx];
579  int scl_attr = win_hl_attr(wp, use_cursor_line_highlight(wp, wlv->lnum) ? HLF_CLS : HLF_SC);
580
581  if (sattr.text[0] && wlv->row == wlv->startrow + wlv->filler_lines && wlv->filler_todo <= 0) {
582    int fill = nrcol ? number_width(wp) + 1 : SIGN_WIDTH;
583    int attr = wlv->sign_cul_attr ? wlv->sign_cul_attr : sattr.hl_id ? syn_id2attr(sattr.hl_id) : 0;
584    attr = hl_combine_attr(scl_attr, attr);
585    draw_col_fill(wlv, schar_from_ascii(' '), fill, attr);
586    int sign_pos = wlv->off - SIGN_WIDTH - (int)nrcol;
587    assert(sign_pos >= 0);
588    linebuf_char[sign_pos] = sattr.text[0];
589    linebuf_char[sign_pos + 1] = sattr.text[1];
590  } else {
591    assert(!nrcol);  // handled in draw_lnum_col()
592    draw_col_fill(wlv, schar_from_ascii(' '), SIGN_WIDTH, scl_attr);
593  }
594}
595
596static inline void get_line_number_str(win_T *wp, linenr_T lnum, char *buf, size_t buf_len)
597{
598  linenr_T num;
599  char *fmt = "%*" PRIdLINENR " ";
600
601  if (wp->w_p_nu && !wp->w_p_rnu) {
602    // 'number' + 'norelativenumber'
603    num = lnum;
604  } else {
605    // 'relativenumber', don't use negative numbers
606    num = abs(get_cursor_rel_lnum(wp, lnum));
607    if (num == 0 && wp->w_p_nu && wp->w_p_rnu) {
608      // 'number' + 'relativenumber'
609      num = lnum;
610      fmt = "%-*" PRIdLINENR " ";
611    }
612  }
613
614  snprintf(buf, buf_len, fmt, number_width(wp), num);
615}
616
617/// Return true if CursorLineNr highlight is to be used for the number column.
618/// - 'cursorline' must be set
619/// - "wlv->lnum" must be the cursor line
620/// - 'cursorlineopt' has "number"
621/// - don't highlight filler lines (when in diff mode)
622/// - When line is wrapped and 'cursorlineopt' does not have "line", only highlight the line number
623///   itself on the first screenline of the wrapped line, otherwise highlight the number column of
624///   all screenlines of the wrapped line.
625static bool use_cursor_line_nr(win_T *wp, winlinevars_T *wlv)
626{
627  return wp->w_p_cul
628         && wlv->lnum == wp->w_cursorline
629         && (wp->w_p_culopt_flags & kOptCuloptFlagNumber)
630         && (wlv->row == wlv->startrow + wlv->filler_lines
631             || (wlv->row > wlv->startrow + wlv->filler_lines
632                 && (wp->w_p_culopt_flags & kOptCuloptFlagLine)));
633}
634
635/// Return line number attribute, combining the appropriate LineNr* highlight
636/// with the highest priority sign numhl highlight, if any.
637static int get_line_number_attr(win_T *wp, winlinevars_T *wlv)
638{
639  int numhl_attr = wlv->sign_num_attr;
640
641  // Get previous sign numhl for virt_lines belonging to the previous line.
642  if ((wlv->n_virt_lines - wlv->filler_todo) < wlv->n_virt_below) {
643    if (wlv->prev_num_attr == -1) {
644      decor_redraw_signs(wp, wp->w_buffer, wlv->lnum - 2, NULL, NULL, NULL, &wlv->prev_num_attr);
645      if (wlv->prev_num_attr > 0) {
646        wlv->prev_num_attr = syn_id2attr(wlv->prev_num_attr);
647      }
648    }
649    numhl_attr = wlv->prev_num_attr;
650  }
651
652  if (use_cursor_line_nr(wp, wlv)) {
653    // TODO(vim): Can we use CursorLine instead of CursorLineNr
654    // when CursorLineNr isn't set?
655    return hl_combine_attr(win_hl_attr(wp, HLF_CLN), numhl_attr);
656  }
657
658  if (wp->w_p_rnu) {
659    if (wlv->lnum < wp->w_cursor.lnum) {
660      // Use LineNrAbove
661      return hl_combine_attr(win_hl_attr(wp, HLF_LNA), numhl_attr);
662    }
663    if (wlv->lnum > wp->w_cursor.lnum) {
664      // Use LineNrBelow
665      return hl_combine_attr(win_hl_attr(wp, HLF_LNB), numhl_attr);
666    }
667  }
668
669  return hl_combine_attr(win_hl_attr(wp, HLF_N), numhl_attr);
670}
671
672/// Display the absolute or relative line number.  After the first row fill with
673/// blanks when the 'n' flag isn't in 'cpo'.
674static void draw_lnum_col(win_T *wp, winlinevars_T *wlv)
675{
676  bool has_cpo_n = vim_strchr(p_cpo, kCpoNumcol) != NULL;
677
678  if ((wp->w_p_nu || wp->w_p_rnu)
679      && (wlv->row == wlv->startrow + wlv->filler_lines || !has_cpo_n)
680      // there is no line number in a wrapped line when "n" is in
681      // 'cpoptions', but 'breakindent' assumes it anyway.
682      && !((has_cpo_n && !wp->w_p_bri) && wp->w_skipcol > 0 && wlv->lnum == wp->w_topline)) {
683    // If 'signcolumn' is set to 'number' and a sign is present in "lnum",
684    // then display the sign instead of the line number.
685    if (wp->w_minscwidth == SCL_NUM && wlv->sattrs[0].text[0]
686        && wlv->row == wlv->startrow + wlv->filler_lines && wlv->filler_todo <= 0) {
687      draw_sign(true, wp, wlv, 0);
688    } else {
689      // Draw the line number (empty space after wrapping).
690      int width = number_width(wp) + 1;
691      int attr = get_line_number_attr(wp, wlv);
692      if (wlv->row == wlv->startrow + wlv->filler_lines
693          && (wp->w_skipcol == 0 || wlv->row > 0 || (wp->w_p_nu && wp->w_p_rnu))) {
694        char buf[32];
695        get_line_number_str(wp, wlv->lnum, buf, sizeof(buf));
696        if (wp->w_skipcol > 0 && wlv->startrow == 0) {
697          for (char *c = buf; *c == ' '; c++) {
698            *c = '-';
699          }
700        }
701        if (wp->w_p_rl) {  // reverse line numbers
702          char *num = skipwhite(buf);
703          rl_mirror_ascii(num, skiptowhite(num));
704        }
705        draw_col_buf(wp, wlv, buf, (size_t)width, attr, NULL, false);
706      } else {
707        draw_col_fill(wlv, schar_from_ascii(' '), width, attr);
708      }
709    }
710  }
711}
712
713/// Build and draw the 'statuscolumn' string for line "lnum" in window "wp".
714static void draw_statuscol(win_T *wp, winlinevars_T *wlv, int col_rows, statuscol_T *stcp)
715{
716  static int prev_virtnum = 0;
717  static win_T *prev_wp = NULL;
718  static linenr_T prev_lnum = 0;
719  static disptick_T prev_tick = 0;
720
721  // Adjust lnum for filler lines belonging to the line above.
722  linenr_T lnum = wlv->lnum - ((wlv->n_virt_lines - wlv->filler_todo) < wlv->n_virt_below);
723
724  // Cache v:virtnum for virtual lines and reset/decrement it accordingly. Only when
725  // lnum < wp->w_topline do we need to check for virt_below on the previous line.
726  // Same strategy is used in mouse_comp_pos() to achieve a distinct row/click_def mapping.
727  bool reset = prev_wp != wp || prev_tick != display_tick || lnum != prev_lnum;
728  int reset_virt = lnum == wlv->lnum ? wlv->filler_lines_skip : wlv->virt_below_skip;
729  if (reset && lnum < wp->w_topline) {
730    int virt_below_prev = 0;
731    int virt_lines_prev = decor_virt_lines(wp, lnum - 1, lnum, &virt_below_prev, NULL, true);
732    int diff_fill_prev = diff_check_fill(wp, lnum - 1);
733    reset_virt += virt_lines_prev + diff_fill_prev - virt_below_prev;
734  }
735  prev_virtnum = (reset ? -reset_virt : prev_virtnum) - (wlv->filler_todo > 0);
736  int virtnum = wlv->filler_todo > 0 ? prev_virtnum : wlv->row - wlv->startrow - wlv->filler_lines;
737  // Set lnum v:vars for first row, first non-filler line, and first filler line
738  // belonging to the current line.
739  linenr_T relnum = (virtnum == -reset_virt - 1 || virtnum == 0)
740                    ? abs(get_cursor_rel_lnum(wp, lnum)) : -1;
741
742  prev_tick = display_tick;
743  prev_lnum = lnum;
744  prev_wp = wp;
745
746  char buf[MAXPATHL];
747  const CharBuf outbuf = { buf, sizeof(buf) };
748  // When a buffer's line count has changed, make a best estimate for the full
749  // width of the status column by building with the largest possible line number.
750  // Add potentially truncated width and rebuild before drawing anything.
751  if (wp->w_statuscol_line_count != wp->w_nrwidth_line_count) {
752    wp->w_statuscol_line_count = wp->w_nrwidth_line_count;
753    int width = build_statuscol_str(wp, wp->w_nrwidth_line_count,
754                                    wp->w_nrwidth_line_count, 0, outbuf, stcp);
755    if (width > stcp->width) {
756      int addwidth = MIN(width - stcp->width, MAX_STCWIDTH - stcp->width);
757      wp->w_nrwidth += addwidth;
758      wp->w_nrwidth_width = wp->w_nrwidth;
759      if (col_rows > 0) {
760        // If only column is being redrawn, we now need to redraw the text as well
761        wp->w_redr_statuscol = true;
762        prev_lnum = 0;
763        return;
764      }
765      stcp->width += addwidth;
766      wp->w_valid &= ~VALID_WCOL;
767    }
768  }
769
770  int width = build_statuscol_str(wp, lnum, relnum, virtnum, outbuf, stcp);
771  // Force a redraw in case of error or when truncated
772  if (*wp->w_p_stc == NUL || (width > stcp->width && stcp->width < MAX_STCWIDTH)) {
773    if (*wp->w_p_stc == NUL) {  // 'statuscolumn' reset due to error
774      wp->w_nrwidth_line_count = 0;
775      wp->w_nrwidth = (wp->w_p_nu || wp->w_p_rnu) * number_width(wp);
776    } else {  // Avoid truncating 'statuscolumn'
777      wp->w_nrwidth += MIN(width - stcp->width, MAX_STCWIDTH - stcp->width);
778      wp->w_nrwidth_width = wp->w_nrwidth;
779    }
780    wp->w_redr_statuscol = true;
781    prev_lnum = 0;
782    return;
783  }
784
785  char *p = buf;
786  char transbuf[MAXPATHL];
787  colnr_T *fold_vcol = NULL;
788  size_t len = strlen(buf);
789  int scl_attr = win_hl_attr(wp, use_cursor_line_highlight(wp, wlv->lnum) ? HLF_CLS : HLF_SC);
790  int num_attr = get_line_number_attr(wp, wlv);
791  int cur_attr = num_attr;
792
793  // Draw each segment with the specified highlighting.
794  for (stl_hlrec_t *sp = stcp->hlrec; sp->start != NULL; sp++) {
795    ptrdiff_t textlen = sp->start - p;
796    // Make all characters printable.
797    size_t translen = transstr_buf(p, textlen, transbuf, MAXPATHL, true);
798    draw_col_buf(wp, wlv, transbuf, translen, cur_attr, fold_vcol, false);
799    int attr = sp->item == STL_SIGNCOL ? scl_attr : sp->item == STL_FOLDCOL ? 0 : num_attr;
800    cur_attr = hl_combine_attr(attr, sp->userhl < 0 ? syn_id2attr(-sp->userhl) : 0);
801    fold_vcol = sp->item == STL_FOLDCOL ? stcp->fold_vcol : NULL;
802    p = sp->start;
803  }
804  size_t translen = transstr_buf(p, buf + len - p, transbuf, MAXPATHL, true);
805  draw_col_buf(wp, wlv, transbuf, translen, cur_attr, fold_vcol, false);
806  draw_col_fill(wlv, schar_from_ascii(' '), stcp->width - width, cur_attr);
807}
808
809/// Whether "attr" draws an underline, undercurl, strikethrough, or overline: a line tied to text
810/// glyphs that looks broken drawn over blank filler cells, unlike a plain background/reverse-video
811/// highlight.
812static bool attr_has_line_deco(int attr)
813{
814  HlAttrs ae = syn_attr2entry(attr);
815  int32_t const mask = HL_UNDERLINE_MASK | HL_STRIKETHROUGH | HL_OVERLINE;
816  return (ae.rgb_ae_attr & mask) != 0 || (ae.cterm_ae_attr & mask) != 0;
817}
818
819static void handle_breakindent(win_T *wp, winlinevars_T *wlv, int gap_decor_attr)
820{
821  // draw 'breakindent': indent wrapped text accordingly
822  // if wlv->need_showbreak is set, breakindent also applies
823  if (wp->w_p_bri && (wlv->row > wlv->startrow + wlv->filler_lines
824                      || wlv->need_showbreak)) {
825    // Extend the still-active decoration/syntax highlight (e.g. a full-width code-block background)
826    // into the indent; it is not ending here, just skipping over screen cells with no buffer text.
827    int attr = gap_decor_attr;
828    if (wlv->diff_hlf != (hlf_T)0) {
829      attr = hl_combine_attr(attr, win_hl_attr(wp, (int)wlv->diff_hlf));
830    }
831    int num = get_breakindent_win(wp, ml_get_buf(wp->w_buffer, wlv->lnum));
832    if (wlv->row == wlv->startrow) {
833      num -= win_col_off2(wp);
834      if (wlv->n_extra < 0) {
835        num = 0;
836      }
837    }
838
839    colnr_T vcol_before = wlv->vcol;
840
841    for (int i = 0; i < num; i++) {
842      linebuf_char[wlv->off] = schar_from_ascii(' ');
843
844      advance_color_col(wlv, wlv->vcol);
845      int myattr = attr;
846      if (wlv->color_cols && wlv->vcol == *wlv->color_cols) {
847        myattr = hl_combine_attr(win_hl_attr(wp, HLF_MC), myattr);
848      }
849      linebuf_attr[wlv->off] = myattr;
850      linebuf_vcol[wlv->off] = wlv->vcol++;  // These are vcols, sorry I don't make the rules
851      wlv->off++;
852    }
853
854    // Correct start of highlighted area for 'breakindent',
855    if (wlv->fromcol >= vcol_before && wlv->fromcol < wlv->vcol) {
856      wlv->fromcol = wlv->vcol;
857    }
858
859    // Correct end of highlighted area for 'breakindent',
860    // required wen 'linebreak' is also set.
861    if (wlv->tocol == vcol_before) {
862      wlv->tocol = wlv->vcol;
863    }
864  }
865
866  if (wp->w_skipcol > 0 && wlv->startrow == 0 && wp->w_p_wrap && wp->w_briopt_sbr) {
867    wlv->need_showbreak = false;
868  }
869}
870
871static void handle_showbreak_and_filler(win_T *wp, winlinevars_T *wlv, int gap_decor_attr)
872{
873  int remaining = wp->w_view_width - wlv->off;
874  if (wlv->filler_todo > wlv->filler_lines - wlv->n_virt_lines) {
875    // TODO(bfredl): check this doesn't inhibit TUI-style
876    //               clear-to-end-of-line.
877    draw_col_fill(wlv, schar_from_ascii(' '), remaining, 0);
878  } else if (wlv->filler_todo > 0) {
879    // Draw "deleted" diff line(s)
880    schar_T c = wp->w_p_fcs_chars.diff;
881    draw_col_fill(wlv, c, remaining, win_hl_attr(wp, HLF_DED));
882  }
883
884  char *const sbr = get_showbreak_value(wp);
885  if (*sbr != NUL && wlv->need_showbreak) {
886    // Draw 'showbreak' at the start of each broken line.
887    // Combine 'showbreak' with 'cursorline' and the still-active decoration/syntax highlight,
888    // prioritizing 'showbreak'.
889    int attr = hl_combine_attr(wlv->cul_attr, gap_decor_attr);
890    attr = hl_combine_attr(attr, win_hl_attr(wp, HLF_AT));
891    colnr_T vcol_before = wlv->vcol;
892    draw_col_buf(wp, wlv, sbr, strlen(sbr), attr, NULL, true);
893    wlv->vcol_sbr = wlv->vcol;
894
895    // Correct start of highlighted area for 'showbreak'.
896    if (wlv->fromcol >= vcol_before && wlv->fromcol < wlv->vcol) {
897      wlv->fromcol = wlv->vcol;
898    }
899
900    // Correct end of highlighted area for 'showbreak',
901    // required when 'linebreak' is also set.
902    if (wlv->tocol == vcol_before) {
903      wlv->tocol = wlv->vcol;
904    }
905  }
906
907  if (wp->w_skipcol == 0 || wlv->startrow > 0 || !wp->w_p_wrap || !wp->w_briopt_sbr) {
908    wlv->need_showbreak = false;
909  }
910}
911
912static void apply_cursorline_highlight(win_T *wp, winlinevars_T *wlv)
913{
914  wlv->cul_attr = win_hl_attr(wp, HLF_CUL);
915  HlAttrs ae = syn_attr2entry(wlv->cul_attr);
916  // We make a compromise here (#7383):
917  //  * low-priority CursorLine if fg is not set
918  //  * high-priority ("same as Vim" priority) CursorLine if fg is set
919  if (ae.rgb_fg_color == -1 && ae.cterm_fg_color == 0) {
920    wlv->line_attr_lowprio = wlv->cul_attr;
921  } else if (!(State & MODE_INSERT) && bt_quickfix(wp->w_buffer)
922             && qf_current_entry(wp) == wlv->lnum) {
923    wlv->line_attr = hl_combine_attr(wlv->cul_attr, wlv->line_attr);
924  } else {
925    wlv->line_attr = wlv->cul_attr;
926  }
927}
928
929static void set_line_attr_for_diff(win_T *wp, winlinevars_T *wlv)
930{
931  wlv->line_attr = win_hl_attr(wp, (int)wlv->diff_hlf);
932  // Overlay CursorLine onto diff-mode highlight.
933  if (wlv->cul_attr) {
934    wlv->line_attr = 0 != wlv->line_attr_lowprio  // Low-priority CursorLine
935                     ? hl_combine_attr(hl_combine_attr(wlv->cul_attr, wlv->line_attr),
936                                       hl_get_underline())
937                     : hl_combine_attr(wlv->line_attr, wlv->cul_attr);
938  }
939}
940
941/// Checks if there is more inline virtual text that need to be drawn.
942static bool has_more_inline_virt(winlinevars_T *wlv, ptrdiff_t v)
943{
944  if (wlv->virt_inline_i < kv_size(wlv->virt_inline)) {
945    return true;
946  }
947
948  int const count = (int)kv_size(decor_state.ranges_i);
949  int const cur_end = decor_state.current_end;
950  int const fut_beg = decor_state.future_begin;
951  int *const indices = decor_state.ranges_i.items;
952  DecorRangeSlot *const slots = decor_state.slots.items;
953
954  int const beg_pos[] = { 0, fut_beg };
955  int const end_pos[] = { cur_end, count };
956
957  for (int pos_i = 0; pos_i < 2; pos_i++) {
958    for (int i = beg_pos[pos_i]; i < end_pos[pos_i]; i++) {
959      DecorRange *item = &slots[indices[i]].range;
960      if (item->start_row != decor_state.row
961          || item->kind != kDecorKindVirtText
962          || item->data.vt->pos != kVPosInline
963          || item->data.vt->width == 0) {
964        continue;
965      }
966      if (item->draw_col >= -1 && item->start_col >= v) {
967        return true;
968      }
969    }
970  }
971  return false;
972}
973
974static void handle_inline_virtual_text(win_T *wp, winlinevars_T *wlv, ptrdiff_t v, bool selected)
975{
976  while (wlv->n_extra == 0) {
977    if (wlv->virt_inline_i >= kv_size(wlv->virt_inline)) {
978      // need to find inline virtual text
979      wlv->virt_inline = VIRTTEXT_EMPTY;
980      wlv->virt_inline_i = 0;
981      DecorState *state = &decor_state;
982      int const end = state->current_end;
983      int *const indices = state->ranges_i.items;
984      DecorRangeSlot *const slots = state->slots.items;
985
986      for (int i = 0; i < end; i++) {
987        DecorRange *item = &slots[indices[i]].range;
988        if (item->draw_col == -3) {
989          // No more inline virtual text before this non-inline virtual text item,
990          // so its position can be decided now.
991          decor_init_draw_col(wlv->off, selected, item);
992        }
993        if (item->start_row != state->row
994            || item->kind != kDecorKindVirtText
995            || item->data.vt->pos != kVPosInline
996            || item->data.vt->width == 0) {
997          continue;
998        }
999        if (item->draw_col >= -1 && item->start_col == v) {
1000          wlv->virt_inline = item->data.vt->data.virt_text;
1001          wlv->virt_inline_hl_mode = item->data.vt->hl_mode;
1002          item->draw_col = INT_MIN;
1003          break;
1004        }
1005      }
1006      if (!kv_size(wlv->virt_inline)) {
1007        // no more inline virtual text here
1008        break;
1009      }
1010    } else {
1011      // already inside existing inline virtual text with multiple chunks
1012      int attr = 0;
1013      char *text = next_virt_text_chunk(wlv->virt_inline, &wlv->virt_inline_i, &attr);
1014      if (text == NULL) {
1015        continue;
1016      }
1017      wlv->p_extra = text;
1018      wlv->n_extra = (int)strlen(text);
1019      if (wlv->n_extra == 0) {
1020        continue;
1021      }
1022      wlv->sc_extra = NUL;
1023      wlv->sc_final = NUL;
1024      wlv->extra_attr = attr;
1025      wlv->n_attr = mb_charlen(text);
1026      // If the text didn't reach until the first window
1027      // column we need to skip cells.
1028      if (wlv->skip_cells > 0) {
1029        int virt_text_width = (int)mb_string2cells(wlv->p_extra);
1030        if (virt_text_width > wlv->skip_cells) {
1031          int skip_cells_remaining = wlv->skip_cells;
1032          // Skip cells in the text.
1033          while (skip_cells_remaining > 0) {
1034            int cells = utf_ptr2cells(wlv->p_extra);
1035            if (cells > skip_cells_remaining) {
1036              break;
1037            }
1038            int c_len = utfc_ptr2len(wlv->p_extra);
1039            skip_cells_remaining -= cells;
1040            wlv->p_extra += c_len;
1041            wlv->n_extra -= c_len;
1042            wlv->n_attr--;
1043          }
1044          // Skipped cells needed to be accounted for in vcol.
1045          wlv->skipped_cells += wlv->skip_cells - skip_cells_remaining;
1046          wlv->skip_cells = skip_cells_remaining;
1047        } else {
1048          // The whole text is left of the window, drop
1049          // it and advance to the next one.
1050          wlv->skip_cells -= virt_text_width;
1051          // Skipped cells needed to be accounted for in vcol.
1052          wlv->skipped_cells += virt_text_width;
1053          wlv->n_attr = 0;
1054          wlv->n_extra = 0;
1055          // Go to the start so the next virtual text chunk can be selected.
1056          continue;
1057        }
1058      }
1059      assert(wlv->n_extra > 0);
1060      wlv->extra_for_extmark = true;
1061    }
1062  }
1063}
1064
1065/// Start a screen line at column zero.
1066static void win_line_start(win_T *wp, winlinevars_T *wlv)
1067{
1068  wlv->col = 0;
1069  wlv->off = 0;
1070  wlv->need_lbr = false;
1071  for (int i = 0; i < wp->w_view_width; i++) {
1072    linebuf_char[i] = schar_from_ascii(' ');
1073    linebuf_attr[i] = 0;
1074    linebuf_vcol[i] = -1;
1075  }
1076}
1077
1078static void fix_for_boguscols(winlinevars_T *wlv)
1079{
1080  wlv->n_extra += wlv->vcol_off_co;
1081  wlv->vcol -= wlv->vcol_off_co;
1082  wlv->vcol_off_co = 0;
1083  wlv->col -= wlv->boguscols;
1084  wlv->old_boguscols = wlv->boguscols;
1085  wlv->boguscols = 0;
1086}
1087
1088static int get_rightmost_vcol(win_T *wp, const int *color_cols)
1089{
1090  int ret = 0;
1091
1092  if (wp->w_p_cuc) {
1093    ret = wp->w_virtcol;
1094  }
1095
1096  if (color_cols) {
1097    // determine rightmost colorcolumn to possibly draw
1098    for (int i = 0; color_cols[i] >= 0; i++) {
1099      ret = MAX(ret, color_cols[i]);
1100    }
1101  }
1102
1103  return ret;
1104}
1105
1106/// Display line "lnum" of window "wp" on the screen.
1107/// wp->w_virtcol needs to be valid.
1108///
1109/// @param lnum         line to display
1110/// @param startrow     first row relative to window grid
1111/// @param endrow       last grid row to be redrawn
1112/// @param col_rows     set to the height of the line when only updating the columns,
1113///                     otherwise set to 0
1114/// @param concealed    only draw virtual lines belonging to the line above
1115/// @param spv          'spell' related variables kept between calls for "wp"
1116/// @param foldinfo     fold info for this line
1117/// @param[in, out] providers  decoration providers active this line
1118///                            items will be disables if they cause errors
1119///                            or explicitly return `false`.
1120///
1121/// @return             the number of last row the line occupies.
1122int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, int col_rows, bool concealed,
1123             spellvars_T *spv, foldinfo_T foldinfo)
1124{
1125  GridView *grid = &wp->w_grid;       // grid specific to the window
1126  const int view_width = wp->w_view_width;
1127  const int view_height = wp->w_view_height;
1128
1129  const bool in_curline = wp == curwin && lnum == curwin->w_cursor.lnum;
1130  const bool has_fold = foldinfo.fi_level != 0 && foldinfo.fi_lines > 0;
1131  const bool has_foldtext = has_fold && wp->w_p_fdt.type != kCallbackNone;
1132
1133  const bool is_wrapped = wp->w_p_wrap
1134                          && !has_fold;       // Never wrap folded lines
1135
1136  int saved_attr2 = 0;                  // char_attr saved for n_attr
1137  int n_attr3 = 0;                      // chars with overruling special attr
1138  int saved_attr3 = 0;                  // char_attr saved for n_attr3
1139
1140  bool lnum_in_visual_area = false;
1141
1142  int char_attr_pri = 0;                // attributes with high priority
1143  int char_attr_base = 0;               // attributes with low priority
1144  bool area_highlighting = false;       // Visual or incsearch highlighting in this line
1145  int vi_attr = 0;                      // attributes for Visual and incsearch highlighting
1146  int area_attr = 0;                    // attributes desired by highlighting
1147  int search_attr = 0;                  // attributes desired by 'hlsearch' or ComplMatchIns
1148  int vcol_save_attr = 0;               // saved attr for 'cursorcolumn'
1149  int decor_attr = 0;                   // attributes desired by syntax and extmarks
1150  int syntax_attr = 0;                  // syntax-only part of "decor_attr"
1151  int gap_attr_save = 0;                // attr for gaps showing no buffer text
1152  bool has_syntax = false;              // this buffer has syntax highl.
1153  int folded_attr = 0;                  // attributes for folded line
1154  int eol_hl_off = 0;                   // 1 if highlighted char after EOL
1155#define SPWORDLEN 150
1156  char nextline[SPWORDLEN * 2];         // text with start of the next line
1157  int nextlinecol = 0;                  // column where nextline[] starts
1158  int nextline_idx = 0;                 // index in nextline[] where next line
1159                                        // starts
1160  int spell_attr = 0;                   // attributes desired by spelling
1161  int word_end = 0;                     // last byte with same spell_attr
1162  int cur_checked_col = 0;              // checked column for current line
1163  bool extra_check = false;             // has extra highlighting
1164  int multi_attr = 0;                   // attributes desired by multibyte
1165  int mb_l = 1;                         // multi-byte byte length
1166  int mb_c = 0;                         // decoded multi-byte character
1167  schar_T mb_schar = 0;                 // complete screen char
1168  int change_start = MAXCOL;            // first col of changed area
1169  int change_end = -1;                  // last col of changed area
1170  bool in_multispace = false;           // in multiple consecutive spaces
1171  int multispace_pos = 0;               // position in lcs-multispace string
1172
1173  int n_extra_next = 0;                 // n_extra to use after current extra chars
1174  int extra_attr_next = -1;             // extra_attr to use after current extra chars
1175
1176  bool search_attr_from_match = false;  // if search_attr is from :match
1177  bool has_decor = false;               // this buffer has decoration
1178
1179  int saved_search_attr = 0;            // search_attr to be used when n_extra goes to zero
1180  int saved_area_attr = 0;              // idem for area_attr
1181  int saved_decor_attr = 0;             // idem for decor_attr
1182  bool saved_search_attr_from_match = false;
1183
1184  int win_col_offset = 0;               // offset for window columns
1185  bool area_active = false;             // whether in Visual selection, for virtual text
1186  bool decor_need_recheck = false;      // call decor_recheck_draw_col() at next char
1187
1188  char buf_fold[FOLD_TEXT_LEN];         // Hold value returned by get_foldtext
1189  VirtText fold_vt = VIRTTEXT_EMPTY;
1190  char *foldtext_free = NULL;
1191
1192  // 'cursorlineopt' has "screenline" and cursor is in this line
1193  bool cul_screenline = false;
1194  // margin columns for the screen line, needed for when 'cursorlineopt'
1195  // contains "screenline"
1196  int left_curline_col = 0;
1197  int right_curline_col = 0;
1198
1199  int match_conc = 0;              ///< cchar for match functions
1200  bool on_last_col = false;
1201  int syntax_flags = 0;
1202  int syntax_seqnr = 0;
1203  int prev_syntax_id = 0;
1204  int conceal_attr = win_hl_attr(wp, HLF_CONCEAL);
1205  bool is_concealing = false;
1206  bool did_wcol = false;
1207#define vcol_hlc(wlv) ((wlv).vcol - (wlv).vcol_off_co)
1208
1209  assert(startrow < endrow);
1210
1211  // variables passed between functions
1212  winlinevars_T wlv = {
1213    .lnum = lnum,
1214    .foldinfo = foldinfo,
1215    .startrow = startrow,
1216    .row = startrow,
1217    .fromcol = -10,
1218    .tocol = MAXCOL,
1219    .vcol_sbr = -1,
1220    .old_boguscols = 0,
1221    .prev_num_attr = -1,
1222  };
1223
1224  buf_T *buf = wp->w_buffer;
1225  // Not drawing text when line is concealed or drawing filler lines beyond last line.
1226  const bool draw_text = !concealed && (lnum != buf->b_ml.ml_line_count + 1);
1227
1228  int decor_provider_end_col;
1229  bool check_decor_providers = false;
1230
1231  if (col_rows == 0 && draw_text) {
1232    // To speed up the loop below, set extra_check when there is linebreak,
1233    // trailing white space and/or syntax processing to be done.
1234    extra_check = wp->w_p_lbr;
1235    if (syntax_present(wp) && !wp->w_s->b_syn_error && !wp->w_s->b_syn_slow && !has_foldtext) {
1236      // Prepare for syntax highlighting in this line.  When there is an
1237      // error, stop syntax highlighting.
1238      int save_did_emsg = did_emsg;
1239      did_emsg = false;
1240      syntax_start(wp, lnum);
1241      if (did_emsg) {
1242        wp->w_s->b_syn_error = true;
1243      } else {
1244        did_emsg = save_did_emsg;
1245        if (!wp->w_s->b_syn_slow) {
1246          has_syntax = true;
1247          extra_check = true;
1248        }
1249      }
1250    }
1251
1252    check_decor_providers = true;
1253
1254    // Check for columns to display for 'colorcolumn'.
1255    wlv.color_cols = wp->w_buffer->terminal ? NULL : wp->w_p_cc_cols;
1256    advance_color_col(&wlv, vcol_hlc(wlv));
1257
1258    // handle Visual active in this window
1259    if (Visual.active && wp->w_buffer == curwin->w_buffer) {
1260      pos_T *top, *bot;
1261
1262      if (ltoreq(curwin->w_cursor, Visual.start)) {
1263        // Visual is after curwin->w_cursor
1264        top = &curwin->w_cursor;
1265        bot = &Visual.start;
1266      } else {
1267        // Visual is before curwin->w_cursor
1268        top = &Visual.start;
1269        bot = &curwin->w_cursor;
1270      }
1271      lnum_in_visual_area = (lnum >= top->lnum && lnum <= bot->lnum);
1272      if (Visual.mode == Ctrl_V) {
1273        // block mode
1274        if (lnum_in_visual_area) {
1275          wlv.fromcol = wp->w_old_cursor_fcol;
1276          wlv.tocol = wp->w_old_cursor_lcol;
1277        }
1278      } else {
1279        // non-block mode
1280        if (lnum > top->lnum && lnum <= bot->lnum) {
1281          wlv.fromcol = 0;
1282        } else if (lnum == top->lnum) {
1283          if (Visual.mode == 'V') {       // linewise
1284            wlv.fromcol = 0;
1285          } else {
1286            getvvcol(wp, top, &wlv.fromcol, NULL, NULL, 0);
1287            if (gchar_pos(top) == NUL) {
1288              wlv.tocol = wlv.fromcol + 1;
1289            }
1290          }
1291        }
1292        if (Visual.mode != 'V' && lnum == bot->lnum) {
1293          if (*p_sel == 'e' && bot->col == 0
1294              && bot->coladd == 0) {
1295            wlv.fromcol = -10;
1296            wlv.tocol = MAXCOL;
1297          } else if (bot->col == MAXCOL) {
1298            wlv.tocol = MAXCOL;
1299          } else {
1300            pos_T pos = *bot;
1301            if (*p_sel == 'e') {
1302              getvvcol(wp, &pos, &wlv.tocol, NULL, NULL, 0);
1303            } else {
1304              getvvcol(wp, &pos, NULL, NULL, &wlv.tocol, 0);
1305              wlv.tocol++;
1306            }
1307          }
1308        }
1309      }
1310
1311      // if inverting in this line set area_highlighting
1312      if (wlv.fromcol >= 0) {
1313        area_highlighting = true;
1314        vi_attr = win_hl_attr(wp, HLF_V);
1315      }
1316      // handle 'incsearch' and ":s///c" highlighting
1317    } else if (Search.hl_match
1318               && wp == curwin
1319               && !has_foldtext
1320               && lnum >= curwin->w_cursor.lnum
1321               && lnum <= curwin->w_cursor.lnum + Search.match_lines) {
1322      if (lnum == curwin->w_cursor.lnum) {
1323        getvcol(curwin, &(curwin->w_cursor), &wlv.fromcol, NULL, NULL, 0);
1324      } else {
1325        wlv.fromcol = 0;
1326      }
1327      if (lnum == curwin->w_cursor.lnum + Search.match_lines) {
1328        pos_T pos = {
1329          .lnum = lnum,
1330          .col = Search.match_endcol,
1331        };
1332        getvcol(curwin, &pos, &wlv.tocol, NULL, NULL, 0);
1333      }
1334      // do at least one character; happens when past end of line
1335      if (wlv.fromcol == wlv.tocol && Search.match_endcol) {
1336        wlv.tocol = wlv.fromcol + 1;
1337      }
1338      area_highlighting = true;
1339      vi_attr = win_hl_attr(wp, HLF_I);
1340    }
1341  }
1342
1343  int bg_attr = win_bg_attr(wp);
1344
1345  int linestatus = 0;
1346  wlv.filler_lines = diff_check_with_linestatus(wp, lnum, &linestatus);
1347  diffline_T line_changes = { 0 };
1348  int change_index = -1;
1349  if (linestatus < 0) {
1350    if (linestatus == -1) {
1351      if (diff_find_change(wp, lnum, &line_changes)) {
1352        wlv.diff_hlf = HLF_ADD;      // added line
1353      } else if (line_changes.num_changes > 0) {
1354        bool added = diff_change_parse(&line_changes, &line_changes.changes[0],
1355                                       &change_start, &change_end);
1356        if (change_start == 0) {
1357          if (added) {
1358            wlv.diff_hlf = HLF_TXA;  // added text on changed line
1359          } else {
1360            wlv.diff_hlf = HLF_TXD;  // changed text on changed line
1361          }
1362        } else {
1363          wlv.diff_hlf = HLF_CHD;    // unchanged text on changed line
1364        }
1365        change_index = 0;
1366      } else {
1367        wlv.diff_hlf = HLF_CHD;      // changed line
1368        change_index = 0;
1369      }
1370    } else {
1371      wlv.diff_hlf = HLF_ADD;               // added line
1372    }
1373    area_highlighting = true;
1374  }
1375  VirtLines virt_lines = KV_INITIAL_VALUE;
1376  wlv.n_virt_lines = decor_virt_lines(wp, lnum - 1, lnum, &wlv.n_virt_below, &virt_lines, true);
1377  // Preserving count of virt_lines for topline visibility
1378  int total_virt_rows = wlv.n_virt_lines;
1379  wlv.filler_lines += wlv.n_virt_lines;
1380  if (lnum == wp->w_topline) {
1381    wlv.virt_below_skip = MIN(wlv.n_virt_below, wlv.n_virt_lines - wp->w_topfill);
1382    wlv.n_virt_below -= wlv.virt_below_skip;
1383    wlv.filler_lines_skip = wlv.filler_lines - wlv.virt_below_skip - wp->w_topfill;
1384    wlv.filler_lines = wp->w_topfill;
1385    wlv.n_virt_lines = MIN(wlv.n_virt_lines, wlv.filler_lines);
1386  }
1387  wlv.filler_todo = wlv.filler_lines;
1388
1389  // Cursor line highlighting for 'cursorline' in the current window.
1390  if (wp->w_p_cul && wp->w_p_culopt_flags != kOptCuloptFlagNumber && lnum == wp->w_cursorline
1391      // Do not show the cursor line in the text when Visual mode is active,
1392      // because it's not clear what is selected then.
1393      && !(wp == curwin && Visual.active)) {
1394    cul_screenline = (is_wrapped && (wp->w_p_culopt_flags & kOptCuloptFlagScreenline));
1395    if (!cul_screenline) {
1396      apply_cursorline_highlight(wp, &wlv);
1397    } else {
1398      margin_columns_win(wp, &left_curline_col, &right_curline_col);
1399    }
1400    area_highlighting = true;
1401  }
1402
1403  int sign_line_attr = 0;
1404  // TODO(bfredl, vigoux): line_attr should not take priority over decoration!
1405  decor_redraw_signs(wp, buf, wlv.lnum - 1, wlv.sattrs,
1406                     &sign_line_attr, &wlv.sign_cul_attr, &wlv.sign_num_attr);
1407
1408  statuscol_T statuscol = { 0 };
1409  if (*wp->w_p_stc != NUL) {
1410    // Draw the 'statuscolumn' if option is set.
1411    statuscol.draw = true;
1412    statuscol.sattrs = wlv.sattrs;
1413    statuscol.lnum = lnum;
1414    statuscol.foldinfo = foldinfo;
1415    statuscol.width = win_col_off(wp);
1416    statuscol.sign_cul_id = use_cursor_line_highlight(wp, lnum) ? wlv.sign_cul_attr : 0;
1417  } else if (wlv.sign_cul_attr > 0) {
1418    wlv.sign_cul_attr = use_cursor_line_highlight(wp, lnum) ? syn_id2attr(wlv.sign_cul_attr) : 0;
1419  }
1420  if (wlv.sign_num_attr > 0) {
1421    wlv.sign_num_attr = syn_id2attr(wlv.sign_num_attr);
1422  }
1423  if (sign_line_attr > 0) {
1424    wlv.line_attr = syn_id2attr(sign_line_attr);
1425  }
1426
1427  // Highlight the current line in the quickfix window.
1428  if (bt_quickfix(wp->w_buffer) && qf_current_entry(wp) == lnum) {
1429    wlv.line_attr = win_hl_attr(wp, HLF_QFL);
1430  }
1431
1432  if (wlv.line_attr_lowprio || wlv.line_attr) {
1433    area_highlighting = true;
1434  }
1435
1436  int line_attr_save = wlv.line_attr;
1437  int line_attr_lowprio_save = wlv.line_attr_lowprio;
1438
1439  if (spv->spv_has_spell && col_rows == 0 && draw_text) {
1440    // Prepare for spell checking.
1441    extra_check = true;
1442
1443    // When a word wrapped from the previous line the start of the
1444    // current line is valid.
1445    if (lnum == spv->spv_checked_lnum) {
1446      cur_checked_col = spv->spv_checked_col;
1447    }
1448    // Previous line was not spell checked, check for capital. This happens
1449    // for the first line in an updated region or after a closed fold.
1450    if (spv->spv_capcol_lnum == 0 && check_need_cap(wp, lnum, 0)) {
1451      spv->spv_cap_col = 0;
1452    } else if (lnum != spv->spv_capcol_lnum) {
1453      spv->spv_cap_col = -1;
1454    }
1455    spv->spv_checked_lnum = 0;
1456
1457    // Get the start of the next line, so that words that wrap to the
1458    // next line are found too: "et<line-break>al.".
1459    // Trick: skip a few chars for C/shell/Vim comments
1460    nextline[SPWORDLEN] = NUL;
1461    if (lnum < wp->w_buffer->b_ml.ml_line_count) {
1462      char *line = ml_get_buf(wp->w_buffer, lnum + 1);
1463      spell_cat_line(nextline + SPWORDLEN, line, SPWORDLEN);
1464    }
1465    char *line = ml_get_buf(wp->w_buffer, lnum);
1466
1467    // If current line is empty, check first word in next line for capital.
1468    char *ptr = skipwhite(line);
1469    if (*ptr == NUL) {
1470      spv->spv_cap_col = 0;
1471      spv->spv_capcol_lnum = lnum + 1;
1472    } else if (spv->spv_cap_col == 0) {
1473      // For checking first word with a capital skip white space.
1474      spv->spv_cap_col = (int)(ptr - line);
1475    }
1476
1477    // Copy the end of the current line into nextline[].
1478    if (nextline[SPWORDLEN] == NUL) {
1479      // No next line or it is empty.
1480      nextlinecol = MAXCOL;
1481      nextline_idx = 0;
1482    } else {
1483      const colnr_T line_len = ml_get_buf_len(wp->w_buffer, lnum);
1484      if (line_len < SPWORDLEN) {
1485        // Short line, use it completely and append the start of the
1486        // next line.
1487        nextlinecol = 0;
1488        memmove(nextline, line, (size_t)line_len);
1489        STRMOVE(nextline + line_len, nextline + SPWORDLEN);
1490        nextline_idx = line_len + 1;
1491      } else {
1492        // Long line, use only the last SPWORDLEN bytes.
1493        nextlinecol = line_len - SPWORDLEN;
1494        memmove(nextline, line + nextlinecol, SPWORDLEN);
1495        nextline_idx = SPWORDLEN + 1;
1496      }
1497    }
1498  }
1499
1500  // current line
1501  char *line = draw_text ? ml_get_buf(wp->w_buffer, lnum) : "";
1502  // current position in "line"
1503  char *ptr = line;
1504
1505  colnr_T trailcol = MAXCOL;  // start of trailing spaces
1506  colnr_T leadcol = 0;        // start of leading spaces
1507
1508  bool lcs_eol_todo = true;  // need to keep track of this even if lcs_eol is NUL
1509  const schar_T lcs_eol = wp->w_p_lcs_chars.eol;  // 'eol' value
1510  schar_T lcs_prec_todo = wp->w_p_lcs_chars.prec;  // 'prec' until it's been used, then NUL
1511
1512  if (wp->w_p_list && !has_foldtext && draw_text) {
1513    if (wp->w_p_lcs_chars.space
1514        || wp->w_p_lcs_chars.multispace != NULL
1515        || wp->w_p_lcs_chars.leadmultispace != NULL
1516        || wp->w_p_lcs_chars.trail
1517        || wp->w_p_lcs_chars.lead
1518        || wp->w_p_lcs_chars.nbsp) {
1519      extra_check = true;
1520    }
1521    // find start of trailing whitespace
1522    if (wp->w_p_lcs_chars.trail) {
1523      trailcol = ml_get_buf_len(wp->w_buffer, lnum);
1524      while (trailcol > 0 && ascii_iswhite(ptr[trailcol - 1])) {
1525        trailcol--;
1526      }
1527      trailcol += (colnr_T)(ptr - line);
1528    }
1529    // find end of leading whitespace
1530    if (wp->w_p_lcs_chars.lead || wp->w_p_lcs_chars.leadmultispace != NULL
1531        || wp->w_p_lcs_chars.leadtab1 != NUL) {
1532      leadcol = 0;
1533      while (ascii_iswhite(ptr[leadcol])) {
1534        leadcol++;
1535      }
1536      if (ptr[leadcol] == NUL) {
1537        // in a line full of spaces all of them are treated as trailing
1538        leadcol = 0;
1539      } else {
1540        // keep track of the first column not filled with spaces
1541        leadcol += (colnr_T)(ptr - line + 1);
1542      }
1543    }
1544  }
1545
1546  // 'nowrap' or 'wrap' and a single line that doesn't fit: Advance to the
1547  // first character to be displayed.
1548  const int start_vcol = wp->w_p_wrap
1549                         ? (startrow == 0 ? wp->w_skipcol : 0)
1550                         : wp->w_leftcol;
1551
1552  if (has_foldtext) {
1553    wlv.vcol = start_vcol;
1554  } else if (start_vcol > 0 && col_rows == 0) {
1555    char *prev_ptr = ptr;
1556    CharSize cs = { 0 };
1557
1558    CharsizeArg csarg;
1559    CSType cstype = init_charsize_arg(&csarg, wp, lnum, line);
1560    csarg.max_head_vcol = start_vcol;
1561    int vcol = wlv.vcol;
1562    StrCharInfo ci = utf_ptr2StrCharInfo(ptr);
1563    while (vcol < start_vcol) {
1564      ClusterInfo cli = utf_ClusterInfo(ci);
1565      cs = win_charsize(cstype, vcol, ci.ptr, ci.chr.value, &csarg, cli.cells);
1566      vcol += cs.width;
1567      prev_ptr = ci.ptr;
1568      if (*prev_ptr == NUL) {
1569        break;
1570      }
1571      ci = cli.next;
1572      if (wp->w_p_list) {
1573        in_multispace = *prev_ptr == ' ' && (*ci.ptr == ' '
1574                                             || (prev_ptr > line && prev_ptr[-1] == ' '));
1575        if (!in_multispace) {
1576          multispace_pos = 0;
1577        } else if (ci.ptr >= line + leadcol
1578                   && wp->w_p_lcs_chars.multispace != NULL) {
1579          multispace_pos++;
1580          if (wp->w_p_lcs_chars.multispace[multispace_pos] == NUL) {
1581            multispace_pos = 0;
1582          }
1583        } else if (ci.ptr < line + leadcol
1584                   && wp->w_p_lcs_chars.leadmultispace != NULL) {
1585          multispace_pos++;
1586          if (wp->w_p_lcs_chars.leadmultispace[multispace_pos] == NUL) {
1587            multispace_pos = 0;
1588          }
1589        }
1590      }
1591    }
1592    wlv.vcol = vcol;
1593    ptr = ci.ptr;
1594    int charsize = cs.width;
1595    int head = cs.head;
1596
1597    // When:
1598    // - 'cuc' is set, or
1599    // - 'colorcolumn' is set, or
1600    // - 'virtualedit' is set, or
1601    // - the visual mode is active, or
1602    // - drawing a fold
1603    // the end of the line may be before the start of the displayed part.
1604    if (wlv.vcol < start_vcol && (wp->w_p_cuc
1605                                  || wlv.color_cols
1606                                  || virtual_active(wp)
1607                                  || (Visual.active && wp->w_buffer == curwin->w_buffer)
1608                                  || has_fold)) {
1609      wlv.vcol = start_vcol;
1610    }
1611
1612    // Handle a character that's not completely on the screen: Put ptr at
1613    // that character but skip the first few screen characters.
1614    if (wlv.vcol > start_vcol) {
1615      wlv.vcol -= charsize;
1616      ptr = prev_ptr;
1617    }
1618
1619    if (start_vcol > wlv.vcol) {
1620      wlv.skip_cells = start_vcol - wlv.vcol - head;
1621    }
1622
1623    // Adjust for when the inverted text is before the screen,
1624    // and when the start of the inverted text is before the screen.
1625    if (wlv.tocol <= wlv.vcol) {
1626      wlv.fromcol = 0;
1627    } else if (wlv.fromcol >= 0 && wlv.fromcol < wlv.vcol) {
1628      wlv.fromcol = wlv.vcol;
1629    }
1630
1631    // When w_skipcol is non-zero, first line needs 'showbreak'
1632    if (wp->w_p_wrap) {
1633      wlv.need_showbreak = true;
1634    }
1635    // When spell checking a word we need to figure out the start of the
1636    // word and if it's badly spelled or not.
1637    if (spv->spv_has_spell) {
1638      colnr_T linecol = (colnr_T)(ptr - line);
1639      hlf_T spell_hlf = HLF_COUNT;
1640
1641      pos_T pos = wp->w_cursor;
1642      wp->w_cursor.lnum = lnum;
1643      wp->w_cursor.col = linecol;
1644      size_t len = spell_move_to(wp, FORWARD, SMT_ALL, true, &spell_hlf);
1645
1646      // spell_move_to() may call ml_get() and make "line" invalid
1647      line = ml_get_buf(wp->w_buffer, lnum);
1648      ptr = line + linecol;
1649
1650      if (len == 0 || wp->w_cursor.col > linecol) {
1651        // no bad word found at line start, don't check until end of a
1652        // word
1653        spell_hlf = HLF_COUNT;
1654        word_end = (int)(spell_to_word_end(ptr, wp) - line + 1);
1655      } else {
1656        // bad word found, use attributes until end of word
1657        assert(len <= INT_MAX);
1658        word_end = wp->w_cursor.col + (int)len + 1;
1659
1660        // Turn index into actual attributes.
1661        if (spell_hlf != HLF_COUNT) {
1662          spell_attr = highlight_attr[spell_hlf];
1663        }
1664      }
1665      wp->w_cursor = pos;
1666
1667      // Need to restart syntax highlighting for this line.
1668      if (has_syntax) {
1669        syntax_start(wp, lnum);
1670      }
1671    }
1672  }
1673
1674  if (check_decor_providers) {
1675    int const col = (int)(ptr - line);
1676    decor_provider_end_col = decor_providers_setup(endrow - startrow,
1677                                                   start_vcol == 0,
1678                                                   lnum,
1679                                                   col,
1680                                                   wp);
1681    line = ml_get_buf(wp->w_buffer, lnum);
1682    ptr = line + col;
1683  }
1684
1685  decor_redraw_line(wp, lnum - 1, &decor_state);
1686  if (!has_decor && decor_has_more_decorations(&decor_state, lnum - 1)) {
1687    has_decor = true;
1688    extra_check = true;
1689  }
1690
1691  if (wlv.fromcol >= wlv.tocol) {
1692    wlv.fromcol = -1;
1693  }
1694
1695  if (col_rows == 0 && draw_text && !has_foldtext) {
1696    const int v = (int)(ptr - line);
1697    area_highlighting |= prepare_search_hl_line(wp, lnum, v,
1698                                                &line, &screen_search_hl, &search_attr,
1699                                                &search_attr_from_match);
1700    ptr = line + v;  // "line" may have been updated
1701  }
1702
1703  if ((State & MODE_INSERT) && ins_compl_win_active(wp)
1704      && (in_curline || ins_compl_lnum_in_range(lnum))) {
1705    area_highlighting = true;
1706  }
1707
1708  win_line_start(wp, &wlv);
1709  bool draw_cols = true;
1710  int leftcols_width = 0;
1711
1712  // won't highlight after TERM_ATTRS_MAX columns
1713  int term_attrs[TERM_ATTRS_MAX] = { 0 };
1714  if (wp->w_buffer->terminal) {
1715    terminal_get_line_attributes(wp->w_buffer->terminal, wp, lnum, term_attrs);
1716    extra_check = true;
1717  }
1718
1719  const bool may_have_inline_virt
1720    = !has_foldtext && buf_meta_total(wp->w_buffer, kMTMetaInline) > 0;
1721  bool has_virt_line = false;
1722  int virt_line_flags = 0;
1723  // Index into virt_lines and the starting row of that line (virt_line_start_row).
1724  // Both persist across iterations to avoid traversing previously visited rows.
1725  int virt_line_index = 0;
1726  int virt_line_start_row = 0;
1727  int virt_line_skip_cells = 0;
1728
1729  // Repeat for each cell in the displayed line.
1730  while (true) {
1731    int has_match_conc = 0;  ///< match wants to conceal
1732    int decor_conceal = 0;
1733
1734    bool did_decrement_ptr = false;
1735
1736    // Get next chunk of extmark highlights if previous approximation was smaller than needed.
1737    if (check_decor_providers && (int)(ptr - line) >= decor_provider_end_col) {
1738      int const col = (int)(ptr - line);
1739      decor_provider_end_col = invoke_range_next(wp, lnum, col, 100);
1740      line = ml_get_buf(wp->w_buffer, lnum);
1741      ptr = line + col;
1742      if (!has_decor && decor_has_more_decorations(&decor_state, lnum - 1)) {
1743        has_decor = true;
1744        extra_check = true;
1745      }
1746    }
1747
1748    // Skip this quickly when working on the text.
1749    if (draw_cols) {
1750      if (cul_screenline) {
1751        wlv.cul_attr = 0;
1752        wlv.line_attr = line_attr_save;
1753        wlv.line_attr_lowprio = line_attr_lowprio_save;
1754      }
1755
1756      assert(wlv.off == 0);
1757
1758      if (wlv.filler_todo > 0) {
1759        // nvim_buf_set_extmark: virt_lines_overflow
1760        int virt_rows_todo = wlv.filler_todo - (wlv.filler_lines - wlv.n_virt_lines);
1761        if (virt_rows_todo > 0) {
1762          int target_row = total_virt_rows - virt_rows_todo;
1763          // Count number of rows spanned by virtual line.
1764          // Find the virtual line containing the target row.
1765          // Set skip cells with the same row-counting function so offset calculation stays in sync
1766          for (; virt_line_index < (int)kv_size(virt_lines); virt_line_index++) {
1767            int line_rows = decor_virt_line_rows(wp, &kv_A(virt_lines, virt_line_index), 0, NULL);
1768            if (target_row < virt_line_start_row + line_rows) {
1769              has_virt_line = true;
1770              virt_line_flags = kv_A(virt_lines, virt_line_index).flags;
1771              decor_virt_line_rows(wp, &kv_A(virt_lines, virt_line_index),
1772                                   target_row - virt_line_start_row,
1773                                   &virt_line_skip_cells);
1774              break;
1775            }
1776            virt_line_start_row += line_rows;
1777          }
1778        }
1779      }
1780
1781      if (has_virt_line && (virt_line_flags & kVLLeftcol)) {
1782        // skip columns
1783      } else if (statuscol.draw) {
1784        // Draw 'statuscolumn' if it is set.
1785        const int v = (int)(ptr - line);
1786        draw_statuscol(wp, &wlv, col_rows, &statuscol);
1787        if (wp->w_redr_statuscol) {
1788          break;
1789        }
1790        if (draw_text) {
1791          // Get the line again as evaluating 'statuscolumn' may free it.
1792          line = ml_get_buf(wp->w_buffer, lnum);
1793          ptr = line + v;
1794        }
1795      } else {
1796        // draw builtin info columns: fold, sign, number
1797        draw_foldcolumn(wp, &wlv);
1798
1799        // wp->w_scwidth is zero if signcol=number is used
1800        for (int sign_idx = 0; sign_idx < wp->w_scwidth; sign_idx++) {
1801          draw_sign(false, wp, &wlv, sign_idx);
1802        }
1803
1804        draw_lnum_col(wp, &wlv);
1805      }
1806
1807      win_col_offset = wlv.off;
1808
1809      // When only updating the columns and that's done, stop here.
1810      if (col_rows > 0) {
1811        wlv_put_linebuf(wp, &wlv, MIN(wlv.off, view_width), false, bg_attr, 0);
1812        // Need to update more screen lines if:
1813        // - 'statuscolumn' needs to be drawn, or
1814        // - LineNrAbove or LineNrBelow is used, or
1815        // - still drawing filler lines.
1816        if ((wlv.row + 1 - wlv.startrow < col_rows
1817             && (statuscol.draw
1818                 || win_hl_attr(wp, HLF_LNA) != win_hl_attr(wp, HLF_N)
1819                 || win_hl_attr(wp, HLF_LNB) != win_hl_attr(wp, HLF_N)))
1820            || wlv.filler_todo > 0) {
1821          wlv.row++;
1822          if (wlv.row == endrow) {
1823            break;
1824          }
1825          wlv.filler_todo--;
1826          has_virt_line = false;
1827          if (wlv.filler_todo == 0 && (wp->w_botfill || !draw_text)) {
1828            break;
1829          }
1830          // win_line_start(wp, &wlv);
1831          wlv.col = 0;
1832          wlv.off = 0;
1833          continue;
1834        } else {
1835          break;
1836        }
1837      }
1838
1839      // Check if 'breakindent' applies and show it. Like the 'linebreak' filler, attrs must not
1840      // extend into this gap either (see attr_has_line_deco()).
1841      int const gap_decor_attr = attr_has_line_deco(gap_attr_save) ? 0 : gap_attr_save;
1842      if (!wp->w_briopt_sbr) {
1843        handle_breakindent(wp, &wlv, gap_decor_attr);
1844      }
1845      handle_showbreak_and_filler(wp, &wlv, gap_decor_attr);
1846      if (wp->w_briopt_sbr) {
1847        handle_breakindent(wp, &wlv, gap_decor_attr);
1848      }
1849
1850      wlv.col = wlv.off;
1851      draw_cols = false;
1852      if (wlv.filler_todo <= 0) {
1853        leftcols_width = wlv.off;
1854      }
1855      if (has_decor && wlv.row == startrow + wlv.filler_lines) {
1856        // hide virt_text on text hidden by 'nowrap' or 'smoothscroll'
1857        decor_redraw_col(wp, (colnr_T)(ptr - line) - 1, wlv.off, true, &decor_state,
1858                         decor_provider_end_col - 1);
1859      }
1860      if (wlv.col >= view_width) {
1861        wlv.col = wlv.off = view_width;
1862        goto end_check;
1863      }
1864    }
1865
1866    if (cul_screenline && wlv.filler_todo <= 0
1867        && wlv.vcol >= left_curline_col && wlv.vcol < right_curline_col) {
1868      apply_cursorline_highlight(wp, &wlv);
1869    }
1870
1871    // When still displaying '$' of change command, stop at cursor.
1872    if (dollar_vcol >= 0 && in_curline && wlv.vcol >= wp->w_virtcol) {
1873      draw_virt_text(wp, buf, win_col_offset, &wlv.col, wlv.row);
1874      // don't clear anything after wlv.col
1875      wlv_put_linebuf(wp, &wlv, wlv.col, false, bg_attr, 0);
1876      // Pretend we have finished updating the window.  Except when
1877      // 'cursorcolumn' is set.
1878      if (wp->w_p_cuc) {
1879        wlv.row = wp->w_cline_row + wp->w_cline_height;
1880      } else {
1881        wlv.row = view_height;
1882      }
1883      break;
1884    }
1885
1886    const bool draw_folded = has_fold && wlv.row == startrow + wlv.filler_lines;
1887    if (draw_folded && wlv.n_extra == 0) {
1888      wlv.char_attr = folded_attr = win_hl_attr(wp, HLF_FL);
1889      decor_attr = 0;
1890    }
1891
1892    int extmark_attr = 0;
1893    if (wlv.filler_todo <= 0
1894        && (area_highlighting || spv->spv_has_spell || extra_check)) {
1895      if (wlv.n_extra == 0 || !wlv.extra_for_extmark) {
1896        wlv.reset_extra_attr = false;
1897      }
1898
1899      if (has_decor && wlv.n_extra == 0) {
1900        // Duplicate the Visual area check after this block,
1901        // but don't check inside p_extra here.
1902        if (wlv.vcol == wlv.fromcol
1903            || (wlv.vcol + 1 == wlv.fromcol
1904                && (wlv.n_extra == 0 && utf_ptr2cells(ptr) > 1))) {
1905          area_active = true;
1906        } else if (area_active && (wlv.vcol == wlv.tocol)) {
1907          area_active = false;
1908        }
1909
1910        bool selected = area_active;
1911        // When there may be inline virtual text, position of non-inline virtual text
1912        // can only be decided after drawing inline virtual text with lower priority.
1913        if (decor_need_recheck) {
1914          if (!may_have_inline_virt) {
1915            decor_recheck_draw_col(wlv.off, selected, &decor_state);
1916          }
1917          decor_need_recheck = false;
1918        }
1919        extmark_attr = decor_redraw_col(wp, (colnr_T)(ptr - line),
1920                                        may_have_inline_virt ? -3 : wlv.off,
1921                                        selected, &decor_state, decor_provider_end_col - 1);
1922        if (may_have_inline_virt) {
1923          handle_inline_virtual_text(wp, &wlv, ptr - line, selected);
1924          if (wlv.n_extra > 0 && wlv.virt_inline_hl_mode <= kHlModeReplace) {
1925            // restore search_attr and area_attr when n_extra is down to zero
1926            // TODO(bfredl): this is ugly as fuck. look if we can do this some other way.
1927            saved_search_attr = search_attr;
1928            saved_area_attr = area_attr;
1929            saved_decor_attr = decor_attr;
1930            saved_search_attr_from_match = search_attr_from_match;
1931            search_attr = 0;
1932            area_attr = 0;
1933            decor_attr = 0;
1934            search_attr_from_match = false;
1935          }
1936        }
1937      }
1938
1939      int *area_attr_p = wlv.extra_for_extmark && wlv.virt_inline_hl_mode <= kHlModeReplace
1940                         ? &saved_area_attr : &area_attr;
1941
1942      // handle Visual or match highlighting in this line
1943      if (wlv.vcol == wlv.fromcol
1944          || (wlv.vcol + 1 == wlv.fromcol
1945              && ((wlv.n_extra == 0 && utf_ptr2cells(ptr) > 1)
1946                  || (wlv.n_extra > 0 && wlv.p_extra != NULL
1947                      && utf_ptr2cells(wlv.p_extra) > 1)))) {
1948        *area_attr_p = vi_attr;                     // start highlighting
1949        area_active = true;
1950      } else if (*area_attr_p != 0 && wlv.vcol == wlv.tocol) {
1951        *area_attr_p = 0;                           // stop highlighting
1952        area_active = false;
1953      }
1954
1955      if (!has_foldtext && wlv.n_extra == 0) {
1956        // Check for start/end of 'hlsearch' and other matches.
1957        // After end, check for start/end of next match.
1958        // When another match, have to check for start again.
1959        const int v = (int)(ptr - line);
1960        search_attr = update_search_hl(wp, lnum, v, &line, &screen_search_hl,
1961                                       &has_match_conc, &match_conc, lcs_eol_todo,
1962                                       &on_last_col, &search_attr_from_match);
1963        ptr = line + v;  // "line" may have been changed
1964
1965        // Do not allow a conceal over EOL otherwise EOL will be missed
1966        // and bad things happen.
1967        if (*ptr == NUL) {
1968          has_match_conc = 0;
1969        }
1970
1971        // Check if ComplMatchIns highlight is needed.
1972        if ((State & MODE_INSERT) && ins_compl_win_active(wp)
1973            && (in_curline || ins_compl_lnum_in_range(lnum))) {
1974          int ins_match_attr = ins_compl_col_range_attr(lnum, (int)(ptr - line));
1975          if (ins_match_attr > 0) {
1976            search_attr = hl_combine_attr(search_attr, ins_match_attr);
1977          }
1978        }
1979      }
1980
1981      if (wlv.diff_hlf != (hlf_T)0) {
1982        if (line_changes.num_changes > 0
1983            && change_index >= 0
1984            && change_index < line_changes.num_changes - 1) {
1985          if (ptr - line
1986              >= line_changes.changes[change_index + 1].dc_start[line_changes.bufidx]) {
1987            change_index += 1;
1988          }
1989        }
1990        bool added = false;
1991        if (line_changes.num_changes > 0 && change_index >= 0
1992            && change_index < line_changes.num_changes) {
1993          added = diff_change_parse(&line_changes, &line_changes.changes[change_index],
1994                                    &change_start, &change_end);
1995        }
1996        // When there is extra text (eg: virtual text) it gets the
1997        // diff highlighting for the line, but not for changed text.
1998        if (wlv.diff_hlf == HLF_CHD && ptr - line >= change_start
1999            && wlv.n_extra == 0) {
2000          wlv.diff_hlf = added ? HLF_TXA : HLF_TXD;   // added/changed text
2001        }
2002        if ((wlv.diff_hlf == HLF_TXD || wlv.diff_hlf == HLF_TXA)
2003            && ((ptr - line >= change_end && wlv.n_extra == 0)
2004                || (wlv.n_extra > 0 && wlv.extra_for_extmark))) {
2005          wlv.diff_hlf = HLF_CHD;                     // changed line
2006        }
2007        set_line_attr_for_diff(wp, &wlv);
2008      }
2009
2010      // Decide which of the highlight attributes to use.
2011      if (area_attr != 0) {
2012        char_attr_pri = hl_combine_attr(wlv.line_attr, area_attr);
2013        if (!Search.hl_match) {
2014          // let search highlight show in Visual area if possible
2015          char_attr_pri = hl_combine_attr(search_attr, char_attr_pri);
2016        }
2017      } else if (search_attr != 0) {
2018        char_attr_pri = hl_combine_attr(wlv.line_attr, search_attr);
2019      } else if (wlv.line_attr != 0
2020                 && ((wlv.fromcol == -10 && wlv.tocol == MAXCOL)
2021                     || wlv.vcol < wlv.fromcol
2022                     || wlv.vcol >= wlv.tocol)) {
2023        // Use wlv.line_attr when not in the Visual or 'incsearch' area
2024        char_attr_pri = wlv.line_attr;
2025      } else {
2026        char_attr_pri = 0;
2027      }
2028      char_attr_base = hl_combine_attr(folded_attr, decor_attr);
2029      wlv.char_attr = hl_combine_attr(char_attr_base, char_attr_pri);
2030    }
2031
2032    if (draw_folded && has_foldtext && wlv.n_extra == 0 && wlv.col == win_col_offset) {
2033      const int v = (int)(ptr - line);
2034      linenr_T lnume = lnum + foldinfo.fi_lines - 1;
2035      memset(buf_fold, ' ', FOLD_TEXT_LEN);
2036      wlv.p_extra = get_foldtext(wp, lnum, lnume, foldinfo, buf_fold, &fold_vt);
2037      wlv.n_extra = (int)strlen(wlv.p_extra);
2038
2039      if (wlv.p_extra != buf_fold) {
2040        assert(foldtext_free == NULL);
2041        foldtext_free = wlv.p_extra;
2042      }
2043      wlv.sc_extra = NUL;
2044      wlv.sc_final = NUL;
2045      wlv.p_extra[wlv.n_extra] = NUL;
2046
2047      // Get the line again as evaluating 'foldtext' may free it.
2048      line = ml_get_buf(wp->w_buffer, lnum);
2049      ptr = line + v;
2050    }
2051
2052    // Draw 'fold' fillchar after 'foldtext', or after 'eol' listchar for transparent 'foldtext'.
2053    if (draw_folded && wlv.n_extra == 0 && wlv.col < view_width
2054        && (has_foldtext || (*ptr == NUL && (!wp->w_p_list || !lcs_eol_todo || lcs_eol == NUL)))) {
2055      // Fill rest of line with 'fold'.
2056      wlv.sc_extra = wp->w_p_fcs_chars.fold;
2057      wlv.sc_final = NUL;
2058      wlv.n_extra = view_width - wlv.col;
2059      // Don't continue search highlighting past the first filler char.
2060      search_attr = 0;
2061    }
2062
2063    if (draw_folded && wlv.n_extra != 0 && wlv.col >= view_width) {
2064      // Truncate the folding.
2065      wlv.n_extra = 0;
2066    }
2067
2068    // Get the next character to put on the screen.
2069    //
2070    // The "p_extra" points to the extra stuff that is inserted to
2071    // represent special characters (non-printable stuff) and other
2072    // things.  When all characters are the same, sc_extra is used.
2073    // If sc_final is set, it will compulsorily be used at the end.
2074    // "p_extra" must end in a NUL to avoid utfc_ptr2len() reads past
2075    // "p_extra[n_extra]".
2076    // For the '$' of the 'list' option, n_extra == 1, p_extra == "".
2077    if (wlv.n_extra > 0) {
2078      if (wlv.sc_extra != NUL || (wlv.n_extra == 1 && wlv.sc_final != NUL)) {
2079        mb_schar = (wlv.n_extra == 1 && wlv.sc_final != NUL) ? wlv.sc_final : wlv.sc_extra;
2080        mb_c = schar_get_first_codepoint(mb_schar);
2081        wlv.n_extra--;
2082      } else {
2083        assert(wlv.p_extra != NULL);
2084        mb_l = utfc_ptr2len(wlv.p_extra);
2085        mb_schar = utfc_ptr2schar(wlv.p_extra, &mb_c);
2086        // mb_l=0 at the end-of-line NUL
2087        if (mb_l > wlv.n_extra || mb_l == 0) {
2088          mb_l = 1;
2089        }
2090
2091        // If a double-width char doesn't fit display a '>' in the last column.
2092        // Don't advance the pointer but put the character at the start of the next line.
2093        if (wlv.col >= view_width - 1 && schar_cells(mb_schar) == 2) {
2094          mb_c = '>';
2095          mb_l = 1;
2096          mb_schar = schar_from_ascii(mb_c);
2097          multi_attr = win_hl_attr(wp, HLF_AT);
2098
2099          if (wlv.cul_attr) {
2100            multi_attr = 0 != wlv.line_attr_lowprio
2101                         ? hl_combine_attr(wlv.cul_attr, multi_attr)
2102                         : hl_combine_attr(multi_attr, wlv.cul_attr);
2103          }
2104        } else {
2105          wlv.n_extra -= mb_l;
2106          wlv.p_extra += mb_l;
2107        }
2108
2109        // If a double-width char doesn't fit at the left side display a '<'.
2110        if (wlv.filler_todo <= 0 && wlv.skip_cells > 0 && mb_l > 1) {
2111          if (wlv.n_extra > 0) {
2112            n_extra_next = wlv.n_extra;
2113            extra_attr_next = wlv.extra_attr;
2114          }
2115          wlv.n_extra = 1;
2116          wlv.sc_extra = schar_from_ascii(MB_FILLER_CHAR);
2117          wlv.sc_final = NUL;
2118          mb_schar = schar_from_ascii(' ');
2119          mb_c = ' ';
2120          mb_l = 1;
2121          (void)mb_l;
2122          wlv.n_attr++;
2123          wlv.extra_attr = win_hl_attr(wp, HLF_AT);
2124        }
2125      }
2126
2127      if (wlv.n_extra <= 0) {
2128        // Only restore search_attr and area_attr when there is no "n_extra" to show.
2129        if (n_extra_next <= 0) {
2130          if (search_attr == 0) {
2131            search_attr = saved_search_attr;
2132            saved_search_attr = 0;
2133          }
2134          if (area_attr == 0 && *ptr != NUL) {
2135            area_attr = saved_area_attr;
2136            saved_area_attr = 0;
2137          }
2138          if (decor_attr == 0) {
2139            decor_attr = saved_decor_attr;
2140            saved_decor_attr = 0;
2141          }
2142          if (wlv.extra_for_extmark) {
2143            // wlv.extra_attr should be used at this position but not any further.
2144            wlv.reset_extra_attr = true;
2145            extra_attr_next = -1;
2146          }
2147          wlv.extra_for_extmark = false;
2148        } else {
2149          assert(wlv.sc_extra != NUL || wlv.sc_final != NUL);
2150          assert(wlv.p_extra != NULL);
2151          wlv.sc_extra = NUL;
2152          wlv.sc_final = NUL;
2153          wlv.n_extra = n_extra_next;
2154          n_extra_next = 0;
2155          // wlv.extra_attr should be used at this position, but extra_attr_next
2156          // should be used after that.
2157          wlv.reset_extra_attr = true;
2158          assert(extra_attr_next >= 0);
2159        }
2160      }
2161    } else if (wlv.filler_todo > 0) {
2162      // Wait with reading text until filler lines are done. Still need to
2163      // initialize these.
2164      mb_c = ' ';
2165      mb_schar = schar_from_ascii(' ');
2166    } else if (has_foldtext || (has_fold && wlv.col >= view_width)) {
2167      // skip writing the buffer line itself
2168      mb_schar = NUL;
2169    } else {
2170      const char *prev_ptr = ptr;
2171
2172      // first byte of next char
2173      int c0 = (uint8_t)(*ptr);
2174      if (c0 == NUL) {
2175        // no more cells to skip
2176        wlv.skip_cells = 0;
2177      }
2178
2179      // Get a character from the line itself.
2180      mb_l = utfc_ptr2len(ptr);
2181      mb_schar = utfc_ptr2schar(ptr, &mb_c);
2182
2183      // Overlong encoded ASCII or ASCII with composing char
2184      // is displayed normally, except a NUL.
2185      if (mb_l > 1 && mb_c < 0x80) {
2186        c0 = mb_c;
2187      }
2188
2189      if ((mb_l == 1 && c0 >= 0x80)
2190          || (mb_l >= 1 && mb_c == 0)
2191          || (mb_l > 1 && (!vim_isprintc(mb_c)))) {
2192        // Illegal UTF-8 byte: display as <xx>.
2193        // Non-printable character : display as ? or fullwidth ?.
2194        transchar_hex(wlv.extra, mb_c);
2195        if (wp->w_p_rl) {  // reverse
2196          rl_mirror_ascii(wlv.extra, NULL);
2197        }
2198
2199        wlv.p_extra = wlv.extra;
2200        mb_c = mb_ptr2char_adv((const char **)&wlv.p_extra);
2201        mb_schar = schar_from_char(mb_c);
2202        wlv.n_extra = (int)strlen(wlv.p_extra);
2203        wlv.sc_extra = NUL;
2204        wlv.sc_final = NUL;
2205        if (area_attr == 0 && search_attr == 0) {
2206          wlv.n_attr = wlv.n_extra + 1;
2207          wlv.extra_attr = win_hl_attr(wp, HLF_8);
2208          saved_attr2 = wlv.char_attr;               // save current attr
2209        }
2210      } else if (mb_l == 0) {        // at the NUL at end-of-line
2211        mb_l = 1;
2212      }
2213      // If a double-width char doesn't fit display a '>' in the
2214      // last column; the character is displayed at the start of the
2215      // next line.
2216      if (wlv.col >= view_width - 1 && schar_cells(mb_schar) == 2) {
2217        mb_schar = schar_from_ascii('>');
2218        mb_c = '>';
2219        mb_l = 1;
2220        multi_attr = win_hl_attr(wp, HLF_AT);
2221        // Put pointer back so that the character will be
2222        // displayed at the start of the next line.
2223        ptr--;
2224        did_decrement_ptr = true;
2225      } else if (*ptr != NUL) {
2226        ptr += mb_l - 1;
2227      }
2228
2229      // If a double-width char doesn't fit at the left side display a '<' in
2230      // the first column.  Don't do this for unprintable characters.
2231      if (wlv.skip_cells > 0 && mb_l > 1 && wlv.n_extra == 0) {
2232        wlv.n_extra = 1;
2233        wlv.sc_extra = schar_from_ascii(MB_FILLER_CHAR);
2234        wlv.sc_final = NUL;
2235        mb_schar = schar_from_ascii(' ');
2236        mb_c = ' ';
2237        mb_l = 1;
2238        if (area_attr == 0 && search_attr == 0) {
2239          wlv.n_attr = wlv.n_extra + 1;
2240          wlv.extra_attr = win_hl_attr(wp, HLF_AT);
2241          saved_attr2 = wlv.char_attr;             // save current attr
2242        }
2243      }
2244      ptr++;
2245
2246      decor_attr = 0;
2247      syntax_attr = 0;
2248      if (extra_check) {
2249        const bool no_plain_buffer = (wp->w_s->b_p_spo_flags & kOptSpoFlagNoplainbuffer) != 0;
2250        bool can_spell = !no_plain_buffer;
2251
2252        // Get extmark and syntax attributes, unless still at the start of the line
2253        // (double-wide char that doesn't fit).
2254        const int v = (int)(ptr - line);
2255        const ptrdiff_t prev_v = prev_ptr - line;
2256        if (has_syntax && v > 0) {
2257          // Get the syntax attribute for the character.  If there
2258          // is an error, disable syntax highlighting.
2259          int save_did_emsg = did_emsg;
2260          did_emsg = false;
2261
2262          decor_attr = get_syntax_attr(v - 1, spv->spv_has_spell ? &can_spell : NULL, false);
2263
2264          if (did_emsg) {
2265            wp->w_s->b_syn_error = true;
2266            has_syntax = false;
2267          } else {
2268            did_emsg = save_did_emsg;
2269          }
2270
2271          if (wp->w_s->b_syn_slow) {
2272            has_syntax = false;
2273          }
2274
2275          // Need to get the line again, a multi-line regexp may
2276          // have made it invalid.
2277          line = ml_get_buf(wp->w_buffer, lnum);
2278          ptr = line + v;
2279          prev_ptr = line + prev_v;
2280
2281          // no concealing past the end of the line, it interferes
2282          // with line highlighting.
2283          syntax_flags = (mb_schar == 0) ? 0 : get_syntax_info(&syntax_seqnr);
2284        }
2285
2286        if (has_decor && v > 0) {
2287          // extmarks take preceedence over syntax.c
2288          syntax_attr = decor_attr;
2289          decor_attr = hl_combine_attr(decor_attr, extmark_attr);
2290          decor_conceal = decor_state.conceal;
2291          can_spell = TRISTATE_TO_BOOL(decor_state.spell, can_spell);
2292        }
2293
2294        char_attr_base = hl_combine_attr(folded_attr, decor_attr);
2295        wlv.char_attr = hl_combine_attr(char_attr_base, char_attr_pri);
2296
2297        // Check spelling (unless at the end of the line).
2298        // Only do this when there is no syntax highlighting, the
2299        // @Spell cluster is not used or the current syntax item
2300        // contains the @Spell cluster.
2301        int v1 = (int)(ptr - line);
2302        if (spv->spv_has_spell && v1 >= word_end && v1 > cur_checked_col) {
2303          spell_attr = 0;
2304          // do not calculate cap_col at the end of the line or when
2305          // only white space is following
2306          if (mb_schar != 0 && (*skipwhite(prev_ptr) != NUL) && can_spell) {
2307            char *p;
2308            hlf_T spell_hlf = HLF_COUNT;
2309            v1 -= mb_l - 1;
2310
2311            // Use nextline[] if possible, it has the start of the
2312            // next line concatenated.
2313            if ((prev_ptr - line) - nextlinecol >= 0) {
2314              p = nextline + ((prev_ptr - line) - nextlinecol);
2315            } else {
2316              p = (char *)prev_ptr;
2317            }
2318            spv->spv_cap_col -= (int)(prev_ptr - line);
2319            size_t tmplen = spell_check(wp, p, &spell_hlf, &spv->spv_cap_col, spv->spv_unchanged);
2320            assert(tmplen <= INT_MAX);
2321            int len = (int)tmplen;
2322            word_end = v1 + len;
2323
2324            // In Insert mode only highlight a word that
2325            // doesn't touch the cursor.
2326            if (spell_hlf != HLF_COUNT
2327                && (State & MODE_INSERT)
2328                && wp->w_cursor.lnum == lnum
2329                && wp->w_cursor.col >= (colnr_T)(prev_ptr - line)
2330                && wp->w_cursor.col < (colnr_T)word_end) {
2331              spell_hlf = HLF_COUNT;
2332              spell_redraw_lnum = lnum;
2333            }
2334
2335            if (spell_hlf == HLF_COUNT && p != prev_ptr
2336                && (p - nextline) + len > nextline_idx) {
2337              // Remember that the good word continues at the
2338              // start of the next line.
2339              spv->spv_checked_lnum = lnum + 1;
2340              spv->spv_checked_col = (int)((p - nextline) + len - nextline_idx);
2341            }
2342
2343            // Turn index into actual attributes.
2344            if (spell_hlf != HLF_COUNT) {
2345              spell_attr = highlight_attr[spell_hlf];
2346            }
2347
2348            if (spv->spv_cap_col > 0) {
2349              if (p != prev_ptr && (p - nextline) + spv->spv_cap_col >= nextline_idx) {
2350                // Remember that the word in the next line
2351                // must start with a capital.
2352                spv->spv_capcol_lnum = lnum + 1;
2353                spv->spv_cap_col = (int)((p - nextline) + spv->spv_cap_col - nextline_idx);
2354              } else {
2355                // Compute the actual column.
2356                spv->spv_cap_col += (int)(prev_ptr - line);
2357              }
2358            }
2359          }
2360        }
2361        if (spell_attr != 0) {
2362          char_attr_base = hl_combine_attr(char_attr_base, spell_attr);
2363          wlv.char_attr = hl_combine_attr(char_attr_base, char_attr_pri);
2364        }
2365
2366        if (wp->w_buffer->terminal) {
2367          wlv.char_attr = hl_combine_attr(wlv.vcol < TERM_ATTRS_MAX ? term_attrs[wlv.vcol] : 0,
2368                                          wlv.char_attr);
2369        }
2370
2371        // Gaps ('linebreak' filler, 'breakindent'/'showbreak' padding) show no buffer text, so only
2372        // an "hl_eol" decoration draws there.
2373        gap_attr_save = has_decor ? hl_combine_attr(syntax_attr, decor_state.current_hl_eol)
2374                                  : decor_attr;
2375
2376        // we don't want linebreak to apply for lines that start with
2377        // leading spaces, followed by long letters (since it would add
2378        // a break at the beginning of a line and this might be unexpected)
2379        //
2380        // So only allow to linebreak, once we have found chars not in
2381        // 'breakat' in the line.
2382        if (wp->w_p_lbr && !wlv.need_lbr && mb_schar != NUL
2383            && !vim_isbreak((uint8_t)(*ptr))) {
2384          wlv.need_lbr = true;
2385        }
2386        // Found last space before word: check for line break.
2387        if (wp->w_p_lbr && c0 == mb_c && mb_c < 128 && wlv.need_lbr
2388            && vim_isbreak(mb_c) && !vim_isbreak((uint8_t)(*ptr))) {
2389          int mb_off = utf_head_off(line, ptr - 1);
2390          char *p = ptr - (mb_off + 1);
2391
2392          CharsizeArg csarg;
2393          CSType cstype = init_charsize_arg_skip_cur_text(&csarg, wp, lnum, line);
2394          // TODO(zeertzjq): consider using CharSize.tail here
2395          StrCharInfo ci = utf_ptr2StrCharInfo(p);
2396          ClusterInfo cli = utf_ClusterInfo(ci);
2397          wlv.n_extra = win_charsize(cstype, wlv.vcol, p, ci.chr.value,
2398                                     &csarg, cli.cells).width - 1;
2399
2400          // Do not bleed attrs into the filler for the pushed-down word (TABs keep their own
2401          // full-width highlight; see attr_has_line_deco()). search_attr also resets when its own
2402          // span ends exactly here (on_last_col), matching its pre-existing semantics.
2403          if (mb_c != TAB) {
2404            if (on_last_col || attr_has_line_deco(search_attr)) {
2405              search_attr = 0;
2406            }
2407            if (has_decor) {
2408              decor_attr = gap_attr_save;
2409            }
2410            if (attr_has_line_deco(decor_attr)) {
2411              decor_attr = 0;
2412            }
2413            if (attr_has_line_deco(area_attr)) {
2414              area_attr = 0;
2415            }
2416          }
2417
2418          if (mb_c == TAB && wlv.n_extra + wlv.col > view_width) {
2419            wlv.n_extra = tabstop_padding(wlv.vcol, wp->w_buffer->b_p_ts,
2420                                          wp->w_buffer->b_p_vts_array) - 1;
2421          }
2422          wlv.sc_extra = schar_from_ascii(mb_off > 0 ? MB_FILLER_CHAR : ' ');
2423          wlv.sc_final = NUL;
2424          if (mb_c < 128 && ascii_iswhite(mb_c)) {
2425            if (mb_c == TAB) {
2426              // See "Tab alignment" below.
2427              fix_for_boguscols(&wlv);
2428            }
2429            if (!wp->w_p_list) {
2430              mb_c = ' ';
2431              mb_schar = schar_from_ascii(mb_c);
2432            }
2433          }
2434        }
2435
2436        if (wp->w_p_list) {
2437          in_multispace = mb_c == ' ' && (*ptr == ' ' || (prev_ptr > line && prev_ptr[-1] == ' '));
2438          if (!in_multispace) {
2439            multispace_pos = 0;
2440          }
2441        }
2442
2443        // 'list': Change char 160 to 'nbsp' and space to 'space'.
2444        // But not when the character is followed by a composing
2445        // character (use mb_l to check that).
2446        if (wp->w_p_list
2447            && ((((mb_c == 160 && mb_l == 2) || (mb_c == 0x202f && mb_l == 3))
2448                 && wp->w_p_lcs_chars.nbsp)
2449                || (mb_c == ' '
2450                    && mb_l == 1
2451                    && (wp->w_p_lcs_chars.space
2452                        || (in_multispace && wp->w_p_lcs_chars.multispace != NULL))
2453                    && ptr - line >= leadcol
2454                    && ptr - line <= trailcol))) {
2455          if (in_multispace && wp->w_p_lcs_chars.multispace != NULL) {
2456            mb_schar = wp->w_p_lcs_chars.multispace[multispace_pos++];
2457            if (wp->w_p_lcs_chars.multispace[multispace_pos] == NUL) {
2458              multispace_pos = 0;
2459            }
2460          } else {
2461            mb_schar = (mb_c == ' ') ? wp->w_p_lcs_chars.space : wp->w_p_lcs_chars.nbsp;
2462          }
2463          wlv.n_attr = 1;
2464          wlv.extra_attr = win_hl_attr(wp, HLF_0);
2465          saved_attr2 = wlv.char_attr;  // save current attr
2466          mb_c = schar_get_first_codepoint(mb_schar);
2467        }
2468
2469        if (mb_c == ' ' && mb_l == 1 && ((trailcol != MAXCOL && ptr > line + trailcol)
2470                                         || (leadcol != 0 && ptr < line + leadcol))) {
2471          if (leadcol != 0 && in_multispace && ptr < line + leadcol
2472              && wp->w_p_lcs_chars.leadmultispace != NULL) {
2473            mb_schar = wp->w_p_lcs_chars.leadmultispace[multispace_pos++];
2474            if (wp->w_p_lcs_chars.leadmultispace[multispace_pos] == NUL) {
2475              multispace_pos = 0;
2476            }
2477          } else if (ptr > line + trailcol && wp->w_p_lcs_chars.trail) {
2478            mb_schar = wp->w_p_lcs_chars.trail;
2479          } else if (ptr < line + leadcol && wp->w_p_lcs_chars.lead) {
2480            mb_schar = wp->w_p_lcs_chars.lead;
2481          } else if (leadcol != 0 && wp->w_p_lcs_chars.space) {
2482            mb_schar = wp->w_p_lcs_chars.space;
2483          }
2484
2485          wlv.n_attr = 1;
2486          wlv.extra_attr = win_hl_attr(wp, HLF_0);
2487          saved_attr2 = wlv.char_attr;  // save current attr
2488          mb_c = schar_get_first_codepoint(mb_schar);
2489        }
2490      }
2491
2492      // Handling of non-printable characters.
2493      if (!vim_isprintc(mb_c)) {
2494        // when getting a character from the file, we may have to
2495        // turn it into something else on the way to putting it on the screen.
2496        if (mb_c == TAB && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) {
2497          int tab_len = 0;
2498          colnr_T vcol_adjusted = wlv.vcol;  // removed showbreak length
2499          schar_T lcs_tab1 = wp->w_p_lcs_chars.tab1;
2500          schar_T lcs_tab2 = wp->w_p_lcs_chars.tab2;
2501          schar_T lcs_tab3 = wp->w_p_lcs_chars.tab3;
2502          // check if leadtab is set in 'listchars'
2503          if (wp->w_p_list && wp->w_p_lcs_chars.leadtab1 != NUL
2504              && ptr < line + leadcol) {
2505            lcs_tab1 = wp->w_p_lcs_chars.leadtab1;
2506            lcs_tab2 = wp->w_p_lcs_chars.leadtab2;
2507            lcs_tab3 = wp->w_p_lcs_chars.leadtab3;
2508          }
2509          char *const sbr = get_showbreak_value(wp);
2510
2511          // Only adjust the tab_len, when at the first column after the
2512          // showbreak value was drawn.
2513          if (*sbr != NUL && wlv.vcol == wlv.vcol_sbr && wp->w_p_wrap) {
2514            vcol_adjusted = wlv.vcol - mb_charlen(sbr);
2515          }
2516          // tab amount depends on current column
2517          tab_len = tabstop_padding(vcol_adjusted,
2518                                    wp->w_buffer->b_p_ts,
2519                                    wp->w_buffer->b_p_vts_array) - 1;
2520
2521          if (!wp->w_p_lbr || !wp->w_p_list) {
2522            wlv.n_extra = tab_len;
2523          } else {
2524            int saved_nextra = wlv.n_extra;
2525
2526            if (wlv.vcol_off_co > 0) {
2527              // there are characters to conceal
2528              tab_len += wlv.vcol_off_co;
2529            }
2530            // boguscols before fix_for_boguscols() from above.
2531            if (lcs_tab1 && wlv.old_boguscols > 0 && wlv.n_extra > tab_len) {
2532              tab_len += wlv.n_extra - tab_len;
2533            }
2534
2535            if (tab_len > 0) {
2536              // If wlv.n_extra > 0, it gives the number of chars
2537              // to use for a tab, else we need to calculate the
2538              // width for a tab.
2539              size_t tab2_len = schar_len(lcs_tab2);
2540              size_t len = (size_t)tab_len * tab2_len;
2541              if (lcs_tab3) {
2542                len += schar_len(lcs_tab3) - tab2_len;
2543              }
2544              if (wlv.n_extra > 0) {
2545                len += (size_t)(wlv.n_extra - tab_len);
2546              }
2547              mb_schar = lcs_tab1;
2548              mb_c = schar_get_first_codepoint(mb_schar);
2549              char *p = get_extra_buf(len + 1);
2550              memset(p, ' ', len);
2551              p[len] = NUL;
2552              wlv.p_extra = p;
2553              for (int i = 0; i < tab_len; i++) {
2554                if (*p == NUL) {
2555                  tab_len = i;
2556                  break;
2557                }
2558                schar_T lcs = lcs_tab2;
2559
2560                // if tab3 is given, use it for the last char
2561                if (lcs_tab3 && i == tab_len - 1) {
2562                  lcs = lcs_tab3;
2563                }
2564                size_t slen = schar_get_adv(&p, lcs);
2565                wlv.n_extra += (int)slen - (saved_nextra > 0 ? 1 : 0);
2566              }
2567
2568              // n_extra will be increased by fix_for_boguscols()
2569              // below, so need to adjust for that here
2570              if (wlv.vcol_off_co > 0) {
2571                wlv.n_extra -= wlv.vcol_off_co;
2572              }
2573            }
2574          }
2575
2576          {
2577            int vc_saved = wlv.vcol_off_co;
2578
2579            // Tab alignment should be identical regardless of
2580            // 'conceallevel' value. So tab compensates of all
2581            // previous concealed characters, and thus resets
2582            // vcol_off_co and boguscols accumulated so far in the
2583            // line. Note that the tab can be longer than
2584            // 'tabstop' when there are concealed characters.
2585            fix_for_boguscols(&wlv);
2586
2587            // Make sure, the highlighting for the tab char will be
2588            // correctly set further below (effectively reverts the
2589            // fix_for_boguscols() call).
2590            if (wlv.n_extra == tab_len + vc_saved && wp->w_p_list
2591                && wp->w_p_lcs_chars.tab1) {
2592              tab_len += vc_saved;
2593            }
2594          }
2595
2596          if (wp->w_p_list) {
2597            mb_schar = (wlv.n_extra == 0 && lcs_tab3) ? lcs_tab3 : lcs_tab1;
2598            if (wp->w_p_lbr && wlv.p_extra != NULL && *wlv.p_extra != NUL) {
2599              wlv.sc_extra = NUL;  // using p_extra from above
2600            } else {
2601              wlv.sc_extra = lcs_tab2;
2602            }
2603            wlv.sc_final = lcs_tab3;
2604            wlv.n_attr = tab_len + 1;
2605            wlv.extra_attr = win_hl_attr(wp, HLF_0);
2606            saved_attr2 = wlv.char_attr;  // save current attr
2607          } else {
2608            wlv.sc_final = NUL;
2609            wlv.sc_extra = schar_from_ascii(' ');
2610            mb_schar = schar_from_ascii(' ');
2611          }
2612          mb_c = schar_get_first_codepoint(mb_schar);
2613        } else if (mb_schar == NUL
2614                   && (wp->w_p_list
2615                       || (wlv.fromcol >= 0
2616                           && wlv.tocol > wlv.vcol
2617                           && Visual.mode != Ctrl_V
2618                           && wlv.col < view_width))
2619                   && lcs_eol_todo && lcs_eol != NUL) {
2620          // Display a '$' after the line or highlight an extra
2621          // character if the line break is included.
2622          // For a diff line the highlighting continues after the "$".
2623          if (wlv.diff_hlf == (hlf_T)0
2624              && wlv.line_attr == 0
2625              && wlv.line_attr_lowprio == 0) {
2626            // In virtualedit, visual selections may extend beyond end of line
2627            if (!(area_highlighting && virtual_active(wp)
2628                  && wlv.tocol != MAXCOL && wlv.vcol < wlv.tocol)) {
2629              wlv.p_extra = "";
2630            }
2631            wlv.n_extra = 0;
2632          }
2633          if (wp->w_p_list && wp->w_p_lcs_chars.eol > 0) {
2634            mb_schar = wp->w_p_lcs_chars.eol;
2635          } else {
2636            mb_schar = schar_from_ascii(' ');
2637          }
2638          lcs_eol_todo = false;
2639          ptr--;  // put it back at the NUL
2640          wlv.extra_attr = win_hl_attr(wp, HLF_AT);
2641          wlv.n_attr = 1;
2642          mb_c = schar_get_first_codepoint(mb_schar);
2643        } else if (mb_schar != NUL) {
2644          xstrlcpy(wlv.extra, transchar_buf(wp->w_buffer, mb_c), sizeof(wlv.extra));
2645          wlv.p_extra = wlv.extra;
2646          if (wlv.n_extra == 0) {
2647            wlv.n_extra = dy_escape_width - 1;
2648          }
2649          if ((dy_flags & kOptDyFlagUhex) && wp->w_p_rl) {
2650            rl_mirror_ascii(wlv.p_extra, NULL);   // reverse "<12>"
2651          }
2652          wlv.sc_extra = NUL;
2653          wlv.sc_final = NUL;
2654          if (wp->w_p_lbr) {
2655            mb_c = (uint8_t)(*wlv.p_extra);
2656            char *p = get_extra_buf((size_t)wlv.n_extra + 1);
2657            memset(p, ' ', (size_t)wlv.n_extra);
2658            memcpy(p, wlv.p_extra + 1, strlen(wlv.p_extra) - 1);
2659            p[wlv.n_extra] = NUL;
2660            wlv.p_extra = p;
2661          } else {
2662            wlv.n_extra = dy_escape_width - 1;
2663            mb_c = (uint8_t)(*wlv.p_extra++);
2664          }
2665          wlv.n_attr = wlv.n_extra + 1;
2666          wlv.extra_attr = win_hl_attr(wp, HLF_8);
2667          saved_attr2 = wlv.char_attr;  // save current attr
2668          mb_schar = schar_from_ascii(mb_c);
2669        } else if (Visual.active
2670                   && (Visual.mode == Ctrl_V || Visual.mode == 'v')
2671                   && virtual_active(wp)
2672                   && wlv.tocol != MAXCOL
2673                   && wlv.vcol < wlv.tocol
2674                   && wlv.col < view_width) {
2675          mb_c = ' ';
2676          mb_schar = schar_from_char(mb_c);
2677          ptr--;  // put it back at the NUL
2678        }
2679      }
2680
2681      if (wp->w_p_cole > 0
2682          && (wp != curwin || lnum != wp->w_cursor.lnum || conceal_cursor_line(wp))
2683          && ((syntax_flags & HL_CONCEAL) != 0 || has_match_conc > 0 || decor_conceal > 0)
2684          && !(lnum_in_visual_area && vim_strchr(wp->w_p_cocu, 'v') == NULL)) {
2685        bool syntax_conceal = (syntax_flags & HL_CONCEAL) != 0;
2686        wlv.char_attr = conceal_attr;
2687        if (((prev_syntax_id != syntax_seqnr && syntax_conceal)
2688             || has_match_conc > 1 || decor_conceal > 1)
2689            && ((syntax_conceal && syn_get_sub_char() != NUL)
2690                || (has_match_conc && match_conc)
2691                || (decor_conceal && decor_state.conceal_char)
2692                || wp->w_p_cole == 1)
2693            && wp->w_p_cole != 3) {
2694          if (schar_cells(mb_schar) > 1) {
2695            // When the first char to be concealed is double-width,
2696            // need to advance one more virtual column.
2697            wlv.n_extra++;
2698          }
2699
2700          // First time at this concealed item: display one
2701          // character.
2702          if (has_match_conc && match_conc) {
2703            mb_schar = schar_from_char(match_conc);
2704          } else if (decor_conceal && decor_state.conceal_char) {
2705            mb_schar = decor_state.conceal_char;
2706            if (decor_state.conceal_attr) {
2707              wlv.char_attr = decor_state.conceal_attr;
2708            }
2709          } else if (syntax_conceal && syn_get_sub_char() != NUL) {
2710            mb_schar = schar_from_char(syn_get_sub_char());
2711          } else if (wp->w_p_lcs_chars.conceal != NUL) {
2712            mb_schar = wp->w_p_lcs_chars.conceal;
2713          } else {
2714            mb_schar = schar_from_ascii(' ');
2715          }
2716
2717          mb_c = schar_get_first_codepoint(mb_schar);
2718
2719          prev_syntax_id = syntax_seqnr;
2720
2721          if (wlv.n_extra > 0) {
2722            wlv.vcol_off_co += wlv.n_extra;
2723          }
2724          wlv.vcol += wlv.n_extra;
2725          if (is_wrapped && wlv.n_extra > 0) {
2726            wlv.boguscols += wlv.n_extra;
2727            wlv.col += wlv.n_extra;
2728          }
2729          wlv.n_extra = 0;
2730          wlv.n_attr = 0;
2731        } else if (wlv.skip_cells == 0) {
2732          is_concealing = true;
2733          wlv.skip_cells = 1;
2734        }
2735      } else {
2736        prev_syntax_id = 0;
2737        is_concealing = false;
2738      }
2739
2740      if (wlv.skip_cells > 0 && did_decrement_ptr) {
2741        // not showing the '>', put pointer back to avoid getting stuck
2742        ptr++;
2743      }
2744    }  // end of printing from buffer content
2745
2746    // In the cursor line and we may be concealing characters: correct
2747    // the cursor column when we reach its position.
2748    // With 'virtualedit' we may never reach cursor position, but we still
2749    // need to correct the cursor column, so do that at end of line.
2750    if (!did_wcol && wlv.filler_todo <= 0
2751        && in_curline && conceal_cursor_line(wp)
2752        && (wlv.vcol + wlv.skip_cells >= wp->w_virtcol || mb_schar == NUL)) {
2753      wp->w_wcol = wlv.col - wlv.boguscols;
2754      // Screen cells concealed before the cursor on this screen line, so
2755      // pum_display() can line the menu up with the visible text;
2756      // "skip_cells" is the concealed cell at the cursor not yet counted.
2757      wp->w_wcol_conceal_off = wlv.vcol_off_co + wlv.skip_cells;
2758      if (wlv.vcol + wlv.skip_cells < wp->w_virtcol) {
2759        // Cursor beyond end of the line with 'virtualedit'.
2760        wp->w_wcol += wp->w_virtcol - wlv.vcol - wlv.skip_cells;
2761      }
2762      wp->w_wrow = wlv.row;
2763      did_wcol = true;
2764      wp->w_valid |= VALID_WCOL|VALID_WROW|VALID_VIRTCOL;
2765    }
2766
2767    // Use "wlv.extra_attr", but don't override visual selection highlighting.
2768    if (wlv.n_attr > 0 && !search_attr_from_match) {
2769      wlv.char_attr = hl_combine_attr(wlv.char_attr, wlv.extra_attr);
2770      if (wlv.reset_extra_attr) {
2771        wlv.reset_extra_attr = false;
2772        if (extra_attr_next >= 0) {
2773          wlv.extra_attr = extra_attr_next;
2774          extra_attr_next = -1;
2775        } else {
2776          wlv.extra_attr = 0;
2777          // search_attr_from_match can be restored now that the extra_attr has been applied
2778          search_attr_from_match = saved_search_attr_from_match;
2779        }
2780      }
2781    }
2782
2783    // Handle the case where we are in column 0 but not on the first
2784    // character of the line and the user wants us to show us a
2785    // special character (via 'listchars' option "precedes:<char>").
2786    if (lcs_prec_todo != NUL
2787        && wp->w_p_list
2788        && (wp->w_p_wrap ? (wp->w_skipcol > 0 && wlv.row == 0) : wp->w_leftcol > 0)
2789        && wlv.filler_todo <= 0
2790        && wlv.skip_cells <= 0
2791        && mb_schar != NUL) {
2792      lcs_prec_todo = NUL;
2793      if (schar_cells(mb_schar) > 1) {
2794        // Double-width character being overwritten by the "precedes"
2795        // character, need to fill up half the character.
2796        wlv.sc_extra = schar_from_ascii(MB_FILLER_CHAR);
2797        wlv.sc_final = NUL;
2798        if (wlv.n_extra > 0) {
2799          assert(wlv.p_extra != NULL);
2800          n_extra_next = wlv.n_extra;
2801          extra_attr_next = wlv.extra_attr;
2802          wlv.n_attr = MAX(wlv.n_attr + 1, 2);
2803        } else {
2804          wlv.n_attr = 2;
2805        }
2806        wlv.n_extra = 1;
2807        wlv.extra_attr = win_hl_attr(wp, HLF_AT);
2808      }
2809      mb_schar = wp->w_p_lcs_chars.prec;
2810      mb_c = schar_get_first_codepoint(mb_schar);
2811      saved_attr3 = wlv.char_attr;  // save current attr
2812      wlv.char_attr = win_hl_attr(wp, HLF_AT);  // overwriting char_attr
2813      n_attr3 = 1;
2814    }
2815
2816    // At end of the text line or just after the last character.
2817    if (mb_schar == NUL && eol_hl_off == 0) {
2818      // flag to indicate whether prevcol equals startcol of search_hl or
2819      // one of the matches
2820      const bool prevcol_hl_flag = get_prevcol_hl_flag(wp, &screen_search_hl,
2821                                                       (colnr_T)(ptr - line) - 1);
2822
2823      // Invert at least one char, used for Visual and empty line or
2824      // highlight match at end of line. If it's beyond the last
2825      // char on the screen, just overwrite that one (tricky!)  Not
2826      // needed when a '$' was displayed for 'list'.
2827      if (lcs_eol_todo
2828          && ((area_attr != 0 && wlv.vcol == wlv.fromcol
2829               && (Visual.mode != Ctrl_V
2830                   || lnum == Visual.start.lnum
2831                   || lnum == curwin->w_cursor.lnum))
2832              // highlight 'hlsearch' match at end of line
2833              || prevcol_hl_flag)) {
2834        int n = 0;
2835
2836        if (wlv.col >= view_width) {
2837          n = -1;
2838        }
2839        if (n != 0) {
2840          // At the window boundary, highlight the last character
2841          // instead (better than nothing).
2842          wlv.off += n;
2843          wlv.col += n;
2844        } else {
2845          // Add a blank character to highlight.
2846          linebuf_char[wlv.off] = schar_from_ascii(' ');
2847        }
2848        if (area_attr == 0 && !has_fold) {
2849          // Use attributes from match with highest priority among
2850          // 'search_hl' and the match list.
2851          get_search_match_hl(wp,
2852                              &screen_search_hl,
2853                              (colnr_T)(ptr - line),
2854                              &wlv.char_attr);
2855        }
2856
2857        const int eol_attr = wlv.cul_attr
2858                             ? hl_combine_attr(wlv.cul_attr, wlv.char_attr)
2859                             : wlv.char_attr;
2860
2861        linebuf_attr[wlv.off] = eol_attr;
2862        linebuf_vcol[wlv.off] = wlv.vcol;
2863        wlv.col++;
2864        wlv.off++;
2865        wlv.vcol++;
2866        eol_hl_off = 1;
2867      }
2868    }
2869
2870    // At end of the text line.
2871    if (mb_schar == NUL) {
2872      // Highlight 'cursorcolumn' & 'colorcolumn' past end of the line.
2873
2874      // check if line ends before left margin
2875      wlv.vcol = MAX(wlv.vcol, start_vcol + wlv.col - win_col_off(wp));
2876      // Get rid of the boguscols now, we want to draw until the right
2877      // edge for 'cursorcolumn'.
2878      wlv.col -= wlv.boguscols;
2879      wlv.boguscols = 0;
2880
2881      advance_color_col(&wlv, vcol_hlc(wlv));
2882
2883      // Make sure alignment is the same regardless
2884      // if listchars=eol:X is used or not.
2885      const int eol_skip = (lcs_eol_todo && eol_hl_off == 0 ? 1 : 0);
2886
2887      if (has_decor) {
2888        decor_redraw_eol(wp, &decor_state, &wlv.line_attr, wlv.col + eol_skip);
2889      }
2890
2891      for (int i = wlv.col; i < view_width; i++) {
2892        linebuf_vcol[wlv.off + (i - wlv.col)] = wlv.vcol + (i - wlv.col);
2893      }
2894
2895      if (((wp->w_p_cuc
2896            && wp->w_virtcol >= vcol_hlc(wlv) - eol_hl_off
2897            && wp->w_virtcol < view_width * (ptrdiff_t)(wlv.row - startrow + 1) + start_vcol
2898            && lnum != wp->w_cursor.lnum)
2899           || wlv.color_cols || wlv.line_attr_lowprio || wlv.line_attr
2900           || wlv.diff_hlf != 0 || wp->w_buffer->terminal)) {
2901        int rightmost_vcol = get_rightmost_vcol(wp, wlv.color_cols);
2902        const int cuc_attr = win_hl_attr(wp, HLF_CUC);
2903        const int mc_attr = win_hl_attr(wp, HLF_MC);
2904
2905        if (wlv.diff_hlf == HLF_TXD || wlv.diff_hlf == HLF_TXA) {
2906          wlv.diff_hlf = HLF_CHD;
2907          set_line_attr_for_diff(wp, &wlv);
2908        }
2909
2910        const int diff_attr = wlv.diff_hlf != 0
2911                              ? win_hl_attr(wp, (int)wlv.diff_hlf)
2912                              : 0;
2913
2914        const int base_attr = hl_combine_attr(wlv.line_attr_lowprio, diff_attr);
2915        if (base_attr || wlv.line_attr || wp->w_buffer->terminal) {
2916          rightmost_vcol = INT_MAX;
2917        }
2918
2919        while (wlv.col < view_width) {
2920          linebuf_char[wlv.off] = schar_from_ascii(' ');
2921
2922          advance_color_col(&wlv, vcol_hlc(wlv));
2923
2924          int col_attr = base_attr;
2925
2926          if (wp->w_p_cuc && vcol_hlc(wlv) == wp->w_virtcol
2927              && lnum != wp->w_cursor.lnum) {
2928            col_attr = hl_combine_attr(col_attr, cuc_attr);
2929          } else if (wlv.color_cols && vcol_hlc(wlv) == *wlv.color_cols) {
2930            col_attr = hl_combine_attr(col_attr, mc_attr);
2931          }
2932
2933          if (wp->w_buffer->terminal && wlv.vcol < TERM_ATTRS_MAX) {
2934            col_attr = hl_combine_attr(col_attr, term_attrs[wlv.vcol]);
2935          }
2936
2937          col_attr = hl_combine_attr(col_attr, wlv.line_attr);
2938
2939          linebuf_attr[wlv.off] = col_attr;
2940          // linebuf_vcol[] already filled by the for loop above
2941          wlv.off++;
2942          wlv.col++;
2943          wlv.vcol++;
2944
2945          if (vcol_hlc(wlv) > rightmost_vcol) {
2946            break;
2947          }
2948        }
2949      }
2950
2951      if (kv_size(fold_vt) > 0) {
2952        draw_virt_text_item(buf, win_col_offset, fold_vt, kHlModeCombine, view_width, 0, 0, false);
2953      }
2954      draw_virt_text(wp, buf, win_col_offset, &wlv.col, wlv.row);
2955      // Set increasing virtual columns in grid->vcols[] to set correct curswant
2956      // (or "coladd" for 'virtualedit') when clicking after end of line.
2957      wlv_put_linebuf(wp, &wlv, wlv.col, true, bg_attr, SLF_INC_VCOL);
2958      wlv.row++;
2959
2960      // Update w_cline_height and w_cline_folded if the cursor line was
2961      // updated (saves a call to plines_win() later).
2962      if (in_curline) {
2963        curwin->w_cline_row = startrow;
2964        curwin->w_cline_height = wlv.row - startrow;
2965        curwin->w_cline_folded = has_fold;
2966        curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW);
2967      }
2968
2969      break;
2970    }
2971
2972    // Show "extends" character from 'listchars' if beyond the line end.
2973    const schar_T lcs_ext = get_lcs_ext(wp);
2974    if (lcs_ext != NUL
2975        && wlv.filler_todo <= 0
2976        && wlv.col == view_width - 1
2977        && !has_foldtext) {
2978      if (has_decor && *ptr == NUL && lcs_eol == 0 && lcs_eol_todo) {
2979        // Tricky: there might be a virtual text just _after_ the last char
2980        decor_redraw_col(wp, (colnr_T)(ptr - line), -1, false, &decor_state,
2981                         decor_provider_end_col - 1);
2982      }
2983      if (*ptr != NUL
2984          || (lcs_eol > 0 && lcs_eol_todo)
2985          || (wlv.n_extra > 0 && (wlv.sc_extra != NUL || *wlv.p_extra != NUL))
2986          || (may_have_inline_virt && has_more_inline_virt(&wlv, ptr - line))) {
2987        mb_schar = lcs_ext;
2988        wlv.char_attr = win_hl_attr(wp, HLF_AT);
2989        mb_c = schar_get_first_codepoint(mb_schar);
2990      }
2991    }
2992
2993    advance_color_col(&wlv, vcol_hlc(wlv));
2994
2995    // Highlight the cursor column if 'cursorcolumn' is set.  But don't
2996    // highlight the cursor position itself.
2997    // Also highlight the 'colorcolumn' if it is different than
2998    // 'cursorcolumn'
2999    vcol_save_attr = -1;
3000    if (!lnum_in_visual_area
3001        && search_attr == 0
3002        && area_attr == 0
3003        && wlv.filler_todo <= 0) {
3004      if (wp->w_p_cuc && vcol_hlc(wlv) == wp->w_virtcol
3005          && lnum != wp->w_cursor.lnum) {
3006        vcol_save_attr = wlv.char_attr;
3007        wlv.char_attr = hl_combine_attr(win_hl_attr(wp, HLF_CUC), wlv.char_attr);
3008      } else if (wlv.color_cols && vcol_hlc(wlv) == *wlv.color_cols) {
3009        vcol_save_attr = wlv.char_attr;
3010        wlv.char_attr = hl_combine_attr(win_hl_attr(wp, HLF_MC), wlv.char_attr);
3011      }
3012    }
3013
3014    if (wlv.filler_todo <= 0) {
3015      // Apply lowest-priority line attr now, so everything can override it.
3016      int low = wlv.line_attr_lowprio;
3017      int high = wlv.char_attr;
3018
3019      if (wlv.line_attr_lowprio != 0) {
3020        HlAttrs line_ae = syn_attr2entry(wlv.line_attr_lowprio);
3021        HlAttrs char_ae = syn_attr2entry(wlv.char_attr);
3022        int win_normal_bg = normal_bg;
3023        int win_normal_cterm_bg = cterm_normal_bg_color;
3024
3025        // Get window-local Normal background (respects 'winhighlight' option).
3026        if (bg_attr != 0) {
3027          HlAttrs norm_ae = syn_attr2entry(bg_attr);
3028          win_normal_bg = norm_ae.rgb_bg_color;
3029          win_normal_cterm_bg = norm_ae.cterm_bg_color;
3030        }
3031        bool char_is_normal_bg = ui_rgb_attached()
3032                                 ? (char_ae.rgb_bg_color == win_normal_bg)
3033                                 : (char_ae.cterm_bg_color == win_normal_cterm_bg);
3034
3035        // If line has background (CursorLine) and char's background equals Normal's background,
3036        // reverse the combination order to let CursorLine override normal_bg.
3037        if ((line_ae.rgb_bg_color >= 0 || line_ae.cterm_bg_color > 0) && char_is_normal_bg) {
3038          low = wlv.char_attr;
3039          high = wlv.line_attr_lowprio;
3040        }
3041      }
3042      wlv.char_attr = hl_combine_attr(low, high);
3043    }
3044
3045    // Store character to be displayed.
3046    // Skip characters that are left of the screen for 'nowrap'.
3047    if (wlv.filler_todo > 0) {
3048      // TODO(bfredl): the main render loop should get called also with the virtual
3049      // lines chunks, so we get line wrapping and other Nice Things.
3050    } else if (wlv.skip_cells <= 0) {
3051      // Store the character.
3052      linebuf_char[wlv.off] = mb_schar;
3053      if (multi_attr) {
3054        linebuf_attr[wlv.off] = multi_attr;
3055        multi_attr = 0;
3056      } else {
3057        linebuf_attr[wlv.off] = wlv.char_attr;
3058      }
3059
3060      linebuf_vcol[wlv.off] = wlv.vcol;
3061
3062      if (schar_cells(mb_schar) > 1) {
3063        // Need to fill two screen columns.
3064        wlv.off++;
3065        wlv.col++;
3066        // UTF-8: Put a 0 in the second screen char.
3067        linebuf_char[wlv.off] = 0;
3068        linebuf_attr[wlv.off] = linebuf_attr[wlv.off - 1];
3069
3070        linebuf_vcol[wlv.off] = ++wlv.vcol;
3071
3072        // When "wlv.tocol" is halfway through a character, set it to the end
3073        // of the character, otherwise highlighting won't stop.
3074        if (wlv.tocol == wlv.vcol) {
3075          wlv.tocol++;
3076        }
3077      }
3078      wlv.off++;
3079      wlv.col++;
3080    } else if (wp->w_p_cole > 0 && is_concealing) {
3081      bool concealed_wide = schar_cells(mb_schar) > 1;
3082
3083      wlv.skip_cells--;
3084      wlv.vcol_off_co++;
3085      if (concealed_wide) {
3086        // When a double-width char is concealed,
3087        // need to advance one more virtual column.
3088        wlv.vcol++;
3089        wlv.vcol_off_co++;
3090      }
3091
3092      if (wlv.n_extra > 0) {
3093        wlv.vcol_off_co += wlv.n_extra;
3094      }
3095
3096      if (is_wrapped) {
3097        // Special voodoo required if 'wrap' is on.
3098        //
3099        // Advance the column indicator to force the line
3100        // drawing to wrap early. This will make the line
3101        // take up the same screen space when parts are concealed,
3102        // so that cursor line computations aren't messed up.
3103        //
3104        // To avoid the fictitious advance of 'wlv.col' causing
3105        // trailing junk to be written out of the screen line
3106        // we are building, 'boguscols' keeps track of the number
3107        // of bad columns we have advanced.
3108        if (wlv.n_extra > 0) {
3109          wlv.vcol += wlv.n_extra;
3110          wlv.col += wlv.n_extra;
3111          wlv.boguscols += wlv.n_extra;
3112          wlv.n_extra = 0;
3113          wlv.n_attr = 0;
3114        }
3115
3116        if (concealed_wide) {
3117          // Need to fill two screen columns.
3118          wlv.boguscols++;
3119          wlv.col++;
3120        }
3121
3122        wlv.boguscols++;
3123        wlv.col++;
3124      } else {
3125        if (wlv.n_extra > 0) {
3126          wlv.vcol += wlv.n_extra;
3127          wlv.n_extra = 0;
3128          wlv.n_attr = 0;
3129        }
3130      }
3131    } else {
3132      wlv.skip_cells--;
3133    }
3134
3135    // The skipped cells need to be accounted for in vcol.
3136    if (wlv.skipped_cells > 0) {
3137      wlv.vcol += wlv.skipped_cells;
3138      wlv.skipped_cells = 0;
3139    }
3140
3141    // Only advance the "wlv.vcol" when after the 'number' or
3142    // 'relativenumber' column.
3143    if (wlv.filler_todo <= 0) {
3144      wlv.vcol++;
3145    }
3146
3147    if (vcol_save_attr >= 0) {
3148      wlv.char_attr = vcol_save_attr;
3149    }
3150
3151    // restore attributes after "precedes" in 'listchars'
3152    if (n_attr3 > 0 && --n_attr3 == 0) {
3153      wlv.char_attr = saved_attr3;
3154    }
3155
3156    // restore attributes after last 'listchars' or 'number' char
3157    if (wlv.n_attr > 0 && --wlv.n_attr == 0) {
3158      wlv.char_attr = saved_attr2;
3159    }
3160
3161    if (has_decor && wlv.filler_todo <= 0 && wlv.col >= view_width) {
3162      // At the end of screen line: might need to peek for decorations just after
3163      // this position.
3164      if (is_wrapped && wlv.n_extra == 0) {
3165        decor_redraw_col(wp, (colnr_T)(ptr - line), -3, false, &decor_state,
3166                         decor_provider_end_col - 1);
3167        // Check position/hiding of virtual text again on next screen line.
3168        decor_need_recheck = true;
3169      } else if (!is_wrapped) {
3170        // Without wrapping, we might need to display right_align and win_col
3171        // virt_text for the entire text line.
3172        decor_recheck_draw_col(-1, true, &decor_state);
3173        decor_redraw_col(wp, MAXCOL, -1, true, &decor_state, decor_provider_end_col - 1);
3174      }
3175    }
3176
3177end_check:
3178    // At end of screen line and there is more to come: Display the line
3179    // so far.  If there is no more to display it is caught above.
3180    if (wlv.col >= view_width && (!has_foldtext || wlv.filler_todo > 0)
3181        && (wlv.col <= leftcols_width
3182            || *ptr != NUL
3183            || wlv.filler_todo > 0
3184            || (wp->w_p_list && wp->w_p_lcs_chars.eol != NUL && lcs_eol_todo)
3185            || (wlv.n_extra != 0 && (wlv.sc_extra != NUL || *wlv.p_extra != NUL))
3186            || (may_have_inline_virt && has_more_inline_virt(&wlv, ptr - line)))) {
3187      int grid_width = wp->w_grid.target->cols;
3188      const bool wrap = is_wrapped                      // Wrapping enabled (not a folded line).
3189                        && wlv.filler_todo <= 0         // Not drawing diff filler lines.
3190                        && lcs_eol_todo                 // Haven't printed the lcs_eol character.
3191                        && wlv.row != endrow - 1        // Not the last line being displayed.
3192                        && view_width == grid_width     // Window spans the width of its grid.
3193                        && !wp->w_p_rl;                 // Not right-to-left.
3194
3195      int draw_col = wlv.col - wlv.boguscols;
3196
3197      for (int i = draw_col; i < view_width; i++) {
3198        linebuf_vcol[wlv.off + (i - draw_col)] = wlv.vcol - 1;
3199      }
3200
3201      // Apply 'cursorline' highlight.
3202      if (wlv.boguscols != 0 && (wlv.line_attr_lowprio != 0 || wlv.line_attr != 0)) {
3203        int attr = hl_combine_attr(wlv.line_attr_lowprio, wlv.line_attr);
3204        while (draw_col < view_width) {
3205          linebuf_char[wlv.off] = schar_from_char(' ');
3206          linebuf_attr[wlv.off] = attr;
3207          // linebuf_vcol[] already filled by the for loop above
3208          wlv.off++;
3209          draw_col++;
3210        }
3211      }
3212
3213      if (has_virt_line) {
3214        VirtLineOverflow overflow = kv_A(virt_lines, virt_line_index).overflow;
3215        bool virt_row_scroll = (overflow == kVLOverflowScroll)
3216                               || ((overflow == kVLOverflowAuto) && !wp->w_p_wrap);
3217        if (virt_row_scroll) {
3218          virt_line_skip_cells = wp->w_leftcol;
3219        }
3220        draw_virt_text_item(buf,
3221                            (virt_line_flags & kVLLeftcol) ? 0 : win_col_offset,
3222                            kv_A(virt_lines, virt_line_index).line,
3223                            kHlModeReplace,
3224                            view_width,
3225                            0,
3226                            virt_line_skip_cells, true);
3227      } else if (wlv.filler_todo <= 0) {
3228        draw_virt_text(wp, buf, win_col_offset, &draw_col, wlv.row);
3229      }
3230
3231      wlv_put_linebuf(wp, &wlv, draw_col, true, bg_attr, wrap ? SLF_WRAP : 0);
3232      if (wrap) {
3233        int current_row = wlv.row;
3234        int dummy_col = 0;  // unused
3235        ScreenGrid *current_grid = grid_adjust(grid, &current_row, &dummy_col);
3236
3237        // Force a redraw of the first column of the next line.
3238        current_grid->attrs[current_grid->line_offset[current_row + 1]] = -1;
3239      }
3240
3241      wlv.boguscols = 0;
3242      wlv.vcol_off_co = 0;
3243      wlv.row++;
3244
3245      // When not wrapping and finished diff lines, break here.
3246      if (!is_wrapped && wlv.filler_todo <= 0) {
3247        break;
3248      }
3249
3250      // When the window is too narrow draw all "@" lines.
3251      if (wlv.col <= leftcols_width) {
3252        win_draw_end(wp, schar_from_ascii('@'), true, wlv.row, wp->w_view_height, HLF_AT);
3253        set_empty_rows(wp, wlv.row);
3254        wlv.row = endrow;
3255      }
3256
3257      // When line got too long for screen break here.
3258      if (wlv.row == endrow) {
3259        wlv.row++;
3260        break;
3261      }
3262
3263      win_line_start(wp, &wlv);
3264      draw_cols = true;
3265
3266      lcs_prec_todo = wp->w_p_lcs_chars.prec;
3267      if (wlv.filler_todo <= 0) {
3268        wlv.need_showbreak = true;
3269      }
3270      if (statuscol.draw && vim_strchr(p_cpo, kCpoNumcol)
3271          && wlv.row > startrow + wlv.filler_lines) {
3272        statuscol.draw = false;  // don't draw status column if "n" is in 'cpo'
3273      }
3274      wlv.filler_todo--;
3275      has_virt_line = false;
3276      virt_line_flags = 0;
3277      // When the filler lines are actually below the last line of the
3278      // file, or we are not drawing text for this line, break here.
3279      if (wlv.filler_todo == 0 && (wp->w_botfill || !draw_text)) {
3280        break;
3281      }
3282    }
3283  }     // for every character in the line
3284
3285  clear_virttext(&fold_vt);
3286  kv_destroy(virt_lines);
3287  xfree(foldtext_free);
3288  return wlv.row;
3289}
3290
3291/// Call grid_put_linebuf() using values from "wlv".
3292/// Also takes care of putting "<<<" on the first line for 'smoothscroll'
3293/// when 'showbreak' is not set.
3294///
3295/// @param clear_end  clear until the end of the screen line.
3296/// @param flags  for grid_put_linebuf(), but shouldn't contain SLF_RIGHTLEFT.
3297static void wlv_put_linebuf(win_T *wp, const winlinevars_T *wlv, int endcol, bool clear_end,
3298                            int bg_attr, int flags)
3299{
3300  GridView *grid = &wp->w_grid;
3301
3302  int startcol = 0;
3303  int clear_width = clear_end ? wp->w_view_width : endcol;
3304
3305  assert(!(flags & SLF_RIGHTLEFT));
3306  if (wp->w_p_rl) {
3307    linebuf_mirror(&startcol, &endcol, &clear_width, wp->w_view_width);
3308    flags |= SLF_RIGHTLEFT;
3309  }
3310
3311  // Take care of putting "<<<" on the first line for 'smoothscroll'.
3312  if (wlv->row == 0 && wp->w_skipcol > 0
3313      // do not overwrite the 'showbreak' text with "<<<"
3314      && *get_showbreak_value(wp) == NUL
3315      // do not overwrite the 'listchars' "precedes" text with "<<<"
3316      && !(wp->w_p_list && wp->w_p_lcs_chars.prec != 0)) {
3317    int off = 0;
3318    if (wp->w_p_nu && wp->w_p_rnu) {
3319      // do not overwrite the line number, change "123 text" to "123<<<xt".
3320      while (off < wp->w_view_width && ascii_isdigit(schar_get_ascii(linebuf_char[off]))) {
3321        off++;
3322      }
3323    }
3324
3325    for (int i = 0; i < 3 && off < wp->w_view_width; i++) {
3326      if (off + 1 < wp->w_view_width && linebuf_char[off + 1] == NUL) {
3327        // When the first half of a double-width character is
3328        // overwritten, change the second half to a space.
3329        linebuf_char[off + 1] = schar_from_ascii(' ');
3330      }
3331      linebuf_char[off] = schar_from_ascii('<');
3332      linebuf_attr[off] = HL_ATTR(HLF_AT);
3333      off++;
3334    }
3335  }
3336
3337  int row = wlv->row;
3338  int coloff = 0;
3339  ScreenGrid *g = grid_adjust(grid, &row, &coloff);
3340  grid_put_linebuf(g, row, coloff, startcol, endcol, clear_width, bg_attr, 0, wlv->vcol - 1, flags);
3341}
3342
3343static int decor_providers_setup(int rows_to_draw, bool draw_from_line_start, linenr_T lnum,
3344                                 colnr_T col, win_T *wp)
3345{
3346  // Approximate the number of bytes that will be drawn.
3347  // Assume we're dealing with 1-cell ascii and ignore
3348  // the effects of 'linebreak', 'breakindent', etc.
3349  int rem_vcols;
3350  if (wp->w_p_wrap) {
3351    int width = wp->w_view_width - win_col_off(wp);
3352    int width2 = width + win_col_off2(wp);
3353
3354    int first_row_width = draw_from_line_start ? width : width2;
3355    rem_vcols = first_row_width + (rows_to_draw - 1) * width2;
3356  } else {
3357    rem_vcols = wp->w_view_width - win_col_off(wp);
3358  }
3359
3360  // Call it here since we need to invalidate the line pointer anyway.
3361  decor_providers_invoke_line(wp, lnum - 1);
3362  validate_virtcol(wp);
3363
3364  return invoke_range_next(wp, lnum, col, rem_vcols + 1);
3365}
3366
3367/// @return New begin column, or INT_MAX.
3368static int invoke_range_next(win_T *wp, int lnum, colnr_T begin_col, colnr_T col_off)
3369{
3370  char const *const line = ml_get_buf(wp->w_buffer, lnum);
3371  int const line_len = ml_get_buf_len(wp->w_buffer, lnum);
3372  col_off = MAX(col_off, 1);
3373
3374  colnr_T new_col;
3375  if (col_off <= line_len - begin_col) {
3376    int end_col = begin_col + col_off;
3377    end_col += mb_off_next(line, line + end_col);
3378    decor_providers_invoke_range(wp, lnum - 1, begin_col, lnum - 1, end_col);
3379    validate_virtcol(wp);
3380    new_col = end_col;
3381  } else {
3382    decor_providers_invoke_range(wp, lnum - 1, begin_col, lnum, 0);
3383    validate_virtcol(wp);
3384    new_col = INT_MAX;
3385  }
3386
3387  return new_col;
3388}