robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
86.4 KiB2743 linesraw
1// move.c: Functions for moving the cursor and scrolling text.
2//
3// There are two ways to move the cursor:
4// 1. Move the cursor directly, the text is scrolled to keep the cursor in the
5//    window.
6// 2. Scroll the text, the cursor is moved into the text visible in the
7//    window.
8// The 'scrolloff' option makes this a bit complicated.
9
10#include <assert.h>
11#include <limits.h>
12#include <stdbool.h>
13#include <stdint.h>
14#include <stdlib.h>
15
16#include "nvim/ascii_defs.h"
17#include "nvim/buffer.h"
18#include "nvim/buffer_defs.h"
19#include "nvim/cursor.h"
20#include "nvim/decoration.h"
21#include "nvim/diff.h"
22#include "nvim/drawscreen.h"
23#include "nvim/errors.h"
24#include "nvim/eval/typval.h"
25#include "nvim/eval/window.h"
26#include "nvim/fold.h"
27#include "nvim/gettext_defs.h"
28#include "nvim/globals.h"
29#include "nvim/grid.h"
30#include "nvim/grid_defs.h"
31#include "nvim/input.h"
32#include "nvim/insert.h"
33#include "nvim/macros_defs.h"
34#include "nvim/mark_defs.h"
35#include "nvim/mbyte.h"
36#include "nvim/memline.h"
37#include "nvim/message.h"
38#include "nvim/mouse.h"
39#include "nvim/move.h"
40#include "nvim/normal.h"
41#include "nvim/normal_defs.h"
42#include "nvim/option.h"
43#include "nvim/option_vars.h"
44#include "nvim/plines.h"
45#include "nvim/pos_defs.h"
46#include "nvim/strings.h"
47#include "nvim/types_defs.h"
48#include "nvim/vim_defs.h"
49#include "nvim/window.h"
50#include "nvim/winfloat.h"
51
52typedef struct {
53  linenr_T lnum;                // line number
54  int fill;                     // filler lines
55  int height;                   // height of added line
56} lineoff_T;
57
58#include "move.c.generated.h"
59
60/// Get the number of screen lines skipped with "wp->w_skipcol".
61static int adjust_plines_for_skipcol(win_T *wp)
62{
63  if (wp->w_skipcol == 0) {
64    return 0;
65  }
66
67  int width = wp->w_view_width - win_col_off(wp);
68  int w2 = width + win_col_off2(wp);
69  if (wp->w_skipcol >= width && w2 > 0) {
70    return (wp->w_skipcol - width) / w2 + 1;
71  }
72
73  return 0;
74}
75
76/// Return how many lines "lnum" will take on the screen, taking into account
77/// whether it is the first line, whether w_skipcol is non-zero and limiting to
78/// the window height.
79int plines_correct_topline(win_T *wp, linenr_T lnum, linenr_T *nextp, bool limit_winheight,
80                           bool *foldedp)
81{
82  int n = plines_win_full(wp, lnum, nextp, foldedp, true, false);
83  if (lnum == wp->w_topline) {
84    n -= adjust_plines_for_skipcol(wp);
85  }
86  if (limit_winheight && n > wp->w_view_height) {
87    return wp->w_view_height;
88  }
89  return n;
90}
91
92// Compute wp->w_botline for the current wp->w_topline.  Can be called after
93// wp->w_topline changed.
94static void comp_botline(win_T *wp)
95{
96  linenr_T lnum;
97  int done;
98
99  // If w_cline_row is valid, start there.
100  // Otherwise have to start at w_topline.
101  check_cursor_moved(wp);
102
103  // The wl_size values computed for the previous redraw give the height of
104  // each displayed line.  When the display is up-to-date they are equal to
105  // what plines_correct_topline() would compute, so reuse them to avoid
106  // walking every line to measure its width on each scroll (like curs_rows()
107  // does).  Only trust them when actually redrawing, the buffer was not
108  // changed, no "$" is displayed for a change and w_lines[] starts at or
109  // above w_topline.  With 'smoothscroll' or filled lines wl_size includes
110  // the skipped rows of the top line and the filler lines, so it does not
111  // match plines_correct_topline(); do not use the cache then.
112  bool use_cache = redrawing()
113                   && !wp->w_buffer->b_mod_set
114                   && dollar_vcol == -1
115                   && wp->w_skipcol == 0
116                   && !win_may_fill(wp)
117                   && wp->w_lines_valid > 0
118                   && wp->w_lines[0].wl_lnum <= wp->w_topline;
119
120  if (wp->w_valid & VALID_CROW) {
121    lnum = wp->w_cursor.lnum;
122    done = wp->w_cline_row;
123  } else {
124    lnum = wp->w_topline;
125    done = 0;
126  }
127
128  // Find the w_lines[] entry for the starting line.
129  int i = 0;
130  if (use_cache) {
131    while (i < wp->w_lines_valid && wp->w_lines[i].wl_lnum < lnum) {
132      i++;
133    }
134  }
135
136  for (; lnum <= wp->w_buffer->b_ml.ml_line_count; i++) {
137    bool valid = false;
138    // Try to use the size from the previous redraw.
139    if (use_cache && i < wp->w_lines_valid) {
140      if (wp->w_lines[i].wl_lnum < lnum || !wp->w_lines[i].wl_valid) {
141        continue;               // skip changed or deleted lines
142      }
143      if (wp->w_lines[i].wl_lnum == lnum) {
144        valid = true;
145      } else {  // wl_lnum > lnum
146        i--;                    // hold at inserted lines
147      }
148    }
149    linenr_T last = lnum;
150    bool folded;
151    int n;
152    // The cache is not used with 'smoothscroll' or filler lines, so here
153    // wl_size holds the same height as plines_correct_topline().
154    if (valid) {
155      n = wp->w_lines[i].wl_size;
156      folded = wp->w_lines[i].wl_folded;
157      last = wp->w_lines[i].wl_lastlnum;
158    } else {
159      n = plines_correct_topline(wp, lnum, &last, true, &folded);
160    }
161    if (lnum <= wp->w_cursor.lnum && last >= wp->w_cursor.lnum) {
162      wp->w_cline_row = done;
163      wp->w_cline_height = n;
164      wp->w_cline_folded = folded;
165      redraw_for_cursorline(wp);
166      wp->w_valid |= (VALID_CROW|VALID_CHEIGHT);
167    }
168    if (done + n > wp->w_view_height) {
169      break;
170    }
171    done += n;
172    lnum = last + 1;
173  }
174
175  // wp->w_botline is the line that is just below the window
176  wp->w_botline = lnum;
177  wp->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
178  wp->w_viewport_invalid = true;
179
180  set_empty_rows(wp, done);
181
182  win_check_anchored_floats(wp);
183}
184
185/// Redraw when w_cline_row changes and 'relativenumber' or 'cursorline' is set.
186/// Also when concealing is on and 'concealcursor' is not active.
187static void redraw_for_cursorline(win_T *wp)
188  FUNC_ATTR_NONNULL_ALL
189{
190  if (wp->w_valid & VALID_CROW) {
191    return;
192  }
193
194  if (wp->w_p_rnu || win_cursorline_standout(wp)) {
195    // win_line() will redraw the number column and cursorline only.
196    redraw_later(wp, UPD_VALID);
197  }
198}
199
200/// Redraw when 'concealcursor' is active, or when w_virtcol changes and:
201/// - 'cursorcolumn' is set, or
202/// - 'cursorlineopt' contains "screenline", or
203/// - Visual mode is active.
204static void redraw_for_cursorcolumn(win_T *wp)
205  FUNC_ATTR_NONNULL_ALL
206{
207  // If the cursor moves horizontally when 'concealcursor' is active, then the
208  // current line needs to be redrawn to calculate the correct cursor position.
209  if (wp == curwin && wp->w_p_cole > 0 && conceal_cursor_line(wp)) {
210    redrawWinline(wp, wp->w_cursor.lnum);
211  }
212
213  if (wp->w_valid & VALID_VIRTCOL) {
214    return;
215  }
216
217  if (wp->w_p_cuc) {
218    // When 'cursorcolumn' is set need to redraw with UPD_SOME_VALID.
219    redraw_later(wp, UPD_SOME_VALID);
220  } else if (wp->w_p_cul && (wp->w_p_culopt_flags & kOptCuloptFlagScreenline)) {
221    // When 'cursorlineopt' contains "screenline" need to redraw with UPD_VALID.
222    redraw_later(wp, UPD_VALID);
223  }
224
225  // When current buffer's cursor moves in Visual mode, redraw it with UPD_INVERTED.
226  if (Visual.active && wp->w_buffer == curbuf) {
227    redraw_buf_later(curbuf, UPD_INVERTED);
228  }
229}
230
231/// Set wp->w_virtcol to a value ("vcol") that is already valid.
232/// Handles redrawing if wp->w_virtcol was previously invalid.
233void set_valid_virtcol(win_T *wp, colnr_T vcol)
234{
235  wp->w_virtcol = vcol;
236  redraw_for_cursorcolumn(wp);
237  wp->w_valid |= VALID_VIRTCOL;
238}
239
240/// Calculates how much the 'listchars' "precedes" or 'smoothscroll' "<<<"
241/// marker overlaps with buffer text for window "wp".
242/// Parameter "extra2" should be the padding on the 2nd line, not the first
243/// line. When "extra2" is -1 calculate the padding.
244/// Returns the number of columns of overlap with buffer text, excluding the
245/// extra padding on the ledge.
246int sms_marker_overlap(win_T *wp, int extra2)
247{
248  if (extra2 == -1) {
249    extra2 = win_col_off(wp) - win_col_off2(wp);
250  }
251  // There is no marker overlap when in showbreak mode, thus no need to
252  // account for it.  See wlv_put_linebuf().
253  if (*get_showbreak_value(wp) != NUL) {
254    return 0;
255  }
256
257  // Overlap when 'list' and 'listchars' "precedes" are set is 1.
258  if (wp->w_p_list && wp->w_p_lcs_chars.prec) {
259    return 1;
260  }
261
262  return extra2 > 3 ? 0 : 3 - extra2;
263}
264
265/// Calculates the skipcol offset for window "wp" given how many
266/// physical lines we want to scroll down.
267static int skipcol_from_plines(win_T *wp, int plines_off)
268{
269  int width1 = wp->w_view_width - win_col_off(wp);
270
271  int skipcol = 0;
272  if (plines_off > 0) {
273    skipcol += width1;
274  }
275  if (plines_off > 1) {
276    skipcol += (width1 + win_col_off2(wp)) * (plines_off - 1);
277  }
278  return skipcol;
279}
280
281/// Set wp->w_skipcol to zero and redraw later if needed.
282static void reset_skipcol(win_T *wp)
283{
284  if (wp->w_skipcol == 0) {
285    return;
286  }
287
288  wp->w_skipcol = 0;
289
290  // Should use the least expensive way that displays all that changed.
291  // UPD_NOT_VALID is too expensive, UPD_REDRAW_TOP does not redraw
292  // enough when the top line gets another screen line.
293  redraw_later(wp, UPD_SOME_VALID);
294}
295
296/// Return true when 'scrolloffpad' may augment 'scrolloff'.
297/// This only applies to automatic cursor visibility correction.
298/// For now 'scrolloffpad' is treated as boolean: 0 disables, > 0 enables.
299static bool use_scrolloffpad(win_T *wp)
300{
301  return get_scrolloff_value(wp) > 0 && get_scrolloffpad_value(wp) > 0;
302}
303
304/// Return true when there are not enough real buffer lines below "lnum" to
305/// satisfy the requested "so" context.
306static bool scrolloffpad_eof_pressure(win_T *wp, linenr_T lnum, OptInt so)
307{
308  if (!use_scrolloffpad(wp) || so <= 0) {
309    return false;
310  }
311
312  // Use subtraction to avoid signed overflow in "lnum + so".
313  return lnum > wp->w_buffer->b_ml.ml_line_count - so;
314}
315
316// Update wp->w_topline to move the cursor onto the screen.
317void update_topline(win_T *wp)
318{
319  bool check_botline = false;
320  OptInt *so_ptr = wp->w_p_so >= 0 ? &wp->w_p_so : &p_so;
321  OptInt save_so = *so_ptr;
322
323  // Cursor is updated instead when this is true for 'splitkeep'.
324  if (skip_update_topline) {
325    return;
326  }
327
328  // If there is no valid screen and when the window height is zero just use
329  // the cursor line.
330  if (!default_grid.chars || wp->w_view_height == 0) {
331    check_cursor_lnum(wp);
332    wp->w_topline = wp->w_cursor.lnum;
333    wp->w_botline = wp->w_topline;
334    wp->w_viewport_invalid = true;
335    wp->w_scbind_pos = 1;
336    return;
337  }
338
339  check_cursor_moved(wp);
340  if (wp->w_valid & VALID_TOPLINE) {
341    return;
342  }
343
344  // When dragging with the mouse, don't scroll that quickly
345  if (mouse_dragging > 0) {
346    *so_ptr = mouse_dragging - 1;
347  }
348  bool eof_pressure = scrolloffpad_eof_pressure(wp, wp->w_cursor.lnum, *so_ptr);
349
350  linenr_T old_topline = wp->w_topline;
351  int old_topfill = wp->w_topfill;
352
353  // If the buffer is empty, always set topline to 1.
354  if (buf_is_empty(wp->w_buffer)) {  // special case - file is empty
355    if (wp->w_topline != 1) {
356      redraw_later(wp, UPD_NOT_VALID);
357    }
358    wp->w_topline = 1;
359    wp->w_botline = 2;
360    wp->w_skipcol = 0;
361    wp->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
362    wp->w_viewport_invalid = true;
363    wp->w_scbind_pos = 1;
364  } else {
365    bool check_topline = false;
366    // If the cursor is above or near the top of the window, scroll the window
367    // to show the line the cursor is in, with 'scrolloff' context.
368    if (wp->w_topline > 1 || wp->w_skipcol > 0) {
369      // If the cursor is above topline, scrolling is always needed.
370      // If the cursor is far below topline and there is no folding,
371      // scrolling down is never needed.
372      if (wp->w_cursor.lnum < wp->w_topline) {
373        check_topline = true;
374      } else if (check_top_offset(wp)) {
375        check_topline = true;
376      } else if (wp->w_skipcol > 0 && wp->w_cursor.lnum == wp->w_topline) {
377        colnr_T vcol;
378
379        // Check that the cursor position is visible.  Add columns for
380        // the marker displayed in the top-left if needed.
381        getvvcol(wp, &wp->w_cursor, &vcol, NULL, NULL, 0);
382        int overlap = sms_marker_overlap(wp, -1);
383        if (wp->w_skipcol + overlap > vcol) {
384          check_topline = true;
385        }
386      }
387    }
388    // Check if there are more filler lines than allowed.
389    if (!check_topline && wp->w_topfill > win_get_fill(wp, wp->w_topline)) {
390      check_topline = true;
391    }
392
393    if (check_topline) {
394      int halfheight = wp->w_view_height / 2 - 1;
395      if (halfheight < 2) {
396        halfheight = 2;
397      }
398      int64_t n;
399      if (win_lines_concealed(wp)) {
400        // Count the number of logical lines between the cursor and
401        // topline + p_so (approximation of how much will be
402        // scrolled).
403        n = 0;
404        for (linenr_T lnum = wp->w_cursor.lnum; lnum < wp->w_topline + *so_ptr; lnum++) {
405          // stop at end of file or when we know we are far off
406          assert(wp->w_buffer != 0);
407          if (lnum >= wp->w_buffer->b_ml.ml_line_count
408              || (n += !decor_conceal_line(wp, lnum, false)) >= halfheight) {
409            break;
410          }
411          hasFolding(wp, lnum, NULL, &lnum);
412        }
413      } else {
414        n = wp->w_topline + *so_ptr - wp->w_cursor.lnum;
415      }
416
417      // If we weren't very close to begin with, we scroll to put the
418      // cursor in the middle of the window.  Otherwise put the cursor
419      // near the top of the window.
420      int min_scroll = scrolljump_value(wp);
421      if (eof_pressure) {
422        scroll_cursor_halfway(wp, true, true);
423      } else if (n >= halfheight && min_scroll < halfheight) {
424        scroll_cursor_halfway(wp, false, false);
425      } else {
426        scroll_cursor_top(wp, min_scroll, false);
427        check_botline = true;
428      }
429    } else {
430      // Make sure topline is the first line of a fold.
431      hasFolding(wp, wp->w_topline, &wp->w_topline, NULL);
432      check_botline = true;
433    }
434  }
435
436  // If the cursor is below the bottom of the window, scroll the window
437  // to put the cursor on the window.
438  // When w_botline is invalid, recompute it first, to avoid a redraw later.
439  // If w_botline was approximated, we might need a redraw later in a few
440  // cases, but we don't want to spend (a lot of) time recomputing w_botline
441  // for every small change.
442  if (check_botline) {
443    if (!(wp->w_valid & VALID_BOTLINE_AP)) {
444      validate_botline_win(wp);
445    }
446
447    assert(wp->w_buffer != 0);
448    if (wp->w_botline <= wp->w_buffer->b_ml.ml_line_count || use_scrolloffpad(wp)) {
449      if (wp->w_cursor.lnum < wp->w_botline) {
450        if ((wp->w_cursor.lnum >= wp->w_botline - *so_ptr || win_lines_concealed(wp))) {
451          lineoff_T loff;
452
453          // Cursor is (a few lines) above botline, check if there are 'scrolloff'
454          // window lines below the cursor.  If not, need to scroll.
455          int n = eof_pressure ? 0 : wp->w_empty_rows;
456          loff.lnum = wp->w_cursor.lnum;
457          // In a fold go to its last line.
458          hasFolding(wp, loff.lnum, NULL, &loff.lnum);
459          loff.fill = 0;
460          n += wp->w_filler_rows;
461          loff.height = 0;
462          while (loff.lnum < wp->w_botline
463                 && (loff.lnum + 1 < wp->w_botline || loff.fill == 0)) {
464            n += loff.height;
465            if (n >= *so_ptr) {
466              break;
467            }
468            botline_forw(wp, &loff);
469          }
470          if (n >= *so_ptr && !eof_pressure) {
471            // sufficient context, no need to scroll
472            check_botline = false;
473          }
474        } else {
475          // sufficient context, no need to scroll
476          check_botline = false;
477        }
478      }
479      if (check_botline) {
480        int64_t n = 0;
481        if (win_lines_concealed(wp)) {
482          // Count the number of logical lines between the cursor and
483          // botline - p_so (approximation of how much will be
484          // scrolled).
485          for (linenr_T lnum = wp->w_cursor.lnum; lnum >= wp->w_botline - *so_ptr; lnum--) {
486            // stop at end of file or when we know we are far off
487            if (lnum <= 0
488                || (n += !decor_conceal_line(wp, lnum - 1, false)) > wp->w_view_height + 1) {
489              break;
490            }
491            hasFolding(wp, lnum, &lnum, NULL);
492          }
493        } else {
494          n = wp->w_cursor.lnum - wp->w_botline + 1 + *so_ptr;
495        }
496        if (n <= wp->w_view_height + 1) {
497          if (eof_pressure) {
498            scroll_cursor_halfway(wp, true, true);
499          } else {
500            scroll_cursor_bot(wp, scrolljump_value(wp), false);
501          }
502        } else {
503          scroll_cursor_halfway(wp, eof_pressure, eof_pressure);
504        }
505      }
506    }
507  }
508  wp->w_valid |= VALID_TOPLINE;
509  wp->w_viewport_invalid = true;
510  win_check_anchored_floats(wp);
511
512  // Need to redraw when topline changed.
513  if (wp->w_topline != old_topline
514      || wp->w_topfill != old_topfill) {
515    dollar_vcol = -1;
516    redraw_later(wp, UPD_VALID);
517
518    // When 'smoothscroll' is not set, should reset w_skipcol.
519    if (!wp->w_p_sms) {
520      reset_skipcol(wp);
521    } else if (wp->w_skipcol != 0) {
522      redraw_later(wp, UPD_SOME_VALID);
523    }
524
525    // May need to set w_skipcol when cursor in w_topline.
526    if (wp->w_cursor.lnum == wp->w_topline) {
527      validate_cursor(wp);
528    }
529  }
530
531  *so_ptr = save_so;
532}
533
534/// Return the scrolljump value to use for the window "wp".
535/// When 'scrolljump' is positive use it as-is.
536/// When 'scrolljump' is negative use it as a percentage of the window height.
537static int scrolljump_value(win_T *wp)
538{
539  int result = p_sj >= 0 ? (int)p_sj : (wp->w_view_height * (int)(-p_sj)) / 100;
540  return result;
541}
542
543/// Return true when there are not 'scrolloff' lines above the cursor for window "wp".
544static bool check_top_offset(win_T *wp)
545{
546  int64_t so = get_scrolloff_value(wp);
547  if (wp->w_cursor.lnum < wp->w_topline + so || win_lines_concealed(wp)) {
548    lineoff_T loff;
549    loff.lnum = wp->w_cursor.lnum;
550    loff.fill = 0;
551    int n = wp->w_topfill;  // always have this context
552    // Count the visible screen lines above the cursor line.
553    while (n < so) {
554      topline_back(wp, &loff);
555      // Stop when included a line above the window.
556      if (loff.lnum < wp->w_topline
557          || (loff.lnum == wp->w_topline && loff.fill > 0)) {
558        break;
559      }
560      n += loff.height;
561    }
562    if (n < so) {
563      return true;
564    }
565  }
566  return false;
567}
568
569/// Update w_curswant.
570void update_curswant_force(void)
571{
572  validate_virtcol(curwin);
573  curwin->w_curswant = curwin->w_virtcol;
574  curwin->w_set_curswant = false;
575}
576
577/// Update w_curswant if w_set_curswant is set.
578void update_curswant(void)
579{
580  if (curwin->w_set_curswant) {
581    update_curswant_force();
582  }
583}
584
585// Check if the cursor has moved.  Set the w_valid flag accordingly.
586void check_cursor_moved(win_T *wp)
587{
588  if (wp->w_cursor.lnum != wp->w_valid_cursor.lnum) {
589    wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL
590                     |VALID_CHEIGHT|VALID_CROW|VALID_TOPLINE);
591
592    // Concealed line visibility toggled.
593    if (wp == curwin && wp->w_valid_cursor.lnum > 0 && wp->w_p_cole >= 2
594        && !conceal_cursor_line(wp)
595        && (decor_conceal_line(wp, wp->w_cursor.lnum - 1, true)
596            || decor_conceal_line(wp, wp->w_valid_cursor.lnum - 1, true))) {
597      changed_window_setting(wp);
598    }
599    wp->w_valid_cursor = wp->w_cursor;
600    wp->w_valid_leftcol = wp->w_leftcol;
601    wp->w_valid_skipcol = wp->w_skipcol;
602    wp->w_viewport_invalid = true;
603  } else if (wp->w_skipcol != wp->w_valid_skipcol) {
604    wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL
605                     |VALID_CHEIGHT|VALID_CROW
606                     |VALID_BOTLINE|VALID_BOTLINE_AP);
607    wp->w_valid_cursor = wp->w_cursor;
608    wp->w_valid_leftcol = wp->w_leftcol;
609    wp->w_valid_skipcol = wp->w_skipcol;
610  } else if (wp->w_cursor.col != wp->w_valid_cursor.col
611             || wp->w_leftcol != wp->w_valid_leftcol
612             || wp->w_cursor.coladd !=
613             wp->w_valid_cursor.coladd) {
614    wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL);
615    wp->w_valid_cursor.col = wp->w_cursor.col;
616    wp->w_valid_leftcol = wp->w_leftcol;
617    wp->w_valid_cursor.coladd = wp->w_cursor.coladd;
618    wp->w_viewport_invalid = true;
619  }
620}
621
622// Call this function when some window settings have changed, which require
623// the cursor position, botline and topline to be recomputed and the window to
624// be redrawn.  E.g, when changing the 'wrap' option or folding.
625void changed_window_setting(win_T *wp)
626{
627  wp->w_lines_valid = 0;
628  changed_line_abv_curs_win(wp);
629  wp->w_valid &= ~(VALID_BOTLINE|VALID_BOTLINE_AP|VALID_TOPLINE);
630  redraw_later(wp, UPD_NOT_VALID);
631}
632
633/// Call changed_window_setting() for every window.
634void changed_window_setting_all(void)
635{
636  FOR_ALL_TAB_WINDOWS(tp, wp) {
637    changed_window_setting(wp);
638  }
639}
640
641// Set wp->w_topline to a certain number.
642void set_topline(win_T *wp, linenr_T lnum)
643{
644  linenr_T prev_topline = wp->w_topline;
645
646  // go to first of folded lines
647  hasFolding(wp, lnum, &lnum, NULL);
648  // Approximate the value of w_botline
649  wp->w_botline += lnum - wp->w_topline;
650  if (wp->w_botline > wp->w_buffer->b_ml.ml_line_count + 1) {
651    wp->w_botline = wp->w_buffer->b_ml.ml_line_count + 1;
652  }
653  wp->w_topline = lnum;
654  wp->w_topline_was_set = true;
655  if (lnum != prev_topline) {
656    // Keep the filler lines when the topline didn't change.
657    wp->w_topfill = 0;
658  }
659  wp->w_valid &= ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_TOPLINE);
660  // Don't set VALID_TOPLINE here, 'scrolloff' needs to be checked.
661  redraw_later(wp, UPD_VALID);
662}
663
664/// Saves the view of `wp`, for restore_viewstate().
665void save_viewstate(win_T *wp, viewstate_T *vs)
666  FUNC_ATTR_NONNULL_ALL
667{
668  vs->vs_curswant = wp->w_curswant;
669  vs->vs_set_curswant = wp->w_set_curswant;
670  vs->vs_leftcol = wp->w_leftcol;
671  vs->vs_skipcol = wp->w_skipcol;
672  vs->vs_topline = wp->w_topline;
673  vs->vs_topfill = wp->w_topfill;
674  vs->vs_botline = wp->w_botline;
675  vs->vs_empty_rows = wp->w_empty_rows;
676}
677
678/// Restores the view saved by save_viewstate(). No validation.
679void restore_viewstate(win_T *wp, const viewstate_T *vs)
680  FUNC_ATTR_NONNULL_ALL
681{
682  wp->w_curswant = vs->vs_curswant;
683  wp->w_set_curswant = vs->vs_set_curswant;
684  wp->w_leftcol = vs->vs_leftcol;
685  wp->w_skipcol = vs->vs_skipcol;
686  wp->w_topline = vs->vs_topline;
687  wp->w_topfill = vs->vs_topfill;
688  wp->w_botline = vs->vs_botline;
689  wp->w_empty_rows = vs->vs_empty_rows;
690}
691
692/// Call this function when the length of the cursor line (in screen
693/// characters) has changed, and the change is before the cursor.
694/// If the line length changed the number of screen lines might change,
695/// requiring updating w_topline.  That may also invalidate w_crow.
696/// Need to take care of w_botline separately!
697void changed_cline_bef_curs(win_T *wp)
698{
699  wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL|VALID_CROW
700                   |VALID_CHEIGHT|VALID_TOPLINE);
701}
702
703// Call this function when the length of a line (in screen characters) above
704// the cursor have changed.
705// Need to take care of w_botline separately!
706void changed_line_abv_curs(void)
707{
708  curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL|VALID_CROW
709                       |VALID_CHEIGHT|VALID_TOPLINE);
710}
711
712void changed_line_abv_curs_win(win_T *wp)
713{
714  wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL|VALID_CROW
715                   |VALID_CHEIGHT|VALID_TOPLINE);
716}
717
718/// Make sure the value of wp->w_botline is valid.
719void validate_botline_win(win_T *wp)
720  FUNC_ATTR_NONNULL_ALL
721{
722  if (!(wp->w_valid & VALID_BOTLINE)) {
723    comp_botline(wp);
724  }
725}
726
727/// Mark wp->w_botline as invalid (because of some change in the buffer).
728void invalidate_botline_win(win_T *wp)
729  FUNC_ATTR_NONNULL_ALL
730{
731  wp->w_valid &= ~(VALID_BOTLINE|VALID_BOTLINE_AP);
732}
733
734void approximate_botline_win(win_T *wp)
735{
736  wp->w_valid &= ~VALID_BOTLINE;
737}
738
739// Return true if wp->w_wrow and wp->w_wcol are valid.
740int cursor_valid(win_T *wp)
741{
742  check_cursor_moved(wp);
743  return (wp->w_valid & (VALID_WROW|VALID_WCOL)) == (VALID_WROW|VALID_WCOL);
744}
745
746// Validate cursor position.  Makes sure w_wrow and w_wcol are valid.
747// w_topline must be valid, you may need to call update_topline() first!
748void validate_cursor(win_T *wp)
749{
750  check_cursor_lnum(wp);
751  check_cursor_moved(wp);
752  if ((wp->w_valid & (VALID_WCOL|VALID_WROW)) != (VALID_WCOL|VALID_WROW)) {
753    curs_columns(wp, true);
754  }
755}
756
757// Compute wp->w_cline_row and wp->w_cline_height, based on the current value
758// of wp->w_topline.
759static void curs_rows(win_T *wp)
760{
761  // Check if wp->w_lines[].wl_size is invalid
762  bool all_invalid = (!redrawing()
763                      || wp->w_lines_valid == 0
764                      || wp->w_lines[0].wl_lnum > wp->w_topline);
765  int i = 0;
766  wp->w_cline_row = 0;
767  for (linenr_T lnum = wp->w_topline; lnum < wp->w_cursor.lnum; i++) {
768    bool valid = false;
769    if (!all_invalid && i < wp->w_lines_valid) {
770      if (wp->w_lines[i].wl_lnum < lnum || !wp->w_lines[i].wl_valid) {
771        continue;                       // skip changed or deleted lines
772      }
773      if (wp->w_lines[i].wl_lnum == lnum) {
774        // Check for newly inserted lines below this row, in which
775        // case we need to check for folded lines.
776        if (!wp->w_buffer->b_mod_set
777            || wp->w_lines[i].wl_lastlnum < wp->w_cursor.lnum
778            || wp->w_buffer->b_mod_top
779            > wp->w_lines[i].wl_lastlnum + 1) {
780          valid = true;
781        }
782      } else if (wp->w_lines[i].wl_lnum > lnum) {
783        i--;                            // hold at inserted lines
784      }
785    }
786    if (valid && (lnum != wp->w_topline || (wp->w_skipcol == 0 && !win_may_fill(wp)))) {
787      lnum = wp->w_lines[i].wl_lastlnum + 1;
788      // Cursor inside folded or concealed lines, don't count this row
789      if (lnum > wp->w_cursor.lnum) {
790        break;
791      }
792      wp->w_cline_row += wp->w_lines[i].wl_size;
793    } else {
794      linenr_T last = lnum;
795      bool folded;
796      int n = plines_correct_topline(wp, lnum, &last, true, &folded);
797      lnum = last + 1;
798      if (lnum + decor_conceal_line(wp, lnum - 1, false) > wp->w_cursor.lnum) {
799        break;
800      }
801      wp->w_cline_row += n;
802    }
803  }
804
805  check_cursor_moved(wp);
806  if (!(wp->w_valid & VALID_CHEIGHT)) {
807    if (all_invalid
808        || i == wp->w_lines_valid
809        || (i < wp->w_lines_valid
810            && (!wp->w_lines[i].wl_valid
811                || wp->w_lines[i].wl_lnum != wp->w_cursor.lnum))) {
812      wp->w_cline_height = plines_win_full(wp, wp->w_cursor.lnum, NULL,
813                                           &wp->w_cline_folded, true, true);
814    } else if (i > wp->w_lines_valid) {
815      // a line that is too long to fit on the last screen line
816      wp->w_cline_height = 0;
817      wp->w_cline_folded = hasFolding(wp, wp->w_cursor.lnum, NULL, NULL);
818    } else {
819      wp->w_cline_height = wp->w_lines[i].wl_size;
820      wp->w_cline_folded = wp->w_lines[i].wl_folded;
821    }
822  }
823
824  redraw_for_cursorline(wp);
825  wp->w_valid |= VALID_CROW|VALID_CHEIGHT;
826}
827
828// Validate wp->w_virtcol only.
829void validate_virtcol(win_T *wp)
830{
831  check_cursor_moved(wp);
832
833  if (wp->w_valid & VALID_VIRTCOL) {
834    return;
835  }
836
837  getvvcol(wp, &wp->w_cursor, NULL, &(wp->w_virtcol), NULL, 0);
838  redraw_for_cursorcolumn(wp);
839  wp->w_valid |= VALID_VIRTCOL;
840}
841
842// Validate wp->w_cline_height only.
843void validate_cheight(win_T *wp)
844{
845  check_cursor_moved(wp);
846
847  if (wp->w_valid & VALID_CHEIGHT) {
848    return;
849  }
850
851  wp->w_cline_height = plines_win_full(wp, wp->w_cursor.lnum,
852                                       NULL, &wp->w_cline_folded,
853                                       true, true);
854  wp->w_valid |= VALID_CHEIGHT;
855}
856
857// Validate w_wcol and w_virtcol only.
858void validate_cursor_col(win_T *wp)
859{
860  validate_virtcol(wp);
861
862  if (wp->w_valid & VALID_WCOL) {
863    return;
864  }
865
866  colnr_T col = wp->w_virtcol;
867  colnr_T off = win_col_off(wp);
868  col += off;
869  int width = wp->w_view_width - off + win_col_off2(wp);
870
871  // long line wrapping, adjust wp->w_wrow
872  if (wp->w_p_wrap && col >= (colnr_T)wp->w_view_width && width > 0) {
873    // use same formula as what is used in curs_columns()
874    col -= ((col - wp->w_view_width) / width + 1) * width;
875  }
876  if (col > (int)wp->w_leftcol) {
877    col -= wp->w_leftcol;
878  } else {
879    col = 0;
880  }
881  wp->w_wcol = col;
882
883  wp->w_valid |= VALID_WCOL;
884}
885
886// Compute offset of a window, occupied by absolute or relative line number,
887// fold column and sign column (these don't move when scrolling horizontally).
888int win_col_off(win_T *wp)
889{
890  return ((wp->w_p_nu || wp->w_p_rnu || *wp->w_p_stc != NUL)
891          ? (number_width(wp) + (*wp->w_p_stc == NUL)) : 0)
892         + win_fdccol_count(wp) + (wp->w_scwidth * SIGN_WIDTH);
893}
894
895// Return the difference in column offset for the second screen line of a
896// wrapped line.  It's positive if 'number' or 'relativenumber' is on and 'n'
897// is in 'cpoptions'.
898int win_col_off2(win_T *wp)
899{
900  if ((wp->w_p_nu || wp->w_p_rnu || *wp->w_p_stc != NUL)
901      && vim_strchr(p_cpo, kCpoNumcol) != NULL) {
902    return number_width(wp) + (*wp->w_p_stc == NUL);
903  }
904  return 0;
905}
906
907// Compute wp->w_wcol and wp->w_virtcol.
908// Also updates wp->w_wrow and wp->w_cline_row.
909// Also updates wp->w_leftcol.
910// @param may_scroll when true, may scroll horizontally
911void curs_columns(win_T *wp, int may_scroll)
912{
913  colnr_T startcol;
914  colnr_T endcol;
915
916  // First make sure that w_topline is valid (after moving the cursor).
917  update_topline(wp);
918
919  // Next make sure that w_cline_row is valid.
920  if (!(wp->w_valid & VALID_CROW)) {
921    curs_rows(wp);
922  }
923
924  // Compute the number of virtual columns.
925  if (wp->w_cline_folded) {
926    // In a folded line the cursor is always in the first column
927    startcol = wp->w_virtcol = endcol = wp->w_leftcol;
928  } else {
929    getvvcol(wp, &wp->w_cursor, &startcol, &(wp->w_virtcol), &endcol, 0);
930  }
931
932  // remove '$' from change command when cursor moves onto it
933  if (startcol > dollar_vcol) {
934    dollar_vcol = -1;
935  }
936
937  int extra = win_col_off(wp);
938  wp->w_wcol = wp->w_virtcol + extra;
939  endcol += extra;
940
941  // Now compute w_wrow, counting screen lines from w_cline_row.
942  wp->w_wrow = wp->w_cline_row;
943
944  int n;
945  int width1 = wp->w_view_width - extra;  // text width for first screen line
946  int width2 = 0;                          // text width for second and later screen line
947  bool did_sub_skipcol = false;
948  if (width1 <= 0) {
949    // No room for text, put cursor in last char of window.
950    // If not wrapping, the last non-empty line.
951    wp->w_wcol = wp->w_view_width - 1;
952    if (wp->w_p_wrap) {
953      wp->w_wrow = wp->w_view_height - 1;
954    } else {
955      wp->w_wrow = wp->w_view_height - 1 - wp->w_empty_rows;
956    }
957  } else if (wp->w_p_wrap && wp->w_view_width != 0) {
958    width2 = width1 + win_col_off2(wp);
959
960    // skip columns that are not visible
961    if (wp->w_cursor.lnum == wp->w_topline
962        && wp->w_skipcol > 0
963        && wp->w_wcol >= wp->w_skipcol) {
964      // Deduct by multiples of width2.  This allows the long line wrapping
965      // formula below to correctly calculate the w_wcol value when wrapping.
966      if (wp->w_skipcol <= width1) {
967        wp->w_wcol -= width2;
968      } else {
969        wp->w_wcol -= width2 * (((wp->w_skipcol - width1) / width2) + 1);
970      }
971
972      did_sub_skipcol = true;
973    }
974
975    // long line wrapping, adjust wp->w_wrow
976    if (wp->w_wcol >= wp->w_view_width) {
977      // this same formula is used in validate_cursor_col()
978      n = (wp->w_wcol - wp->w_view_width) / width2 + 1;
979      wp->w_wcol -= n * width2;
980      wp->w_wrow += n;
981    }
982  } else if (may_scroll
983             && !wp->w_cline_folded) {
984    // No line wrapping: compute wp->w_leftcol if scrolling is on and line
985    // is not folded.
986    // If scrolling is off, wp->w_leftcol is assumed to be 0
987
988    // If Cursor is left of the screen, scroll rightwards.
989    // If Cursor is right of the screen, scroll leftwards.
990    // If we get closer to the edge than 'sidescrolloff', scroll a little extra.
991    int64_t siso = get_sidescrolloff_value(wp);
992    int64_t off_left = startcol - wp->w_leftcol - siso;
993    int64_t off_right = endcol - wp->w_leftcol - (wp->w_view_width - siso) + 1;
994    if (off_left < 0 || off_right > 0) {
995      int64_t diff = (off_left < 0) ? -off_left : off_right;
996
997      // When far off or not enough room on either side, put cursor in
998      // middle of window.
999      int new_leftcol;
1000      if (p_ss == 0 || diff >= width1 / 2 || off_right >= off_left) {
1001        new_leftcol = wp->w_wcol - extra - width1 / 2;
1002      } else {
1003        if (diff < p_ss) {
1004          assert(p_ss <= INT_MAX);
1005          diff = p_ss;
1006        }
1007        if (off_left < 0) {
1008          new_leftcol = wp->w_leftcol - (int)diff;
1009        } else {
1010          new_leftcol = wp->w_leftcol + (int)diff;
1011        }
1012      }
1013      new_leftcol = MAX(new_leftcol, 0);
1014      if (new_leftcol != (int)wp->w_leftcol) {
1015        wp->w_leftcol = new_leftcol;
1016        win_check_anchored_floats(wp);
1017        // screen has to be redrawn with new wp->w_leftcol
1018        redraw_later(wp, UPD_NOT_VALID);
1019      }
1020    }
1021    wp->w_wcol -= wp->w_leftcol;
1022  } else if (wp->w_wcol > (int)wp->w_leftcol) {
1023    wp->w_wcol -= wp->w_leftcol;
1024  } else {
1025    wp->w_wcol = 0;
1026  }
1027
1028  // Skip over filler lines.  At the top use w_topfill, there
1029  // may be some filler lines above the window.
1030  if (wp->w_cursor.lnum == wp->w_topline) {
1031    wp->w_wrow += wp->w_topfill;
1032  } else {
1033    wp->w_wrow += win_get_fill(wp, wp->w_cursor.lnum);
1034  }
1035
1036  int plines = 0;
1037  int64_t so = get_scrolloff_value(wp);
1038  colnr_T prev_skipcol = wp->w_skipcol;
1039  if ((wp->w_wrow >= wp->w_view_height
1040       || ((prev_skipcol > 0
1041            || wp->w_wrow + so >= wp->w_view_height)
1042           && (plines = plines_win_nofill(wp, wp->w_cursor.lnum, false)) - 1
1043           >= wp->w_view_height))
1044      && wp->w_view_height != 0
1045      && wp->w_cursor.lnum == wp->w_topline
1046      && width2 > 0
1047      && wp->w_view_width != 0) {
1048    // Cursor past end of screen.  Happens with a single line that does
1049    // not fit on screen.  Find a skipcol to show the text around the
1050    // cursor.  Avoid scrolling all the time. compute value of "extra":
1051    // 1: Less than "p_so" lines above
1052    // 2: Less than "p_so" lines below
1053    // 3: both of them
1054    extra = 0;
1055    if (wp->w_skipcol + so * width2 > wp->w_virtcol) {
1056      extra = 1;
1057    }
1058    // Compute last display line of the buffer line that we want at the
1059    // bottom of the window.
1060    if (plines == 0) {
1061      plines = plines_win(wp, wp->w_cursor.lnum, false);
1062    }
1063    plines--;
1064    if (plines > wp->w_wrow + so) {
1065      assert(wp->w_wrow + so <= INT_MAX);
1066      n = (int)(wp->w_wrow + so);
1067    } else {
1068      n = plines;
1069    }
1070    if ((colnr_T)n >= wp->w_view_height + wp->w_skipcol / width2 - so) {
1071      extra += 2;
1072    }
1073
1074    if (extra == 3 || wp->w_view_height <= so * 2) {
1075      // not enough room for 'scrolloff', put cursor in the middle
1076      n = wp->w_virtcol / width2;
1077      if (n > wp->w_view_height / 2) {
1078        n -= wp->w_view_height / 2;
1079      } else {
1080        n = 0;
1081      }
1082      // don't skip more than necessary
1083      if (n > plines - wp->w_view_height + 1) {
1084        n = plines - wp->w_view_height + 1;
1085      }
1086      wp->w_skipcol = n > 0 ? width1 + (n - 1) * width2
1087                            : 0;
1088    } else if (extra == 1) {
1089      // less than 'scrolloff' lines above, decrease skipcol
1090      assert(so <= INT_MAX);
1091      extra = (int)((wp->w_skipcol + so * width2 - wp->w_virtcol
1092                     + width2 - 1) / width2);
1093      if (extra > 0) {
1094        if ((colnr_T)(extra * width2) > wp->w_skipcol) {
1095          extra = wp->w_skipcol / width2;
1096        }
1097        wp->w_skipcol -= extra * width2;
1098      }
1099    } else if (extra == 2) {
1100      // less than 'scrolloff' lines below, increase skipcol
1101      endcol = (n - wp->w_view_height + 1) * width2;
1102      while (endcol > wp->w_virtcol) {
1103        endcol -= width2;
1104      }
1105      wp->w_skipcol = MAX(wp->w_skipcol, endcol);
1106    }
1107
1108    // adjust w_wrow for the changed w_skipcol
1109    if (did_sub_skipcol) {
1110      wp->w_wrow -= (wp->w_skipcol - prev_skipcol) / width2;
1111    } else {
1112      wp->w_wrow -= wp->w_skipcol / width2;
1113    }
1114
1115    if (wp->w_wrow >= wp->w_view_height) {
1116      // small window, make sure cursor is in it
1117      extra = wp->w_wrow - wp->w_view_height + 1;
1118      wp->w_skipcol += extra * width2;
1119      wp->w_wrow -= extra;
1120    }
1121
1122    // extra could be either positive or negative
1123    extra = (prev_skipcol - wp->w_skipcol) / width2;
1124    // TODO(bfredl): this is very suspicious when not called by win_update()
1125    // We should not randomly alter screen state outside of update_screen() :(
1126    if (wp->w_grid.target) {
1127      win_scroll_lines(wp, 0, extra);
1128    }
1129  } else if (!wp->w_p_sms) {
1130    wp->w_skipcol = 0;
1131  }
1132  if (prev_skipcol != wp->w_skipcol) {
1133    redraw_later(wp, UPD_SOME_VALID);
1134  }
1135
1136  redraw_for_cursorcolumn(wp);
1137
1138  // now w_leftcol and w_skipcol are valid, avoid check_cursor_moved()
1139  // thinking otherwise
1140  wp->w_valid_leftcol = wp->w_leftcol;
1141  wp->w_valid_skipcol = wp->w_skipcol;
1142
1143  wp->w_valid |= VALID_WCOL|VALID_WROW|VALID_VIRTCOL;
1144}
1145
1146/// Compute the screen position of text character at "pos" in window "wp"
1147/// The resulting values are one-based, zero when character is not visible.
1148///
1149/// @param[out] rowp screen row
1150/// @param[out] scolp start screen column
1151/// @param[out] ccolp cursor screen column
1152/// @param[out] ecolp end screen column
1153void textpos2screenpos(win_T *wp, pos_T *pos, int *rowp, int *scolp, int *ccolp, int *ecolp,
1154                       bool local)
1155{
1156  colnr_T scol = 0;
1157  colnr_T ccol = 0;
1158  colnr_T ecol = 0;
1159  int row = 0;
1160  colnr_T coloff = 0;
1161  bool visible_row = false;
1162  bool is_folded = false;
1163
1164  linenr_T lnum = pos->lnum;
1165  if (lnum >= wp->w_topline && lnum <= wp->w_botline) {
1166    is_folded = hasFolding(wp, lnum, &lnum, NULL);
1167    row = plines_m_win(wp, wp->w_topline, lnum - 1, INT_MAX);
1168    // "row" should be the screen line where line "lnum" begins, which can
1169    // be negative if "lnum" is "w_topline" and "w_skipcol" is non-zero.
1170    row -= adjust_plines_for_skipcol(wp);
1171    // Add filler lines above this buffer line.
1172    row += lnum == wp->w_topline ? wp->w_topfill : win_get_fill(wp, lnum);
1173    visible_row = true;
1174  } else if (!local || lnum < wp->w_topline) {
1175    row = 0;
1176  } else {
1177    row = wp->w_view_height - 1;
1178  }
1179
1180  bool existing_row = (lnum > 0 && lnum <= wp->w_buffer->b_ml.ml_line_count);
1181
1182  if ((local || visible_row) && existing_row) {
1183    const colnr_T off = win_col_off(wp);
1184    if (is_folded) {
1185      row += (local ? 0 : wp->w_winrow + wp->w_winrow_off) + 1;
1186      coloff = (local ? 0 : wp->w_wincol + wp->w_wincol_off) + 1 + off;
1187    } else {
1188      assert(lnum == pos->lnum);
1189      getvcol(wp, pos, &scol, &ccol, &ecol, 0);
1190
1191      // similar to what is done in validate_cursor_col()
1192      colnr_T col = scol;
1193      col += off;
1194      int width = wp->w_view_width - off + win_col_off2(wp);
1195
1196      // long line wrapping, adjust row
1197      if (wp->w_p_wrap && col >= (colnr_T)wp->w_view_width && width > 0) {
1198        // use same formula as what is used in curs_columns()
1199        int rowoff = visible_row ? ((col - wp->w_view_width) / width + 1) : 0;
1200        col -= rowoff * width;
1201        row += rowoff;
1202      }
1203
1204      col -= wp->w_leftcol;
1205
1206      if (col >= 0 && col < wp->w_view_width && row >= 0 && row < wp->w_view_height) {
1207        coloff = col - scol + (local ? 0 : wp->w_wincol + wp->w_wincol_off) + 1;
1208        row += (local ? 0 : wp->w_winrow + wp->w_winrow_off) + 1;
1209      } else {
1210        // character is left, right or below of the window
1211        scol = ccol = ecol = 0;
1212        if (local) {
1213          coloff = col < 0 ? -1 : wp->w_view_width + 1;
1214        } else {
1215          row = 0;
1216        }
1217      }
1218    }
1219  }
1220  *rowp = row;
1221  *scolp = scol + coloff;
1222  *ccolp = ccol + coloff;
1223  *ecolp = ecol + coloff;
1224}
1225
1226/// "screenpos({winid}, {lnum}, {col})" function
1227void f_screenpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1228{
1229  tv_dict_alloc_ret(rettv);
1230  dict_T *dict = rettv->vval.v_dict;
1231
1232  win_T *wp = find_win_by_nr_or_id(&argvars[0]);
1233  if (wp == NULL) {
1234    return;
1235  }
1236
1237  pos_T pos = {
1238    .lnum = (linenr_T)tv_get_number(&argvars[1]),
1239    .col = (colnr_T)tv_get_number(&argvars[2]) - 1,
1240    .coladd = 0
1241  };
1242  if (pos.lnum > wp->w_buffer->b_ml.ml_line_count) {
1243    semsg(_(e_invalid_line_number_nr), pos.lnum);
1244    return;
1245  }
1246  pos.col = MAX(pos.col, 0);
1247  int row = 0;
1248  int scol = 0;
1249  int ccol = 0;
1250  int ecol = 0;
1251  textpos2screenpos(wp, &pos, &row, &scol, &ccol, &ecol, false);
1252
1253  tv_dict_add_nr(dict, S_LEN("row"), row);
1254  tv_dict_add_nr(dict, S_LEN("col"), scol);
1255  tv_dict_add_nr(dict, S_LEN("curscol"), ccol);
1256  tv_dict_add_nr(dict, S_LEN("endcol"), ecol);
1257}
1258
1259/// Convert a virtual (screen) column to a character column.  The first column
1260/// is one.  For a multibyte character, the column number of the first byte is
1261/// returned.
1262static int virtcol2col(win_T *wp, linenr_T lnum, int vcol)
1263{
1264  int offset = vcol2col(wp, lnum, vcol - 1, NULL);
1265  char *line = ml_get_buf(wp->w_buffer, lnum);
1266  char *p = line + offset;
1267
1268  if (*p == NUL) {
1269    if (p == line) {  // empty line
1270      return 0;
1271    }
1272    // Move to the first byte of the last char.
1273    MB_PTR_BACK(line, p);
1274  }
1275  return (int)(p - line + 1);
1276}
1277
1278/// "virtcol2col({winid}, {lnum}, {col})" function
1279void f_virtcol2col(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1280{
1281  rettv->vval.v_number = -1;
1282
1283  if (tv_check_for_number_arg(argvars, 0) == FAIL
1284      || tv_check_for_number_arg(argvars, 1) == FAIL
1285      || tv_check_for_number_arg(argvars, 2) == FAIL) {
1286    return;
1287  }
1288
1289  win_T *wp = find_win_by_nr_or_id(&argvars[0]);
1290  if (wp == NULL) {
1291    return;
1292  }
1293
1294  bool error = false;
1295  linenr_T lnum = (linenr_T)tv_get_number_chk(&argvars[1], &error);
1296  if (error || lnum < 0 || lnum > wp->w_buffer->b_ml.ml_line_count) {
1297    return;
1298  }
1299
1300  int screencol = (int)tv_get_number_chk(&argvars[2], &error);
1301  if (error || screencol < 0) {
1302    return;
1303  }
1304
1305  rettv->vval.v_number = virtcol2col(wp, lnum, screencol);
1306}
1307
1308/// Make sure the cursor is in the visible part of the topline after scrolling
1309/// the screen with 'smoothscroll'.
1310static void cursor_correct_sms(win_T *wp)
1311{
1312  if (!wp->w_p_sms || !wp->w_p_wrap || wp->w_cursor.lnum != wp->w_topline) {
1313    return;
1314  }
1315
1316  int64_t so = get_scrolloff_value(wp);
1317  int width1 = wp->w_view_width - win_col_off(wp);
1318  int width2 = width1 + win_col_off2(wp);
1319  int64_t so_cols = so == 0 ? 0 : width1 + (so - 1) * width2;
1320  int space_cols = (wp->w_view_height - 1) * width2;
1321  int size = so == 0 ? 0 : linetabsize_eol(wp, wp->w_topline);
1322
1323  if (wp->w_topline == 1 && wp->w_skipcol == 0) {
1324    so_cols = 0;               // Ignore 'scrolloff' at top of buffer.
1325  } else if (so_cols > space_cols / 2) {
1326    so_cols = space_cols / 2;  // Not enough room: put cursor in the middle.
1327  }
1328
1329  // Not enough screen lines in topline: ignore 'scrolloff'.
1330  while (so_cols > size && so_cols - width2 >= width1 && width1 > 0) {
1331    so_cols -= width2;
1332  }
1333  if (so_cols >= width1 && so_cols > size) {
1334    so_cols -= width1;
1335  }
1336
1337  int overlap = wp->w_skipcol == 0
1338                ? 0 : sms_marker_overlap(wp, wp->w_view_width - width2);
1339  // If we have non-zero scrolloff, ignore marker overlap.
1340  int64_t top = wp->w_skipcol + (so_cols != 0 ? so_cols : overlap);
1341  int64_t bot = wp->w_skipcol + width1 + (wp->w_view_height - 1) * width2 - so_cols;
1342
1343  validate_virtcol(wp);
1344  colnr_T col = wp->w_virtcol;
1345
1346  if (col < top) {
1347    if (col < width1) {
1348      col += width1;
1349    }
1350    while (width2 > 0 && col < top) {
1351      col += width2;
1352    }
1353  } else {
1354    while (width2 > 0 && col >= bot) {
1355      col -= width2;
1356    }
1357  }
1358
1359  if (col != wp->w_virtcol) {
1360    wp->w_curswant = col;
1361    int rc = coladvance(wp, wp->w_curswant);
1362    // validate_virtcol() marked various things as valid, but after
1363    // moving the cursor they need to be recomputed
1364    wp->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_CHEIGHT|VALID_CROW|VALID_VIRTCOL);
1365    if (rc == FAIL && wp->w_skipcol > 0
1366        && wp->w_cursor.lnum < wp->w_buffer->b_ml.ml_line_count) {
1367      validate_virtcol(wp);
1368      if (wp->w_virtcol < wp->w_skipcol + overlap) {
1369        // Cursor still not visible: move it to the next line instead.
1370        wp->w_cursor.lnum++;
1371        wp->w_cursor.col = 0;
1372        wp->w_cursor.coladd = 0;
1373        wp->w_curswant = 0;
1374        wp->w_valid &= ~VALID_VIRTCOL;
1375      }
1376    }
1377  }
1378}
1379
1380/// Scroll "count" lines up or down, and redraw.
1381void scroll_redraw(int up, linenr_T count)
1382{
1383  linenr_T prev_topline = curwin->w_topline;
1384  int prev_skipcol = curwin->w_skipcol;
1385  int prev_topfill = curwin->w_topfill;
1386  linenr_T prev_lnum = curwin->w_cursor.lnum;
1387
1388  bool moved = up
1389               ? scrollup(curwin, count, true)
1390               : scrolldown(curwin, count, true);
1391
1392  if (get_scrolloff_value(curwin) > 0) {
1393    // Adjust the cursor position for 'scrolloff'.  Mark w_topline as
1394    // valid, otherwise the screen jumps back at the end of the file.
1395    cursor_correct(curwin);
1396    check_cursor_moved(curwin);
1397    curwin->w_valid |= VALID_TOPLINE;
1398
1399    // If moved back to where we were, at least move the cursor, otherwise
1400    // we get stuck at one position.  Don't move the cursor up if the
1401    // first line of the buffer is already on the screen
1402    while (curwin->w_topline == prev_topline
1403           && curwin->w_skipcol == prev_skipcol
1404           && curwin->w_topfill == prev_topfill) {
1405      if (up) {
1406        if (curwin->w_cursor.lnum > prev_lnum
1407            || cursor_down(1L, false) == FAIL) {
1408          break;
1409        }
1410      } else {
1411        if (curwin->w_cursor.lnum < prev_lnum
1412            || prev_topline == 1L
1413            || cursor_up(1L, false) == FAIL) {
1414          break;
1415        }
1416      }
1417      // Mark w_topline as valid, otherwise the screen jumps back at the
1418      // end of the file.
1419      check_cursor_moved(curwin);
1420      curwin->w_valid |= VALID_TOPLINE;
1421    }
1422  }
1423
1424  if (moved) {
1425    curwin->w_viewport_invalid = true;
1426  }
1427
1428  cursor_correct_sms(curwin);
1429  if (curwin->w_cursor.lnum != prev_lnum) {
1430    coladvance(curwin, curwin->w_curswant);
1431  }
1432  redraw_later(curwin, UPD_VALID);
1433}
1434
1435/// Scroll a window down by "line_count" logical lines.  "CTRL-Y"
1436///
1437/// @param line_count number of lines to scroll
1438/// @param byfold if true, count a closed fold as one line
1439bool scrolldown(win_T *wp, linenr_T line_count, int byfold)
1440{
1441  int done = 0;                // total # of physical lines done
1442  int width1 = 0;
1443  int width2 = 0;
1444  bool do_sms = wp->w_p_wrap && wp->w_p_sms;
1445
1446  if (do_sms) {
1447    width1 = wp->w_view_width - win_col_off(wp);
1448    width2 = width1 + win_col_off2(wp);
1449  }
1450
1451  // Make sure w_topline is at the first of a sequence of folded lines.
1452  hasFolding(wp, wp->w_topline, &wp->w_topline, NULL);
1453  validate_cursor(wp);            // w_wrow needs to be valid
1454  for (int todo = line_count; todo > 0; todo--) {
1455    bool can_fill = wp->w_topfill < wp->w_view_height - 1
1456                    && wp->w_topfill < win_get_fill(wp, wp->w_topline);
1457    // break when at the very top
1458    if (wp->w_topline == 1 && !can_fill && (!do_sms || wp->w_skipcol < width1)) {
1459      break;
1460    }
1461    if (do_sms && wp->w_skipcol >= width1) {
1462      // scroll a screen line down
1463      if (wp->w_skipcol >= width1 + width2) {
1464        wp->w_skipcol -= width2;
1465      } else {
1466        wp->w_skipcol -= width1;
1467      }
1468      redraw_later(wp, UPD_NOT_VALID);
1469      done++;
1470    } else if (can_fill) {
1471      wp->w_topfill++;
1472      done++;
1473    } else {
1474      // scroll a text line down
1475      wp->w_topline--;
1476      wp->w_skipcol = 0;
1477      wp->w_topfill = 0;
1478      // A sequence of folded lines only counts for one logical line
1479      linenr_T first;
1480      if (hasFolding(wp, wp->w_topline, &first, NULL)) {
1481        done += !decor_conceal_line(wp, first - 1, false);
1482        if (!byfold) {
1483          todo -= wp->w_topline - first - 1;
1484        }
1485        wp->w_botline -= wp->w_topline - first;
1486        wp->w_topline = first;
1487      } else if (decor_conceal_line(wp, wp->w_topline - 1, false)) {
1488        todo++;
1489      } else {
1490        if (do_sms) {
1491          int size = linetabsize_eol(wp, wp->w_topline);
1492          if (size > width1) {
1493            wp->w_skipcol = width1;
1494            size -= width1;
1495            redraw_later(wp, UPD_NOT_VALID);
1496          }
1497          while (size > width2) {
1498            wp->w_skipcol += width2;
1499            size -= width2;
1500          }
1501          done++;
1502        } else {
1503          done += plines_win_nofill(wp, wp->w_topline, true);
1504        }
1505      }
1506    }
1507    wp->w_botline--;                // approximate w_botline
1508    invalidate_botline_win(wp);
1509  }
1510
1511  // Adjust for concealed lines above w_topline
1512  while (wp->w_topline > 1 && decor_conceal_line(wp, wp->w_topline - 2, false)) {
1513    wp->w_topline--;
1514    hasFolding(wp, wp->w_topline, &wp->w_topline, NULL);
1515  }
1516
1517  wp->w_wrow += done;               // keep w_wrow updated
1518  wp->w_cline_row += done;          // keep w_cline_row updated
1519
1520  if (wp->w_cursor.lnum == wp->w_topline) {
1521    wp->w_cline_row = 0;
1522  }
1523  check_topfill(wp, true);
1524
1525  // Compute the row number of the last row of the cursor line
1526  // and move the cursor onto the displayed part of the window.
1527  int wrow = wp->w_wrow;
1528  if (wp->w_p_wrap && wp->w_view_width != 0) {
1529    validate_virtcol(wp);
1530    validate_cheight(wp);
1531    wrow += wp->w_cline_height - 1 -
1532            wp->w_virtcol / wp->w_view_width;
1533  }
1534  bool moved = false;
1535  while (wrow >= wp->w_view_height && wp->w_cursor.lnum > 1) {
1536    linenr_T first;
1537    if (hasFolding(wp, wp->w_cursor.lnum, &first, NULL)) {
1538      wrow -= !decor_conceal_line(wp, wp->w_cursor.lnum - 1, false);
1539      wp->w_cursor.lnum = MAX(first - 1, 1);
1540    } else {
1541      wrow -= plines_win(wp, wp->w_cursor.lnum--, true);
1542    }
1543    wp->w_valid &=
1544      ~(VALID_WROW|VALID_WCOL|VALID_CHEIGHT|VALID_CROW|VALID_VIRTCOL);
1545    moved = true;
1546  }
1547  if (moved) {
1548    // Move cursor to first line of closed fold.
1549    foldAdjustCursor(wp);
1550    coladvance(wp, wp->w_curswant);
1551  }
1552  wp->w_cursor.lnum = MAX(wp->w_cursor.lnum, wp->w_topline);
1553
1554  return moved;
1555}
1556
1557/// Scroll a window up by "line_count" logical lines.  "CTRL-E"
1558///
1559/// @param line_count number of lines to scroll
1560/// @param byfold if true, count a closed fold as one line
1561bool scrollup(win_T *wp, linenr_T line_count, bool byfold)
1562{
1563  linenr_T topline = wp->w_topline;
1564  linenr_T botline = wp->w_botline;
1565  bool do_sms = wp->w_p_wrap && wp->w_p_sms;
1566
1567  if (do_sms || (byfold && win_lines_concealed(wp)) || win_may_fill(wp)) {
1568    int width1 = wp->w_view_width - win_col_off(wp);
1569    int width2 = width1 + win_col_off2(wp);
1570    int size = 0;
1571    const colnr_T prev_skipcol = wp->w_skipcol;
1572
1573    if (do_sms) {
1574      size = linetabsize_eol(wp, wp->w_topline);
1575    }
1576
1577    // diff mode: first consume "topfill"
1578    // 'smoothscroll': increase "w_skipcol" until it goes over the end of
1579    // the line, then advance to the next line.
1580    // folding: count each sequence of folded lines as one logical line.
1581    for (int todo = line_count; todo > 0; todo--) {
1582      todo += decor_conceal_line(wp, wp->w_topline - 1, false);
1583      if (wp->w_topfill > 0) {
1584        wp->w_topfill--;
1585      } else {
1586        linenr_T lnum = wp->w_topline;
1587        if (byfold) {
1588          // for a closed fold: go to the last line in the fold
1589          hasFolding(wp, lnum, NULL, &lnum);
1590        }
1591        if (lnum == wp->w_topline && do_sms) {
1592          // 'smoothscroll': increase "w_skipcol" until it goes over
1593          // the end of the line, then advance to the next line.
1594          int add = wp->w_skipcol > 0 ? width2 : width1;
1595          wp->w_skipcol += add;
1596          if (wp->w_skipcol >= size) {
1597            if (lnum == wp->w_buffer->b_ml.ml_line_count) {
1598              // at the last screen line, can't scroll further
1599              wp->w_skipcol -= add;
1600              break;
1601            }
1602            lnum++;
1603          }
1604        } else {
1605          if (lnum >= wp->w_buffer->b_ml.ml_line_count) {
1606            break;
1607          }
1608          lnum++;
1609        }
1610
1611        if (lnum > wp->w_topline) {
1612          // approximate w_botline
1613          wp->w_botline += lnum - wp->w_topline;
1614          wp->w_topline = lnum;
1615          wp->w_topfill = win_get_fill(wp, lnum);
1616          wp->w_skipcol = 0;
1617          if (todo > 1 && do_sms) {
1618            size = linetabsize_eol(wp, wp->w_topline);
1619          }
1620        }
1621      }
1622    }
1623
1624    if (prev_skipcol > 0 || wp->w_skipcol > 0) {
1625      // need to redraw more, because wl_size of the (new) topline may
1626      // now be invalid
1627      redraw_later(wp, UPD_NOT_VALID);
1628    }
1629  } else {
1630    wp->w_topline += line_count;
1631    wp->w_botline += line_count;            // approximate w_botline
1632  }
1633
1634  wp->w_topline = MIN(wp->w_topline, wp->w_buffer->b_ml.ml_line_count);
1635  wp->w_botline = MIN(wp->w_botline, wp->w_buffer->b_ml.ml_line_count + 1);
1636
1637  check_topfill(wp, false);
1638
1639  // Make sure w_topline is at the first of a sequence of folded lines.
1640  hasFolding(wp, wp->w_topline, &wp->w_topline, NULL);
1641
1642  wp->w_valid &= ~(VALID_WROW|VALID_CROW|VALID_BOTLINE);
1643  if (wp->w_cursor.lnum < wp->w_topline) {
1644    wp->w_cursor.lnum = wp->w_topline;
1645    wp->w_valid &=
1646      ~(VALID_WROW|VALID_WCOL|VALID_CHEIGHT|VALID_CROW|VALID_VIRTCOL);
1647    coladvance(wp, wp->w_curswant);
1648  }
1649
1650  bool moved = topline != wp->w_topline || botline != wp->w_botline;
1651
1652  return moved;
1653}
1654
1655/// Called after changing the cursor column: make sure that curwin->w_skipcol is
1656/// valid for 'smoothscroll'.
1657void adjust_skipcol(void)
1658{
1659  if (!curwin->w_p_wrap || !curwin->w_p_sms || curwin->w_cursor.lnum != curwin->w_topline) {
1660    return;
1661  }
1662
1663  int width1 = curwin->w_view_width - win_col_off(curwin);
1664  if (width1 <= 0) {
1665    return;  // no text will be displayed
1666  }
1667  int width2 = width1 + win_col_off2(curwin);
1668  int64_t so = get_scrolloff_value(curwin);
1669  int64_t scrolloff_cols = so == 0 ? 0 : width1 + (so - 1) * width2;
1670  bool scrolled = false;
1671
1672  validate_cheight(curwin);
1673  if (curwin->w_cline_height == curwin->w_view_height
1674      // w_cline_height may be capped at w_view_height, check there aren't
1675      // actually more lines.
1676      && plines_win(curwin, curwin->w_cursor.lnum, false) <= curwin->w_view_height) {
1677    // the line just fits in the window, don't scroll
1678    reset_skipcol(curwin);
1679    return;
1680  }
1681
1682  validate_virtcol(curwin);
1683  int overlap = sms_marker_overlap(curwin, curwin->w_view_width - width2);
1684  while (curwin->w_skipcol > 0
1685         && curwin->w_virtcol < curwin->w_skipcol + overlap + scrolloff_cols) {
1686    // scroll a screen line down
1687    if (curwin->w_skipcol >= width1 + width2) {
1688      curwin->w_skipcol -= width2;
1689    } else {
1690      curwin->w_skipcol -= width1;
1691    }
1692    scrolled = true;
1693  }
1694  if (scrolled) {
1695    validate_virtcol(curwin);
1696    redraw_later(curwin, UPD_NOT_VALID);
1697    return;  // don't scroll in the other direction now
1698  }
1699  int row = 0;
1700  int64_t col = curwin->w_virtcol + scrolloff_cols;
1701
1702  // Avoid adjusting for 'scrolloff' beyond the text line height.
1703  if (scrolloff_cols > 0) {
1704    int size = linetabsize_eol(curwin, curwin->w_topline);
1705    size = width1 + width2 * ((size - width1 + width2 - 1) / width2);
1706    while (col > size) {
1707      col -= width2;
1708    }
1709  }
1710  col -= curwin->w_skipcol;
1711
1712  if (col >= width1) {
1713    col -= width1;
1714    row++;
1715  }
1716  if (col > width2) {
1717    row += (int)(col / width2);
1718  }
1719  if (row >= curwin->w_view_height) {
1720    if (curwin->w_skipcol == 0) {
1721      curwin->w_skipcol += width1;
1722      row--;
1723    }
1724    if (row >= curwin->w_view_height) {
1725      curwin->w_skipcol += (row - curwin->w_view_height) * width2;
1726    }
1727    redraw_later(curwin, UPD_NOT_VALID);
1728  }
1729}
1730
1731/// Don't end up with too many filler lines in the window.
1732///
1733/// @param down  when true scroll down when not enough space
1734void check_topfill(win_T *wp, bool down)
1735{
1736  if (wp->w_topfill > 0) {
1737    int n = plines_win_nofill(wp, wp->w_topline, true);
1738    if (wp->w_topfill + n > wp->w_view_height) {
1739      if (down && wp->w_topline > 1) {
1740        wp->w_topline--;
1741        wp->w_topfill = 0;
1742      } else {
1743        wp->w_topfill = wp->w_view_height - n;
1744        wp->w_topfill = MAX(wp->w_topfill, 0);
1745      }
1746    }
1747  }
1748  win_check_anchored_floats(wp);
1749}
1750
1751// Scroll the screen one line down, but don't do it if it would move the
1752// cursor off the screen.
1753void scrolldown_clamp(void)
1754{
1755  bool can_fill = (curwin->w_topfill < win_get_fill(curwin, curwin->w_topline));
1756
1757  if (curwin->w_topline <= 1
1758      && !can_fill) {
1759    return;
1760  }
1761
1762  validate_cursor(curwin);        // w_wrow needs to be valid
1763
1764  // Compute the row number of the last row of the cursor line
1765  // and make sure it doesn't go off the screen. Make sure the cursor
1766  // doesn't go past 'scrolloff' lines from the screen end.
1767  int end_row = curwin->w_wrow;
1768  if (can_fill) {
1769    end_row++;
1770  } else {
1771    end_row += plines_win_nofill(curwin, curwin->w_topline - 1, true);
1772  }
1773  if (curwin->w_p_wrap && curwin->w_view_width != 0) {
1774    validate_cheight(curwin);
1775    validate_virtcol(curwin);
1776    end_row += curwin->w_cline_height - 1 -
1777               curwin->w_virtcol / curwin->w_view_width;
1778  }
1779  if (end_row < curwin->w_view_height - get_scrolloff_value(curwin)) {
1780    if (can_fill) {
1781      curwin->w_topfill++;
1782      check_topfill(curwin, true);
1783    } else {
1784      curwin->w_topline--;
1785      curwin->w_topfill = 0;
1786    }
1787    hasFolding(curwin, curwin->w_topline, &curwin->w_topline, NULL);
1788    curwin->w_botline--;            // approximate w_botline
1789    curwin->w_valid &= ~(VALID_WROW|VALID_CROW|VALID_BOTLINE);
1790  }
1791}
1792
1793// Scroll the screen one line up, but don't do it if it would move the cursor
1794// off the screen.
1795void scrollup_clamp(void)
1796{
1797  if (curwin->w_topline == curbuf->b_ml.ml_line_count
1798      && curwin->w_topfill == 0) {
1799    return;
1800  }
1801
1802  validate_cursor(curwin);        // w_wrow needs to be valid
1803
1804  // Compute the row number of the first row of the cursor line
1805  // and make sure it doesn't go off the screen. Make sure the cursor
1806  // doesn't go before 'scrolloff' lines from the screen start.
1807  int start_row = (curwin->w_wrow
1808                   - plines_win_nofill(curwin, curwin->w_topline, true)
1809                   - curwin->w_topfill);
1810  if (curwin->w_p_wrap && curwin->w_view_width != 0) {
1811    validate_virtcol(curwin);
1812    start_row -= curwin->w_virtcol / curwin->w_view_width;
1813  }
1814  if (start_row >= get_scrolloff_value(curwin)) {
1815    if (curwin->w_topfill > 0) {
1816      curwin->w_topfill--;
1817    } else {
1818      hasFolding(curwin, curwin->w_topline, NULL, &curwin->w_topline);
1819      curwin->w_topline++;
1820    }
1821    curwin->w_botline++;                // approximate w_botline
1822    curwin->w_valid &= ~(VALID_WROW|VALID_CROW|VALID_BOTLINE);
1823  }
1824}
1825
1826// Add one line above "lp->lnum".  This can be a filler line, a closed fold or
1827// a (wrapped) text line.  Uses and sets "lp->fill".
1828// Returns the height of the added line in "lp->height".
1829// Lines above the first one are incredibly high: MAXCOL.
1830// When "winheight" is true limit to window height.
1831static void topline_back_winheight(win_T *wp, lineoff_T *lp, int winheight)
1832{
1833  if (lp->fill < win_get_fill(wp, lp->lnum)) {
1834    // Add a filler line
1835    lp->fill++;
1836    lp->height = 1;
1837  } else {
1838    lp->lnum--;
1839    lp->fill = 0;
1840    if (lp->lnum < 1) {
1841      lp->height = MAXCOL;
1842    } else if (hasFolding(wp, lp->lnum, &lp->lnum, NULL)) {
1843      // Add a closed fold unless concealed.
1844      lp->height = !decor_conceal_line(wp, lp->lnum - 1, false);
1845    } else {
1846      lp->height = plines_win_nofill(wp, lp->lnum, winheight);
1847    }
1848  }
1849}
1850
1851static void topline_back(win_T *wp, lineoff_T *lp)
1852{
1853  topline_back_winheight(wp, lp, true);
1854}
1855
1856// Add one line below "lp->lnum".  This can be a filler line, a closed fold or
1857// a (wrapped) text line.  Uses and sets "lp->fill".
1858// Returns the height of the added line in "lp->height".
1859// Lines below the last one are incredibly high.
1860static void botline_forw(win_T *wp, lineoff_T *lp)
1861{
1862  if (lp->fill < win_get_fill(wp, lp->lnum + 1)) {
1863    // Add a filler line.
1864    lp->fill++;
1865    lp->height = 1;
1866  } else {
1867    lp->lnum++;
1868    lp->fill = 0;
1869    assert(wp->w_buffer != 0);
1870    if (lp->lnum > wp->w_buffer->b_ml.ml_line_count) {
1871      lp->height = MAXCOL;
1872    } else if (hasFolding(wp, lp->lnum, NULL, &lp->lnum)) {
1873      // Add a closed fold unless concealed.
1874      lp->height = !decor_conceal_line(wp, lp->lnum - 1, false);
1875    } else {
1876      lp->height = plines_win_nofill(wp, lp->lnum, true);
1877    }
1878  }
1879}
1880
1881// Recompute topline to put the cursor at the top of the window.
1882// Scroll at least "min_scroll" lines.
1883// If "always" is true, always set topline (for "zt").
1884void scroll_cursor_top(win_T *wp, int min_scroll, int always)
1885{
1886  linenr_T old_topline = wp->w_topline;
1887  int old_skipcol = wp->w_skipcol;
1888  linenr_T old_topfill = wp->w_topfill;
1889  int64_t off = get_scrolloff_value(wp);
1890
1891  if (mouse_dragging > 0) {
1892    off = mouse_dragging - 1;
1893  }
1894
1895  // Decrease topline until:
1896  // - it has become 1
1897  // - (part of) the cursor line is moved off the screen or
1898  // - moved at least 'scrolljump' lines and
1899  // - at least 'scrolloff' lines above and below the cursor
1900  validate_cheight(wp);
1901  int scrolled = 0;
1902  int used = wp->w_cline_height;  // includes filler lines above
1903  if (wp->w_cursor.lnum < wp->w_topline) {
1904    scrolled = used;
1905  }
1906
1907  linenr_T top;  // just above displayed lines
1908  linenr_T bot;  // just below displayed lines
1909  if (hasFolding(wp, wp->w_cursor.lnum, &top, &bot)) {
1910    top--;
1911    bot++;
1912  } else {
1913    top = wp->w_cursor.lnum - 1;
1914    bot = wp->w_cursor.lnum + 1;
1915  }
1916  linenr_T new_topline = top + 1;
1917
1918  // "used" already contains the number of filler lines above, don't add it
1919  // again.
1920  // Hide filler lines above cursor line by adding them to "extra".
1921  int extra = win_get_fill(wp, wp->w_cursor.lnum);
1922
1923  // Check if the lines from "top" to "bot" fit in the window.  If they do,
1924  // set new_topline and advance "top" and "bot" to include more lines.
1925  while (top > 0) {
1926    int i = plines_win_nofill(wp, top, true);
1927    hasFolding(wp, top, &top, NULL);
1928    if (top < wp->w_topline) {
1929      scrolled += i;
1930    }
1931
1932    // If scrolling is needed, scroll at least 'sj' lines.
1933    if ((new_topline >= wp->w_topline || scrolled > min_scroll) && extra >= off) {
1934      break;
1935    }
1936
1937    used += i;
1938    if (extra + i <= off && bot < wp->w_buffer->b_ml.ml_line_count) {
1939      used += plines_win_full(wp, bot, &bot, NULL, true, true);
1940    }
1941    if (used > wp->w_view_height) {
1942      break;
1943    }
1944
1945    extra += i;
1946    new_topline = top;
1947    top--;
1948    bot++;
1949  }
1950
1951  // If we don't have enough space, put cursor in the middle.
1952  // This makes sure we get the same position when using "k" and "j"
1953  // in a small window.
1954  if (used > wp->w_view_height) {
1955    scroll_cursor_halfway(wp, false, false);
1956  } else {
1957    // If "always" is false, only adjust topline to a lower value, higher
1958    // value may happen with wrapping lines.
1959    if (new_topline < wp->w_topline || always) {
1960      wp->w_topline = new_topline;
1961    }
1962    wp->w_topline = MIN(wp->w_topline, wp->w_cursor.lnum);
1963    wp->w_topfill = win_get_fill(wp, wp->w_topline);
1964    if (wp->w_topfill > 0 && extra > off) {
1965      wp->w_topfill -= extra - (int)off;
1966      wp->w_topfill = MAX(wp->w_topfill, 0);
1967    }
1968    check_topfill(wp, false);
1969    if (wp->w_topline != old_topline) {
1970      reset_skipcol(wp);
1971    } else if (wp->w_topline == wp->w_cursor.lnum) {
1972      validate_virtcol(wp);
1973      if (wp->w_skipcol >= wp->w_virtcol) {
1974        // Skip up to the screen line the cursor is in, so that the
1975        // position in the line is kept.
1976        int width1 = wp->w_view_width - win_col_off(wp);
1977        int width2 = width1 + win_col_off2(wp);
1978        int plines_off = 0;
1979        if (width2 > 0 && wp->w_virtcol >= width1) {
1980          plines_off = (wp->w_virtcol - width1) / width2 + 1;
1981        }
1982        int skipcol = skipcol_from_plines(wp, plines_off);
1983        if (skipcol != wp->w_skipcol) {
1984          wp->w_skipcol = skipcol;
1985          redraw_later(wp, UPD_SOME_VALID);
1986        }
1987      }
1988    }
1989    if (wp->w_topline != old_topline
1990        || wp->w_skipcol != old_skipcol
1991        || wp->w_topfill != old_topfill) {
1992      wp->w_valid &=
1993        ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
1994    }
1995    wp->w_valid |= VALID_TOPLINE;
1996    wp->w_viewport_invalid = true;
1997  }
1998}
1999
2000// Set w_empty_rows and w_filler_rows for window "wp", having used up "used"
2001// screen lines for text lines.
2002void set_empty_rows(win_T *wp, int used)
2003{
2004  wp->w_filler_rows = 0;
2005  if (used == 0) {
2006    wp->w_empty_rows = 0;  // single line that doesn't fit
2007  } else {
2008    wp->w_empty_rows = wp->w_view_height - used;
2009    if (wp->w_botline <= wp->w_buffer->b_ml.ml_line_count) {
2010      wp->w_filler_rows = win_get_fill(wp, wp->w_botline);
2011      if (wp->w_empty_rows > wp->w_filler_rows) {
2012        wp->w_empty_rows -= wp->w_filler_rows;
2013      } else {
2014        wp->w_filler_rows = wp->w_empty_rows;
2015        wp->w_empty_rows = 0;
2016      }
2017    }
2018  }
2019}
2020
2021/// Recompute topline to put the cursor at the bottom of the window.
2022/// When scrolling scroll at least "min_scroll" lines.
2023/// If "set_topbot" is true, set topline and botline first (for "zb").
2024/// This is messy stuff!!!
2025void scroll_cursor_bot(win_T *wp, int min_scroll, bool set_topbot)
2026{
2027  lineoff_T loff;
2028  linenr_T old_topline = wp->w_topline;
2029  int old_skipcol = wp->w_skipcol;
2030  int old_topfill = wp->w_topfill;
2031  linenr_T old_botline = wp->w_botline;
2032  int old_valid = wp->w_valid;
2033  int old_empty_rows = wp->w_empty_rows;
2034  linenr_T cln = wp->w_cursor.lnum;  // Cursor Line Number
2035  bool do_sms = wp->w_p_wrap && wp->w_p_sms;
2036
2037  if (set_topbot) {
2038    int used = 0;
2039    linenr_T cln_last = cln;
2040    hasFolding(wp, cln, NULL, &cln_last);
2041    wp->w_botline = cln_last + 1;
2042    loff.lnum = cln_last + 1;
2043    loff.fill = 0;
2044    while (true) {
2045      topline_back_winheight(wp, &loff, false);
2046      if (loff.height == MAXCOL) {
2047        break;
2048      }
2049      if (used + loff.height > wp->w_view_height) {
2050        if (do_sms) {
2051          // 'smoothscroll' and 'wrap' are set.  The above line is
2052          // too long to show in its entirety, so we show just a part
2053          // of it.
2054          if (used < wp->w_view_height) {
2055            int plines_offset = used + loff.height - wp->w_view_height;
2056            used = wp->w_view_height;
2057            wp->w_topfill = loff.fill;
2058            wp->w_topline = loff.lnum;
2059            wp->w_skipcol = skipcol_from_plines(wp, plines_offset);
2060          }
2061        }
2062        break;
2063      }
2064      wp->w_topfill = loff.fill;
2065      wp->w_topline = loff.lnum;
2066      used += loff.height;
2067    }
2068
2069    set_empty_rows(wp, used);
2070    wp->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
2071    if (wp->w_topline != old_topline
2072        || wp->w_topfill != old_topfill
2073        || wp->w_skipcol != old_skipcol
2074        || wp->w_skipcol != 0) {
2075      wp->w_valid &= ~(VALID_WROW|VALID_CROW);
2076      if (wp->w_skipcol != old_skipcol) {
2077        redraw_later(wp, UPD_NOT_VALID);
2078      } else {
2079        reset_skipcol(wp);
2080      }
2081    }
2082  } else {
2083    validate_botline_win(wp);
2084  }
2085
2086  // The lines of the cursor line itself are always used.
2087  int used = plines_win_nofill(wp, cln, true);
2088
2089  int scrolled = 0;
2090  // If the cursor is on or below botline, we will at least scroll by the
2091  // height of the cursor line, which is "used".  Correct for empty lines,
2092  // which are really part of botline.
2093  if (cln >= wp->w_botline) {
2094    scrolled = used;
2095    if (cln == wp->w_botline) {
2096      scrolled -= wp->w_empty_rows;
2097    }
2098    if (do_sms) {
2099      // 'smoothscroll' and 'wrap' are set.
2100      // Calculate how many screen lines the current top line of window
2101      // occupies. If it is occupying more than the entire window, we
2102      // need to scroll the additional clipped lines to scroll past the
2103      // top line before we can move on to the other lines.
2104      int top_plines = plines_win_nofill(wp, wp->w_topline, false);
2105      int width1 = wp->w_view_width - win_col_off(wp);
2106
2107      if (width1 > 0) {
2108        int width2 = width1 + win_col_off2(wp);
2109        int skip_lines = 0;
2110
2111        // A similar formula is used in curs_columns().
2112        if (wp->w_skipcol > width1) {
2113          skip_lines += (wp->w_skipcol - width1) / width2 + 1;
2114        } else if (wp->w_skipcol > 0) {
2115          skip_lines = 1;
2116        }
2117
2118        top_plines -= skip_lines;
2119        if (top_plines > wp->w_view_height) {
2120          scrolled += (top_plines - wp->w_view_height);
2121        }
2122      }
2123    }
2124  }
2125
2126  lineoff_T boff;
2127  // Stop counting lines to scroll when
2128  // - hitting start of the file
2129  // - scrolled nothing or at least 'sj' lines
2130  // - at least 'so' lines below the cursor
2131  // - lines between botline and cursor have been counted
2132  if (!hasFolding(wp, wp->w_cursor.lnum, &loff.lnum, &boff.lnum)) {
2133    loff.lnum = cln;
2134    boff.lnum = cln;
2135  }
2136  loff.fill = 0;
2137  boff.fill = 0;
2138  int fill_below_window = win_get_fill(wp, wp->w_botline) - wp->w_filler_rows;
2139
2140  int extra = 0;
2141  int64_t so = get_scrolloff_value(wp);
2142  while (loff.lnum > 1) {
2143    // Stop when scrolled nothing or at least "min_scroll", found "extra"
2144    // context for 'scrolloff' and counted all lines below the window.
2145    if ((((scrolled <= 0 || scrolled >= min_scroll)
2146          && extra >= (mouse_dragging > 0 ? mouse_dragging - 1 : so))
2147         || boff.lnum + 1 > wp->w_buffer->b_ml.ml_line_count)
2148        && loff.lnum <= wp->w_botline
2149        && (loff.lnum < wp->w_botline
2150            || loff.fill >= fill_below_window)) {
2151      break;
2152    }
2153
2154    linenr_T loff_lnum_before = loff.lnum;
2155    // Add one line above
2156    topline_back(wp, &loff);
2157    if (loff.height == MAXCOL) {
2158      used = MAXCOL;
2159    } else {
2160      used += loff.height;
2161    }
2162    if (used > wp->w_view_height) {
2163      break;
2164    }
2165    if (loff.lnum >= wp->w_botline
2166        && (loff.lnum > wp->w_botline
2167            || loff.fill <= fill_below_window)) {
2168      // Count screen lines that are below the window.
2169      scrolled += loff.height;
2170      if (loff.lnum == wp->w_botline && loff_lnum_before > curwin->w_botline) {
2171        scrolled -= wp->w_empty_rows;
2172      }
2173    }
2174
2175    if (boff.lnum < wp->w_buffer->b_ml.ml_line_count) {
2176      linenr_T boff_lnum_before = boff.lnum;
2177      // Add one line below
2178      botline_forw(wp, &boff);
2179      assert(boff.height != MAXCOL);
2180      used += boff.height;
2181      if (used > wp->w_view_height) {
2182        break;
2183      }
2184      if (extra < (mouse_dragging > 0 ? mouse_dragging - 1 : so)
2185          || scrolled < min_scroll) {
2186        extra += boff.height;
2187        if (boff.lnum >= wp->w_botline
2188            || (boff.lnum + 1 == wp->w_botline
2189                && boff.fill > wp->w_filler_rows)) {
2190          // Count screen lines that are below the window.
2191          scrolled += boff.height;
2192          if (boff.lnum >= curwin->w_botline && boff_lnum_before < curwin->w_botline) {
2193            scrolled -= wp->w_empty_rows;
2194          }
2195        }
2196      }
2197    }
2198  }
2199
2200  linenr_T line_count;
2201  // wp->w_empty_rows is larger, no need to scroll
2202  if (scrolled <= 0) {
2203    line_count = 0;
2204    // more than a screenfull, don't scroll but redraw
2205  } else if (used > wp->w_view_height) {
2206    line_count = used;
2207    // scroll minimal number of lines
2208  } else {
2209    line_count = 0;
2210    boff.fill = wp->w_topfill;
2211    boff.lnum = wp->w_topline - 1;
2212    int i;
2213    for (i = 0; i < scrolled && boff.lnum < wp->w_botline;) {
2214      botline_forw(wp, &boff);
2215      i += boff.height;
2216      line_count++;
2217    }
2218    if (i < scrolled) {         // below wp->w_botline, don't scroll
2219      line_count = 9999;
2220    }
2221  }
2222
2223  // Scroll up if the cursor is off the bottom of the screen a bit.
2224  // Otherwise put it at 1/2 of the screen.
2225  bool eof_pressure = scrolloffpad_eof_pressure(wp, cln, so);
2226  if (line_count >= wp->w_view_height && line_count > min_scroll) {
2227    scroll_cursor_halfway(wp, eof_pressure, true);
2228  } else if (line_count > 0) {
2229    if (do_sms) {
2230      scrollup(wp, scrolled, true);  // TODO(vim):
2231    } else {
2232      scrollup(wp, line_count, true);
2233    }
2234  }
2235
2236  // If topline didn't change we need to restore w_botline and w_empty_rows
2237  // (we changed them).
2238  // If topline did change, update_screen() will set botline.
2239  if (wp->w_topline == old_topline && wp->w_skipcol == old_skipcol && set_topbot) {
2240    wp->w_botline = old_botline;
2241    wp->w_empty_rows = old_empty_rows;
2242    wp->w_valid = old_valid;
2243  }
2244  wp->w_valid |= VALID_TOPLINE;
2245  wp->w_viewport_invalid = true;
2246
2247  // Make sure cursor is still visible after adjusting skipcol for "zb".
2248  if (set_topbot) {
2249    cursor_correct_sms(wp);
2250  }
2251}
2252
2253/// Recompute topline to put the cursor halfway across the window
2254///
2255/// @param atend if true, also put the cursor halfway to the end of the file.
2256///
2257void scroll_cursor_halfway(win_T *wp, bool atend, bool prefer_above)
2258{
2259  linenr_T old_topline = wp->w_topline;
2260  lineoff_T loff = { .lnum = wp->w_cursor.lnum };
2261  lineoff_T boff = { .lnum = wp->w_cursor.lnum };
2262  hasFolding(wp, loff.lnum, &loff.lnum, &boff.lnum);
2263  int used = plines_win_nofill(wp, loff.lnum, true);
2264  loff.fill = 0;
2265  boff.fill = 0;
2266  linenr_T topline = loff.lnum;
2267  colnr_T skipcol = 0;
2268
2269  int want_height;
2270  bool do_sms = wp->w_p_wrap && wp->w_p_sms;
2271  if (do_sms) {
2272    // 'smoothscroll' and 'wrap' are set
2273    if (atend) {
2274      want_height = (wp->w_view_height - used) / 2;
2275      used = 0;
2276    } else {
2277      want_height = wp->w_view_height;
2278    }
2279  }
2280
2281  int topfill = 0;
2282  int above = 0;
2283  int below = 0;
2284  while (topline > 1) {
2285    // If using smoothscroll, we can precisely scroll to the
2286    // exact point where the cursor is halfway down the screen.
2287    if (do_sms) {
2288      topline_back_winheight(wp, &loff, false);
2289      if (loff.height == MAXCOL) {
2290        break;
2291      }
2292      used += loff.height;
2293      if (!atend && boff.lnum < wp->w_buffer->b_ml.ml_line_count) {
2294        botline_forw(wp, &boff);
2295        used += boff.height;
2296      }
2297      if (used > want_height) {
2298        if (used - loff.height < want_height) {
2299          topline = loff.lnum;
2300          topfill = loff.fill;
2301          skipcol = skipcol_from_plines(wp, used - want_height);
2302        }
2303        break;
2304      }
2305      topline = loff.lnum;
2306      topfill = loff.fill;
2307      continue;
2308    }
2309
2310    // If not using smoothscroll, we have to iteratively find how many
2311    // lines to scroll down to roughly fit the cursor.
2312    // This may not be right in the middle if the lines'
2313    // physical height > 1 (e.g. 'wrap' is on).
2314
2315    // Depending on "prefer_above" we add a line above or below first.
2316    // Loop twice to avoid duplicating code.
2317    bool done = false;
2318    for (int round = 1; round <= 2; round++) {
2319      if (prefer_above
2320          ? (round == 2 && below < above)
2321          : (round == 1 && below <= above)) {
2322        // add a line below the cursor
2323        if (boff.lnum < wp->w_buffer->b_ml.ml_line_count) {
2324          botline_forw(wp, &boff);
2325          used += boff.height;
2326          if (used > wp->w_view_height) {
2327            done = true;
2328            break;
2329          }
2330          below += boff.height;
2331        } else {
2332          below++;                    // count a "~" line
2333          if (atend) {
2334            used++;
2335          }
2336        }
2337      }
2338
2339      if (prefer_above
2340          ? (round == 1 && below >= above)
2341          : (round == 1 && below > above)) {
2342        // add a line above the cursor
2343        topline_back(wp, &loff);
2344        if (loff.height == MAXCOL) {
2345          used = MAXCOL;
2346        } else {
2347          used += loff.height;
2348        }
2349        if (used > wp->w_view_height) {
2350          done = true;
2351          break;
2352        }
2353        above += loff.height;
2354        topline = loff.lnum;
2355        topfill = loff.fill;
2356      }
2357    }
2358    if (done) {
2359      break;
2360    }
2361  }
2362
2363  if (!hasFolding(wp, topline, &wp->w_topline, NULL)
2364      && (wp->w_topline != topline || skipcol != 0 || wp->w_skipcol != 0)) {
2365    wp->w_topline = topline;
2366    if (skipcol != 0) {
2367      wp->w_skipcol = skipcol;
2368      redraw_later(wp, UPD_NOT_VALID);
2369    } else if (do_sms) {
2370      reset_skipcol(wp);
2371    }
2372  }
2373  wp->w_topfill = topfill;
2374  if (old_topline > wp->w_topline + wp->w_view_height) {
2375    wp->w_botfill = false;
2376  }
2377  check_topfill(wp, false);
2378  wp->w_valid &= ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);
2379  wp->w_valid |= VALID_TOPLINE;
2380}
2381
2382// Correct the cursor position so that it is in a part of the screen at least
2383// 'so' lines from the top and bottom, if possible.
2384// If not possible, put it at the same position as scroll_cursor_halfway().
2385// When called topline must be valid!
2386void cursor_correct(win_T *wp)
2387{
2388  // How many lines we would like to have above/below the cursor depends on
2389  // whether the first/last line of the file is on screen.
2390  int64_t above_wanted = get_scrolloff_value(wp);
2391  int64_t below_wanted = get_scrolloff_value(wp);
2392  if (mouse_dragging > 0) {
2393    above_wanted = mouse_dragging - 1;
2394    below_wanted = mouse_dragging - 1;
2395  }
2396  if (wp->w_topline == 1) {
2397    above_wanted = 0;
2398    int max_off = wp->w_view_height / 2;
2399    below_wanted = MIN(below_wanted, max_off);
2400  }
2401  validate_botline_win(wp);
2402  if (wp->w_botline == wp->w_buffer->b_ml.ml_line_count + 1
2403      && mouse_dragging == 0) {
2404    // Missing context below EOF must not move the cursor up.  Automatic
2405    // scrolling handles the centering for 'scrolloffpad'.
2406    below_wanted = 0;
2407    int max_off = (wp->w_view_height - 1) / 2;
2408    above_wanted = MIN(above_wanted, max_off);
2409  }
2410
2411  // If there are sufficient file-lines above and below the cursor, we can
2412  // return now.
2413  linenr_T cln = wp->w_cursor.lnum;  // Cursor Line Number
2414  if (cln >= wp->w_topline + above_wanted
2415      && cln < wp->w_botline - below_wanted
2416      && !win_lines_concealed(wp)) {
2417    return;
2418  }
2419
2420  // Narrow down the area where the cursor can be put by taking lines from
2421  // the top and the bottom until:
2422  // - the desired context lines are found
2423  // - the lines from the top is past the lines from the bottom
2424  linenr_T topline = wp->w_topline;
2425  linenr_T botline = wp->w_botline - 1;
2426  // count filler lines as context
2427  int above = wp->w_topfill;  // screen lines above topline
2428  int below = wp->w_filler_rows;  // screen lines below botline
2429  while ((above < above_wanted || below < below_wanted) && topline < botline) {
2430    if (below < below_wanted && (below <= above || above >= above_wanted)) {
2431      below += plines_win_full(wp, botline, NULL, NULL, true, true);
2432      hasFolding(wp, botline, &botline, NULL);
2433      botline--;
2434    }
2435    if (above < above_wanted && (above < below || below >= below_wanted)) {
2436      above += plines_win_nofill(wp, topline, true);
2437      hasFolding(wp, topline, NULL, &topline);
2438
2439      // Count filler lines below this line as context.
2440      if (topline < botline) {
2441        above += win_get_fill(wp, topline + 1);
2442      }
2443      topline++;
2444    }
2445  }
2446  if (topline == botline || botline == 0) {
2447    wp->w_cursor.lnum = topline;
2448  } else if (topline > botline) {
2449    wp->w_cursor.lnum = botline;
2450  } else {
2451    if (cln < topline && wp->w_topline > 1) {
2452      wp->w_cursor.lnum = topline;
2453      wp->w_valid &=
2454        ~(VALID_WROW|VALID_WCOL|VALID_CHEIGHT|VALID_CROW);
2455    }
2456    if (cln > botline && wp->w_botline <= wp->w_buffer->b_ml.ml_line_count) {
2457      wp->w_cursor.lnum = botline;
2458      wp->w_valid &=
2459        ~(VALID_WROW|VALID_WCOL|VALID_CHEIGHT|VALID_CROW);
2460    }
2461  }
2462  check_cursor_moved(wp);
2463  wp->w_valid |= VALID_TOPLINE;
2464  wp->w_viewport_invalid = true;
2465}
2466
2467/// Decide how much overlap to use for page-up or page-down scrolling.
2468/// This is symmetric, so that doing both keeps the same lines displayed.
2469/// Three lines are examined:
2470///
2471///  before CTRL-F          after CTRL-F / before CTRL-B
2472///     etc.                    l1
2473///  l1 last but one line       ------------
2474///  l2 last text line          l2 top text line
2475///  -------------              l3 second text line
2476///  l3                            etc.
2477static int get_scroll_overlap(Direction dir)
2478{
2479  lineoff_T loff;
2480  int min_height = curwin->w_view_height - 2;
2481
2482  validate_botline_win(curwin);
2483  if ((dir == BACKWARD && curwin->w_topline == 1)
2484      || (dir == FORWARD && curwin->w_botline > curbuf->b_ml.ml_line_count)) {
2485    return min_height + 2;  // no overlap, still handle 'smoothscroll'
2486  }
2487
2488  loff.lnum = dir == FORWARD ? curwin->w_botline : curwin->w_topline - 1;
2489  loff.fill = win_get_fill(curwin, loff.lnum + (dir == BACKWARD))
2490              - (dir == FORWARD ? curwin->w_filler_rows : curwin->w_topfill);
2491  loff.height = loff.fill > 0 ? 1 : plines_win_nofill(curwin, loff.lnum, true);
2492
2493  int h1 = loff.height;
2494  if (h1 > min_height) {
2495    return min_height + 2;  // no overlap
2496  }
2497  if (dir == FORWARD) {
2498    topline_back(curwin, &loff);
2499  } else {
2500    botline_forw(curwin, &loff);
2501  }
2502
2503  int h2 = loff.height;
2504  if (h2 == MAXCOL || h2 + h1 > min_height) {
2505    return min_height + 2;  // no overlap
2506  }
2507  if (dir == FORWARD) {
2508    topline_back(curwin, &loff);
2509  } else {
2510    botline_forw(curwin, &loff);
2511  }
2512
2513  int h3 = loff.height;
2514  if (h3 == MAXCOL || h3 + h2 > min_height) {
2515    return min_height + 2;  // no overlap
2516  }
2517  if (dir == FORWARD) {
2518    topline_back(curwin, &loff);
2519  } else {
2520    botline_forw(curwin, &loff);
2521  }
2522
2523  int h4 = loff.height;
2524  if (h4 == MAXCOL || h4 + h3 + h2 > min_height || h3 + h2 + h1 > min_height) {
2525    return min_height + 1;  // 1 line overlap
2526  } else {
2527    return min_height;      // 2 lines overlap
2528  }
2529}
2530
2531/// Scroll "count" lines with 'smoothscroll' in direction "dir". Return true
2532/// when scrolling happened. Adjust "curscount" for scrolling different amount
2533/// of lines when 'smoothscroll' is disabled.
2534static bool scroll_with_sms(Direction dir, int count, int *curscount)
2535{
2536  int prev_sms = curwin->w_p_sms;
2537  colnr_T prev_skipcol = curwin->w_skipcol;
2538  linenr_T prev_topline = curwin->w_topline;
2539  int prev_topfill = curwin->w_topfill;
2540
2541  curwin->w_p_sms = true;
2542  scroll_redraw(dir == FORWARD, count);
2543
2544  // Not actually smoothscrolling but ended up with partially visible line.
2545  // Continue scrolling until skipcol is zero.
2546  if (!prev_sms && curwin->w_skipcol > 0) {
2547    int fixdir = dir;
2548    // Reverse the scroll direction when topline already changed. One line
2549    // extra for scrolling backward so that consuming skipcol is symmetric.
2550    if (labs(curwin->w_topline - prev_topline) > (dir == BACKWARD)) {
2551      fixdir = dir * -1;
2552    }
2553
2554    int width1 = curwin->w_view_width - win_col_off(curwin);
2555    int width2 = width1 + win_col_off2(curwin);
2556    count = 1 + (curwin->w_skipcol - width1 - 1) / width2;
2557    if (fixdir == FORWARD) {
2558      count = 1 + (linetabsize_eol(curwin, curwin->w_topline)
2559                   - curwin->w_skipcol - width1 + width2 - 1) / width2;
2560    }
2561    scroll_redraw(fixdir == FORWARD, count);
2562    *curscount += count * (fixdir == dir ? 1 : -1);
2563  }
2564  curwin->w_p_sms = prev_sms;
2565
2566  return curwin->w_topline != prev_topline
2567         || curwin->w_topfill != prev_topfill
2568         || curwin->w_skipcol != prev_skipcol;
2569}
2570
2571/// Move screen "count" (half) pages up ("dir" is BACKWARD) or down ("dir" is
2572/// FORWARD) and update the screen. Handle moving the cursor and not scrolling
2573/// to reveal end of buffer lines for half-page scrolling with CTRL-D and CTRL-U.
2574///
2575/// @return  FAIL for failure, OK otherwise.
2576int pagescroll(Direction dir, int count, bool half)
2577{
2578  bool did_move = false;
2579  int buflen = curbuf->b_ml.ml_line_count;
2580  colnr_T prev_col = curwin->w_cursor.col;
2581  colnr_T prev_curswant = curwin->w_curswant;
2582  linenr_T prev_lnum = curwin->w_cursor.lnum;
2583  oparg_T oa = { 0 };
2584  cmdarg_T ca = { 0 };
2585  ca.oap = &oa;
2586
2587  if (half) {
2588    // Scroll [count], 'scroll' or current window height lines.
2589    if (count) {
2590      curwin->w_p_scr = MIN(curwin->w_view_height, count);
2591    }
2592    count = MIN(curwin->w_view_height, (int)curwin->w_p_scr);
2593
2594    int curscount = count;
2595    // Adjust count so as to not reveal end of buffer lines.
2596    if (dir == FORWARD
2597        && (curwin->w_topline + curwin->w_view_height + count > buflen
2598            || win_lines_concealed(curwin))) {
2599      int n = plines_correct_topline(curwin, curwin->w_topline, NULL, false, NULL);
2600      if (n - count < curwin->w_view_height && curwin->w_topline < buflen) {
2601        n += plines_m_win(curwin, curwin->w_topline + 1, buflen, curwin->w_view_height + count);
2602      }
2603      if (n < curwin->w_view_height + count) {
2604        count = n - curwin->w_view_height;
2605      }
2606    }
2607
2608    // (Try to) scroll the window unless already at the end of the buffer.
2609    if (count > 0) {
2610      did_move = scroll_with_sms(dir, count, &curscount);
2611      curwin->w_cursor.lnum = prev_lnum;
2612      curwin->w_cursor.col = prev_col;
2613      curwin->w_curswant = prev_curswant;
2614    }
2615
2616    // Move the cursor the same amount of screen lines, skipping over
2617    // concealed lines as those were not included in "curscount".
2618    if (curwin->w_p_wrap) {
2619      nv_screengo(&oa, dir, curscount, true);
2620    } else if (dir == FORWARD) {
2621      cursor_down_inner(curwin, curscount, true);
2622    } else {
2623      cursor_up_inner(curwin, curscount, true);
2624    }
2625  } else {
2626    // Scroll [count] times 'window' or current window height lines.
2627    count *= ((ONE_WINDOW && p_window > 0 && p_window < Rows - 1)
2628              ? MAX(1, (int)p_window - 2) : get_scroll_overlap(dir));
2629    did_move = scroll_with_sms(dir, count, &count);
2630
2631    if (did_move) {
2632      // Place cursor at top or bottom of window.
2633      validate_botline_win(curwin);
2634      linenr_T lnum = (dir == FORWARD ? curwin->w_topline : curwin->w_botline - 1);
2635      // In silent Ex mode the value of w_botline - 1 may be 0,
2636      // but cursor lnum needs to be at least 1.
2637      curwin->w_cursor.lnum = MAX(lnum, 1);
2638    }
2639  }
2640
2641  if (get_scrolloff_value(curwin) > 0) {
2642    cursor_correct(curwin);
2643  }
2644  // Move cursor to first line of closed fold.
2645  foldAdjustCursor(curwin);
2646
2647  did_move = did_move
2648             || prev_col != curwin->w_cursor.col
2649             || prev_lnum != curwin->w_cursor.lnum;
2650
2651  // Error if both the viewport and cursor did not change.
2652  if (!did_move) {
2653    beep_flush();
2654  } else if (!curwin->w_p_sms) {
2655    beginline(BL_SOL | BL_FIX);
2656  } else if (p_sol) {
2657    nv_g_home_m_cmd(&ca);
2658  }
2659
2660  return did_move ? OK : FAIL;
2661}
2662
2663void do_check_cursorbind(void)
2664{
2665  static win_T *prev_curwin = NULL;
2666  static buf_T *prev_curbuf = NULL;
2667  static varnumber_T prev_changedtick = 0;
2668  static pos_T prev_cursor = { 0, 0, 0 };
2669
2670  assert(curwin != NULL && curbuf != NULL);
2671  // Nothing to do when the cursor didn't move and the text didn't change.
2672  // After a change the corresponding line in a diff may be different.
2673  if (curwin == prev_curwin && curbuf == prev_curbuf
2674      && buf_get_changedtick(curbuf) == prev_changedtick
2675      && equalpos(curwin->w_cursor, prev_cursor)) {
2676    return;
2677  }
2678  prev_curwin = curwin;
2679  prev_curbuf = curbuf;
2680  prev_changedtick = buf_get_changedtick(curbuf);
2681  prev_cursor = curwin->w_cursor;
2682
2683  linenr_T line = curwin->w_cursor.lnum;
2684  colnr_T col = curwin->w_cursor.col;
2685  colnr_T coladd = curwin->w_cursor.coladd;
2686  colnr_T curswant = curwin->w_curswant;
2687  bool set_curswant = curwin->w_set_curswant;
2688  win_T *old_curwin = curwin;
2689  buf_T *old_curbuf = curbuf;
2690  int old_VIsual_select = Visual.select;
2691  int old_VIsual_active = Visual.active;
2692
2693  // loop through the cursorbound windows
2694  Visual.select = Visual.active = false;
2695  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2696    curwin = wp;
2697    curbuf = curwin->w_buffer;
2698    // skip original window and windows with 'nocursorbind'
2699    if (curwin != old_curwin && curwin->w_p_crb) {
2700      if (curwin->w_p_diff) {
2701        curwin->w_cursor.lnum =
2702          diff_get_corresponding_line(old_curbuf, line);
2703      } else {
2704        curwin->w_cursor.lnum = line;
2705      }
2706      curwin->w_cursor.col = col;
2707      curwin->w_cursor.coladd = coladd;
2708      curwin->w_curswant = curswant;
2709      curwin->w_set_curswant = set_curswant;
2710
2711      // Make sure the cursor is in a valid position.  Temporarily set
2712      // "restart_edit" to allow the cursor to be beyond the EOL.
2713      {
2714        int restart_edit_save = restart_edit;
2715        restart_edit = true;
2716        check_cursor(curwin);
2717
2718        // Avoid a scroll here for the cursor position, 'scrollbind' is
2719        // more important.
2720        if (!curwin->w_p_scb) {
2721          validate_cursor(curwin);
2722        }
2723
2724        restart_edit = restart_edit_save;
2725      }
2726      // Correct cursor for multi-byte character.
2727      mb_adjust_cursor();
2728      redraw_later(curwin, UPD_VALID);
2729
2730      // Only scroll when 'scrollbind' hasn't done this.
2731      if (!curwin->w_p_scb) {
2732        update_topline(curwin);
2733      }
2734      curwin->w_redr_status = true;
2735    }
2736  }
2737
2738  // reset current-window
2739  Visual.select = old_VIsual_select;
2740  Visual.active = old_VIsual_active;
2741  curwin = old_curwin;
2742  curbuf = old_curbuf;
2743}