robin/laufey

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

glepnirfix(ui): missing vertical separator for a winbar only window (#41151)6d8401f8d5

master
94.4 KiB2883 linesraw
1// drawscreen.c: Code for updating all the windows on the screen.
2// This is the top level, drawline.c is the middle and grid.c the lower level.
3
4// update_screen() is the function that updates all windows and status lines.
5// It is called from the main loop when must_redraw is non-zero.  It may be
6// called from other places when an immediate screen update is needed.
7//
8// The part of the buffer that is displayed in a window is set with:
9// - w_topline (first buffer line in window)
10// - w_topfill (filler lines above the first line)
11// - w_leftcol (leftmost window cell in window),
12// - w_skipcol (skipped window cells of first line)
13//
14// Commands that only move the cursor around in a window, do not need to take
15// action to update the display.  The main loop will check if w_topline is
16// valid and update it (scroll the window) when needed.
17//
18// Commands that scroll a window change w_topline and must call
19// check_cursor() to move the cursor into the visible part of the window, and
20// call redraw_later(wp, UPD_VALID) to have the window displayed by update_screen()
21// later.
22//
23// Commands that change text in the buffer must call changed_bytes() or
24// changed_lines() to mark the area that changed and will require updating
25// later.  The main loop will call update_screen(), which will update each
26// window that shows the changed buffer.  This assumes text above the change
27// can remain displayed as it is.  Text after the change may need updating for
28// scrolling, folding and syntax highlighting.
29//
30// Commands that change how a window is displayed (e.g., setting 'list') or
31// invalidate the contents of a window in another way (e.g., change fold
32// settings), must call redraw_later(wp, UPD_NOT_VALID) to have the whole window
33// redisplayed by update_screen() later.
34//
35// Commands that change how a buffer is displayed (e.g., setting 'tabstop')
36// must call redraw_curbuf_later(UPD_NOT_VALID) to have all the windows for the
37// buffer redisplayed by update_screen() later.
38//
39// Commands that change highlighting and possibly cause a scroll too must call
40// redraw_later(wp, UPD_SOME_VALID) to update the whole window but still use
41// scrolling to avoid redrawing everything.  But the length of displayed lines
42// must not change, use UPD_NOT_VALID then.
43//
44// Commands that move the window position must call redraw_later(wp, UPD_NOT_VALID).
45// TODO(neovim): should minimize redrawing by scrolling when possible.
46//
47// Commands that change everything (e.g., resizing the screen) must call
48// redraw_all_later(UPD_NOT_VALID) or redraw_all_later(UPD_CLEAR).
49//
50// Things that are handled indirectly:
51// - When messages scroll the screen up, msg_scrolled will be set and
52//   update_screen() called to redraw.
53
54#include <assert.h>
55#include <inttypes.h>
56#include <limits.h>
57#include <stdbool.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61
62#include "klib/kvec.h"
63#include "nvim/api/private/defs.h"
64#include "nvim/ascii_defs.h"
65#include "nvim/autocmd.h"
66#include "nvim/autocmd_defs.h"
67#include "nvim/buffer.h"
68#include "nvim/buffer_defs.h"
69#include "nvim/charset.h"
70#include "nvim/cmdexpand.h"
71#include "nvim/context.h"
72#include "nvim/decoration.h"
73#include "nvim/decoration_defs.h"
74#include "nvim/decoration_provider.h"
75#include "nvim/diff.h"
76#include "nvim/digraph.h"
77#include "nvim/drawline.h"
78#include "nvim/drawscreen.h"
79#include "nvim/eval/vars.h"
80#include "nvim/ex_getln.h"
81#include "nvim/fold.h"
82#include "nvim/fold_defs.h"
83#include "nvim/gettext_defs.h"
84#include "nvim/globals.h"
85#include "nvim/grid.h"
86#include "nvim/grid_defs.h"
87#include "nvim/highlight.h"
88#include "nvim/highlight_defs.h"
89#include "nvim/highlight_group.h"
90#include "nvim/input.h"
91#include "nvim/insexpand.h"
92#include "nvim/marktree_defs.h"
93#include "nvim/match.h"
94#include "nvim/mbyte.h"
95#include "nvim/memline.h"
96#include "nvim/message.h"
97#include "nvim/move.h"
98#include "nvim/normal.h"
99#include "nvim/normal_defs.h"
100#include "nvim/option.h"
101#include "nvim/option_vars.h"
102#include "nvim/os/os_defs.h"
103#include "nvim/plines.h"
104#include "nvim/popupmenu.h"
105#include "nvim/pos_defs.h"
106#include "nvim/profile.h"
107#include "nvim/regexp.h"
108#include "nvim/search.h"
109#include "nvim/spell.h"
110#include "nvim/state.h"
111#include "nvim/state_defs.h"
112#include "nvim/statusline.h"
113#include "nvim/strings.h"
114#include "nvim/syntax.h"
115#include "nvim/syntax_defs.h"
116#include "nvim/terminal.h"
117#include "nvim/types_defs.h"
118#include "nvim/ui.h"
119#include "nvim/ui_compositor.h"
120#include "nvim/ui_defs.h"
121#include "nvim/version.h"
122#include "nvim/vim_defs.h"
123#include "nvim/window.h"
124
125/// corner value flags for hsep_connected and vsep_connected
126typedef enum {
127  WC_TOP_LEFT = 0,
128  WC_TOP_RIGHT,
129  WC_BOTTOM_LEFT,
130  WC_BOTTOM_RIGHT,
131} WindowCorner;
132
133#include "drawscreen.c.generated.h"
134
135static bool redraw_popupmenu = false;
136static bool msg_grid_invalid = false;
137static bool resizing_autocmd = false;
138static bool conceal_cursor_used = false;
139
140/// Check if the cursor line needs to be redrawn because of 'concealcursor'.
141///
142/// When cursor is moved at the same time, both lines will be redrawn regardless.
143void conceal_check_cursor_line(void)
144{
145  bool should_conceal = conceal_cursor_line(curwin);
146  if (curwin->w_p_cole <= 0 || conceal_cursor_used == should_conceal) {
147    return;
148  }
149
150  redrawWinline(curwin, curwin->w_cursor.lnum);
151
152  // Concealed line visibility toggled.
153  if (decor_conceal_line(curwin, curwin->w_cursor.lnum - 1, true)) {
154    changed_window_setting(curwin);
155  }
156  // Need to recompute cursor column, e.g., when starting Visual mode
157  // without concealing.
158  curs_columns(curwin, true);
159}
160
161/// Resize default_grid to Rows and Columns.
162///
163/// Allocate default_grid.chars[] and other grid arrays.
164///
165/// There may be some time between setting Rows and Columns and (re)allocating
166/// default_grid arrays.  This happens when starting up and when
167/// (manually) changing the screen size.  Always use default_grid.rows and
168/// default_grid.cols to access items in default_grid.chars[].  Use Rows and
169/// Columns for positioning text etc. where the final size of the screen is
170/// needed.
171///
172/// @return  whether resizing has been done
173bool default_grid_alloc(void)
174{
175  static bool resizing = false;
176
177  // It's possible that we produce an out-of-memory message below, which
178  // will cause this function to be called again.  To break the loop, just
179  // return here.
180  if (resizing) {
181    return false;
182  }
183  resizing = true;
184
185  // Allocation of the screen buffers is done only when the size changes and
186  // when Rows and Columns have been set.
187  if ((default_grid.chars != NULL
188       && Rows == default_grid.rows
189       && Columns == default_grid.cols)
190      || Rows == 0 || Columns == 0) {
191    resizing = false;
192    return false;
193  }
194
195  // We're changing the size of the screen.
196  // - Allocate new arrays for default_grid
197  // - Move lines from the old arrays into the new arrays, clear extra
198  //   lines (unless the screen is going to be cleared).
199  // - Free the old arrays.
200  //
201  // If anything fails, make grid arrays NULL, so we don't do anything!
202  // Continuing with the old arrays may result in a crash, because the
203  // size is wrong.
204
205  grid_alloc(&default_grid, Rows, Columns, true, true);
206
207  stl_clear_click_defs(tab_page_click_defs, tab_page_click_defs_size);
208  tab_page_click_defs = stl_alloc_click_defs(tab_page_click_defs, Columns,
209                                             &tab_page_click_defs_size);
210
211  default_grid.comp_height = Rows;
212  default_grid.comp_width = Columns;
213
214  default_grid.handle = DEFAULT_GRID_HANDLE;
215
216  resizing = false;
217  return true;
218}
219
220void screenclear(void)
221{
222  msg_check_for_delay(false);
223
224  if (starting == NO_SCREEN || default_grid.chars == NULL) {
225    return;
226  }
227
228  // blank out the default grid
229  for (int i = 0; i < default_grid.rows; i++) {
230    grid_clear_line(&default_grid, default_grid.line_offset[i],
231                    default_grid.cols, true);
232  }
233
234  ui_call_grid_clear(1);  // clear the display
235  ui_comp_set_screen_valid(true);
236
237  ns_hl_fast = -1;
238
239  clear_cmdline = false;
240  mode_displayed = false;
241
242  redraw_all_later(UPD_NOT_VALID);
243  cmdline_was_last_drawn = false;
244  redraw_cmdline = true;
245  redraw_tabline = true;
246  redraw_popupmenu = true;
247  pum_invalidate();
248  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
249    if (wp->w_floating) {
250      wp->w_redr_type = UPD_CLEAR;
251    }
252  }
253  if (must_redraw == UPD_CLEAR) {
254    must_redraw = UPD_NOT_VALID;  // no need to clear again
255  }
256  compute_cmdrow();
257  msg_row = cmdline_row;  // put cursor on last line for messages
258  msg_col = 0;
259  msg_reset_scroll();     // can't scroll back
260  msg_didany = false;
261  msg_didout = false;
262  if (HL_ATTR(HLF_MSG) > 0 && msg_use_grid() && msg_grid.chars) {
263    grid_invalidate(&msg_grid);
264    msg_grid_validate();
265    msg_grid_invalid = false;
266    clear_cmdline = true;
267  }
268}
269
270/// Unlike cmdline "one_key" prompts, the message part of the prompt is not stored
271/// to be re-emitted: avoid clearing the prompt from the message grid.
272static bool cmdline_number_prompt(void)
273{
274  return !ui_has(kUIMessages) && (State & MODE_CMDLINE) && get_cmdline_info()->mouse_used != NULL;
275}
276
277/// Set dimensions of the Nvim application "screen".
278void screen_resize(int width, int height)
279{
280  // Avoid recursiveness, can happen when setting the window size causes
281  // another window-changed signal.
282  if (updating_screen || resizing_screen || cmdline_number_prompt()) {
283    return;
284  }
285
286  if (width < 0 || height < 0) {    // just checking...
287    return;
288  }
289
290  if (State == MODE_HITRETURN || State == MODE_SETWSIZE) {
291    // postpone the resizing
292    State = MODE_SETWSIZE;
293    return;
294  }
295
296  resizing_screen = true;
297
298  Rows = height;
299  Columns = width;
300  check_screensize();
301  if (!ui_has(kUIMessages)) {
302    // clamp 'cmdheight'
303    int max_p_ch = Rows - min_rows(curtab) + 1;
304    if (p_ch > 0 && p_ch > max_p_ch) {
305      p_ch = MAX(max_p_ch, 1);
306      curtab->tp_ch_used = p_ch;
307    }
308    // clamp 'cmdheight' for other tab pages
309    FOR_ALL_TABS(tp) {
310      if (tp == curtab) {
311        continue;  // already set above
312      }
313      int max_tp_ch = Rows - min_rows(tp) + 1;
314      if (tp->tp_ch_used > 0 && tp->tp_ch_used > max_tp_ch) {
315        tp->tp_ch_used = MAX(max_tp_ch, 1);
316      }
317    }
318  }
319  height = Rows;
320  width = Columns;
321  p_lines = Rows;
322  p_columns = Columns;
323
324  ui_call_grid_resize(1, width, height);
325
326  int retry_count = 0;
327  resizing_autocmd = true;
328
329  // In rare cases, autocommands may have altered Rows or Columns,
330  // so retry to check if we need to allocate the screen again.
331  while (default_grid_alloc()) {
332    // win_new_screensize will recompute floats position, but tell the
333    // compositor to not redraw them yet
334    ui_comp_set_screen_valid(false);
335    if (msg_grid.chars) {
336      msg_grid_invalid = true;
337    }
338
339    RedrawingDisabled++;
340
341    win_new_screensize();      // fit the windows in the new sized screen
342
343    comp_col();           // recompute columns for shown command and ruler
344
345    RedrawingDisabled--;
346
347    // Do not apply autocommands more than 3 times to avoid an endless loop
348    // in case applying autocommands always changes Rows or Columns.
349    if (++retry_count > 3) {
350      break;
351    }
352
353    apply_autocmds(EVENT_VIMRESIZED, NULL, NULL, false, curbuf);
354  }
355
356  resizing_autocmd = false;
357  redraw_all_later(UPD_CLEAR);
358
359  if (State != MODE_ASKMORE && State != MODE_EXTERNCMD) {
360    screenclear();
361  }
362
363  if (starting != NO_SCREEN) {
364    maketitle();
365
366    changed_line_abv_curs();
367    invalidate_botline_win(curwin);
368
369    // We only redraw when it's needed:
370    // - While at the more prompt or executing an external command, don't
371    //   redraw, but position the cursor.
372    // - While editing the command line, only redraw that. TODO: lies
373    // - Otherwise, redraw right now, and position the cursor.
374    if (State == MODE_ASKMORE || State == MODE_EXTERNCMD
375        || ((State & MODE_CMDLINE) && get_cmdline_info()->one_key)) {
376      if (State & MODE_CMDLINE) {
377        update_screen();
378      }
379      if (msg_grid.chars) {
380        msg_grid_validate();
381      }
382      // TODO(bfredl): sometimes messes up the output. Implement clear+redraw
383      // also for the pager? (or: what if the pager was just a modal window?)
384      ui_comp_set_screen_valid(true);
385      repeat_message();
386    } else {
387      if (curwin->w_p_scb) {
388        do_check_scrollbind(true);
389      }
390      if (State & MODE_CMDLINE) {
391        redraw_popupmenu = false;
392        update_screen();
393        redrawcmdline();
394        if (pum_drawn()) {
395          cmdline_pum_display(false);
396        }
397      } else {
398        update_topline(curwin);
399        if (pum_drawn()) {
400          // TODO(bfredl): ins_compl_show_pum wants to redraw the screen first.
401          // For now make sure the nested update_screen() won't redraw the
402          // pum at the old position. Try to untangle this later.
403          redraw_popupmenu = false;
404          ins_compl_show_pum();
405        }
406        update_screen();
407        if (redrawing()) {
408          setcursor();
409        }
410      }
411    }
412    ui_flush();
413  }
414  resizing_screen = false;
415}
416
417/// Check if the new Nvim application "screen" dimensions are valid.
418/// Correct it if it's too small or way too big.
419void check_screensize(void)
420{
421  // Limit Rows and Columns to avoid an overflow in Rows * Columns.
422  // need room for one window and command line
423  Rows = MIN(MAX(Rows, min_rows_for_all_tabpages()), 1000);
424  Columns = MIN(MAX(Columns, MIN_COLUMNS), 10000);
425}
426
427/// Return true if redrawing should currently be done.
428bool redrawing(void)
429{
430  return !RedrawingDisabled
431         && !(p_lz && char_avail() && !KeyTyped && !do_redraw);
432}
433
434/// Redraw the parts of the screen that is marked for redraw.
435///
436/// Most code shouldn't call this directly, rather use redraw_later() and
437/// and redraw_all_later() to mark parts of the screen as needing a redraw.
438int update_screen(void)
439{
440  static bool still_may_intro = true;
441  if (still_may_intro) {
442    if (!may_show_intro()) {
443      redraw_later(firstwin, UPD_NOT_VALID);
444      still_may_intro = false;
445    }
446  }
447
448  bool is_stl_global = global_stl_height() > 0;
449
450  // Don't do anything if the screen structures are (not yet) valid.
451  // A VimResized autocmd can invoke redrawing in the middle of a resize,
452  // which would bypass the checks in screen_resize for popupmenu etc.
453  if (resizing_autocmd || !default_grid.chars) {
454    return FAIL;
455  }
456
457  // May have postponed updating diffs.
458  if (need_diff_redraw) {
459    diff_redraw(true);
460  }
461
462  // Postpone the redrawing when it's not needed and when being called
463  // recursively.
464  if (!redrawing() || updating_screen || cmdline_number_prompt()) {
465    return FAIL;
466  }
467
468  // Restore actual curwin before redrawing.
469  win_T *save_curwin = ctx_saved_curwin();
470  win_T *restore_curwin = save_curwin != NULL ? curwin : NULL;
471  if (save_curwin != NULL) {
472    curwin = save_curwin;
473    curbuf = curwin->w_buffer;
474  }
475
476  int type = must_redraw;
477
478  // must_redraw is reset here, so that when we run into some weird
479  // reason to redraw while busy redrawing (e.g., asynchronous
480  // scrolling), or update_topline() in win_update() will cause a
481  // scroll, or a decoration provider requires a redraw, the screen
482  // will be redrawn later or in win_update().
483  must_redraw = 0;
484
485  updating_screen = true;
486
487  display_tick++;  // let syntax code know we're in a next round of
488                   // display updating
489
490  // glyph cache full, very rare
491  if (schar_cache_clear_if_full()) {
492    // must use CLEAR, as the contents of screen buffers cannot be
493    // compared to their previous state here.
494    // TODO(bfredl): if start to cache schar_T values in places (like fcs/lcs)
495    // we need to revalidate these here as well!
496    type = MAX(type, UPD_CLEAR);
497  }
498
499  // Tricky: vim code can reset msg_scrolled behind our back, so need
500  // separate bookkeeping for now.
501  if (msg_did_scroll) {
502    msg_did_scroll = false;
503    msg_scrolled_at_flush = 0;
504  }
505
506  if (type >= UPD_CLEAR || !default_grid.valid) {
507    ui_comp_set_screen_valid(false);
508  }
509
510  // if the screen was scrolled up when displaying a message, scroll it down
511  if (msg_scrolled || msg_grid_invalid) {
512    clear_cmdline = true;
513    int valid = MAX(Rows - msg_scrollsize(), 0);
514    if (msg_grid.chars) {
515      // non-displayed part of msg_grid is considered invalid.
516      for (int i = 0; i < MIN(msg_scrollsize(), msg_grid.rows); i++) {
517        grid_clear_line(&msg_grid, msg_grid.line_offset[i],
518                        msg_grid.cols, i < p_ch);
519      }
520    }
521    msg_grid.throttled = false;
522    bool was_invalidated = false;
523
524    // UPD_CLEAR is already handled
525    if (type == UPD_NOT_VALID && !ui_has(kUIMultigrid) && msg_scrolled) {
526      was_invalidated = ui_comp_set_screen_valid(false);
527      for (int i = valid; i < Rows - p_ch; i++) {
528        grid_clear_line(&default_grid, default_grid.line_offset[i],
529                        Columns, false);
530      }
531      FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
532        if (wp->w_floating) {
533          continue;
534        }
535        if (W_ENDROW(wp) > valid) {
536          // TODO(bfredl): too pessimistic. type could be UPD_NOT_VALID
537          // only because windows that are above the separator.
538          wp->w_redr_type = MAX(wp->w_redr_type, UPD_NOT_VALID);
539        }
540        if (!is_stl_global && W_ENDROW(wp) + wp->w_status_height > valid) {
541          wp->w_redr_status = true;
542        }
543      }
544      if (is_stl_global && Rows - p_ch - 1 > valid) {
545        curwin->w_redr_status = true;
546      }
547    }
548    msg_grid_set_pos(Rows - (int)p_ch, false);
549    msg_grid_invalid = false;
550    if (was_invalidated) {
551      // screen was only invalid for the msgarea part.
552      // @TODO(bfredl): using the same "valid" flag
553      // for both messages and floats moving is bit of a mess.
554      ui_comp_set_screen_valid(true);
555    }
556    msg_scrolled = 0;
557    msg_scrolled_at_flush = 0;
558    msg_grid_scroll_discount = 0;
559    need_wait_return = false;
560  }
561
562  win_ui_flush(true);
563
564  // reset cmdline_row now (may have been changed temporarily)
565  compute_cmdrow();
566
567  bool hl_changed = false;
568  // Check for changed highlighting
569  if (need_highlight_changed) {
570    highlight_changed();
571    hl_changed = true;
572  }
573
574  if (type == UPD_CLEAR) {          // first clear screen
575    screenclear();  // will reset clear_cmdline
576                    // and set UPD_NOT_VALID for each window
577    cmdline_screen_cleared();   // clear external cmdline state
578    if (ui_has(kUIMessages)) {
579      ui_call_msg_clear();
580    }
581    type = UPD_NOT_VALID;
582    // must_redraw may be set indirectly, avoid another redraw later
583    must_redraw = 0;
584  } else if (!default_grid.valid) {
585    grid_invalidate(&default_grid);
586    default_grid.valid = true;
587  }
588
589  // might need to clear space on default_grid for the message area.
590  if (type == UPD_NOT_VALID && clear_cmdline && !ui_has(kUIMessages)) {
591    grid_clear(&default_gridview, Rows - (int)p_ch, Rows, 0, Columns, 0);
592  }
593
594  ui_comp_set_screen_valid(true);
595
596  decor_providers_start();
597
598  // "start" callback could have changed highlights for global elements
599  if (win_check_ns_hl(NULL)) {
600    redraw_cmdline = true;
601    redraw_tabline = true;
602  }
603
604  if (clear_cmdline) {          // going to clear cmdline (done below)
605    msg_check_for_delay(false);
606  }
607
608  // Force redraw when width of 'number' or 'relativenumber' column
609  // changes.
610  // TODO(bfredl): special casing curwin here is SÅ JÄVLA BULL.
611  // Either this should be done for all windows or not at all.
612  if (curwin->w_redr_type < UPD_NOT_VALID
613      && curwin->w_nrwidth != ((curwin->w_p_nu || curwin->w_p_rnu || *curwin->w_p_stc)
614                               ? number_width(curwin) : 0)) {
615    curwin->w_redr_type = UPD_NOT_VALID;
616  }
617
618  if (curwin->w_redr_type == UPD_INVERTED) {
619    // Update w_curswant so that the end of Visual selection is correct.
620    update_curswant();
621  }
622
623  // Redraw the tab pages line if needed.
624  if (redraw_tabline || type >= UPD_NOT_VALID) {
625    update_window_hl(curwin, type >= UPD_NOT_VALID);
626    FOR_ALL_TABS(tp) {
627      if (tp != curtab) {
628        update_window_hl(tp->tp_curwin, type >= UPD_NOT_VALID);
629      }
630    }
631    draw_tabline();
632  }
633
634  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
635    if (wp->w_config.hide && wp->w_grid_alloc.chars) {
636      continue;  // Skip hidden windows unless not allocated yet.
637    }
638    // Correct stored syntax highlighting info for changes in each displayed
639    // buffer.  Each buffer must only be done once.
640    update_window_hl(wp, type >= UPD_NOT_VALID || hl_changed);
641
642    buf_T *buf = wp->w_buffer;
643    if (buf->b_mod_set) {
644      if (buf->b_mod_tick_syn < display_tick
645          && syntax_present(wp)) {
646        syn_stack_apply_changes(buf);
647        buf->b_mod_tick_syn = display_tick;
648      }
649
650      if (buf->b_mod_tick_decor < display_tick) {
651        decor_providers_invoke_buf(buf);
652        buf->b_mod_tick_decor = display_tick;
653      }
654    }
655  }
656
657  // Go from top to bottom through the windows, redrawing the ones that need it.
658  bool did_one = false;
659  screen_search_hl.rm.regprog = NULL;
660
661  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
662    if (wp->w_config.hide && wp->w_grid_alloc.chars) {
663      if (wp == curwin && global_stl_height() > 0) {
664        win_redr_status(wp);
665      }
666      wp->w_redr_type = 0;
667      continue;  // Skip hidden windows unless not allocated yet.
668    }
669
670    if (wp->w_redr_type == UPD_CLEAR && wp->w_floating && wp->w_grid_alloc.chars) {
671      grid_invalidate(&wp->w_grid_alloc);
672      wp->w_redr_type = UPD_NOT_VALID;
673    }
674
675    win_check_ns_hl(wp);
676
677    // reallocate grid if needed.
678    win_grid_alloc(wp);
679
680    if (wp->w_redr_border || wp->w_redr_type >= UPD_NOT_VALID) {
681      grid_draw_border(&wp->w_grid_alloc, &wp->w_config, wp->w_border_adj, (int)wp->w_p_winbl,
682                       wp->w_ns_hl_attr, wp->w_hl_attr_normal);
683    }
684
685    if (wp->w_redr_type != 0) {
686      if (!did_one) {
687        did_one = true;
688        start_search_hl();
689      }
690      win_update(wp);
691    }
692
693    // redraw status line and window bar after the window to minimize cursor movement
694    if (wp->w_redr_status) {
695      win_redr_winbar(wp);
696      win_redr_status(wp);
697    }
698  }
699
700  // Draw separator connectors for all windows after all window updates, so that
701  // connectors overwrite vsep/hsep characters regardless of which windows were redrawn.
702  if (did_one) {
703    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
704      draw_sep_connectors_win(wp);
705    }
706  }
707
708  end_search_hl();
709
710  // May need to redraw the popup menu.
711  if (pum_drawn() && must_redraw_pum) {
712    win_check_ns_hl(curwin);
713    pum_redraw();
714  } else if (State & MODE_CMDLINE) {
715    pum_check_clear();
716  }
717
718  win_check_ns_hl(NULL);
719
720  // Reset b_mod_set.  Going through all windows is probably faster than going
721  // through all buffers (there could be many buffers).
722  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
723    wp->w_buffer->b_mod_set = false;
724  }
725
726  updating_screen = false;
727
728  if (need_maketitle) {
729    maketitle();
730  }
731
732  // Clear or redraw the command line.  Done last, because scrolling may
733  // mess up the command line.
734  if (clear_cmdline || redraw_cmdline || redraw_mode) {
735    showmode();
736  }
737
738  // May put up an introductory message when not editing a file
739  if (still_may_intro) {
740    intro_message(false);
741  }
742  repeat_message();
743
744  decor_providers_invoke_end();
745
746  // Either cmdline is cleared, not drawn or mode is last drawn.
747  // This does not (necessarily) overwrite an external cmdline.
748  if (!ui_has(kUICmdline)) {
749    cmdline_was_last_drawn = false;
750  }
751
752  // Restore temporary autocmd curwin.
753  if (restore_curwin != NULL) {
754    curwin = restore_curwin;
755    curbuf = curwin->w_buffer;
756  }
757
758  return OK;
759}
760
761/// Prepare for 'hlsearch' highlighting.
762void start_search_hl(void)
763{
764  if (!p_hls || Search.no_hlsearch) {
765    return;
766  }
767
768  end_search_hl();  // just in case it wasn't called before
769  last_pat_prog(&screen_search_hl.rm);
770  // Set the time limit to 'redrawtime'.
771  screen_search_hl.tm = profile_setlimit(p_rdt);
772}
773
774/// Clean up for 'hlsearch' highlighting.
775void end_search_hl(void)
776{
777  if (screen_search_hl.rm.regprog == NULL) {
778    return;
779  }
780
781  vim_regfree(screen_search_hl.rm.regprog);
782  screen_search_hl.rm.regprog = NULL;
783}
784
785/// Set cursor to its position in the current window.
786void setcursor(void)
787{
788  setcursor_mayforce(curwin, false);
789}
790
791/// Set cursor to its position in the current window.
792/// @param force  when true, also when not redrawing.
793void setcursor_mayforce(win_T *wp, bool force)
794{
795  if (force || redrawing()) {
796    validate_cursor(wp);
797
798    int row = wp->w_wrow;
799    int col = wp->w_wcol;
800    if (wp->w_p_rl) {
801      // With 'rightleft' set and the cursor on a double-wide character,
802      // position it on the leftmost column.
803      char *cursor = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum) + wp->w_cursor.col;
804      col = wp->w_view_width - wp->w_wcol - ((utf_ptr2cells(cursor) == 2
805                                              && vim_isprintc(utf_ptr2char(cursor))) ? 2 : 1);
806    }
807
808    ScreenGrid *grid = grid_adjust(&wp->w_grid, &row, &col);
809    if (grid) {
810      ui_grid_cursor_goto(grid->handle, row, col);
811    }
812  }
813}
814
815/// Mark the title and icon for redraw if either of them uses statusline format.
816///
817/// @return  whether either title or icon uses statusline format.
818bool redraw_custom_title_later(void)
819{
820  if ((p_icon && (stl_syntax & STL_IN_ICON))
821      || (p_title && (stl_syntax & STL_IN_TITLE))) {
822    need_maketitle = true;
823    return true;
824  }
825  return false;
826}
827
828/// Show current cursor info in ruler and various other places
829///
830/// @param always  if false, only show ruler if position has changed.
831void show_cursor_info_later(bool force)
832{
833  int state = get_real_state();
834  int empty_line = (State & MODE_INSERT) == 0
835                   && *ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum) == NUL;
836
837  // Only draw when something changed.
838  validate_virtcol(curwin);
839  if (force
840      || curwin->w_cursor.lnum != curwin->w_stl_cursor.lnum
841      || curwin->w_cursor.col != curwin->w_stl_cursor.col
842      || curwin->w_virtcol != curwin->w_stl_virtcol
843      || curwin->w_cursor.coladd != curwin->w_stl_cursor.coladd
844      || curwin->w_topline != curwin->w_stl_topline
845      || curwin->w_buffer->b_ml.ml_line_count != curwin->w_stl_line_count
846      || curwin->w_topfill != curwin->w_stl_topfill
847      || empty_line != curwin->w_stl_empty
848      || reg_recording != curwin->w_stl_recording
849      || state != curwin->w_stl_state
850      || (Visual.active && (Visual.mode != curwin->w_stl_visual_mode
851                            || Visual.start.lnum != curwin->w_stl_visual_pos.lnum
852                            || Visual.start.col != curwin->w_stl_visual_pos.col
853                            || Visual.start.coladd != curwin->w_stl_visual_pos.coladd))) {
854    if (curwin->w_status_height || global_stl_height()) {
855      curwin->w_redr_status = true;
856    } else {
857      redraw_cmdline = true;
858    }
859
860    if (*p_wbr != NUL || *curwin->w_p_wbr != NUL) {
861      curwin->w_redr_status = true;
862    }
863
864    redraw_custom_title_later();
865  }
866
867  curwin->w_stl_cursor = curwin->w_cursor;
868  curwin->w_stl_virtcol = curwin->w_virtcol;
869  curwin->w_stl_empty = (char)empty_line;
870  curwin->w_stl_topline = curwin->w_topline;
871  curwin->w_stl_line_count = curwin->w_buffer->b_ml.ml_line_count;
872  curwin->w_stl_topfill = curwin->w_topfill;
873  curwin->w_stl_recording = reg_recording;
874  curwin->w_stl_state = state;
875  if (Visual.active) {
876    curwin->w_stl_visual_mode = Visual.mode;
877    curwin->w_stl_visual_pos = Visual.start;
878  }
879}
880
881/// @return true when postponing displaying the mode message: when not redrawing
882/// or inside a mapping.
883bool skip_showmode(void)
884{
885  // Call char_avail() only when we are going to show something, because it
886  // takes a bit of time.  redrawing() may also call char_avail().
887  if (global_busy || msg_silent != 0 || !redrawing() || (char_avail() && !KeyTyped)) {
888    redraw_mode = true;  // show mode later
889    return true;
890  }
891  return false;
892}
893
894/// Show the current mode and ruler.
895///
896/// If clear_cmdline is true, clear the rest of the cmdline.
897/// If clear_cmdline is false there may be a message there that needs to be
898/// cleared only if a mode is shown.
899/// If redraw_mode is true show or clear the mode.
900/// @return the length of the message (0 if no message).
901int showmode(void)
902{
903  int length = 0;
904
905  // Don't make non-flushed message part of the showmode.
906  msg_ext_ui_flush();
907
908  msg_grid_validate();
909
910  bool do_mode = ((p_smd && msg_silent == 0)
911                  && ((State & MODE_TERMINAL)
912                      || (State & MODE_INSERT)
913                      || restart_edit != NUL
914                      || Visual.active));
915
916  bool can_show_mode = (p_ch != 0 || ui_has(kUIMessages));
917  if ((do_mode || reg_recording != 0) && can_show_mode) {
918    if (skip_showmode()) {
919      return 0;  // show mode later
920    }
921
922    bool nwr_save = need_wait_return;
923
924    // wait a bit before overwriting an important message
925    msg_check_for_delay(false);
926
927    // if the cmdline is more than one line high, erase top lines
928    bool need_clear = clear_cmdline;
929    if (clear_cmdline && cmdline_row < Rows - 1) {
930      msg_clr_cmdline();  // will reset clear_cmdline
931    }
932
933    // Position on the last line in the window, column 0
934    msg_pos_mode();
935    int hl_id = HLF_CM;  // Highlight mode
936
937    // When the screen is too narrow to show the entire mode message,
938    // avoid scrolling and truncate instead.
939    msg_no_more = true;
940    int save_lines_left = lines_left;
941    lines_left = 0;
942
943    if (do_mode) {
944      msg_puts_hl("--", hl_id, false);
945      // CTRL-X in Insert mode
946      if (edit_submode != NULL && !shortmess(kShmCompletionmenu)) {
947        // These messages can get long, avoid a wrap in a narrow window.
948        // Prefer showing edit_submode_extra. With external messages there
949        // is no imposed limit.
950        if (ui_has(kUIMessages)) {
951          length = INT_MAX;
952        } else {
953          length = (Rows - msg_row) * Columns - 3;
954        }
955        if (edit_submode_extra != NULL) {
956          length -= vim_strsize(edit_submode_extra);
957        }
958        if (length > 0) {
959          if (edit_submode_pre != NULL) {
960            length -= vim_strsize(edit_submode_pre);
961          }
962          if (length - vim_strsize(edit_submode) > 0) {
963            if (edit_submode_pre != NULL) {
964              msg_puts_hl(edit_submode_pre, hl_id, false);
965            }
966            msg_puts_hl(edit_submode, hl_id, false);
967          }
968          if (edit_submode_extra != NULL) {
969            msg_puts_hl(" ", hl_id, false);  // Add a space in between.
970            int sub_id = edit_submode_highl < HLF_COUNT ? (int)edit_submode_highl : hl_id;
971            msg_puts_hl(edit_submode_extra, sub_id, false);
972          }
973        }
974      } else {
975        if (State & MODE_TERMINAL) {
976          msg_puts_hl(_(" TERMINAL"), hl_id, false);
977        } else if (State & VREPLACE_FLAG) {
978          msg_puts_hl(_(" VREPLACE"), hl_id, false);
979        } else if (State & REPLACE_FLAG) {
980          msg_puts_hl(_(" REPLACE"), hl_id, false);
981        } else if (State & MODE_INSERT) {
982          if (p_ri) {
983            msg_puts_hl(_(" REVERSE"), hl_id, false);
984          }
985          msg_puts_hl(_(" INSERT"), hl_id, false);
986        } else if (restart_edit == 'I' || restart_edit == 'i'
987                   || restart_edit == 'a' || restart_edit == 'A') {
988          if (curbuf->terminal) {
989            msg_puts_hl(_(" (terminal)"), hl_id, false);
990          } else {
991            msg_puts_hl(_(" (insert)"), hl_id, false);
992          }
993        } else if (restart_edit == 'R') {
994          msg_puts_hl(_(" (replace)"), hl_id, false);
995        } else if (restart_edit == 'V') {
996          msg_puts_hl(_(" (vreplace)"), hl_id, false);
997        }
998        if (State & MODE_LANGMAP) {
999          if (curwin->w_p_arab) {
1000            msg_puts_hl(_(" Arabic"), hl_id, false);
1001          } else if (get_keymap_str(curwin, " (%s)", NameBuff, MAXPATHL) > 0) {
1002            msg_puts_hl(NameBuff, hl_id, false);
1003          }
1004        }
1005        if ((State & MODE_INSERT) && p_paste) {
1006          msg_puts_hl(_(" (paste)"), hl_id, false);
1007        }
1008
1009        if (Visual.active) {
1010          char *p;
1011
1012          // Don't concatenate separate words to avoid translation
1013          // problems.
1014          switch ((Visual.select ? 4 : 0)
1015                  + (Visual.mode == Ctrl_V) * 2
1016                  + (Visual.mode == 'V')) {
1017          case 0:
1018            p = N_(" VISUAL"); break;
1019          case 1:
1020            p = N_(" VISUAL LINE"); break;
1021          case 2:
1022            p = N_(" VISUAL BLOCK"); break;
1023          case 4:
1024            p = N_(" SELECT"); break;
1025          case 5:
1026            p = N_(" SELECT LINE"); break;
1027          default:
1028            p = N_(" SELECT BLOCK"); break;
1029          }
1030          msg_puts_hl(_(p), hl_id, false);
1031        }
1032        msg_puts_hl(" --", hl_id, false);
1033      }
1034
1035      need_clear = true;
1036    }
1037    if (reg_recording != 0
1038        && edit_submode == NULL             // otherwise it gets too long
1039        ) {
1040      recording_mode(hl_id);
1041      need_clear = true;
1042    }
1043
1044    mode_displayed = true;
1045    if (need_clear || clear_cmdline || redraw_mode) {
1046      msg_clr_eos();
1047    }
1048    msg_didout = false;                 // overwrite this message
1049    length = msg_col;
1050    msg_col = 0;
1051    msg_no_more = false;
1052    lines_left = save_lines_left;
1053    need_wait_return = nwr_save;        // never ask for hit-return for this
1054  } else if (clear_cmdline && msg_silent == 0) {
1055    // Clear the whole command line.  Will reset "clear_cmdline".
1056    msg_clr_cmdline();
1057  } else if (redraw_mode) {
1058    msg_pos_mode();
1059    msg_clr_eos();
1060  }
1061
1062  // NB: also handles clearing the showmode if it was empty or disabled
1063  msg_ext_flush_showmode();
1064
1065  // In Visual mode the size of the selected area must be redrawn.
1066  if (Visual.active) {
1067    clear_showcmd();
1068  }
1069
1070  redraw_ruler();      // check if ruler should be redrawn
1071  redraw_cmdline = false;
1072  redraw_mode = false;
1073  clear_cmdline = false;
1074
1075  return length;
1076}
1077
1078/// Position for a mode message.
1079static void msg_pos_mode(void)
1080{
1081  msg_col = 0;
1082  msg_row = Rows - 1;
1083}
1084
1085/// Delete mode message.  Used when ESC is typed which is expected to end
1086/// Insert mode (but Insert mode didn't end yet!).
1087/// Caller should check "mode_displayed".
1088void unshowmode(bool force)
1089{
1090  // Don't delete it right now, when not redrawing or inside a mapping.
1091  if (!redrawing() || (!force && char_avail() && !KeyTyped)) {
1092    redraw_cmdline = true;  // delete mode later
1093  } else {
1094    clearmode();
1095  }
1096}
1097
1098// Clear the mode message.
1099void clearmode(void)
1100{
1101  const int save_msg_row = msg_row;
1102  const int save_msg_col = msg_col;
1103
1104  msg_ext_ui_flush();
1105  msg_pos_mode();
1106  if (reg_recording != 0) {
1107    recording_mode(HLF_CM);
1108  }
1109  msg_clr_eos();
1110  msg_ext_flush_showmode();
1111
1112  msg_col = save_msg_col;
1113  msg_row = save_msg_row;
1114}
1115
1116static void recording_mode(int hl_id)
1117{
1118  if (shortmess(kShmRecording)) {
1119    return;
1120  }
1121
1122  msg_puts_hl(_("recording"), hl_id, false);
1123  char s[4];
1124  snprintf(s, ARRAY_SIZE(s), " @%c", reg_recording);
1125  msg_puts_hl(s, hl_id, false);
1126}
1127
1128#define COL_RULER 18        // columns needed by standard ruler
1129
1130/// Compute columns for ruler and shown command. 'sc_col' is also used to
1131/// decide what the maximum length of a message on the status line can be.
1132/// If there is a status line for the last window, 'sc_col' is independent
1133/// of 'ru_col'.
1134void comp_col(void)
1135{
1136  bool last_has_status = last_stl_height(false) > 0;
1137
1138  sc_col = 0;
1139  ru_col = 0;
1140  if (p_ru) {
1141    ru_col = (ru_wid ? ru_wid : COL_RULER);
1142    // no last status line, adjust sc_col
1143    if (!last_has_status) {
1144      sc_col = ru_col;
1145    }
1146  }
1147  if (p_sc && *p_sloc == 'l') {
1148    sc_col += SHOWCMD_COLS;
1149    if (!p_ru || last_has_status) {         // no need for separating space
1150      sc_col++;
1151    }
1152  }
1153  assert(sc_col >= 0
1154         && INT_MIN + sc_col <= Columns);
1155  sc_col = Columns - sc_col;
1156  assert(ru_col >= 0
1157         && INT_MIN + ru_col <= Columns);
1158  ru_col = Columns - ru_col;
1159  if (sc_col <= 0) {            // screen too narrow, will become a mess
1160    sc_col = 1;
1161  }
1162  if (ru_col <= 0) {
1163    ru_col = 1;
1164  }
1165  set_vim_var_nr(VV_ECHOSPACE, sc_col - 1);
1166}
1167
1168/// Redraw entire window "wp" if "auto" 'signcolumn' width has changed.
1169static bool win_redraw_signcols(win_T *wp)
1170{
1171  buf_T *buf = wp->w_buffer;
1172
1173  if (!buf->b_signcols.autom
1174      && (*wp->w_p_stc != NUL || (wp->w_maxscwidth > 1 && wp->w_minscwidth != wp->w_maxscwidth))) {
1175    buf->b_signcols.autom = true;
1176    buf_signcols_count_range(buf, 0, buf->b_ml.ml_line_count - 1, MAXLNUM, kFalse);
1177  }
1178
1179  while (buf->b_signcols.max > 0 && buf->b_signcols.count[buf->b_signcols.max - 1] == 0) {
1180    buf->b_signcols.max--;
1181  }
1182
1183  int width = MIN(wp->w_maxscwidth, buf->b_signcols.max);
1184  bool rebuild_stc = buf->b_signcols.max != buf->b_signcols.last_max && *wp->w_p_stc != NUL;
1185
1186  if (rebuild_stc) {
1187    wp->w_nrwidth_line_count = 0;
1188  } else if (wp->w_minscwidth == 0 && wp->w_maxscwidth == 1) {
1189    width = buf_meta_total(buf, kMTMetaSignText) > 0;
1190  }
1191
1192  int scwidth = wp->w_scwidth;
1193  wp->w_scwidth = MAX(MAX(0, wp->w_minscwidth), width);
1194  return (wp->w_scwidth != scwidth || rebuild_stc);
1195}
1196
1197/// Check if horizontal separator of window "wp" at specified window corner is connected to the
1198/// horizontal separator of another window
1199/// Assumes global statusline is enabled
1200static bool hsep_connected(win_T *wp, WindowCorner corner)
1201{
1202  bool before = (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT);
1203  int sep_row = (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT)
1204                ? wp->w_winrow - 1 : W_ENDROW(wp);
1205  frame_T *fr = wp->w_frame;
1206
1207  while (fr->fr_parent != NULL) {
1208    if (fr->fr_parent->fr_layout == FR_ROW && (before ? fr->fr_prev : fr->fr_next) != NULL) {
1209      fr = before ? fr->fr_prev : fr->fr_next;
1210      break;
1211    }
1212    fr = fr->fr_parent;
1213  }
1214  if (fr->fr_parent == NULL) {
1215    return false;
1216  }
1217  while (fr->fr_layout != FR_LEAF) {
1218    fr = fr->fr_child;
1219    if (fr->fr_parent->fr_layout == FR_ROW && before) {
1220      while (fr->fr_next != NULL) {
1221        fr = fr->fr_next;
1222      }
1223    } else {
1224      while (fr->fr_next != NULL && frame2win(fr)->w_winrow + fr->fr_height < sep_row) {
1225        fr = fr->fr_next;
1226      }
1227    }
1228  }
1229
1230  return (sep_row == fr->fr_win->w_winrow - 1 || sep_row == W_ENDROW(fr->fr_win));
1231}
1232
1233/// Check if vertical separator of window "wp" at specified window corner is connected to the
1234/// vertical separator of another window
1235static bool vsep_connected(win_T *wp, WindowCorner corner)
1236{
1237  bool before = (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT);
1238  int sep_col = (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT)
1239                ? wp->w_wincol - 1 : W_ENDCOL(wp);
1240  frame_T *fr = wp->w_frame;
1241
1242  while (fr->fr_parent != NULL) {
1243    if (fr->fr_parent->fr_layout == FR_COL && (before ? fr->fr_prev : fr->fr_next) != NULL) {
1244      fr = before ? fr->fr_prev : fr->fr_next;
1245      break;
1246    }
1247    fr = fr->fr_parent;
1248  }
1249  if (fr->fr_parent == NULL) {
1250    return false;
1251  }
1252  while (fr->fr_layout != FR_LEAF) {
1253    fr = fr->fr_child;
1254    if (fr->fr_parent->fr_layout == FR_COL && before) {
1255      while (fr->fr_next != NULL) {
1256        fr = fr->fr_next;
1257      }
1258    } else {
1259      while (fr->fr_next != NULL && frame2win(fr)->w_wincol + fr->fr_width < sep_col) {
1260        fr = fr->fr_next;
1261      }
1262    }
1263  }
1264
1265  return (sep_col == fr->fr_win->w_wincol - 1 || sep_col == W_ENDCOL(fr->fr_win));
1266}
1267
1268/// Draw the vertical separator right of window "wp"
1269static void draw_vsep_win(win_T *wp)
1270{
1271  if (!wp->w_vsep_width) {
1272    return;
1273  }
1274
1275  // draw the vertical separator right of this window
1276  for (int row = wp->w_winrow; row < W_ENDROW(wp); row++) {
1277    grid_line_start(&default_gridview, row);
1278    grid_line_put_schar(W_ENDCOL(wp), wp->w_p_fcs_chars.vert, win_hl_attr(wp, HLF_C));
1279    grid_line_flush();
1280  }
1281}
1282
1283/// Draw the horizontal separator below window "wp"
1284static void draw_hsep_win(win_T *wp)
1285{
1286  if (!wp->w_hsep_height) {
1287    return;
1288  }
1289
1290  // draw the horizontal separator below this window
1291  grid_line_start(&default_gridview, W_ENDROW(wp));
1292  grid_line_fill(wp->w_wincol, W_ENDCOL(wp), wp->w_p_fcs_chars.horiz, win_hl_attr(wp, HLF_C));
1293  grid_line_flush();
1294}
1295
1296/// Get the separator connector for specified window corner of window "wp"
1297static schar_T get_corner_sep_connector(win_T *wp, WindowCorner corner)
1298{
1299  // It's impossible for windows to be connected neither vertically nor horizontally
1300  // So if they're not vertically connected, assume they're horizontally connected
1301  if (vsep_connected(wp, corner)) {
1302    if (hsep_connected(wp, corner)) {
1303      return wp->w_p_fcs_chars.verthoriz;
1304    } else if (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT) {
1305      return wp->w_p_fcs_chars.vertright;
1306    } else {
1307      return wp->w_p_fcs_chars.vertleft;
1308    }
1309  } else if (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT) {
1310    return wp->w_p_fcs_chars.horizdown;
1311  } else {
1312    return wp->w_p_fcs_chars.horizup;
1313  }
1314}
1315
1316/// Draw separator connecting characters on the corners of window "wp"
1317static void draw_sep_connectors_win(win_T *wp)
1318{
1319  // Don't draw separator connectors unless global statusline is enabled and the window has
1320  // either a horizontal or vertical separator
1321  if (global_stl_height() == 0 || !(wp->w_hsep_height == 1 || wp->w_vsep_width == 1)) {
1322    return;
1323  }
1324
1325  int hl = win_hl_attr(wp, HLF_C);
1326
1327  // Determine which edges of the screen the window is located on so we can avoid drawing separators
1328  // on corners contained in those edges
1329  bool win_at_top;
1330  bool win_at_bottom = wp->w_hsep_height == 0;
1331  bool win_at_left;
1332  bool win_at_right = wp->w_vsep_width == 0;
1333  frame_T *frp;
1334
1335  for (frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
1336    if (frp->fr_parent->fr_layout == FR_COL && frp->fr_prev != NULL) {
1337      break;
1338    }
1339  }
1340  win_at_top = frp->fr_parent == NULL;
1341  for (frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
1342    if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_prev != NULL) {
1343      break;
1344    }
1345  }
1346  win_at_left = frp->fr_parent == NULL;
1347
1348  // Draw the appropriate separator connector in every corner where drawing them is necessary
1349  // Make sure not to send cursor position updates to ui.
1350  bool top_left = !(win_at_top || win_at_left);
1351  bool top_right = !(win_at_top || win_at_right);
1352  bool bot_left = !(win_at_bottom || win_at_left);
1353  bool bot_right = !(win_at_bottom || win_at_right);
1354
1355  if (top_left) {
1356    grid_line_start(&default_gridview, wp->w_winrow - 1);
1357    grid_line_put_schar(wp->w_wincol - 1, get_corner_sep_connector(wp, WC_TOP_LEFT), hl);
1358    grid_line_flush();
1359  }
1360  if (top_right) {
1361    grid_line_start(&default_gridview, wp->w_winrow - 1);
1362    grid_line_put_schar(W_ENDCOL(wp), get_corner_sep_connector(wp, WC_TOP_RIGHT), hl);
1363    grid_line_flush();
1364  }
1365  if (bot_left) {
1366    grid_line_start(&default_gridview, W_ENDROW(wp));
1367    grid_line_put_schar(wp->w_wincol - 1, get_corner_sep_connector(wp, WC_BOTTOM_LEFT), hl);
1368    grid_line_flush();
1369  }
1370  if (bot_right) {
1371    grid_line_start(&default_gridview, W_ENDROW(wp));
1372    grid_line_put_schar(W_ENDCOL(wp), get_corner_sep_connector(wp, WC_BOTTOM_RIGHT), hl);
1373    grid_line_flush();
1374  }
1375}
1376
1377/// Update a single window.
1378///
1379/// This may cause the windows below it also to be redrawn (when clearing the
1380/// screen or scrolling lines).
1381///
1382/// How the window is redrawn depends on wp->w_redr_type.  Each type also
1383/// implies the one below it.
1384/// UPD_NOT_VALID    redraw the whole window
1385/// UPD_SOME_VALID   redraw the whole window but do scroll when possible
1386/// UPD_REDRAW_TOP   redraw the top w_upd_rows window lines, otherwise like UPD_VALID
1387/// UPD_INVERTED     redraw the changed part of the Visual area
1388/// UPD_INVERTED_ALL redraw the whole Visual area
1389/// UPD_VALID        1. scroll up/down to adjust for a changed w_topline
1390///                  2. update lines at the top when scrolled down
1391///                  3. redraw changed text:
1392///                     - if wp->w_buffer->b_mod_set set, update lines between
1393///                       b_mod_top and b_mod_bot.
1394///                     - if wp->w_redraw_top non-zero, redraw lines between
1395///                       wp->w_redraw_top and wp->w_redraw_bot.
1396///                     - continue redrawing when syntax status is invalid.
1397///                  4. if scrolled up, update lines at the bottom.
1398/// This results in three areas that may need updating:
1399/// top: from first row to top_end (when scrolled down)
1400/// mid: from mid_start to mid_end (update inversion or changed text)
1401/// bot: from bot_start to last row (when scrolled up)
1402static void win_update(win_T *wp)
1403{
1404  // Return early when the windows would overflow the shrunk terminal window
1405  // avoiding invalid drawing an assert failure
1406  if (wp->w_grid.target == &default_grid && wp->w_wincol >= Columns) {
1407    return;
1408  }
1409
1410  int top_end = 0;              // Below last row of the top area that needs
1411                                // updating.  0 when no top area updating.
1412  int mid_start = 999;          // first row of the mid area that needs
1413                                // updating.  999 when no mid area updating.
1414  int mid_end = 0;              // Below last row of the mid area that needs
1415                                // updating.  0 when no mid area updating.
1416  int bot_start = 999;          // first row of the bot area that needs
1417                                // updating.  999 when no bot area updating
1418  bool scrolled_down = false;   // true when scrolled down when w_topline got smaller a bit
1419  bool scrolled_for_mod = false;  // true after scrolling for changed lines
1420  bool top_to_mod = false;      // redraw above mod_top
1421
1422  int bot_scroll_start = 999;   // first line that needs to be redrawn due to
1423                                // scrolling. only used for EOB
1424
1425  static bool recursive = false;  // being called recursively
1426
1427  // Remember what happened to the previous line.
1428  enum {
1429    DID_NONE = 1,  // didn't update a line
1430    DID_LINE = 2,  // updated a normal line
1431    DID_FOLD = 3,  // updated a folded line
1432  } did_update = DID_NONE;
1433
1434  linenr_T syntax_last_parsed = 0;              // last parsed text line
1435  linenr_T mod_top = 0;
1436  linenr_T mod_bot = 0;
1437
1438  int type = wp->w_redr_type;
1439
1440  if (type >= UPD_NOT_VALID) {
1441    wp->w_redr_status = true;
1442    wp->w_lines_valid = 0;
1443  }
1444
1445  // Window is zero-height: Only need to draw the separator
1446  if (wp->w_view_height == 0) {
1447    // draw the vertical separator right of this window
1448    draw_vsep_win(wp);
1449    // draw the horizontal separator below this window
1450    draw_hsep_win(wp);
1451    wp->w_redr_type = 0;
1452    return;
1453  }
1454
1455  // Window is zero-width: Only need to draw the separator.
1456  if (wp->w_view_width == 0) {
1457    // draw the vertical separator right of this window
1458    draw_vsep_win(wp);
1459    wp->w_redr_type = 0;
1460    return;
1461  }
1462
1463  buf_T *buf = wp->w_buffer;
1464
1465  // reset got_int, otherwise regexp won't work
1466  int save_got_int = got_int;
1467  got_int = 0;
1468  // Set the time limit to 'redrawtime'.
1469  proftime_T syntax_tm = profile_setlimit(p_rdt);
1470  syn_set_timeout(&syntax_tm);
1471
1472  win_extmark_arr.size = 0;
1473
1474  decor_redraw_reset(wp, &decor_state);
1475
1476  decor_providers_invoke_win(wp);
1477
1478  if (buf->terminal && terminal_suspended(buf->terminal)) {
1479    static VirtTextChunk chunk = { .text = "[Process suspended]", .hl_id = -1 };
1480    static DecorVirtText virt_text = {
1481      .priority = DECOR_PRIORITY_BASE,
1482      .pos = kVPosWinCol,
1483      .data.virt_text = { .items = &chunk, .size = 1 },
1484    };
1485    decor_range_add_virt(&decor_state, buf->b_ml.ml_line_count - 1, 0,
1486                         buf->b_ml.ml_line_count - 1, 0, &virt_text, false);
1487  }
1488
1489  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
1490    if (win->w_buffer == wp->w_buffer && win_redraw_signcols(win)) {
1491      changed_line_abv_curs_win(win);
1492      redraw_later(win, UPD_NOT_VALID);
1493    }
1494  }
1495  buf->b_signcols.last_max = buf->b_signcols.max;
1496
1497  // Validate w_virtcol here as it can change the redraw type.
1498  validate_virtcol(wp);
1499  type = wp->w_redr_type;
1500
1501  init_search_hl(wp, &screen_search_hl);
1502
1503  // Make sure skipcol is valid, it depends on various options and the window
1504  // width.
1505  if (wp->w_skipcol > 0 && wp->w_view_width > win_col_off(wp)) {
1506    int w = 0;
1507    int width1 = wp->w_view_width - win_col_off(wp);
1508    int width2 = width1 + win_col_off2(wp);
1509    int add = width1;
1510
1511    while (w < wp->w_skipcol) {
1512      if (w > 0) {
1513        add = width2;
1514      }
1515      w += add;
1516    }
1517    if (w != wp->w_skipcol) {
1518      // always round down, the higher value may not be valid
1519      wp->w_skipcol = w - add;
1520    }
1521  }
1522
1523  const int nrwidth_before = wp->w_nrwidth;
1524  int nrwidth_new = (wp->w_p_nu || wp->w_p_rnu || *wp->w_p_stc) ? number_width(wp) : 0;
1525  // Force redraw when width of 'number' or 'relativenumber' column changes.
1526  if (wp->w_nrwidth != nrwidth_new) {
1527    type = UPD_NOT_VALID;
1528    changed_line_abv_curs_win(wp);
1529    wp->w_nrwidth = nrwidth_new;
1530  } else {
1531    // Set mod_top to the first line that needs displaying because of
1532    // changes.  Set mod_bot to the first line after the changes.
1533    mod_top = wp->w_redraw_top;
1534    if (wp->w_redraw_bot != 0) {
1535      mod_bot = wp->w_redraw_bot + 1;
1536    } else {
1537      mod_bot = 0;
1538    }
1539    if (buf->b_mod_set) {
1540      if (mod_top == 0 || mod_top > buf->b_mod_top) {
1541        mod_top = buf->b_mod_top;
1542        // Need to redraw lines above the change that may be included
1543        // in a pattern match.
1544        if (syntax_present(wp)) {
1545          mod_top -= buf->b_s.b_syn_sync_linebreaks;
1546          mod_top = MAX(mod_top, 1);
1547        }
1548      }
1549      if (mod_bot == 0 || mod_bot < buf->b_mod_bot) {
1550        mod_bot = buf->b_mod_bot;
1551      }
1552
1553      // When 'hlsearch' is on and using a multi-line search pattern, a
1554      // change in one line may make the Search highlighting in a
1555      // previous line invalid.  Simple solution: redraw all visible
1556      // lines above the change.
1557      // Same for a match pattern.
1558      if (screen_search_hl.rm.regprog != NULL
1559          && re_multiline(screen_search_hl.rm.regprog)) {
1560        top_to_mod = true;
1561      } else {
1562        const matchitem_T *cur = wp->w_match_head;
1563        while (cur != NULL) {
1564          if (cur->mit_match.regprog != NULL
1565              && re_multiline(cur->mit_match.regprog)) {
1566            top_to_mod = true;
1567            break;
1568          }
1569          cur = cur->mit_next;
1570        }
1571      }
1572    }
1573
1574    if (search_hl_has_cursor_lnum > 0) {
1575      // CurSearch was used last time, need to redraw the line with it to
1576      // avoid having two matches highlighted with CurSearch.
1577      if (mod_top == 0 || mod_top > search_hl_has_cursor_lnum) {
1578        mod_top = search_hl_has_cursor_lnum;
1579      }
1580      if (mod_bot == 0 || mod_bot < search_hl_has_cursor_lnum + 1) {
1581        mod_bot = search_hl_has_cursor_lnum + 1;
1582      }
1583    }
1584
1585    if (mod_top != 0 && win_lines_concealed(wp)) {
1586      // A change in a line can cause lines above it to become folded or
1587      // unfolded.  Find the top most buffer line that may be affected.
1588      // If the line was previously folded and displayed, get the first
1589      // line of that fold.  If the line is folded now, get the first
1590      // folded line.  Use the minimum of these two.
1591
1592      // Find last valid w_lines[] entry above mod_top.  Set lnumt to
1593      // the line below it.  If there is no valid entry, use w_topline.
1594      // Find the first valid w_lines[] entry below mod_bot.  Set lnumb
1595      // to this line.  If there is no valid entry, use MAXLNUM.
1596      linenr_T lnumt = wp->w_topline;
1597      linenr_T lnumb = MAXLNUM;
1598      for (int i = 0; i < wp->w_lines_valid; i++) {
1599        if (wp->w_lines[i].wl_valid) {
1600          if (wp->w_lines[i].wl_lastlnum < mod_top) {
1601            lnumt = wp->w_lines[i].wl_lastlnum + 1;
1602          }
1603          if (lnumb == MAXLNUM && wp->w_lines[i].wl_lnum >= mod_bot) {
1604            lnumb = wp->w_lines[i].wl_lnum;
1605            // When there is a fold column it might need updating
1606            // in the next line ("J" just above an open fold).
1607            if (compute_foldcolumn(wp, 0) > 0) {
1608              lnumb++;
1609            }
1610          }
1611        }
1612      }
1613
1614      hasFolding(wp, mod_top, &mod_top, NULL);
1615      mod_top = MIN(mod_top, lnumt);
1616
1617      // Now do the same for the bottom line (one above mod_bot).
1618      mod_bot--;
1619      hasFolding(wp, mod_bot, NULL, &mod_bot);
1620      mod_bot++;
1621      mod_bot = MAX(mod_bot, lnumb);
1622    }
1623
1624    // When a change starts above w_topline and the end is below
1625    // w_topline, start redrawing at w_topline.
1626    // If the end of the change is above w_topline: do like no change was
1627    // made, but redraw the first line to find changes in syntax.
1628    if (mod_top != 0 && mod_top < wp->w_topline) {
1629      if (mod_bot > wp->w_topline) {
1630        mod_top = wp->w_topline;
1631      } else if (syntax_present(wp)) {
1632        top_end = 1;
1633      }
1634    }
1635  }
1636
1637  wp->w_redraw_top = 0;  // reset for next time
1638  wp->w_redraw_bot = 0;
1639  search_hl_has_cursor_lnum = 0;
1640
1641  // When only displaying the lines at the top, set top_end.  Used when
1642  // window has scrolled down for msg_scrolled.
1643  if (type == UPD_REDRAW_TOP) {
1644    int j = 0;
1645    for (int i = 0; i < wp->w_lines_valid; i++) {
1646      j += wp->w_lines[i].wl_size;
1647      if (j >= wp->w_upd_rows) {
1648        top_end = j;
1649        break;
1650      }
1651    }
1652    if (top_end == 0) {
1653      // not found (cannot happen?): redraw everything
1654      type = UPD_NOT_VALID;
1655    } else {
1656      // top area defined, the rest is UPD_VALID
1657      type = UPD_VALID;
1658    }
1659  }
1660
1661  // Below logic compares wp->w_topline against wp->w_lines[0].wl_lnum,
1662  // which may point to a line below wp->w_topline if it is concealed;
1663  // incurring scrolling even though wp->w_topline is still the same.
1664  // Compare against an adjusted topline instead:
1665  linenr_T topline_conceal = wp->w_topline;
1666  while (topline_conceal < buf->b_ml.ml_line_count
1667         && decor_conceal_line(wp, topline_conceal - 1, false)) {
1668    topline_conceal++;
1669    hasFolding(wp, topline_conceal, NULL, &topline_conceal);
1670  }
1671
1672  // If there are no changes on the screen that require a complete redraw,
1673  // handle three cases:
1674  // 1: we are off the top of the screen by a few lines: scroll down
1675  // 2: wp->w_topline is below wp->w_lines[0].wl_lnum: may scroll up
1676  // 3: wp->w_topline is wp->w_lines[0].wl_lnum: find first entry in
1677  //    w_lines[] that needs updating.
1678  if ((type == UPD_VALID || type == UPD_SOME_VALID
1679       || type == UPD_INVERTED || type == UPD_INVERTED_ALL)
1680      && !wp->w_botfill && !wp->w_old_botfill) {
1681    if (mod_top != 0
1682        && wp->w_topline == mod_top
1683        && (!wp->w_lines[0].wl_valid
1684            || topline_conceal == wp->w_lines[0].wl_lnum)) {
1685      // w_topline is the first changed line and window is not scrolled,
1686      // the scrolling from changed lines will be done further down.
1687    } else if (wp->w_lines[0].wl_valid
1688               && (topline_conceal < wp->w_lines[0].wl_lnum
1689                   || (topline_conceal == wp->w_lines[0].wl_lnum
1690                       && wp->w_topfill > wp->w_old_topfill))) {
1691      // New topline is above old topline: May scroll down.
1692      int j;
1693      if (win_lines_concealed(wp)) {
1694        // Count the number of lines we are off, counting a sequence
1695        // of folded lines as one, and skip concealed lines.
1696        j = 0;
1697        for (linenr_T ln = wp->w_topline; ln < wp->w_lines[0].wl_lnum; ln++) {
1698          j += !decor_conceal_line(wp, ln - 1, false);
1699          if (j >= wp->w_view_height - 2) {
1700            break;
1701          }
1702          hasFolding(wp, ln, NULL, &ln);
1703        }
1704      } else {
1705        j = wp->w_lines[0].wl_lnum - wp->w_topline;
1706      }
1707      if (j < wp->w_view_height - 2) {               // not too far off
1708        int i = plines_m_win(wp, wp->w_topline, wp->w_lines[0].wl_lnum - 1, wp->w_view_height);
1709        // insert extra lines for previously invisible filler lines
1710        if (wp->w_lines[0].wl_lnum != wp->w_topline) {
1711          i += win_get_fill(wp, wp->w_lines[0].wl_lnum) - wp->w_old_topfill;
1712        }
1713        if (i != 0 && i < wp->w_view_height - 2) {  // less than a screen off
1714          // Try to insert the correct number of lines.
1715          // If not the last window, delete the lines at the bottom.
1716          // win_ins_lines may fail when the terminal can't do it.
1717          win_scroll_lines(wp, 0, i);
1718          bot_scroll_start = 0;
1719          if (wp->w_lines_valid != 0) {
1720            // Need to update rows that are new, stop at the
1721            // first one that scrolled down.
1722            top_end = i;
1723            scrolled_down = true;
1724
1725            // Move the entries that were scrolled, disable
1726            // the entries for the lines to be redrawn.
1727            if ((wp->w_lines_valid += (linenr_T)j) > wp->w_view_height) {
1728              wp->w_lines_valid = wp->w_view_height;
1729            }
1730            int idx;
1731            for (idx = wp->w_lines_valid; idx - j >= 0; idx--) {
1732              wp->w_lines[idx] = wp->w_lines[idx - j];
1733            }
1734            while (idx >= 0) {
1735              wp->w_lines[idx--].wl_valid = false;
1736            }
1737          }
1738        } else {
1739          mid_start = 0;  // redraw all lines
1740        }
1741      } else {
1742        mid_start = 0;  // redraw all lines
1743      }
1744    } else {
1745      // New topline is at or below old topline: May scroll up.
1746      // When topline didn't change, find first entry in w_lines[] that
1747      // needs updating.
1748
1749      // try to find wp->w_topline in wp->w_lines[].wl_lnum
1750      int j = -1;
1751      int row = 0;
1752      for (int i = 0; i < wp->w_lines_valid; i++) {
1753        if (wp->w_lines[i].wl_valid
1754            && wp->w_lines[i].wl_lnum == wp->w_topline) {
1755          j = i;
1756          break;
1757        }
1758        row += wp->w_lines[i].wl_size;
1759      }
1760      if (j == -1) {
1761        // if wp->w_topline is not in wp->w_lines[].wl_lnum redraw all
1762        // lines
1763        mid_start = 0;
1764      } else {
1765        // Try to delete the correct number of lines.
1766        // wp->w_topline is at wp->w_lines[i].wl_lnum.
1767
1768        // If the topline didn't change, delete old filler lines,
1769        // otherwise delete filler lines of the new topline...
1770        if (wp->w_lines[0].wl_lnum == wp->w_topline) {
1771          row += wp->w_old_topfill;
1772        } else {
1773          row += win_get_fill(wp, wp->w_topline);
1774        }
1775        // ... but don't delete new filler lines.
1776        row -= wp->w_topfill;
1777        if (row > 0) {
1778          win_scroll_lines(wp, 0, -row);
1779          bot_start = wp->w_view_height - row;
1780          bot_scroll_start = bot_start;
1781        }
1782        if ((row == 0 || bot_start < 999) && wp->w_lines_valid != 0) {
1783          // Skip the lines (below the deleted lines) that are still
1784          // valid and don't need redrawing.    Copy their info
1785          // upwards, to compensate for the deleted lines.  Set
1786          // bot_start to the first row that needs redrawing.
1787          bot_start = 0;
1788          int idx = 0;
1789          while (true) {
1790            wp->w_lines[idx] = wp->w_lines[j];
1791            // stop at line that didn't fit, unless it is still
1792            // valid (no lines deleted)
1793            if (row > 0 && bot_start + row
1794                + (int)wp->w_lines[j].wl_size > wp->w_view_height) {
1795              wp->w_lines_valid = idx + 1;
1796              break;
1797            }
1798            bot_start += wp->w_lines[idx++].wl_size;
1799
1800            // stop at the last valid entry in w_lines[].wl_size
1801            if (++j >= wp->w_lines_valid) {
1802              wp->w_lines_valid = idx;
1803              break;
1804            }
1805          }
1806
1807          // Correct the first entry for filler lines at the top
1808          // when it won't get updated below.
1809          if (win_may_fill(wp) && bot_start > 0) {
1810            wp->w_lines[0].wl_size
1811              = (uint16_t)plines_correct_topline(wp, wp->w_topline, NULL, true, NULL);
1812          }
1813        }
1814      }
1815    }
1816
1817    // When starting redraw in the first line, redraw all lines.
1818    if (mid_start == 0) {
1819      mid_end = wp->w_view_height;
1820    }
1821  } else {
1822    // Not UPD_VALID or UPD_INVERTED: redraw all lines.
1823    mid_start = 0;
1824    mid_end = wp->w_view_height;
1825  }
1826
1827  if (type == UPD_SOME_VALID) {
1828    // UPD_SOME_VALID: redraw all lines.
1829    mid_start = 0;
1830    mid_end = wp->w_view_height;
1831    type = UPD_NOT_VALID;
1832  }
1833
1834  // check if we are updating or removing the inverted part
1835  if ((Visual.active && buf == curwin->w_buffer)
1836      || (wp->w_old_cursor_lnum != 0 && type != UPD_NOT_VALID)) {
1837    linenr_T from, to;
1838
1839    if (Visual.active) {
1840      if (Visual.mode != wp->w_old_visual_mode || type == UPD_INVERTED_ALL) {
1841        // If the type of Visual selection changed, redraw the whole
1842        // selection.  Also when the ownership of the X selection is
1843        // gained or lost.
1844        if (curwin->w_cursor.lnum < Visual.start.lnum) {
1845          from = curwin->w_cursor.lnum;
1846          to = Visual.start.lnum;
1847        } else {
1848          from = Visual.start.lnum;
1849          to = curwin->w_cursor.lnum;
1850        }
1851        // redraw more when the cursor moved as well
1852        from = MIN(MIN(from, wp->w_old_cursor_lnum), wp->w_old_visual_lnum);
1853        to = MAX(MAX(to, wp->w_old_cursor_lnum), wp->w_old_visual_lnum);
1854      } else {
1855        // Find the line numbers that need to be updated: The lines
1856        // between the old cursor position and the current cursor
1857        // position.  Also check if the Visual position changed.
1858        if (curwin->w_cursor.lnum < wp->w_old_cursor_lnum) {
1859          from = curwin->w_cursor.lnum;
1860          to = wp->w_old_cursor_lnum;
1861        } else {
1862          from = wp->w_old_cursor_lnum;
1863          to = curwin->w_cursor.lnum;
1864          if (from == 0) {              // Visual mode just started
1865            from = to;
1866          }
1867        }
1868
1869        if (Visual.start.lnum != wp->w_old_visual_lnum
1870            || Visual.start.col != wp->w_old_visual_col) {
1871          if (wp->w_old_visual_lnum < from
1872              && wp->w_old_visual_lnum != 0) {
1873            from = wp->w_old_visual_lnum;
1874          }
1875          to = MAX(MAX(to, wp->w_old_visual_lnum), Visual.start.lnum);
1876          from = MIN(from, Visual.start.lnum);
1877        }
1878      }
1879
1880      // If in block mode and changed column or curwin->w_curswant:
1881      // update all lines.
1882      // First compute the actual start and end column.
1883      if (Visual.mode == Ctrl_V) {
1884        colnr_T fromc, toc;
1885        getvcols(wp, &Visual.start, &curwin->w_cursor, &fromc, &toc, GETVCOL_END_EXCL_LBR);
1886        toc++;
1887        // Highlight to the end of the line, unless 'virtualedit' has
1888        // "block".
1889        if (curwin->w_curswant == MAXCOL) {
1890          if (get_ve_flags(curwin) & kOptVeFlagBlock) {
1891            pos_T pos;
1892            int cursor_above = curwin->w_cursor.lnum < Visual.start.lnum;
1893
1894            // Need to find the longest line.
1895            toc = 0;
1896            pos.coladd = 0;
1897            for (pos.lnum = curwin->w_cursor.lnum;
1898                 cursor_above ? pos.lnum <= Visual.start.lnum : pos.lnum >= Visual.start.lnum;
1899                 pos.lnum += cursor_above ? 1 : -1) {
1900              colnr_T t;
1901
1902              pos.col = ml_get_buf_len(wp->w_buffer, pos.lnum);
1903              getvvcol(wp, &pos, NULL, NULL, &t, 0);
1904              toc = MAX(toc, t);
1905            }
1906            toc++;
1907          } else {
1908            toc = MAXCOL;
1909          }
1910        }
1911
1912        if (fromc != wp->w_old_cursor_fcol
1913            || toc != wp->w_old_cursor_lcol) {
1914          from = MIN(from, Visual.start.lnum);
1915          to = MAX(to, Visual.start.lnum);
1916        }
1917        wp->w_old_cursor_fcol = fromc;
1918        wp->w_old_cursor_lcol = toc;
1919      }
1920    } else {
1921      // Use the line numbers of the old Visual area.
1922      if (wp->w_old_cursor_lnum < wp->w_old_visual_lnum) {
1923        from = wp->w_old_cursor_lnum;
1924        to = wp->w_old_visual_lnum;
1925      } else {
1926        from = wp->w_old_visual_lnum;
1927        to = wp->w_old_cursor_lnum;
1928      }
1929    }
1930
1931    // There is no need to update lines above the top of the window.
1932    from = MAX(from, wp->w_topline);
1933
1934    // If we know the value of w_botline, use it to restrict the update to
1935    // the lines that are visible in the window.
1936    if (wp->w_valid & VALID_BOTLINE) {
1937      from = MIN(from, wp->w_botline - 1);
1938      to = MIN(to, wp->w_botline - 1);
1939    }
1940
1941    // Find the minimal part to be updated.
1942    // Watch out for scrolling that made entries in w_lines[] invalid.
1943    // E.g., CTRL-U makes the first half of w_lines[] invalid and sets
1944    // top_end; need to redraw from top_end to the "to" line.
1945    // A middle mouse click with a Visual selection may change the text
1946    // above the Visual area and reset wl_valid, do count these for
1947    // mid_end (in srow).
1948    if (mid_start > 0) {
1949      linenr_T lnum = wp->w_topline;
1950      int idx = 0;
1951      int srow = 0;
1952      if (scrolled_down) {
1953        mid_start = top_end;
1954      } else {
1955        mid_start = 0;
1956      }
1957      while (lnum < from && idx < wp->w_lines_valid) {          // find start
1958        if (wp->w_lines[idx].wl_valid) {
1959          mid_start += wp->w_lines[idx].wl_size;
1960        } else if (!scrolled_down) {
1961          srow += wp->w_lines[idx].wl_size;
1962        }
1963        idx++;
1964        if (idx < wp->w_lines_valid && wp->w_lines[idx].wl_valid) {
1965          lnum = wp->w_lines[idx].wl_lnum;
1966        } else {
1967          lnum++;
1968        }
1969      }
1970      srow += mid_start;
1971      mid_end = wp->w_view_height;
1972      for (; idx < wp->w_lines_valid; idx++) {                  // find end
1973        if (wp->w_lines[idx].wl_valid
1974            && wp->w_lines[idx].wl_lnum >= to + 1) {
1975          // Only update until first row of this line
1976          mid_end = srow;
1977          break;
1978        }
1979        srow += wp->w_lines[idx].wl_size;
1980      }
1981    }
1982  }
1983
1984  if (Visual.active && buf == curwin->w_buffer) {
1985    wp->w_old_visual_mode = (char)Visual.mode;
1986    wp->w_old_cursor_lnum = curwin->w_cursor.lnum;
1987    wp->w_old_visual_lnum = Visual.start.lnum;
1988    wp->w_old_visual_col = Visual.start.col;
1989    wp->w_old_curswant = curwin->w_curswant;
1990  } else {
1991    wp->w_old_visual_mode = 0;
1992    wp->w_old_cursor_lnum = 0;
1993    wp->w_old_visual_lnum = 0;
1994    wp->w_old_visual_col = 0;
1995  }
1996
1997  foldinfo_T cursorline_fi = { 0 };
1998  win_update_cursorline(wp, &cursorline_fi);
1999  if (wp == curwin) {
2000    conceal_cursor_used = conceal_cursor_line(curwin);
2001  }
2002
2003  win_check_ns_hl(wp);
2004
2005  spellvars_T spv = { 0 };
2006  linenr_T lnum = wp->w_topline;  // first line shown in window
2007  // Initialize spell related variables for the first drawn line.
2008  if (spell_check_window(wp)) {
2009    spv.spv_has_spell = true;
2010    spv.spv_unchanged = mod_top == 0;
2011  }
2012
2013  // Update all the window rows.
2014  int idx = 0;                    // first entry in w_lines[].wl_size
2015  int row = 0;                    // current window row to display
2016  int srow = 0;                   // starting row of the current line
2017
2018  bool eof = false;             // if true, we hit the end of the file
2019  bool didline = false;         // if true, we finished the last line
2020  while (true) {
2021    // stop updating when reached the end of the window (check for _past_
2022    // the end of the window is at the end of the loop)
2023    if (row == wp->w_view_height) {
2024      didline = true;
2025      break;
2026    }
2027
2028    // stop updating when hit the end of the file
2029    if (lnum > buf->b_ml.ml_line_count) {
2030      eof = true;
2031      break;
2032    }
2033
2034    // Remember the starting row of the line that is going to be dealt
2035    // with.  It is used further down when the line doesn't fit.
2036    srow = row;
2037
2038    // Update a line when it is in an area that needs updating, when it
2039    // has changes or w_lines[idx] is invalid.
2040    // "bot_start" may be halfway a wrapped line after using
2041    // win_scroll_lines(), check if the current line includes it.
2042    // When syntax folding is being used, the saved syntax states will
2043    // already have been updated, we can't see where the syntax state is
2044    // the same again, just update until the end of the window.
2045    if (row < top_end
2046        || (row >= mid_start && row < mid_end)
2047        || top_to_mod
2048        || idx >= wp->w_lines_valid
2049        || (row + wp->w_lines[idx].wl_size > bot_start)
2050        || (mod_top != 0
2051            && (lnum == mod_top
2052                || (lnum >= mod_top
2053                    && (lnum < mod_bot
2054                        || did_update == DID_FOLD
2055                        || (did_update == DID_LINE
2056                            && syntax_present(wp)
2057                            && ((foldmethodIsSyntax(wp)
2058                                 && hasAnyFolding(wp))
2059                                || syntax_check_changed(lnum)))
2060                        // match in fixed position might need redraw
2061                        // if lines were inserted or deleted
2062                        || (wp->w_match_head != NULL
2063                            && buf->b_mod_set && buf->b_mod_xlines != 0)))))
2064        || lnum == wp->w_cursorline
2065        || lnum == wp->w_last_cursorline) {
2066      if (lnum == mod_top) {
2067        top_to_mod = false;
2068      }
2069
2070      // When lines are folded, display one line for all of them.
2071      // Otherwise, display normally (can be several display lines when
2072      // 'wrap' is on).
2073      foldinfo_T foldinfo = wp->w_p_cul && lnum == wp->w_cursor.lnum
2074                            ? cursorline_fi : fold_info(wp, lnum);
2075
2076      // If the line is concealed and has no filler lines, go to the next line.
2077      bool concealed = decor_conceal_line(wp, lnum - 1, false);
2078      if (concealed && win_get_fill(wp, lnum) == 0) {
2079        if (lnum == mod_top && lnum < mod_bot) {
2080          mod_top += foldinfo.fi_lines ? foldinfo.fi_lines : 1;
2081        }
2082        lnum += foldinfo.fi_lines ? foldinfo.fi_lines : 1;
2083        spv.spv_capcol_lnum = 0;
2084        continue;
2085      }
2086
2087      // When at start of changed lines: May scroll following lines
2088      // up or down to minimize redrawing.
2089      // Don't do this when the change continues until the end.
2090      // Don't scroll for changed lines in the top area if that's already
2091      // done above, but do scroll for changed lines below the top area.
2092      if (!scrolled_for_mod && mod_bot != MAXLNUM
2093          && lnum >= mod_top && lnum < MAX(mod_bot, mod_top + 1)
2094          && (!scrolled_down || row >= top_end)) {
2095        scrolled_for_mod = true;
2096
2097        int old_cline_height = 0;
2098        int old_rows = 0;
2099        linenr_T l;
2100        int i;
2101
2102        // Count the old number of window rows, using w_lines[], which
2103        // should still contain the sizes for the lines as they are
2104        // currently displayed.
2105        for (i = idx; i < wp->w_lines_valid; i++) {
2106          // Only valid lines have a meaningful wl_lnum.  Invalid
2107          // lines are part of the changed area.
2108          if (wp->w_lines[i].wl_valid
2109              && wp->w_lines[i].wl_lnum == mod_bot) {
2110            break;
2111          }
2112          if (wp->w_lines[i].wl_lnum == wp->w_cursor.lnum) {
2113            old_cline_height = wp->w_lines[i].wl_size;
2114          }
2115          old_rows += wp->w_lines[i].wl_size;
2116          if (wp->w_lines[i].wl_valid
2117              && wp->w_lines[i].wl_lastlnum + 1 == mod_bot) {
2118            // Must have found the last valid entry above mod_bot.
2119            // Add following invalid entries.
2120            i++;
2121            while (i < wp->w_lines_valid
2122                   && !wp->w_lines[i].wl_valid) {
2123              old_rows += wp->w_lines[i++].wl_size;
2124            }
2125            break;
2126          }
2127        }
2128
2129        if (i >= wp->w_lines_valid) {
2130          // We can't find a valid line below the changed lines,
2131          // need to redraw until the end of the window.
2132          // Inserting/deleting lines has no use.
2133          bot_start = 0;
2134          bot_scroll_start = 0;
2135        } else {
2136          int new_rows = 0;
2137          // Able to count old number of rows: Count new window
2138          // rows, and may insert/delete lines
2139          int j = idx;
2140          for (l = lnum; l < mod_bot; l++) {
2141            if (dollar_vcol >= 0 && wp == curwin
2142                && old_cline_height > 0 && l == wp->w_cursor.lnum) {
2143              // When dollar_vcol >= 0, cursor line isn't fully
2144              // redrawn, and its height remains unchanged.
2145              new_rows += old_cline_height;
2146              j++;
2147            } else {
2148              int n = plines_correct_topline(wp, l, &l, true, NULL);
2149              new_rows += n;
2150              j += n > 0;  // don't count concealed lines
2151            }
2152            if (new_rows > wp->w_view_height - row - 2) {
2153              // it's getting too much, must redraw the rest
2154              new_rows = 9999;
2155              break;
2156            }
2157          }
2158          int xtra_rows = new_rows - old_rows;
2159          if (xtra_rows < 0) {
2160            // May scroll text up.  If there is not enough
2161            // remaining text or scrolling fails, must redraw the
2162            // rest.  If scrolling works, must redraw the text
2163            // below the scrolled text.
2164            if (row - xtra_rows >= wp->w_view_height - 2) {
2165              mod_bot = MAXLNUM;
2166            } else {
2167              win_scroll_lines(wp, row, xtra_rows);
2168              bot_start = wp->w_view_height + xtra_rows;
2169              bot_scroll_start = bot_start;
2170            }
2171          } else if (xtra_rows > 0) {
2172            // May scroll text down.  If there is not enough
2173            // remaining text of scrolling fails, must redraw the
2174            // rest.
2175            if (row + xtra_rows >= wp->w_view_height - 2) {
2176              mod_bot = MAXLNUM;
2177            } else {
2178              win_scroll_lines(wp, row + old_rows, xtra_rows);
2179              bot_scroll_start = 0;
2180              if (top_end > row + old_rows) {
2181                // Scrolled the part at the top that requires
2182                // updating down.
2183                top_end += xtra_rows;
2184              }
2185            }
2186          }
2187
2188          // When not updating the rest, may need to move w_lines[]
2189          // entries.
2190          if (mod_bot != MAXLNUM && i != j) {
2191            if (j < i) {
2192              int x = row + new_rows;
2193
2194              // move entries in w_lines[] upwards
2195              while (true) {
2196                // stop at last valid entry in w_lines[]
2197                if (i >= wp->w_lines_valid) {
2198                  wp->w_lines_valid = j;
2199                  break;
2200                }
2201                wp->w_lines[j] = wp->w_lines[i];
2202                // stop at a line that won't fit
2203                if (x + (int)wp->w_lines[j].wl_size
2204                    > wp->w_view_height) {
2205                  wp->w_lines_valid = j + 1;
2206                  break;
2207                }
2208                x += wp->w_lines[j++].wl_size;
2209                i++;
2210              }
2211              bot_start = MIN(bot_start, x);
2212            } else {       // j > i
2213                           // move entries in w_lines[] downwards
2214              j -= i;
2215              wp->w_lines_valid += (linenr_T)j;
2216              wp->w_lines_valid = MIN(wp->w_lines_valid, wp->w_view_height);
2217              for (i = wp->w_lines_valid; i - j >= idx; i--) {
2218                wp->w_lines[i] = wp->w_lines[i - j];
2219              }
2220
2221              // The w_lines[] entries for inserted lines are
2222              // now invalid, but wl_size may be used above.
2223              // Reset to zero.
2224              while (i >= idx) {
2225                wp->w_lines[i].wl_size = 0;
2226                wp->w_lines[i--].wl_valid = false;
2227              }
2228            }
2229          }
2230        }
2231      }
2232
2233      if (foldinfo.fi_lines == 0
2234          && idx < wp->w_lines_valid
2235          && wp->w_lines[idx].wl_valid
2236          && wp->w_lines[idx].wl_lnum == lnum
2237          && lnum > wp->w_topline
2238          && !(dy_flags & (kOptDyFlagLastline | kOptDyFlagTruncate))
2239          && srow + wp->w_lines[idx].wl_size > wp->w_view_height
2240          && win_get_fill(wp, lnum) == 0) {
2241        // This line is not going to fit.  Don't draw anything here,
2242        // will draw "@  " lines below.
2243        row = wp->w_view_height + 1;
2244      } else {
2245        prepare_search_hl(wp, &screen_search_hl, lnum);
2246        // Let the syntax stuff know we skipped a few lines.
2247        if (syntax_last_parsed != 0 && syntax_last_parsed + 1 < lnum
2248            && syntax_present(wp)) {
2249          syntax_end_parsing(wp, syntax_last_parsed + 1);
2250        }
2251
2252        bool display_buf_line = !concealed
2253                                && (foldinfo.fi_lines == 0 || wp->w_p_fdt.type == kCallbackNone);
2254
2255        // Display one line
2256        spellvars_T zero_spv = { 0 };
2257        row = win_line(wp, lnum, srow, wp->w_view_height, 0, concealed,
2258                       display_buf_line ? &spv : &zero_spv, foldinfo);
2259
2260        if (display_buf_line) {
2261          syntax_last_parsed = lnum;
2262        } else {
2263          spv.spv_capcol_lnum = 0;
2264        }
2265
2266        linenr_T lastlnum = lnum + foldinfo.fi_lines - (foldinfo.fi_lines > 0);
2267        wp->w_lines[idx].wl_folded = foldinfo.fi_lines > 0;
2268        wp->w_lines[idx].wl_foldend = lastlnum;
2269        wp->w_lines[idx].wl_lastlnum = lastlnum;
2270        did_update = foldinfo.fi_lines > 0 ? DID_FOLD : DID_LINE;
2271
2272        // Adjust "wl_lastlnum" for concealed lines below this line, unless it should
2273        // still be drawn for below virt_lines attached to the current line. Below
2274        // virt_lines attached to a second adjacent concealed line are concealed.
2275        bool virt_below = decor_virt_lines(wp, lastlnum, lastlnum + 1, NULL, NULL, true) > 0;
2276        while (!virt_below && wp->w_lines[idx].wl_lastlnum < buf->b_ml.ml_line_count
2277               && decor_conceal_line(wp, wp->w_lines[idx].wl_lastlnum, false)) {
2278          virt_below = false;
2279          wp->w_lines[idx].wl_lastlnum++;
2280          hasFolding(wp, wp->w_lines[idx].wl_lastlnum, NULL, &wp->w_lines[idx].wl_lastlnum);
2281        }
2282      }
2283
2284      wp->w_lines[idx].wl_lnum = lnum;
2285      wp->w_lines[idx].wl_valid = true;
2286
2287      bool is_curline = wp == curwin && lnum == wp->w_cursor.lnum;
2288
2289      if (row > wp->w_view_height) {         // past end of grid
2290        // we may need the size of that too long line later on
2291        if (dollar_vcol == -1 || !is_curline) {
2292          wp->w_lines[idx].wl_size = (uint16_t)plines_win(wp, lnum, true);
2293        }
2294        idx++;
2295        break;
2296      }
2297      if (dollar_vcol == -1 || !is_curline) {
2298        wp->w_lines[idx].wl_size = (uint16_t)(row - srow);
2299      }
2300      lnum = wp->w_lines[idx++].wl_lastlnum + 1;
2301    } else {
2302      // If:
2303      // - 'number' is set and below inserted/deleted lines, or
2304      // - 'relativenumber' is set and cursor moved vertically,
2305      // the text doesn't need to be redrawn, but the number column does.
2306      if ((wp->w_p_nu && mod_top != 0 && lnum >= mod_bot
2307           && buf->b_mod_set && buf->b_mod_xlines != 0)
2308          || (wp->w_p_rnu && wp->w_last_cursor_lnum_rnu != wp->w_cursor.lnum)) {
2309        foldinfo_T info = wp->w_p_cul && lnum == wp->w_cursor.lnum
2310                          ? cursorline_fi : fold_info(wp, lnum);
2311        win_line(wp, lnum, srow, wp->w_view_height, wp->w_lines[idx].wl_size, false, &spv, info);
2312      }
2313
2314      // This line does not need to be drawn, advance to the next one.
2315      row += wp->w_lines[idx++].wl_size;
2316      if (row > wp->w_view_height) {  // past end of screen
2317        break;
2318      }
2319      lnum = wp->w_lines[idx - 1].wl_lastlnum + 1;
2320      did_update = DID_NONE;
2321      spv.spv_capcol_lnum = 0;
2322    }
2323
2324    // 'statuscolumn' width has changed or errored, start from the top.
2325    if (wp->w_redr_statuscol) {
2326redr_statuscol:
2327      wp->w_redr_statuscol = false;
2328      idx = 0;
2329      row = 0;
2330      lnum = wp->w_topline;
2331      wp->w_lines_valid = 0;
2332      wp->w_valid &= ~VALID_WCOL;
2333      decor_redraw_reset(wp, &decor_state);
2334      decor_providers_invoke_win(wp);
2335      continue;
2336    }
2337
2338    if (lnum > buf->b_ml.ml_line_count) {
2339      eof = true;
2340      break;
2341    }
2342  }
2343  // End of loop over all window lines.
2344
2345  // Now that the window has been redrawn with the old and new cursor line,
2346  // update w_last_cursorline.
2347  wp->w_last_cursorline = wp->w_cursorline;
2348
2349  wp->w_last_cursor_lnum_rnu = wp->w_p_rnu ? wp->w_cursor.lnum : 0;
2350
2351  wp->w_lines_valid = MAX(wp->w_lines_valid, idx);
2352
2353  wp->w_display_tick = display_tick;
2354
2355  // Let the syntax stuff know we stop parsing here.
2356  if (syntax_last_parsed != 0 && syntax_present(wp)) {
2357    syntax_end_parsing(wp, syntax_last_parsed + 1);
2358  }
2359
2360  const linenr_T old_botline = wp->w_botline;
2361
2362  // If we didn't hit the end of the file, and we didn't finish the last
2363  // line we were working on, then the line didn't fit.
2364  wp->w_empty_rows = 0;
2365  wp->w_filler_rows = 0;
2366  if (!eof && !didline) {
2367    int at_attr = hl_combine_attr(win_bg_attr(wp), win_hl_attr(wp, HLF_AT));
2368    if (lnum == wp->w_topline) {
2369      // Single line that does not fit!
2370      // Don't overwrite it, it can be edited.
2371      wp->w_botline = lnum + 1;
2372    } else if (win_get_fill(wp, lnum) >= wp->w_view_height - srow) {
2373      // Window ends in filler lines.
2374      wp->w_botline = lnum;
2375      wp->w_filler_rows = wp->w_view_height - srow;
2376    } else if (dy_flags & kOptDyFlagTruncate) {      // 'display' has "truncate"
2377      // Last line isn't finished: Display "@@@" in the last screen line.
2378      grid_line_start(&wp->w_grid, wp->w_view_height - 1);
2379      grid_line_fill(0, MIN(wp->w_view_width, 3), wp->w_p_fcs_chars.lastline, at_attr);
2380      grid_line_fill(3, wp->w_view_width, schar_from_ascii(' '), at_attr);
2381      grid_line_flush();
2382      set_empty_rows(wp, srow);
2383      wp->w_botline = lnum;
2384    } else if (dy_flags & kOptDyFlagLastline) {      // 'display' has "lastline"
2385      // Last line isn't finished: Display "@@@" at the end.
2386      // If this would split a doublewidth char in two, we need to display "@@@@" instead
2387      grid_line_start(&wp->w_grid, wp->w_view_height - 1);
2388      int width = grid_line_getchar(MAX(wp->w_view_width - 3, 0), NULL) == NUL ? 4 : 3;
2389      grid_line_fill(MAX(wp->w_view_width - width, 0), wp->w_view_width,
2390                     wp->w_p_fcs_chars.lastline, at_attr);
2391      grid_line_flush();
2392      set_empty_rows(wp, srow);
2393      wp->w_botline = lnum;
2394    } else {
2395      win_draw_end(wp, wp->w_p_fcs_chars.lastline, true, srow,
2396                   wp->w_view_height, HLF_AT);
2397      set_empty_rows(wp, srow);
2398      wp->w_botline = lnum;
2399    }
2400  } else {
2401    if (eof) {  // we hit the end of the file
2402      wp->w_botline = buf->b_ml.ml_line_count + 1;
2403      int j = win_get_fill(wp, wp->w_botline);
2404      if (j > 0 && !wp->w_botfill && row < wp->w_view_height) {
2405        // Display filler text below last line. win_line() will check
2406        // for ml_line_count+1 and only draw filler lines
2407        spellvars_T zero_spv = { 0 };
2408        foldinfo_T zero_foldinfo = { 0 };
2409        row = win_line(wp, wp->w_botline, row, wp->w_view_height, 0, false, &zero_spv,
2410                       zero_foldinfo);
2411        if (wp->w_redr_statuscol) {
2412          eof = false;
2413          goto redr_statuscol;
2414        }
2415      }
2416    } else if (dollar_vcol == -1 || wp != curwin) {
2417      wp->w_botline = lnum;
2418    }
2419
2420    // Make sure the rest of the screen is blank.
2421    // write the "eob" character from 'fillchars' to rows that aren't part
2422    // of the file.
2423    // TODO(bfredl): just keep track of the valid EOB area from last redraw?
2424    int lastline = bot_scroll_start;
2425    if (mid_end >= row) {
2426      lastline = MIN(lastline, mid_start);
2427    }
2428    // if (mod_bot > buf->b_ml.ml_line_count + 1) {
2429    if (mod_bot > buf->b_ml.ml_line_count) {
2430      lastline = 0;
2431    }
2432
2433    win_draw_end(wp, wp->w_p_fcs_chars.eob, false, MAX(lastline, row),
2434                 wp->w_view_height,
2435                 HLF_EOB);
2436    set_empty_rows(wp, row);
2437  }
2438
2439  if (wp->w_redr_type >= UPD_REDRAW_TOP) {
2440    draw_vsep_win(wp);
2441    draw_hsep_win(wp);
2442  }
2443  syn_set_timeout(NULL);
2444
2445  // Reset the type of redrawing required, the window has been updated.
2446  wp->w_redr_type = 0;
2447  wp->w_old_topfill = wp->w_topfill;
2448  wp->w_old_botfill = wp->w_botfill;
2449
2450  // Send win_extmarks if needed
2451  for (size_t n = 0; n < kv_size(win_extmark_arr); n++) {
2452    ui_call_win_extmark(wp->w_grid_alloc.handle, wp->handle,
2453                        kv_A(win_extmark_arr, n).ns_id, (Integer)kv_A(win_extmark_arr, n).mark_id,
2454                        kv_A(win_extmark_arr, n).win_row, kv_A(win_extmark_arr, n).win_col);
2455  }
2456
2457  if (dollar_vcol == -1 || wp != curwin) {
2458    // There is a trick with w_botline.  If we invalidate it on each
2459    // change that might modify it, this will cause a lot of expensive
2460    // calls to plines_win() in update_topline() each time.  Therefore the
2461    // value of w_botline is often approximated, and this value is used to
2462    // compute the value of w_topline.  If the value of w_botline was
2463    // wrong, check that the value of w_topline is correct (cursor is on
2464    // the visible part of the text).  If it's not, we need to redraw
2465    // again.  Mostly this just means scrolling up a few lines, so it
2466    // doesn't look too bad.  Only do this for the current window (where
2467    // changes are relevant).
2468    wp->w_valid |= VALID_BOTLINE;
2469    wp->w_viewport_invalid = true;
2470    if (wp == curwin && wp->w_botline != old_botline && !recursive) {
2471      recursive = true;
2472      curwin->w_valid &= ~VALID_TOPLINE;
2473      update_topline(curwin);  // may invalidate w_botline again
2474      // New redraw either due to updated topline or reset skipcol.
2475      if (must_redraw != 0) {
2476        // Don't update for changes in buffer again.
2477        const bool mod_set = curbuf->b_mod_set;
2478        curbuf->b_mod_set = false;
2479        curs_columns(curwin, true);
2480        win_update(curwin);
2481        must_redraw = 0;
2482        curbuf->b_mod_set = mod_set;
2483      }
2484      recursive = false;
2485    }
2486  }
2487
2488  if (nrwidth_before != wp->w_nrwidth && buf->terminal) {
2489    terminal_check_size(buf->terminal);
2490  }
2491
2492  // restore got_int, unless CTRL-C was hit while redrawing
2493  if (!got_int) {
2494    got_int = save_got_int;
2495  }
2496}
2497
2498/// Scroll `line_count` lines at 'row' in window 'wp'.
2499///
2500/// Positive `line_count` means scrolling down, so that more space is available
2501/// at 'row'. Negative `line_count` implies deleting lines at `row`.
2502void win_scroll_lines(win_T *wp, int row, int line_count)
2503{
2504  if (!redrawing() || line_count == 0) {
2505    return;
2506  }
2507
2508  int col = 0;
2509  int row_off = 0;
2510  ScreenGrid *grid = grid_adjust(&wp->w_grid, &row_off, &col);
2511
2512  // TODO(bfredl): this is due to the call in curs_columns(). We really don't want to
2513  // fiddle with the screen outside of update_screen() like this.
2514  int checked_width = MIN(grid->cols - col, wp->w_view_width);
2515  int checked_height = MIN(grid->rows - row_off, wp->w_view_height);
2516
2517  // No lines are being moved, just draw over the entire area
2518  if (row + abs(line_count) >= checked_height) {
2519    return;
2520  }
2521
2522  if (line_count < 0) {
2523    grid_del_lines(grid, row + row_off, -line_count,
2524                   checked_height + row_off, col, checked_width);
2525  } else {
2526    grid_ins_lines(grid, row + row_off, line_count,
2527                   checked_height + row_off, col, checked_width);
2528  }
2529}
2530
2531/// Clear lines near the end of the window and mark the unused lines with "c1".
2532/// When "draw_margin" is true, then draw the sign/fold/number columns.
2533void win_draw_end(win_T *wp, schar_T c1, bool draw_margin, int startrow, int endrow, hlf_T hl)
2534{
2535  assert(hl >= 0 && hl < HLF_COUNT);
2536  const int view_width = wp->w_view_width;
2537  const int fdc = compute_foldcolumn(wp, 0);
2538  const int scwidth = wp->w_scwidth;
2539
2540  for (int row = startrow; row < endrow; row++) {
2541    grid_line_start(&wp->w_grid, row);
2542
2543    int n = 0;
2544    if (draw_margin) {
2545      // draw the fold column
2546      if (fdc > 0) {
2547        n = grid_line_fill(n, MIN(view_width, n + fdc),
2548                           schar_from_ascii(' '), win_hl_attr(wp, HLF_FC));
2549      }
2550
2551      // draw the sign column
2552      if (scwidth > 0) {
2553        n = grid_line_fill(n, MIN(view_width, n + scwidth * SIGN_WIDTH),
2554                           schar_from_ascii(' '), win_hl_attr(wp, HLF_SC));
2555      }
2556
2557      // draw the number column
2558      if ((wp->w_p_nu || wp->w_p_rnu) && vim_strchr(p_cpo, kCpoNumcol) == NULL) {
2559        int width = number_width(wp) + 1;
2560        n = grid_line_fill(n, MIN(view_width, n + width),
2561                           schar_from_ascii(' '), win_hl_attr(wp, HLF_N));
2562      }
2563    }
2564
2565    int attr = win_hl_attr(wp, (int)hl);
2566
2567    if (n < view_width) {
2568      grid_line_put_schar(n, c1, attr);
2569      n++;
2570    }
2571
2572    grid_line_clear_end(n, view_width, win_bg_attr(wp), attr);
2573
2574    if (wp->w_p_rl) {
2575      grid_line_mirror(view_width);
2576    }
2577    grid_line_flush();
2578  }
2579}
2580
2581/// Compute the width of the foldcolumn.  Based on 'foldcolumn' and how much
2582/// space is available for window "wp", minus "col".
2583int compute_foldcolumn(win_T *wp, int col)
2584{
2585  int fdc = win_fdccol_count(wp);
2586  int wmw = wp == curwin && p_wmw == 0 ? 1 : (int)p_wmw;
2587  int n = wp->w_view_width - (col + wmw);
2588
2589  return MIN(fdc, n);
2590}
2591
2592/// Return the width of the 'number' and 'relativenumber' column.
2593/// Caller may need to check if 'number' or 'relativenumber' is set.
2594/// Otherwise it depends on 'numberwidth' and the line count.
2595int number_width(win_T *wp)
2596{
2597  linenr_T lnum;
2598
2599  if (wp->w_p_rnu && !wp->w_p_nu) {
2600    // cursor line shows "0"
2601    lnum = wp->w_view_height;
2602  } else {
2603    // cursor line shows absolute line number
2604    lnum = wp->w_buffer->b_ml.ml_line_count;
2605  }
2606
2607  if (lnum == wp->w_nrwidth_line_count) {
2608    return wp->w_nrwidth_width;
2609  }
2610  wp->w_nrwidth_line_count = lnum;
2611
2612  // reset for 'statuscolumn'
2613  if (*wp->w_p_stc != NUL) {
2614    wp->w_statuscol_line_count = 0;  // make sure width is re-estimated
2615    wp->w_nrwidth_width = (wp->w_p_nu || wp->w_p_rnu) * (int)wp->w_p_nuw;
2616    return wp->w_nrwidth_width;
2617  }
2618
2619  int n = 0;
2620  do {
2621    lnum /= 10;
2622    n++;
2623  } while (lnum > 0);
2624
2625  // 'numberwidth' gives the minimal width plus one
2626  n = MAX(n, (int)wp->w_p_nuw - 1);
2627
2628  // If 'signcolumn' is set to 'number' and there is a sign to display, then
2629  // the minimal width for the number column is 2.
2630  if (n < 2 && buf_meta_total(wp->w_buffer, kMTMetaSignText) && wp->w_minscwidth == SCL_NUM) {
2631    n = 2;
2632  }
2633
2634  wp->w_nrwidth_width = n;
2635  return n;
2636}
2637
2638/// Redraw a window later, with wp->w_redr_type >= type.
2639///
2640/// Set must_redraw only if not already set to a higher value.
2641/// e.g. if must_redraw is UPD_CLEAR, type UPD_NOT_VALID will do nothing.
2642void redraw_later(win_T *wp, int type)
2643{
2644  // curwin may have been set to NULL when exiting
2645  assert(wp != NULL || exiting);
2646  if (!exiting && !redraw_not_allowed && wp->w_redr_type < type) {
2647    wp->w_redr_type = type;
2648    if (type >= UPD_NOT_VALID) {
2649      wp->w_lines_valid = 0;
2650    }
2651    must_redraw = MAX(must_redraw, type);  // must_redraw is the maximum of all windows
2652  }
2653}
2654
2655/// Mark all windows to be redrawn later.
2656void redraw_all_later(int type)
2657{
2658  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2659    redraw_later(wp, type);
2660  }
2661  // This may be needed when switching tabs.
2662  set_must_redraw(type);
2663}
2664
2665/// Set "must_redraw" to "type" unless it already has a higher value
2666/// or it is currently not allowed.
2667void set_must_redraw(int type)
2668{
2669  if (!redraw_not_allowed) {
2670    must_redraw = MAX(must_redraw, type);
2671  }
2672}
2673
2674void screen_invalidate_highlights(void)
2675{
2676  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2677    redraw_later(wp, UPD_NOT_VALID);
2678    wp->w_grid_alloc.valid = false;
2679  }
2680}
2681
2682/// Mark all windows that are editing the current buffer to be updated later.
2683void redraw_curbuf_later(int type)
2684{
2685  redraw_buf_later(curbuf, type);
2686}
2687
2688void redraw_buf_later(buf_T *buf, int type)
2689{
2690  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2691    if (wp->w_buffer == buf) {
2692      redraw_later(wp, type);
2693    }
2694  }
2695}
2696
2697void redraw_buf_line_later(buf_T *buf, linenr_T line, bool force)
2698{
2699  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2700    if (wp->w_buffer == buf) {
2701      redrawWinline(wp, MIN(line, buf->b_ml.ml_line_count));
2702      if (force && line > buf->b_ml.ml_line_count) {
2703        wp->w_redraw_bot = line;
2704      }
2705    }
2706  }
2707}
2708
2709void redraw_win_range_later(win_T *wp, linenr_T first, linenr_T last)
2710{
2711  if (last >= wp->w_topline && first < wp->w_botline) {
2712    if (wp->w_redraw_top == 0 || wp->w_redraw_top > first) {
2713      wp->w_redraw_top = first;
2714    }
2715    if (wp->w_redraw_bot == 0 || wp->w_redraw_bot < last) {
2716      wp->w_redraw_bot = last;
2717    }
2718    redraw_later(wp, UPD_VALID);
2719  }
2720}
2721
2722/// Changed something in the current window, at buffer line "lnum", that
2723/// requires that line and possibly other lines to be redrawn.
2724/// Used when entering/leaving Insert mode with the cursor on a folded line.
2725/// Used to remove the "$" from a change command.
2726/// Note that when also inserting/deleting lines w_redraw_top and w_redraw_bot
2727/// may become invalid and the whole window will have to be redrawn.
2728void redrawWinline(win_T *wp, linenr_T lnum)
2729  FUNC_ATTR_NONNULL_ALL
2730{
2731  redraw_win_range_later(wp, lnum, lnum);
2732}
2733
2734void redraw_buf_range_later(buf_T *buf, linenr_T first, linenr_T last)
2735{
2736  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2737    if (wp->w_buffer == buf) {
2738      redraw_win_range_later(wp, first, last);
2739    }
2740  }
2741}
2742
2743/// called when the status bars for the buffer 'buf' need to be updated
2744void redraw_buf_status_later(buf_T *buf)
2745{
2746  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2747    if (wp->w_buffer == buf
2748        && (wp->w_status_height
2749            || (wp == curwin && global_stl_height())
2750            || wp->w_winbar_height)) {
2751      wp->w_redr_status = true;
2752      set_must_redraw(UPD_VALID);
2753    }
2754  }
2755}
2756
2757/// Mark all status lines and window bars for redraw; used after first :cd
2758void status_redraw_all(void)
2759{
2760  bool is_stl_global = global_stl_height() != 0;
2761
2762  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2763    if ((!is_stl_global && wp->w_status_height) || wp == curwin
2764        || wp->w_winbar_height) {
2765      wp->w_redr_status = true;
2766      redraw_later(wp, UPD_VALID);
2767    }
2768  }
2769}
2770
2771/// Marks all status lines and window bars of the current buffer for redraw.
2772void status_redraw_curbuf(void)
2773{
2774  status_redraw_buf(curbuf);
2775}
2776
2777/// Marks all status lines and window bars of the given buffer for redraw.
2778void status_redraw_buf(buf_T *buf)
2779{
2780  bool is_stl_global = global_stl_height() != 0;
2781
2782  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2783    if (wp->w_buffer == buf && ((!is_stl_global && wp->w_status_height)
2784                                || (is_stl_global && wp == curwin) || wp->w_winbar_height)) {
2785      wp->w_redr_status = true;
2786      redraw_later(wp, UPD_VALID);
2787    }
2788  }
2789  // Redraw the ruler if it is in the command line and was not marked for redraw above
2790  if (p_ru && !curwin->w_status_height && !curwin->w_redr_status) {
2791    redraw_cmdline = true;
2792    redraw_later(curwin, UPD_VALID);
2793  }
2794}
2795
2796/// Redraw all status lines that need to be redrawn.
2797void redraw_statuslines(void)
2798{
2799  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2800    if (wp->w_redr_status) {
2801      win_check_ns_hl(wp);
2802      win_redr_winbar(wp);
2803      win_redr_status(wp);
2804    }
2805  }
2806
2807  win_check_ns_hl(NULL);
2808  if (redraw_tabline) {
2809    draw_tabline();
2810  }
2811
2812  if (need_maketitle) {
2813    maketitle();
2814  }
2815}
2816
2817/// Redraw all status lines at the bottom of frame "frp".
2818void win_redraw_last_status(const frame_T *frp)
2819  FUNC_ATTR_NONNULL_ARG(1)
2820{
2821  if (frp->fr_layout == FR_LEAF) {
2822    frp->fr_win->w_redr_status = true;
2823  } else if (frp->fr_layout == FR_ROW) {
2824    FOR_ALL_FRAMES(frp, frp->fr_child) {
2825      win_redraw_last_status(frp);
2826    }
2827  } else {
2828    assert(frp->fr_layout == FR_COL);
2829    frp = frp->fr_child;
2830    while (frp->fr_next != NULL) {
2831      frp = frp->fr_next;
2832    }
2833    win_redraw_last_status(frp);
2834  }
2835}
2836
2837/// Return true if the cursor line in window "wp" may be concealed, according
2838/// to the 'concealcursor' option.
2839bool conceal_cursor_line(const win_T *wp)
2840  FUNC_ATTR_NONNULL_ALL
2841{
2842  int c;
2843
2844  if (*wp->w_p_cocu == NUL) {
2845    return false;
2846  }
2847  if (get_real_state() & MODE_VISUAL) {
2848    c = 'v';
2849  } else if (State & MODE_INSERT) {
2850    c = 'i';
2851  } else if (State & MODE_NORMAL) {
2852    c = 'n';
2853  } else if (State & MODE_CMDLINE) {
2854    c = 'c';
2855  } else {
2856    return false;
2857  }
2858  return vim_strchr(wp->w_p_cocu, c) != NULL;
2859}
2860
2861/// Whether cursorline is drawn in a special way
2862///
2863/// If true, both old and new cursorline will need to be redrawn when moving cursor within windows.
2864bool win_cursorline_standout(const win_T *wp)
2865  FUNC_ATTR_NONNULL_ALL
2866{
2867  return wp->w_p_cul || (wp == curwin && wp->w_p_cole > 0 && !conceal_cursor_line(wp));
2868}
2869
2870/// Update w_cursorline, taking care to set it to the to the start of a closed fold.
2871///
2872/// @param[out] foldinfo foldinfo for the cursor line
2873void win_update_cursorline(win_T *wp, foldinfo_T *foldinfo)
2874{
2875  wp->w_cursorline = win_cursorline_standout(wp) ? wp->w_cursor.lnum : 0;
2876  if (wp->w_p_cul) {
2877    // Make sure that the cursorline on a closed fold is redrawn
2878    *foldinfo = fold_info(wp, wp->w_cursor.lnum);
2879    if (foldinfo->fi_level != 0 && foldinfo->fi_lines > 0) {
2880      wp->w_cursorline = foldinfo->fi_lnum;
2881    }
2882  }
2883}