robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
34.5 KiB1105 linesraw
1// plines.c: calculate the vertical and horizontal size of text in a window
2
3#include <limits.h>
4#include <stdbool.h>
5#include <stdint.h>
6#include <string.h>
7
8#include "nvim/api/extmark.h"
9#include "nvim/ascii_defs.h"
10#include "nvim/buffer.h"
11#include "nvim/buffer_defs.h"
12#include "nvim/charset.h"
13#include "nvim/decoration.h"
14#include "nvim/decoration_defs.h"
15#include "nvim/diff.h"
16#include "nvim/fold.h"
17#include "nvim/globals.h"
18#include "nvim/indent.h"
19#include "nvim/macros_defs.h"
20#include "nvim/mark_defs.h"
21#include "nvim/marktree.h"
22#include "nvim/mbyte.h"
23#include "nvim/mbyte_defs.h"
24#include "nvim/memline.h"
25#include "nvim/move.h"
26#include "nvim/option.h"
27#include "nvim/option_vars.h"
28#include "nvim/plines.h"
29#include "nvim/pos_defs.h"
30#include "nvim/state.h"
31#include "nvim/state_defs.h"
32#include "nvim/types_defs.h"
33
34#include "plines.c.generated.h"
35
36/// Functions calculating horizontal size of text, when displayed in a window.
37
38/// Return the number of cells the first char in "p" will take on the screen,
39/// taking into account the size of a tab.
40/// Also see getvcol()
41///
42/// @param p
43/// @param col
44///
45/// @return Number of cells.
46///
47/// @see charsize_nowrap()
48int win_chartabsize(win_T *wp, char *p, colnr_T col)
49{
50  buf_T *buf = wp->w_buffer;
51  if (*p == TAB && (!wp->w_p_list || wp->w_p_lcs_chars.tab1)) {
52    return tabstop_padding(col, buf->b_p_ts, buf->b_p_vts_array);
53  }
54  return ptr2cells(p);
55}
56
57/// Like linetabsize_str(), but "s" starts at virtual column "startvcol".
58///
59/// @param startvcol
60/// @param s
61///
62/// @return Number of cells the string will take on the screen.
63int linetabsize_col(int startvcol, char *s)
64{
65  CharsizeArg csarg;
66  CSType const cstype = init_charsize_arg(&csarg, curwin, 0, s);
67  if (cstype == kCharsizeFast) {
68    return linesize_fast(&csarg, startvcol, MAXCOL);
69  } else {
70    return linesize_regular(&csarg, startvcol, MAXCOL);
71  }
72}
73
74/// Return the number of cells line "lnum" of window "wp" will take on the
75/// screen, taking into account the size of a tab and inline virtual text.
76/// Doesn't count the size of 'listchars' "eol".
77int linetabsize(win_T *wp, linenr_T lnum)
78{
79  return win_linetabsize(wp, lnum, ml_get_buf(wp->w_buffer, lnum), MAXCOL);
80}
81
82/// Like linetabsize(), but counts the size of 'listchars' "eol".
83int linetabsize_eol(win_T *wp, linenr_T lnum)
84{
85  return linetabsize(wp, lnum)
86         + ((wp->w_p_list && wp->w_p_lcs_chars.eol != NUL) ? 1 : 0);
87}
88
89static const uint32_t inline_filter[kMTMetaCount] = {[kMTMetaInline] = kMTFilterSelect };
90
91/// Prepare the structure passed to charsize functions.
92///
93/// "line" is the start of the line.
94/// When "lnum" is zero do not use inline virtual text.
95CSType init_charsize_arg(CharsizeArg *csarg, win_T *wp, linenr_T lnum, char *line)
96{
97  csarg->win = wp;
98  csarg->line = line;
99  csarg->max_head_vcol = 0;
100  csarg->cur_text_width_left = 0;
101  csarg->cur_text_width_right = 0;
102  csarg->virt_row = -1;
103  csarg->skip_cur_text = false;
104  csarg->indent_width = INT_MIN;
105  csarg->use_tabstop = !wp->w_p_list || wp->w_p_lcs_chars.tab1;
106
107  if (lnum > 0) {
108    if (marktree_itr_get_filter(wp->w_buffer->b_marktree, lnum - 1, 0, lnum, 0,
109                                inline_filter, csarg->iter)) {
110      csarg->virt_row = lnum - 1;
111    }
112  }
113
114  if (csarg->virt_row >= 0
115      || (wp->w_p_wrap && (wp->w_p_lbr || wp->w_p_bri || *get_showbreak_value(wp) != NUL))) {
116    return kCharsizeRegular;
117  } else {
118    return kCharsizeFast;
119  }
120}
121
122/// Like init_charsize_arg(), but do not count inline virtual text at the measured character.
123/// The 'linebreak' lookahead can still use "virt_row", without initializing "iter".
124CSType init_charsize_arg_skip_cur_text(CharsizeArg *csarg, win_T *wp, linenr_T lnum, char *line)
125{
126  CSType cstype = init_charsize_arg(csarg, wp, 0, line);
127  csarg->skip_cur_text = true;
128  if (lnum > 0 && buf_meta_total(wp->w_buffer, kMTMetaInline) > 0) {
129    csarg->virt_row = lnum - 1;
130    cstype = kCharsizeRegular;
131  }
132  return cstype;
133}
134
135/// Total width of inline virtual text at buffer column "col" of row "row", advancing "iter".
136/// Call with non-decreasing "col", like the walks in charsize_regular().
137static int inline_virt_text_width(win_T *wp, MarkTreeIter *iter, int row, int col)
138{
139  buf_T *const buf = wp->w_buffer;
140  int width = 0;
141  while (true) {
142    MTKey mark = marktree_itr_current(iter);
143    if (mark.pos.row != row || mark.pos.col > col) {
144      break;
145    } else if (mark.pos.col == col && !mt_invalid(mark) && ns_in_win(mark.ns, wp)) {
146      DecorInline decor = mt_decor(mark);
147      DecorVirtText *vt = decor.ext ? decor.data.ext.vt : NULL;
148      while (vt) {
149        if (!(vt->flags & kVTIsLines) && vt->pos == kVPosInline) {
150          width += vt->width;
151        }
152        vt = vt->next;
153      }
154    }
155    marktree_itr_next_filter(buf->b_marktree, iter, row + 1, 0, inline_filter);
156  }
157  return width;
158}
159
160/// Get the number of cells taken up on the screen for the given arguments.
161/// "csarg->cur_text_width_left" and "csarg->cur_text_width_right" are set
162/// to the extra size for inline virtual text.
163///
164/// When "csarg->max_head_vcol" is positive, only count in "head" the size
165/// of 'showbreak'/'breakindent' before "csarg->max_head_vcol".
166/// When "csarg->max_head_vcol" is negative, only count in "head" the size
167/// of 'showbreak'/'breakindent' before where cursor should be placed.
168CharSize charsize_regular(CharsizeArg *csarg, char *const cur, colnr_T const vcol,
169                          int32_t const cur_char, int mb_width)
170{
171  csarg->cur_text_width_left = 0;
172  csarg->cur_text_width_right = 0;
173
174  win_T *wp = csarg->win;
175  buf_T *buf = wp->w_buffer;
176  char *line = csarg->line;
177  bool const use_tabstop = cur_char == TAB && csarg->use_tabstop;
178  int mb_added = 0;
179
180  bool has_lcs_eol = wp->w_p_list && wp->w_p_lcs_chars.eol != NUL;
181
182  // First get normal size, without 'linebreak' or inline virtual text
183  int size;
184  int is_doublewidth = false;
185  if (use_tabstop) {
186    size = tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array);
187  } else if (*cur == NUL) {
188    // 1 cell for EOL list char (if present), as opposed to the two cell ^@
189    // for a NUL character in the text.
190    size = has_lcs_eol ? 1 : 0;
191  } else if (cur_char < 0) {
192    size = kInvalidByteCells;
193  } else {
194    size = mb_width;
195    is_doublewidth = size == 2 && cur_char >= 0x80;
196  }
197
198  if (csarg->virt_row >= 0 && !csarg->skip_cur_text) {
199    int tab_size = size;
200    int col = (int)(cur - line);
201    while (true) {
202      MTKey mark = marktree_itr_current(csarg->iter);
203      if (mark.pos.row != csarg->virt_row || mark.pos.col > col) {
204        break;
205      } else if (mark.pos.col == col) {
206        if (!mt_invalid(mark) && ns_in_win(mark.ns, wp)) {
207          DecorInline decor = mt_decor(mark);
208          DecorVirtText *vt = decor.ext ? decor.data.ext.vt : NULL;
209          while (vt) {
210            if (!(vt->flags & kVTIsLines) && vt->pos == kVPosInline) {
211              if (mt_right(mark)) {
212                csarg->cur_text_width_right += vt->width;
213              } else {
214                csarg->cur_text_width_left += vt->width;
215              }
216              size += vt->width;
217              if (use_tabstop) {
218                // tab size changes because of the inserted text
219                size -= tab_size;
220                tab_size = tabstop_padding(vcol + size, buf->b_p_ts, buf->b_p_vts_array);
221                size += tab_size;
222              }
223            }
224            vt = vt->next;
225          }
226        }
227      }
228      marktree_itr_next_filter(wp->w_buffer->b_marktree, csarg->iter, csarg->virt_row + 1, 0,
229                               inline_filter);
230    }
231  }
232
233  if (is_doublewidth && wp->w_p_wrap && in_win_border(wp, vcol + size - 2)) {
234    // Count the ">" in the last column.
235    size++;
236    mb_added = 1;
237  }
238
239  char *const sbr = get_showbreak_value(wp);
240
241  // May have to add something for 'breakindent' and/or 'showbreak'
242  // string at the start of a screen line.
243  int head = mb_added;
244  // When "size" is 0, no new screen line is started.
245  if (size > 0 && wp->w_p_wrap && (*sbr != NUL || wp->w_p_bri)) {
246    int col_off_prev = win_col_off(wp);
247    int width2 = wp->w_view_width - col_off_prev + win_col_off2(wp);
248    colnr_T wcol = vcol + col_off_prev;
249    colnr_T max_head_vcol = csarg->max_head_vcol;
250    int added = 0;
251
252    // cells taken by 'showbreak'/'breakindent' before current char
253    int head_prev = 0;
254    if (wcol >= wp->w_view_width) {
255      wcol -= wp->w_view_width;
256      col_off_prev = wp->w_view_width - width2;
257      if (wcol >= width2 && width2 > 0) {
258        wcol %= width2;
259      }
260      head_prev = csarg->indent_width;
261      if (head_prev == INT_MIN) {
262        head_prev = 0;
263        if (*sbr != NUL) {
264          head_prev += vim_strsize(sbr);
265        }
266        if (wp->w_p_bri) {
267          head_prev += get_breakindent_win(wp, line);
268        }
269        csarg->indent_width = head_prev;
270      }
271      if (wcol < head_prev) {
272        head_prev -= wcol;
273        wcol += head_prev;
274        added += head_prev;
275        if (max_head_vcol <= 0 || vcol < max_head_vcol) {
276          head += head_prev;
277        }
278      } else {
279        head_prev = 0;
280      }
281      wcol += col_off_prev;
282    }
283
284    if (wcol + size > wp->w_view_width) {
285      // cells taken by 'showbreak'/'breakindent' halfway current char
286      int head_mid = csarg->indent_width;
287      if (head_mid == INT_MIN) {
288        head_mid = 0;
289        if (*sbr != NUL) {
290          head_mid += vim_strsize(sbr);
291        }
292        if (wp->w_p_bri) {
293          head_mid += get_breakindent_win(wp, line);
294        }
295        csarg->indent_width = head_mid;
296      }
297      if (head_mid > 0) {
298        // Calculate effective window width.
299        int prev_rem = wp->w_view_width - wcol;
300        int width = width2 - head_mid;
301
302        if (width <= 0) {
303          width = 1;
304        }
305        // Divide "size - prev_rem" by "width", rounding up.
306        int cnt = (size - prev_rem + width - 1) / width;
307        added += cnt * head_mid;
308
309        if (max_head_vcol == 0 || vcol + size + added < max_head_vcol) {
310          head += cnt * head_mid;
311        } else if (width2 > 0 && max_head_vcol > vcol + head_prev + prev_rem) {
312          head += (max_head_vcol - (vcol + head_prev + prev_rem)
313                   + width2 - 1) / width2 * head_mid;
314        } else if (max_head_vcol < 0) {
315          int off = mb_added + virt_text_cursor_off(csarg, *cur == NUL);
316          if (off >= prev_rem) {
317            if (size > off) {
318              head += (1 + (off - prev_rem) / width) * head_mid;
319            } else {
320              head += (off - prev_rem + width - 1) / width * head_mid;
321            }
322          }
323        }
324      }
325    }
326
327    size += added;
328  }
329
330  int size_before_lbr = size;
331  bool need_lbr = false;
332  // If 'linebreak' set check at a blank before a non-blank if the line
333  // needs a break here.
334  if (wp->w_p_lbr && wp->w_p_wrap && wp->w_view_width != 0
335      && vim_isbreak((uint8_t)cur[0]) && !vim_isbreak((uint8_t)cur[1])) {
336    char *t = csarg->line;
337    while (vim_isbreak((uint8_t)t[0])) {
338      t++;
339    }
340    // 'linebreak' is only needed when not in leading whitespace.
341    need_lbr = cur >= t;
342  }
343  if (need_lbr) {
344    char *s = cur;
345    // Count all characters from first non-blank after a blank up to next
346    // non-blank after a blank.
347    int numberextra = win_col_off(wp);
348    colnr_T col_adj = size - 1;
349    colnr_T colmax = (colnr_T)(wp->w_view_width - numberextra - col_adj);
350    if (vcol >= colmax) {
351      colmax += col_adj;
352      int n = colmax + win_col_off2(wp);
353      if (n > 0) {
354        colmax += (((vcol + col_adj - colmax) / n) + 1) * n - col_adj;
355      }
356    }
357
358    // Inline virtual text widens the word, so count it like the loop above does for one
359    // character. Needs its own iterator, since this looks ahead of "csarg->iter".
360    MarkTreeIter virt_iter[1];
361    int has_virt = csarg->virt_row < 0 ? 0 : -1;  // -1: not sought yet
362
363    colnr_T vcol2 = vcol;
364    while (true) {
365      char *ps = s;
366      MB_PTR_ADV(s);
367      int c = (uint8_t)(*s);
368      if (!(c != NUL
369            && (vim_isbreak(c) || vcol2 == vcol || !vim_isbreak((uint8_t)(*ps))))) {
370        break;
371      }
372
373      int const col = (int)(s - line);
374      if (has_virt < 0) {
375        has_virt = marktree_itr_get_filter(buf->b_marktree, csarg->virt_row, col,
376                                           csarg->virt_row + 1, 0, inline_filter, virt_iter);
377      }
378      int const virt_width = has_virt
379                             ? inline_virt_text_width(wp, virt_iter, csarg->virt_row, col) : 0;
380      vcol2 += virt_width;
381      vcol2 += win_chartabsize(wp, s, vcol2);
382      if (vcol2 >= colmax) {  // doesn't fit
383        size = colmax - vcol + col_adj;
384        break;
385      }
386    }
387  }
388
389  int tail = size - size_before_lbr;
390
391  return (CharSize){ .width = size, .head = head, .tail = tail };
392}
393
394/// Like charsize_regular(), except it doesn't handle inline virtual text,
395/// 'linebreak', 'breakindent' or 'showbreak'.
396/// Handles normal characters, tabs and wrapping.
397/// This function is always inlined.
398///
399/// @see charsize_regular
400/// @see charsize_fast
401static inline CharSize charsize_fast_impl(win_T *const wp, const char *cur, bool use_tabstop,
402                                          colnr_T const vcol, int32_t const cur_char, int mb_width)
403  FUNC_ATTR_PURE FUNC_ATTR_ALWAYS_INLINE
404{
405  // A tab gets expanded, depending on the current column
406  if (cur_char == TAB && use_tabstop) {
407    return (CharSize){
408      .width = tabstop_padding(vcol, wp->w_buffer->b_p_ts,
409                               wp->w_buffer->b_p_vts_array)
410    };
411  } else {
412    int width;
413    if (cur_char < 0) {
414      width = kInvalidByteCells;
415    } else {
416      // TODO(bfredl): perf: often cur_char is enough at this point to determine width.
417      // we likely want a specialized version of utf_ptr2StrCharInfo also determining
418      // the ptr2cells width at the same time without any extra decoding. (also applies
419      // to charsize_regular and charsize_nowrap)
420      width = mb_width;
421    }
422
423    // If a double-width char doesn't fit at the end of a line, it wraps to the next line,
424    // and the last column displays a '>'.
425    if (width == 2 && cur_char >= 0x80 && wp->w_p_wrap && in_win_border(wp, vcol)) {
426      return (CharSize){ .width = 3, .head = 1 };
427    } else {
428      return (CharSize){ .width = width };
429    }
430  }
431}
432
433/// Like charsize_regular(), except it doesn't handle inline virtual text,
434/// 'linebreak', 'breakindent' or 'showbreak'.
435/// Handles normal characters, tabs and wrapping.
436/// Can be used if CSType is kCharsizeFast.
437///
438/// @see charsize_regular
439CharSize charsize_fast(CharsizeArg *csarg, const char *cur, colnr_T vcol, int32_t cur_char,
440                       int mb_width)
441  FUNC_ATTR_PURE
442{
443  return charsize_fast_impl(csarg->win, cur, csarg->use_tabstop, vcol, cur_char, mb_width);
444}
445
446/// Get the number of cells taken up on the screen at given virtual column.
447///
448/// @see win_chartabsize()
449int charsize_nowrap(buf_T *buf, const char *cur, bool use_tabstop, colnr_T vcol, int32_t cur_char,
450                    int mb_width)
451{
452  if (cur_char == TAB && use_tabstop) {
453    return tabstop_padding(vcol, buf->b_p_ts, buf->b_p_vts_array);
454  } else if (cur_char < 0) {
455    return kInvalidByteCells;
456  } else {
457    return mb_width;
458  }
459}
460
461/// Check that virtual column "vcol" is in the rightmost column of window "wp".
462///
463/// @param  wp    window
464/// @param  vcol  column number
465static bool in_win_border(win_T *wp, colnr_T vcol)
466  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
467{
468  if (wp->w_view_width == 0) {
469    // there is no border
470    return false;
471  }
472  int width1 = wp->w_view_width - win_col_off(wp);  // width of first line (after line number)
473
474  if ((int)vcol < width1 - 1) {
475    return false;
476  }
477
478  if ((int)vcol == width1 - 1) {
479    return true;
480  }
481  int width2 = width1 + win_col_off2(wp);  // width of further lines
482
483  if (width2 <= 0) {
484    return false;
485  }
486  return (vcol - width1) % width2 == width2 - 1;
487}
488
489/// Calculate virtual column until the given "len".
490///
491/// @param csarg    Argument to charsize functions.
492/// @param vcol_arg Starting virtual column.
493/// @param len      First byte of the end character, or MAXCOL.
494///
495/// @return virtual column before the character at "len",
496///         or full size of the line if "len" is MAXCOL.
497int linesize_regular(CharsizeArg *const csarg, int vcol_arg, colnr_T const len)
498{
499  char *const line = csarg->line;
500  int64_t vcol = vcol_arg;
501
502  StrCharInfo ci = utf_ptr2StrCharInfo(line);
503  while (ci.ptr - line < len && *ci.ptr != NUL) {
504    ClusterInfo cli = utf_ClusterInfo(ci);
505    vcol += charsize_regular(csarg, ci.ptr, vcol_arg, ci.chr.value, cli.cells).width;
506    ci = cli.next;
507    if (vcol > MAXCOL) {
508      vcol_arg = MAXCOL;
509      break;
510    } else {
511      vcol_arg = (int)vcol;
512    }
513  }
514
515  // Check for inline virtual text after the end of the line.
516  if (len == MAXCOL && csarg->virt_row >= 0 && *ci.ptr == NUL) {
517    int head = charsize_regular(csarg, ci.ptr, vcol_arg, ci.chr.value, 0).head;
518    vcol += csarg->cur_text_width_left + csarg->cur_text_width_right + head;
519    vcol_arg = vcol > MAXCOL ? MAXCOL : (int)vcol;
520  }
521
522  return vcol_arg;
523}
524
525/// Like linesize_regular(), but can be used when CSType is kCharsizeFast.
526///
527/// @see linesize_regular
528int linesize_fast(CharsizeArg const *const csarg, int vcol_arg, colnr_T const len)
529{
530  win_T *const wp = csarg->win;
531  bool const use_tabstop = csarg->use_tabstop;
532
533  char *const line = csarg->line;
534  int64_t vcol = vcol_arg;
535
536  StrCharInfo ci = utf_ptr2StrCharInfo(line);
537  while (ci.ptr - line < len && *ci.ptr != NUL) {
538    ClusterInfo cli = utf_ClusterInfo(ci);
539    vcol += charsize_fast_impl(wp, ci.ptr, use_tabstop, vcol_arg, ci.chr.value, cli.cells).width;
540    ci = cli.next;
541    if (vcol > MAXCOL) {
542      vcol_arg = MAXCOL;
543      break;
544    } else {
545      vcol_arg = (int)vcol;
546    }
547  }
548
549  return vcol_arg;
550}
551
552/// Get how many virtual columns inline virtual text should offset the cursor.
553///
554/// @param csarg   should contain information stored by charsize_regular()
555///                about widths of left and right gravity virtual text
556/// @param on_NUL  whether this is the end of the line
557static int virt_text_cursor_off(const CharsizeArg *csarg, bool on_NUL)
558{
559  int off = 0;
560  if (!on_NUL || !(State & MODE_NORMAL)) {
561    off += csarg->cur_text_width_left;
562  }
563  if (!on_NUL && (State & MODE_NORMAL)) {
564    off += csarg->cur_text_width_right;
565  }
566  return off;
567}
568
569/// Get virtual column number of pos.
570///  start: on the first position of this character (TAB, ctrl)
571/// cursor: where the cursor is on this character (first char, except for TAB)
572///    end: on the last position of this character (TAB, ctrl)
573///
574/// When 'linebreak' follows this character, "end" is set to the position before
575/// 'linebreak' if "flags" contains GETVCOL_END_EXCL_LBR, otherwise it's set to
576/// the end of 'linebreak'.
577///
578/// This is used very often, keep it fast!
579///
580/// @param wp
581/// @param pos
582/// @param start
583/// @param cursor
584/// @param end
585/// @param flags
586void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end, int flags)
587{
588  char *const line = ml_get_buf(wp->w_buffer, pos->lnum);  // start of the line
589  colnr_T const end_col = pos->col;
590
591  CharsizeArg csarg;
592  bool on_NUL = false;
593  CSType const cstype = init_charsize_arg(&csarg, wp, pos->lnum, line);
594  csarg.max_head_vcol = -1;
595
596  colnr_T vcol = 0;
597  CharSize char_size;
598  StrCharInfo ci = utf_ptr2StrCharInfo(line);
599  if (cstype == kCharsizeFast) {
600    bool const use_tabstop = csarg.use_tabstop;
601    while (true) {
602      if (*ci.ptr == NUL) {
603        // if cursor is at NUL, it is treated like 1 cell char
604        char_size = (CharSize){ .width = 1 };
605        break;
606      }
607      ClusterInfo cli = utf_ClusterInfo(ci);
608      char_size = charsize_fast_impl(wp, ci.ptr, use_tabstop, vcol, ci.chr.value, cli.cells);
609      StrCharInfo const next = cli.next;
610      if (next.ptr - line > end_col) {
611        break;
612      }
613      ci = next;
614      vcol += char_size.width;
615    }
616  } else {
617    while (true) {
618      ClusterInfo cli = utf_ClusterInfo(ci);
619      char_size = charsize_regular(&csarg, ci.ptr, vcol, ci.chr.value, cli.cells);
620      // make sure we don't go past the end of the line
621      if (*ci.ptr == NUL) {
622        // NUL at end of line only takes one column unless there is virtual text
623        char_size.width = 1 + csarg.cur_text_width_left + csarg.cur_text_width_right;
624        on_NUL = true;
625        break;
626      }
627      StrCharInfo const next = cli.next;
628      if (next.ptr - line > end_col) {
629        break;
630      }
631      ci = next;
632      vcol += char_size.width;
633    }
634  }
635
636  if (*ci.ptr == NUL && end_col < MAXCOL && end_col > ci.ptr - line) {
637    pos->col = (colnr_T)(ci.ptr - line);
638  }
639
640  int incr = char_size.width;
641  int head = char_size.head;
642  int tail = char_size.tail;
643
644  if (start != NULL) {
645    *start = vcol + head;
646  }
647  if (end != NULL) {
648    *end = vcol + incr - (flags & GETVCOL_END_EXCL_LBR ? tail : 0) - 1;
649  }
650  if (cursor != NULL) {
651    if (ci.chr.value == TAB
652        && (State & MODE_NORMAL)
653        && !wp->w_p_list
654        && !virtual_active(wp)
655        && !(Visual.active && ((*p_sel == 'e') || ltoreq(*pos, Visual.start)))) {
656      // TODO(zeertzjq): subtracting "tail" may lead to better cursor position
657      *cursor = vcol + incr - 1;  // cursor at end
658    } else {
659      vcol += virt_text_cursor_off(&csarg, on_NUL);
660      *cursor = vcol + head;  // cursor at start
661    }
662  }
663}
664
665/// Get virtual cursor column in the current window, pretending 'list' is off.
666///
667/// @param posp
668///
669/// @return The virtual cursor column.
670colnr_T getvcol_nolist(pos_T *posp)
671{
672  int list_save = curwin->w_p_list;
673  colnr_T vcol;
674
675  curwin->w_p_list = false;
676  if (posp->coladd) {
677    getvvcol(curwin, posp, NULL, &vcol, NULL, 0);
678  } else {
679    getvcol(curwin, posp, NULL, &vcol, NULL, 0);
680  }
681  curwin->w_p_list = list_save;
682  return vcol;
683}
684
685/// Get virtual column in virtual mode.
686///
687/// @param wp
688/// @param pos
689/// @param start
690/// @param cursor
691/// @param end
692/// @param flags
693void getvvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end, int flags)
694{
695  colnr_T col;
696
697  if (virtual_active(wp)) {
698    // For virtual mode, only want one value
699    getvcol(wp, pos, &col, NULL, NULL, flags);
700
701    colnr_T coladd = pos->coladd;
702    colnr_T endadd = 0;
703
704    // Cannot put the cursor on part of a wide character.
705    char *ptr = ml_get_buf(wp->w_buffer, pos->lnum);
706
707    if (pos->col < ml_get_buf_len(wp->w_buffer, pos->lnum)) {
708      int c = utf_ptr2char(ptr + pos->col);
709      if ((c != TAB) && vim_isprintc(c)) {
710        endadd = (colnr_T)(ptr2cells(ptr + pos->col) - 1);
711        if (coladd > endadd) {
712          endadd = 0;  // past end of line
713        } else {
714          coladd = 0;
715        }
716      }
717    }
718    col += coladd;
719
720    if (start != NULL) {
721      *start = col;
722    }
723    if (cursor != NULL) {
724      *cursor = col;
725    }
726    if (end != NULL) {
727      *end = col + endadd;
728    }
729  } else {
730    getvcol(wp, pos, start, cursor, end, flags);
731  }
732}
733
734/// Get the leftmost and rightmost virtual column of pos1 and pos2.
735/// Used for Visual block mode.
736///
737/// @param wp
738/// @param pos1
739/// @param pos2
740/// @param left
741/// @param right
742/// @param flags
743void getvcols(win_T *wp, pos_T *pos1, pos_T *pos2, colnr_T *left, colnr_T *right, int flags)
744{
745  colnr_T from1;
746  colnr_T from2;
747  colnr_T to1;
748  colnr_T to2;
749
750  if (lt(*pos1, *pos2)) {
751    getvvcol(wp, pos1, &from1, NULL, &to1, flags);
752    getvvcol(wp, pos2, &from2, NULL, &to2, flags);
753  } else {
754    getvvcol(wp, pos2, &from1, NULL, &to1, flags);
755    getvvcol(wp, pos1, &from2, NULL, &to2, flags);
756  }
757
758  if (from2 < from1) {
759    *left = from2;
760  } else {
761    *left = from1;
762  }
763
764  if (to2 > to1) {
765    if ((*p_sel == 'e') && (from2 - 1 >= to1)) {
766      *right = from2 - 1;
767    } else {
768      *right = to2;
769    }
770  } else {
771    *right = to1;
772  }
773}
774
775/// Functions calculating vertical size of text when displayed inside a window.
776/// Calls horizontal size functions defined above.
777
778/// Check if there may be filler lines anywhere in window "wp".
779bool win_may_fill(win_T *wp)
780{
781  return ((wp->w_p_diff && diffopt_filler())
782          || buf_meta_total(wp->w_buffer, kMTMetaLines));
783}
784
785/// Return the number of filler lines above "lnum".
786///
787/// @param wp
788/// @param lnum
789///
790/// @return Number of filler lines above lnum
791int win_get_fill(win_T *wp, linenr_T lnum)
792{
793  return decor_virt_lines(wp, lnum - 1, lnum, NULL, NULL, true) + diff_check_fill(wp, lnum);
794}
795
796/// Return the number of window lines occupied by buffer line "lnum".
797/// Includes any filler lines.
798///
799/// @param limit_winheight  when true limit to window height
800int plines_win(win_T *wp, linenr_T lnum, bool limit_winheight)
801{
802  // Check for filler lines above this buffer line.
803  return plines_win_nofill(wp, lnum, limit_winheight) + win_get_fill(wp, lnum);
804}
805
806/// Return the number of window lines occupied by buffer line "lnum".
807/// Does not include filler lines.
808///
809/// @param limit_winheight  when true limit to window height
810int plines_win_nofill(win_T *wp, linenr_T lnum, bool limit_winheight)
811{
812  if (decor_conceal_line(wp, lnum - 1, false)) {
813    return 0;
814  }
815
816  if (!wp->w_p_wrap) {
817    return 1;
818  }
819
820  if (wp->w_view_width == 0) {
821    return 1;
822  }
823
824  // Folded lines are handled just like an empty line.
825  if (lineFolded(wp, lnum)) {
826    return 1;
827  }
828
829  const int lines = plines_win_nofold(wp, lnum);
830  if (limit_winheight && lines > wp->w_view_height) {
831    return wp->w_view_height;
832  }
833  return lines;
834}
835
836/// Get number of window lines physical line "lnum" will occupy in window "wp".
837/// Does not care about folding, 'wrap' or filler lines.
838int plines_win_nofold(win_T *wp, linenr_T lnum)
839{
840  char *s = ml_get_buf(wp->w_buffer, lnum);
841  CharsizeArg csarg;
842  CSType const cstype = init_charsize_arg(&csarg, wp, lnum, s);
843  if (*s == NUL && csarg.virt_row < 0) {
844    return 1;  // be quick for an empty line
845  }
846
847  int64_t col;
848  if (cstype == kCharsizeFast) {
849    col = linesize_fast(&csarg, 0, MAXCOL);
850  } else {
851    col = linesize_regular(&csarg, 0, MAXCOL);
852  }
853
854  // If list mode is on, then the '$' at the end of the line may take up one
855  // extra column.
856  if (wp->w_p_list && wp->w_p_lcs_chars.eol != NUL) {
857    col += 1;
858  }
859
860  // Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
861  int width = wp->w_view_width - win_col_off(wp);
862  if (width <= 0) {
863    return 32000;  // bigger than the number of screen lines
864  }
865  if (col <= width) {
866    return 1;
867  }
868  col -= width;
869  width += win_col_off2(wp);
870  const int64_t lines = (col + (width - 1)) / width + 1;
871  return (lines > 0 && lines <= INT_MAX) ? (int)lines : INT_MAX;
872}
873
874/// Like plines_win(), but only reports the number of physical screen lines
875/// used from the start of the line to the given byte column.
876int plines_win_col(win_T *wp, linenr_T lnum, long column)
877{
878  // Check for filler lines above this buffer line.
879  int lines = win_get_fill(wp, lnum);
880
881  if (!wp->w_p_wrap) {
882    return lines + 1;
883  }
884
885  if (wp->w_view_width == 0) {
886    return lines + 1;
887  }
888
889  char *line = ml_get_buf(wp->w_buffer, lnum);
890
891  CharsizeArg csarg;
892  CSType const cstype = init_charsize_arg(&csarg, wp, lnum, line);
893
894  colnr_T vcol = 0;
895  StrCharInfo ci = utf_ptr2StrCharInfo(line);
896  if (cstype == kCharsizeFast) {
897    bool const use_tabstop = csarg.use_tabstop;
898    while (*ci.ptr != NUL && ci.ptr < line + column) {
899      ClusterInfo cli = utf_ClusterInfo(ci);
900      vcol += charsize_fast_impl(wp, ci.ptr, use_tabstop, vcol, ci.chr.value, cli.cells).width;
901      ci = cli.next;
902    }
903  } else {
904    while (*ci.ptr != NUL && ci.ptr < line + column) {
905      ClusterInfo cli = utf_ClusterInfo(ci);
906      vcol += charsize_regular(&csarg, ci.ptr, vcol, ci.chr.value, cli.cells).width;
907      ci = cli.next;
908    }
909  }
910
911  // If current char is a TAB, and the TAB is not displayed as ^I, and we're not
912  // in MODE_INSERT state, then col must be adjusted so that it represents the
913  // last screen position of the TAB.  This only fixes an error when the TAB
914  // wraps from one screen line to the next (when 'columns' is not a multiple
915  // of 'ts') -- webb.
916  colnr_T col = vcol;
917  if (ci.chr.value == TAB && (State & MODE_NORMAL) && csarg.use_tabstop) {
918    col += win_charsize(cstype, col, ci.ptr, ci.chr.value, &csarg, 1).width - 1;
919  }
920
921  // Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
922  int width = wp->w_view_width - win_col_off(wp);
923  if (width <= 0) {
924    return 9999;
925  }
926
927  lines += 1;
928  if (col > width) {
929    lines += (col - width) / (width + win_col_off2(wp)) + 1;
930  }
931  return lines;
932}
933
934/// Get the number of screen lines buffer line "lnum" will take in window "wp".
935/// This takes care of both folds and topfill.
936///
937/// XXX: Because of topfill, this only makes sense when lnum >= wp->w_topline.
938///
939/// @param[in]  wp               window the line is in
940/// @param[in]  lnum             line number
941/// @param[out] nextp            if not NULL, the last line of a fold
942/// @param[out] foldedp          if not NULL, whether lnum is on a fold
943/// @param[in]  cache            whether to use the window's cache for folds
944/// @param[in]  limit_winheight  when true limit to window height
945///
946/// @return the total number of screen lines
947int plines_win_full(win_T *wp, linenr_T lnum, linenr_T *const nextp, bool *const foldedp,
948                    const bool cache, const bool limit_winheight)
949{
950  bool folded = hasFoldingWin(wp, lnum, &lnum, nextp, cache, NULL);
951  if (foldedp != NULL) {
952    *foldedp = folded;
953  }
954
955  int filler_lines = lnum == wp->w_topline ? wp->w_topfill : win_get_fill(wp, lnum);
956
957  if (decor_conceal_line(wp, lnum - 1, false)) {
958    return filler_lines;
959  }
960
961  return (folded ? 1 : plines_win_nofill(wp, lnum, limit_winheight)) + filler_lines;
962}
963
964/// Return number of window lines a physical line range will occupy in window "wp".
965/// Takes into account folding, 'wrap', topfill and filler lines beyond the end of the buffer.
966///
967/// XXX: Because of topfill, this only makes sense when first >= wp->w_topline.
968///
969/// @param first  first line number
970/// @param last   last line number
971/// @param max    number of lines to limit the height to
972///
973/// @see win_text_height
974int plines_m_win(win_T *wp, linenr_T first, linenr_T last, int max)
975{
976  int count = 0;
977
978  while (first <= last && count < max) {
979    linenr_T next = first;
980    count += plines_win_full(wp, first, &next, NULL, false, false);
981    first = next + 1;
982  }
983  if (first == wp->w_buffer->b_ml.ml_line_count + 1) {
984    count += win_get_fill(wp, first);
985  }
986  return MIN(max, count);
987}
988
989/// Return total number of physical and filler lines in a physical line range.
990/// Doesn't treat a fold as a single line or consider a wrapped line multiple lines,
991/// unlike plines_m_win() or win_text_height().
992///
993/// Mainly used for calculating scrolling offsets.
994int plines_m_win_fill(win_T *wp, linenr_T first, linenr_T last)
995{
996  int count = last - first + 1 + decor_virt_lines(wp, first - 1, last, NULL, NULL, false);
997
998  if (diffopt_filler()) {
999    for (int lnum = first; lnum <= last; lnum++) {
1000      // Note: this also considers folds (no filler lines inside folds).
1001      int n = diff_check_fill(wp, lnum);
1002      count += MAX(n, 0);
1003    }
1004  }
1005
1006  return MAX(count, 0);
1007}
1008
1009/// Get the number of screen lines a range of text will take in window "wp".
1010///
1011/// @param[in] start_lnum    Starting line number, 1-based inclusive.
1012/// @param[in] start_vcol    >= 0: Starting virtual column index on "start_lnum",
1013///                                0-based inclusive, rounded down to full screen lines.
1014///                          < 0:  Count a full "start_lnum", including filler lines above.
1015/// @param[in,out] end_lnum  Ending line number, 1-based inclusive. Set to last line for
1016///                          which the height is calculated (smaller if "max" is reached).
1017/// @param[in,out] end_vcol  >= 0: Ending virtual column index on "end_lnum",
1018///                                0-based exclusive, rounded up to full screen lines.
1019///                          < 0:  Count a full "end_lnum", not including filler lines below.
1020///                          Set to the number of columns in "end_lnum" to reach "max".
1021/// @param[in] max           Don't calculate the height for lines beyond the line where "max"
1022///                          height is reached.
1023/// @param[out] fill         If not NULL, set to the number of filler lines in the range.
1024int64_t win_text_height(win_T *const wp, const linenr_T start_lnum, const int64_t start_vcol,
1025                        linenr_T *const end_lnum, int64_t *const end_vcol, int64_t *const fill,
1026                        int64_t const max)
1027{
1028  int width1 = wp->w_view_width - win_col_off(wp);
1029  int width2 = width1 + win_col_off2(wp);
1030  width1 = MAX(width1, 0);
1031  width2 = MAX(width2, 0);
1032  int64_t height_sum_fill = 0;
1033  int64_t height_cur_nofill = 0;
1034  int64_t height_sum_nofill = 0;
1035  linenr_T lnum = start_lnum;
1036  linenr_T cur_lnum = lnum;
1037  bool cur_folded = false;
1038
1039  if (start_vcol >= 0) {
1040    linenr_T lnum_next = lnum;
1041    cur_folded = hasFolding(wp, lnum, &lnum, &lnum_next);
1042    height_cur_nofill = plines_win_nofill(wp, lnum, false);
1043    height_sum_nofill += height_cur_nofill;
1044    const int64_t row_off = (start_vcol < width1 || width2 <= 0)
1045                            ? 0
1046                            : 1 + (start_vcol - width1) / width2;
1047    height_sum_nofill -= MIN(row_off, height_cur_nofill);
1048    lnum = lnum_next + 1;
1049  }
1050
1051  while (lnum <= *end_lnum && height_sum_nofill + height_sum_fill < max) {
1052    linenr_T lnum_next = lnum;
1053    cur_folded = hasFolding(wp, lnum, &lnum, &lnum_next);
1054    height_sum_fill += win_get_fill(wp, lnum);
1055    height_cur_nofill = plines_win_nofill(wp, lnum, false);
1056    height_sum_nofill += height_cur_nofill;
1057    cur_lnum = lnum;
1058    lnum = lnum_next + 1;
1059  }
1060
1061  int64_t vcol_end = *end_vcol;
1062  bool use_vcol = vcol_end >= 0 && lnum > *end_lnum;
1063  if (use_vcol) {
1064    height_sum_nofill -= height_cur_nofill;
1065    const int64_t row_off = vcol_end == 0
1066                            ? 0
1067                            : (vcol_end <= width1 || width2 <= 0)
1068                            ? 1
1069                            : 1 + (vcol_end - width1 + width2 - 1) / width2;
1070    height_sum_nofill += MIN(row_off, height_cur_nofill);
1071  }
1072
1073  if (cur_folded) {
1074    vcol_end = 0;
1075  } else {
1076    int linesize = linetabsize_eol(wp, cur_lnum);
1077    vcol_end = MIN(use_vcol ? vcol_end : INT64_MAX, linesize);
1078  }
1079
1080  int64_t overflow = height_sum_nofill + height_sum_fill - max;
1081  if (overflow > 0 && width2 > 0 && vcol_end > width2) {
1082    vcol_end -= (vcol_end - width1) % width2 + (overflow - 1) * width2;
1083  }
1084
1085  *end_lnum = cur_lnum;
1086  *end_vcol = vcol_end;
1087  if (fill != NULL) {
1088    *fill = height_sum_fill;
1089  }
1090  return height_sum_fill + height_sum_nofill;
1091}
1092
1093/// Return the maximum display width of lines "first" through "last".
1094///
1095/// @param max  stop measuring once this width is reached
1096///
1097/// @return  maximum display width, capped at "max"
1098int win_max_displaywidth(win_T *wp, linenr_T first, linenr_T last, int max)
1099{
1100  int width = 0;
1101  for (linenr_T lnum = first; lnum <= last && width < max; lnum++) {
1102    width = MAX(width, linetabsize(wp, lnum));
1103  }
1104  return MIN(max, width);
1105}