robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
55.9 KiB1904 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "nvim/ascii_defs.h"
8#include "nvim/assert_defs.h"
9#include "nvim/buffer.h"
10#include "nvim/buffer_defs.h"
11#include "nvim/change.h"
12#include "nvim/charset.h"
13#include "nvim/cursor.h"
14#include "nvim/drawscreen.h"
15#include "nvim/errors.h"
16#include "nvim/eval.h"
17#include "nvim/eval/typval.h"
18#include "nvim/eval/typval_defs.h"
19#include "nvim/eval/vars.h"
20#include "nvim/ex_cmds_defs.h"
21#include "nvim/ex_docmd.h"
22#include "nvim/extmark.h"
23#include "nvim/extmark_defs.h"
24#include "nvim/gettext_defs.h"
25#include "nvim/globals.h"
26#include "nvim/indent.h"
27#include "nvim/indent_c.h"
28#include "nvim/insert.h"
29#include "nvim/mark_defs.h"
30#include "nvim/mbyte.h"
31#include "nvim/mbyte_defs.h"
32#include "nvim/memline.h"
33#include "nvim/memory.h"
34#include "nvim/message.h"
35#include "nvim/move.h"
36#include "nvim/ops.h"
37#include "nvim/option.h"
38#include "nvim/option_defs.h"
39#include "nvim/option_vars.h"
40#include "nvim/optionstr.h"
41#include "nvim/os/input.h"
42#include "nvim/plines.h"
43#include "nvim/pos_defs.h"
44#include "nvim/regexp.h"
45#include "nvim/regexp_defs.h"
46#include "nvim/search.h"
47#include "nvim/state_defs.h"
48#include "nvim/strings.h"
49#include "nvim/textformat.h"
50#include "nvim/types_defs.h"
51#include "nvim/undo.h"
52#include "nvim/vim_defs.h"
53
54#include "indent.c.generated.h"
55
56#include "options_keysets.generated.h"
57
58/// Set the integer values corresponding to the string setting of 'vartabstop'.
59/// "array" will be set, caller must free it if needed.
60///
61/// @return  false for an error.
62bool tabstop_set(char *var, colnr_T **array)
63{
64  int valcount = 1;
65
66  if (var[0] == NUL || (var[0] == '0' && var[1] == NUL)) {
67    *array = NULL;
68    return true;
69  }
70
71  for (char *cp = var; *cp != NUL; cp++) {
72    if (cp == var || cp[-1] == ',') {
73      char *end = cp;
74
75      // Use def=1 so that overflow/too-large values pass this check and are
76      // instead rejected by the "n > TABSTOP_MAX" check in the loop below.
77      if (getdigits(&end, false, 1) <= 0) {
78        if (cp != end) {
79          emsg(_(e_positive));
80        } else {
81          semsg(_(e_invarg2), cp);
82        }
83        return false;
84      }
85    }
86
87    if (ascii_isdigit(*cp)) {
88      continue;
89    }
90    if (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL) {
91      valcount++;
92      continue;
93    }
94    semsg(_(e_invarg2), var);
95    return false;
96  }
97
98  *array = (colnr_T *)xmalloc((unsigned)(valcount + 1) * sizeof(int));
99  (*array)[0] = (colnr_T)valcount;
100
101  int t = 1;
102  for (char *cp = var; *cp != NUL;) {
103    int n = atoi(cp);
104
105    // Catch negative values, overflow and ridiculous big values.
106    if (n <= 0 || n > TABSTOP_MAX) {
107      semsg(_(e_invarg2), cp);
108      XFREE_CLEAR(*array);
109      return false;
110    }
111    (*array)[t++] = n;
112    while (*cp != NUL && *cp != ',') {
113      cp++;
114    }
115    if (*cp != NUL) {
116      cp++;
117    }
118  }
119
120  return true;
121}
122
123/// Calculate the number of screen spaces a tab will occupy.
124/// If "vts" is set then the tab widths are taken from that array,
125/// otherwise the value of ts is used.
126int tabstop_padding(colnr_T col, OptInt ts_arg, const colnr_T *vts)
127  FUNC_ATTR_PURE
128{
129  OptInt ts = ts_arg == 0 ? 8 : ts_arg;
130  colnr_T tabcol = 0;
131  int t;
132  int padding = 0;
133
134  if (vts == NULL || vts[0] == 0) {
135    return (int)(ts - (col % ts));
136  }
137
138  const int tabcount = vts[0];
139
140  for (t = 1; t <= tabcount; t++) {
141    tabcol += vts[t];
142    if (tabcol > col) {
143      padding = tabcol - col;
144      break;
145    }
146  }
147  if (t > tabcount) {
148    padding = vts[tabcount] - ((col - tabcol) % vts[tabcount]);
149  }
150
151  return padding;
152}
153
154/// Find the size of the tab that covers a particular column.
155///
156/// If this is being called as part of a shift operation, col is not the cursor
157/// column but is the column number to the left of the first non-whitespace
158/// character in the line.  If the shift is to the left (left == true), then
159/// return the size of the tab interval to the left of the column.
160int tabstop_at(colnr_T col, OptInt ts, const colnr_T *vts, bool left)
161{
162  if (vts == NULL || vts[0] == 0) {
163    return (int)ts;
164  }
165
166  colnr_T tabcol = 0;  // Column of the tab stop under consideration.
167  int t;  // Tabstop index in the list of variable tab stops.
168  int tab_size = 0;  // Size of the tab stop interval to the right or left of the col.
169  const int tabcount  // Number of tab stops in the list of variable tab stops.
170    = vts[0];
171  for (t = 1; t <= tabcount; t++) {
172    tabcol += vts[t];
173    if (tabcol > col) {
174      // If shifting left (left == true), and if the column to the left of
175      // the first first non-blank character (col) in the line is
176      // already to the left of the first tabstop, set the shift amount
177      // (tab_size) to just enough to shift the line to the left margin.
178      // The value doesn't seem to matter as long as it is at least that
179      // distance.
180      if (left && (t == 1)) {
181        tab_size = col;
182      } else {
183        tab_size = vts[t - (left ? 1 : 0)];
184      }
185      break;
186    }
187  }
188  if (t > tabcount) {  // If the value of the index t is beyond the
189                       // end of the list, use the tab stop value at
190                       // the end of the list.
191    tab_size = vts[tabcount];
192  }
193
194  return tab_size;
195}
196
197/// Find the column on which a tab starts.
198colnr_T tabstop_start(colnr_T col, int ts, colnr_T *vts)
199{
200  colnr_T tabcol = 0;
201
202  if (vts == NULL || vts[0] == 0) {
203    return col - col % ts;
204  }
205
206  const int tabcount = vts[0];
207  for (int t = 1; t <= tabcount; t++) {
208    tabcol += vts[t];
209    if (tabcol > col) {
210      return (tabcol - vts[t]);
211    }
212  }
213
214  const int excess = (tabcol % vts[tabcount]);
215  return col - (col - excess) % vts[tabcount];
216}
217
218/// Find the number of tabs and spaces necessary to get from one column
219/// to another.
220void tabstop_fromto(colnr_T start_col, colnr_T end_col, int ts_arg, const colnr_T *vts, int *ntabs,
221                    int *nspcs)
222{
223  int spaces = end_col - start_col;
224  colnr_T tabcol = 0;
225  int padding = 0;
226  int t;
227  int ts = ts_arg == 0 ? (int)curbuf->b_p_ts : ts_arg;
228  assert(ts != 0);  // suppress clang "Division by zero"
229
230  if (vts == NULL || vts[0] == 0) {
231    int tabs = 0;
232
233    const int initspc = (ts - (start_col % ts));
234    if (spaces >= initspc) {
235      spaces -= initspc;
236      tabs++;
237    }
238    tabs += (spaces / ts);
239    spaces -= ((spaces / ts) * ts);
240
241    *ntabs = tabs;
242    *nspcs = spaces;
243    return;
244  }
245
246  // Find the padding needed to reach the next tabstop.
247  const int tabcount = vts[0];
248  for (t = 1; t <= tabcount; t++) {
249    tabcol += vts[t];
250    if (tabcol > start_col) {
251      padding = tabcol - start_col;
252      break;
253    }
254  }
255  if (t > tabcount) {
256    padding = vts[tabcount] - ((start_col - tabcol) % vts[tabcount]);
257  }
258
259  // If the space needed is less than the padding no tabs can be used.
260  if (spaces < padding) {
261    *ntabs = 0;
262    *nspcs = spaces;
263    return;
264  }
265
266  *ntabs = 1;
267  spaces -= padding;
268
269  // At least one tab has been used. See if any more will fit.
270  while (spaces != 0 && ++t <= tabcount) {
271    padding = vts[t];
272    if (spaces < padding) {
273      *nspcs = spaces;
274      return;
275    }
276    *ntabs += 1;
277    spaces -= padding;
278  }
279
280  *ntabs += spaces / (int)vts[tabcount];
281  *nspcs = spaces % (int)vts[tabcount];
282}
283
284/// Copy a tabstop array, allocating space for the new array.
285int *tabstop_copy(const int *oldts)
286{
287  if (oldts == 0) {
288    return 0;
289  }
290
291  int *newts = xmalloc((unsigned)(oldts[0] + 1) * sizeof(int));
292  for (int t = 0; t <= oldts[0]; t++) {
293    newts[t] = oldts[t];
294  }
295
296  return newts;
297}
298
299/// Return a count of the number of tabstops.
300int tabstop_count(colnr_T *ts)
301{
302  return ts != NULL ? (int)ts[0] : 0;
303}
304
305/// Return the first tabstop, or 8 if there are no tabstops defined.
306int tabstop_first(colnr_T *ts)
307{
308  return ts != NULL ? (int)ts[1] : 8;
309}
310
311/// Return the effective shiftwidth value for current buffer, using the
312/// 'tabstop' value when 'shiftwidth' is zero.
313int get_sw_value(buf_T *buf)
314{
315  int result = get_sw_value_col(buf, 0, false);
316  return result;
317}
318
319/// Idem, using "pos".
320static int get_sw_value_pos(buf_T *buf, pos_T *pos, bool left)
321{
322  pos_T save_cursor = curwin->w_cursor;
323
324  curwin->w_cursor = *pos;
325  int sw_value = get_sw_value_col(buf, get_nolist_virtcol(), left);
326  curwin->w_cursor = save_cursor;
327  return sw_value;
328}
329
330/// Idem, using the first non-black in the current line.
331int get_sw_value_indent(buf_T *buf, bool left)
332{
333  pos_T pos = curwin->w_cursor;
334
335  pos.col = (colnr_T)getwhitecols_curline();
336  return get_sw_value_pos(buf, &pos, left);
337}
338
339/// Idem, using virtual column "col".
340int get_sw_value_col(buf_T *buf, colnr_T col, bool left)
341{
342  return buf->b_p_sw ? (int)buf->b_p_sw
343                     : tabstop_at(col, buf->b_p_ts, buf->b_p_vts_array, left);
344}
345
346/// Return the effective softtabstop value for the current buffer,
347/// using the shiftwidth  value when 'softtabstop' is negative.
348int get_sts_value(void)
349{
350  int result = curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : (int)curbuf->b_p_sts;
351  return result;
352}
353
354/// Count the size (in window cells) of the indent in the current line.
355int get_indent(void)
356{
357  return indent_size_ts(get_cursor_line_ptr(), curbuf->b_p_ts, curbuf->b_p_vts_array);
358}
359
360/// Count the size (in window cells) of the indent in line "lnum".
361int get_indent_lnum(linenr_T lnum)
362{
363  return indent_size_ts(ml_get(lnum), curbuf->b_p_ts, curbuf->b_p_vts_array);
364}
365
366/// Count the size (in window cells) of the indent in line "lnum" of buffer "buf".
367int get_indent_buf(buf_T *buf, linenr_T lnum)
368{
369  return indent_size_ts(ml_get_buf(buf, lnum), buf->b_p_ts, buf->b_p_vts_array);
370}
371
372/// Compute the size of the indent (in window cells) in line "ptr",
373/// without tabstops (count tab as ^I or <09>).
374int indent_size_no_ts(char const *ptr)
375  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
376{
377  int tab_size = dy_escape_width;
378
379  int vcol = 0;
380  while (true) {
381    char const c = *ptr++;
382    if (c == ' ') {
383      vcol++;
384    } else if (c == TAB) {
385      vcol += tab_size;
386    } else {
387      return vcol;
388    }
389  }
390}
391
392/// Compute the size of the indent (in window cells) in line "ptr",
393/// using tabstops
394int indent_size_ts(char const *ptr, OptInt ts, colnr_T *vts)
395  FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_PURE
396{
397  assert(char2cells(' ') == 1);
398
399  int vcol = 0;
400  int tabstop_width, next_tab_vcol;
401
402  if (vts == NULL || vts[0] < 1) {  // tab has fixed width
403    // can ts be 0 ? This is from tabstop_padding().
404    tabstop_width = (int)(ts == 0 ? 8 : ts);
405    next_tab_vcol = tabstop_width;
406  } else {  // tab has variable width
407    colnr_T *cur_tabstop = vts + 1;
408    colnr_T *const last_tabstop = vts + vts[0];
409
410    while (cur_tabstop != last_tabstop) {
411      int cur_vcol = vcol;
412      vcol += *cur_tabstop++;
413      assert(cur_vcol < vcol);
414
415      do {
416        char const c = *ptr++;
417        if (c == ' ') {
418          cur_vcol++;
419        } else if (c == TAB) {
420          break;
421        } else {
422          return cur_vcol;
423        }
424      } while (cur_vcol != vcol);
425    }
426
427    tabstop_width = *last_tabstop;
428    next_tab_vcol = vcol + tabstop_width;
429  }
430
431  assert(tabstop_width != 0);
432  while (true) {
433    char const c = *ptr++;
434    if (c == ' ') {
435      vcol++;
436      next_tab_vcol += (vcol == next_tab_vcol) ? tabstop_width : 0;
437    } else if (c == TAB) {
438      vcol = next_tab_vcol;
439      next_tab_vcol += tabstop_width;
440    } else {
441      return vcol;
442    }
443  }
444}
445
446/// Set the indent of the current line.
447/// Leaves the cursor on the first non-blank in the line.
448/// Caller must take care of undo.
449/// "flags":
450///  SIN_CHANGED:    call changed_bytes() if the line was changed.
451///  SIN_INSERT: insert the indent in front of the line.
452///  SIN_UNDO:   save line for undo before changing it.
453///  SIN_NOMARK: don't move extmarks (because just after ml_append or something)
454///  @param size measured in spaces
455///
456/// @return  true if the line was changed.
457bool set_indent(int size, int flags)
458{
459  char *newline;
460  char *oldline;
461  char *s;
462  int doit = false;
463  int ind_done = 0;  // Measured in spaces.
464  int tab_pad;
465  bool retval = false;
466
467  // Number of initial whitespace chars when 'et' and 'pi' are both set.
468  int orig_char_len = -1;
469
470  // First check if there is anything to do and compute the number of
471  // characters needed for the indent.
472  int todo = size;
473  int ind_len = 0;  // Measured in characters.
474  char *p = oldline = get_cursor_line_ptr();
475  int line_len = get_cursor_line_len() + 1;  // size of the line (including the NUL)
476
477  // Calculate the buffer size for the new indent, and check to see if it
478  // isn't already set.
479  // If 'expandtab' isn't set: use TABs; if both 'expandtab' and
480  // 'preserveindent' are set count the number of characters at the
481  // beginning of the line to be copied.
482  if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi)) {
483    int ind_col = 0;
484    // If 'preserveindent' is set then reuse as much as possible of
485    // the existing indent structure for the new indent.
486    if (!(flags & SIN_INSERT) && curbuf->b_p_pi) {
487      ind_done = 0;
488
489      // Count as many characters as we can use.
490      while (todo > 0 && ascii_iswhite(*p)) {
491        if (*p == TAB) {
492          tab_pad = tabstop_padding(ind_done,
493                                    curbuf->b_p_ts,
494                                    curbuf->b_p_vts_array);
495
496          // Stop if this tab will overshoot the target.
497          if (todo < tab_pad) {
498            break;
499          }
500          todo -= tab_pad;
501          ind_len++;
502          ind_done += tab_pad;
503        } else {
504          todo--;
505          ind_len++;
506          ind_done++;
507        }
508        p++;
509      }
510
511      // These diverge from this point.
512      ind_col = ind_done;
513      // Set initial number of whitespace chars to copy if we are
514      // preserving indent but expandtab is set.
515      if (curbuf->b_p_et) {
516        orig_char_len = ind_len;
517      }
518      // Fill to next tabstop with a tab, if possible.
519      tab_pad = tabstop_padding(ind_done,
520                                curbuf->b_p_ts,
521                                curbuf->b_p_vts_array);
522      if ((todo >= tab_pad) && (orig_char_len == -1)) {
523        doit = true;
524        todo -= tab_pad;
525        ind_len++;
526
527        // ind_done += tab_pad;
528        ind_col += tab_pad;
529      }
530    }
531
532    // Count tabs required for indent.
533    while (true) {
534      tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts, curbuf->b_p_vts_array);
535      if (todo < tab_pad) {
536        break;
537      }
538      if (*p != TAB) {
539        doit = true;
540      } else {
541        p++;
542      }
543      todo -= tab_pad;
544      ind_len++;
545      ind_col += tab_pad;
546    }
547  }
548
549  // Count spaces required for indent.
550  while (todo > 0) {
551    if (*p != ' ') {
552      doit = true;
553    } else {
554      p++;
555    }
556    todo--;
557    ind_len++;
558
559    // ind_done++;
560  }
561
562  // Return if the indent is OK already.
563  if (!doit && !ascii_iswhite(*p) && !(flags & SIN_INSERT)) {
564    return false;
565  }
566
567  // Allocate memory for the new line.
568  if (flags & SIN_INSERT) {
569    p = oldline;
570  } else {
571    p = skipwhite(p);
572    line_len -= (int)(p - oldline);
573  }
574
575  // If 'preserveindent' and 'expandtab' are both set keep the original
576  // characters and allocate accordingly.  We will fill the rest with spaces
577  // after the if (!curbuf->b_p_et) below.
578  int skipcols = 0;  // number of columns (in bytes) that were presved
579  if (orig_char_len != -1) {
580    int newline_size;  // = orig_char_len + size - ind_done + line_len
581    STRICT_ADD(orig_char_len, size, &newline_size, int);
582    STRICT_SUB(newline_size, ind_done, &newline_size, int);
583    STRICT_ADD(newline_size, line_len, &newline_size, int);
584    assert(newline_size >= 0);
585    newline = xmalloc((size_t)newline_size);
586    todo = size - ind_done;
587
588    // Set total length of indent in characters, which may have been
589    // undercounted until now.
590    ind_len = orig_char_len + todo;
591    p = oldline;
592    s = newline;
593    skipcols = orig_char_len;
594
595    while (orig_char_len > 0) {
596      *s++ = *p++;
597      orig_char_len--;
598    }
599
600    // Skip over any additional white space (useful when newindent is less
601    // than old).
602    while (ascii_iswhite(*p)) {
603      p++;
604    }
605  } else {
606    todo = size;
607    assert(ind_len + line_len >= 0);
608    size_t newline_size;
609    STRICT_ADD(ind_len, line_len, &newline_size, size_t);
610    newline = xmalloc(newline_size);
611    s = newline;
612  }
613
614  // Put the characters in the new line.
615  // if 'expandtab' isn't set: use TABs
616  if (!curbuf->b_p_et) {
617    // If 'preserveindent' is set then reuse as much as possible of
618    // the existing indent structure for the new indent.
619    if (!(flags & SIN_INSERT) && curbuf->b_p_pi) {
620      p = oldline;
621      ind_done = 0;
622
623      while (todo > 0 && ascii_iswhite(*p)) {
624        if (*p == TAB) {
625          tab_pad = tabstop_padding(ind_done,
626                                    curbuf->b_p_ts,
627                                    curbuf->b_p_vts_array);
628
629          // Stop if this tab will overshoot the target.
630          if (todo < tab_pad) {
631            break;
632          }
633          todo -= tab_pad;
634          ind_done += tab_pad;
635        } else {
636          todo--;
637          ind_done++;
638        }
639        *s++ = *p++;
640        skipcols++;
641      }
642
643      // Fill to next tabstop with a tab, if possible.
644      tab_pad = tabstop_padding(ind_done,
645                                curbuf->b_p_ts,
646                                curbuf->b_p_vts_array);
647
648      if (todo >= tab_pad) {
649        *s++ = TAB;
650        todo -= tab_pad;
651        ind_done += tab_pad;
652      }
653      p = skipwhite(p);
654    }
655
656    while (true) {
657      tab_pad = tabstop_padding(ind_done,
658                                curbuf->b_p_ts,
659                                curbuf->b_p_vts_array);
660      if (todo < tab_pad) {
661        break;
662      }
663      *s++ = TAB;
664      todo -= tab_pad;
665      ind_done += tab_pad;
666    }
667  }
668
669  while (todo > 0) {
670    *s++ = ' ';
671    todo--;
672  }
673  memmove(s, p, (size_t)line_len);
674
675  // Replace the line (unless undo fails).
676  if (!(flags & SIN_UNDO) || (u_savesub(curwin->w_cursor.lnum) == OK)) {
677    const colnr_T old_offset = (colnr_T)(p - oldline);
678    const colnr_T new_offset = (colnr_T)(s - newline);
679
680    // this may free "newline"
681    ml_replace(curwin->w_cursor.lnum, newline, false);
682    if (!(flags & SIN_NOMARK)) {
683      extmark_splice_cols(curbuf,
684                          (int)curwin->w_cursor.lnum - 1,
685                          skipcols,
686                          old_offset - skipcols,
687                          new_offset - skipcols,
688                          kExtmarkUndo);
689    }
690
691    if (flags & SIN_CHANGED) {
692      changed_bytes(curwin->w_cursor.lnum, 0);
693    }
694
695    // Correct saved cursor position if it is in this line.
696    if (saved_cursor.lnum == curwin->w_cursor.lnum) {
697      if (saved_cursor.col >= old_offset) {
698        // Cursor was after the indent, adjust for the number of
699        // bytes added/removed.
700        saved_cursor.col += ind_len - old_offset;
701      } else if (saved_cursor.col >= new_offset) {
702        // Cursor was in the indent, and is now after it, put it back
703        // at the start of the indent (replacing spaces with TAB).
704        saved_cursor.col = new_offset;
705      }
706    }
707    retval = true;
708  } else {
709    xfree(newline);
710  }
711  curwin->w_cursor.col = ind_len;
712  return retval;
713}
714
715// Return the indent of the current line after a number.  Return -1 if no
716// number was found.  Used for 'n' in 'formatoptions': numbered list.
717// Since a pattern is used it can actually handle more than numbers.
718int get_number_indent(linenr_T lnum)
719{
720  colnr_T col;
721  pos_T pos;
722  regmatch_T regmatch;
723  int lead_len = 0;  // Length of comment leader.
724
725  if (lnum > curbuf->b_ml.ml_line_count) {
726    return -1;
727  }
728  pos.lnum = 0;
729
730  // In format_lines() (i.e. not insert mode), fo+=q is needed too...
731  if ((State & MODE_INSERT) || has_format_option(kFoQComs)) {
732    lead_len = get_leader_len(ml_get(lnum), NULL, false, true);
733  }
734  regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
735
736  if (regmatch.regprog != NULL) {
737    regmatch.rm_ic = false;
738
739    // vim_regexec() expects a pointer to a line.  This lets us
740    // start matching for the flp beyond any comment leader...
741    if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, 0)) {
742      pos.lnum = lnum;
743      pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
744      pos.coladd = 0;
745    }
746    vim_regfree(regmatch.regprog);
747  }
748
749  if ((pos.lnum == 0) || (*ml_get_pos(&pos) == NUL)) {
750    return -1;
751  }
752  getvcol(curwin, &pos, &col, NULL, NULL, 0);
753  return (int)col;
754}
755
756/// Check "briopt" as 'breakindentopt' and update the members of "wp".
757/// This is called when 'breakindentopt' is changed and when a window is
758/// initialized
759///
760/// @param briopt  when NULL: use "wp->w_p_briopt"
761/// @param wp      when NULL: only check "briopt"
762///
763/// @return  FAIL for failure, OK otherwise.
764void briopt_check(win_T *wp)
765{
766  if (wp == NULL) {
767    return;  // Setting the global value: nothing to apply to a window.
768  }
769  // 'breakindentopt' is stored as its ":set" string (validated when set); reify it into a keyset and
770  // map that onto the applied per-window fields.
771  OptKeyDict_briopt *v = opt_keyset(wp->w_p_briopt, kOptBreakindentopt, NULL);
772  wp->w_briopt_shift = HAS_KEY(v, briopt, shift) ? (int)v->shift : 0;
773  wp->w_briopt_min = HAS_KEY(v, briopt, min) ? (int)v->min : 20;
774  wp->w_briopt_sbr = HAS_KEY(v, briopt, sbr);
775  wp->w_briopt_list = HAS_KEY(v, briopt, list) ? (int)v->list : 0;
776  wp->w_briopt_vcol = HAS_KEY(v, briopt, column) ? (int)v->column : 0;
777}
778
779// Return appropriate space number for breakindent, taking influencing
780// parameters into account. Window must be specified, since it is not
781// necessarily always the current one.
782int get_breakindent_win(win_T *wp, char *line)
783  FUNC_ATTR_NONNULL_ALL
784{
785  static int prev_indent = 0;  // cached indent value
786  static OptInt prev_ts = 0;  // cached tabstop value
787  static colnr_T *prev_vts = NULL;  // cached vartabs values
788  static int prev_fnum = 0;  // cached buffer number
789  static char *prev_line = NULL;  // cached copy of "line"
790  static varnumber_T prev_tick = 0;  // changedtick of cached value
791  static int prev_list = 0;  // cached list indent
792  static int prev_listopt = 0;  // cached w_p_briopt_list value
793  static bool prev_no_ts = false;  // cached no_ts value
794  static unsigned prev_dy_uhex = 0;   // cached 'display' "uhex" value
795  static char *prev_flp = NULL;  // cached formatlistpat value
796  int bri = 0;
797  // window width minus window margin space, i.e. what rests for text
798  const int eff_wwidth = wp->w_view_width - win_col_off(wp) + win_col_off2(wp);
799
800  // In list mode, if 'listchars' "tab" isn't set, a TAB is displayed as ^I.
801  const bool no_ts = wp->w_p_list && wp->w_p_lcs_chars.tab1 == NUL;
802
803  // Used cached indent, unless
804  // - buffer changed, or
805  // - 'tabstop' changed, or
806  // - 'vartabstop' changed, or
807  // - buffer was changed, or
808  // - 'breakindentopt' "list" changed, or
809  // - 'list' or 'listchars' "tab" changed, or
810  // - 'display' "uhex" flag changed, or
811  // - 'formatlistpat' changed, or
812  // - line changed.
813  if (prev_fnum != wp->w_buffer->b_fnum
814      || prev_ts != wp->w_buffer->b_p_ts
815      || prev_vts != wp->w_buffer->b_p_vts_array
816      || prev_tick != buf_get_changedtick(wp->w_buffer)
817      || prev_listopt != wp->w_briopt_list
818      || prev_no_ts != no_ts
819      || prev_dy_uhex != (dy_flags & kOptDyFlagUhex)
820      || prev_flp == NULL
821      || strcmp(prev_flp, get_flp_value(wp->w_buffer)) != 0
822      || prev_line == NULL || strcmp(prev_line, line) != 0) {
823    prev_fnum = wp->w_buffer->b_fnum;
824    xfree(prev_line);
825    prev_line = xstrdup(line);
826    prev_ts = wp->w_buffer->b_p_ts;
827    prev_vts = wp->w_buffer->b_p_vts_array;
828    if (wp->w_briopt_vcol == 0) {
829      if (no_ts) {
830        prev_indent = indent_size_no_ts(line);
831      } else {
832        prev_indent = indent_size_ts(line, wp->w_buffer->b_p_ts,
833                                     wp->w_buffer->b_p_vts_array);
834      }
835    }
836    prev_tick = buf_get_changedtick(wp->w_buffer);
837    prev_listopt = wp->w_briopt_list;
838    prev_list = 0;
839    prev_no_ts = no_ts;
840    prev_dy_uhex = (dy_flags & kOptDyFlagUhex);
841    xfree(prev_flp);
842    prev_flp = xstrdup(get_flp_value(wp->w_buffer));
843    // add additional indent for numbered lists
844    if (wp->w_briopt_list != 0 && wp->w_briopt_vcol == 0) {
845      regmatch_T regmatch = {
846        .regprog = vim_regcomp(prev_flp, RE_MAGIC + RE_STRING + RE_AUTO + RE_STRICT),
847      };
848      if (regmatch.regprog != NULL) {
849        regmatch.rm_ic = false;
850        if (vim_regexec(&regmatch, line, 0)) {
851          if (wp->w_briopt_list > 0) {
852            prev_list += wp->w_briopt_list;
853          } else {
854            char *ptr = *regmatch.startp;
855            char *end_ptr = *regmatch.endp;
856            int indent = 0;
857            // Compute the width of the matched text.
858            // Use win_chartabsize() so that TAB size is correct,
859            // while wrapping is ignored.
860            while (ptr < end_ptr) {
861              indent += win_chartabsize(wp, ptr, indent);
862              MB_PTR_ADV(ptr);
863            }
864            prev_indent = indent;
865          }
866        }
867        vim_regfree(regmatch.regprog);
868      }
869    }
870  }
871  if (wp->w_briopt_vcol != 0) {
872    // column value has priority
873    bri = wp->w_briopt_vcol;
874    prev_list = 0;
875  } else {
876    bri = prev_indent + wp->w_briopt_shift;
877  }
878
879  // Add offset for number column, if 'n' is in 'cpoptions'
880  bri += win_col_off2(wp);
881
882  // add additional indent for numbered lists
883  if (wp->w_briopt_list > 0) {
884    bri += prev_list;
885  }
886
887  // indent minus the length of the showbreak string
888  if (wp->w_briopt_sbr) {
889    bri -= vim_strsize(get_showbreak_value(wp));
890  }
891
892  // never indent past left window margin
893  if (bri < 0) {
894    bri = 0;
895  } else if (bri > eff_wwidth - wp->w_briopt_min) {
896    // always leave at least bri_min characters on the left,
897    // if text width is sufficient
898    bri = (eff_wwidth - wp->w_briopt_min < 0)
899          ? 0 : eff_wwidth - wp->w_briopt_min;
900  }
901
902  return bri;
903}
904
905// When extra == 0: Return true if the cursor is before or on the first
906// non-blank in the line.
907// When extra == 1: Return true if the cursor is before the first non-blank in
908// the line.
909bool inindent(int extra)
910{
911  char *ptr;
912  colnr_T col;
913
914  for (col = 0, ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) {
915    ptr++;
916  }
917
918  if (col >= curwin->w_cursor.col + extra) {
919    return true;
920  }
921  return false;
922}
923
924/// Handle reindenting a block of lines.
925void op_reindent(oparg_T *oap, Indenter how)
926{
927  int i = 0;
928  linenr_T first_changed = 0;
929  linenr_T last_changed = 0;
930  linenr_T start_lnum = curwin->w_cursor.lnum;
931
932  // Don't even try when 'modifiable' is off.
933  if (!MODIFIABLE(curbuf)) {
934    emsg(_(e_modifiable));
935    return;
936  }
937
938  // Save for undo.  Do this once for all lines, much faster than doing this
939  // for each line separately, especially when undoing.
940  if (u_savecommon(curbuf, start_lnum - 1, start_lnum + oap->line_count,
941                   start_lnum + oap->line_count, false) == OK) {
942    int amount;
943    for (i = oap->line_count - 1; i >= 0 && !got_int; i--) {
944      // it's a slow thing to do, so give feedback so there's no worry
945      // that the computer's just hung.
946
947      if (i > 1
948          && (i % 50 == 0 || i == oap->line_count - 1)
949          && oap->line_count > p_report) {
950        snprintf(IObuff, IOSIZE, _("%" PRId64 " lines to indent... "), (int64_t)i);
951        // Restore cursor to avoid redrawing curwin in msg_show callback.
952        linenr_T save_lnum = curwin->w_cursor.lnum;
953        curwin->w_cursor.lnum = start_lnum;
954        msg_progress(IObuff, "nvim.indent", "running", 0, true, false, false);
955        curwin->w_cursor.lnum = save_lnum;
956      }
957
958      // Be vi-compatible: For lisp indenting the first line is not
959      // indented, unless there is only one line.
960      if (i != oap->line_count - 1 || oap->line_count == 1 || how != get_lisp_indent) {
961        char *l = skipwhite(get_cursor_line_ptr());
962        // Get indent for this line unless it is blank.
963        amount = *l == NUL ? 0 : how();
964        if (amount >= 0 && set_indent(amount, 0)) {
965          // did change the indent, call changed_lines() later
966          if (first_changed == 0) {
967            first_changed = curwin->w_cursor.lnum;
968          }
969          last_changed = curwin->w_cursor.lnum;
970        }
971      }
972      curwin->w_cursor.lnum++;
973      curwin->w_cursor.col = 0;      // make sure it's valid
974    }
975  }
976
977  // put cursor on first non-blank of indented line
978  curwin->w_cursor.lnum = start_lnum;
979  beginline(BL_SOL | BL_FIX);
980
981  // Mark changed lines so that they will be redrawn.  When Visual
982  // highlighting was present, need to continue until the last line.  When
983  // there is no change still need to remove the Visual highlighting.
984  if (last_changed != 0) {
985    changed_lines(curbuf, first_changed, 0,
986                  oap->is_VIsual ? start_lnum + oap->line_count
987                                 : last_changed + 1, 0, true);
988  } else if (oap->is_VIsual) {
989    redraw_curbuf_later(UPD_INVERTED);
990  }
991
992  if (oap->line_count > p_report) {
993    i = oap->line_count - (i + 1);
994    snprintf(IObuff, IOSIZE,
995             NGETTEXT("%" PRId64 " line indented ", "%" PRId64 " lines indented ", i), (int64_t)i);
996    msg_progress(IObuff, "nvim.indent", "success", 0, true, false, false);
997  }
998  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
999    // set '[ and '] marks
1000    curbuf->b_op_start = oap->start;
1001    curbuf->b_op_end = oap->end;
1002  }
1003}
1004
1005/// @return  true if lines starting with '#' should be left aligned.
1006bool preprocs_left(void)
1007{
1008  return ((curbuf->b_p_si && !curbuf->b_p_cin)
1009          || (curbuf->b_p_cin && in_cinkeys('#', ' ', true)
1010              && curbuf->b_ind_hash_comment == 0));
1011}
1012
1013/// @return  true if the conditions are OK for smart indenting.
1014bool may_do_si(void)
1015{
1016  return curbuf->b_p_si && !curbuf->b_p_cin && curbuf->b_p_inde.type == kCallbackNone && !p_paste;
1017}
1018
1019// Try to do some very smart auto-indenting.
1020// Used when inserting a "normal" character.
1021void ins_try_si(int c)
1022{
1023  pos_T *pos;
1024
1025  // do some very smart indenting when entering '{' or '}'
1026  if (((Ins.did_si || Ins.can_si_back) && c == '{') || (Ins.can_si && c == '}' && inindent(0))) {
1027    pos_T old_pos;
1028    char *ptr;
1029    int i;
1030    bool temp;
1031    // for '}' set indent equal to indent of line containing matching '{'
1032    if (c == '}' && (pos = findmatch(NULL, '{')) != NULL) {
1033      old_pos = curwin->w_cursor;
1034      // If the matching '{' has a ')' immediately before it (ignoring
1035      // white-space), then line up with the start of the line
1036      // containing the matching '(' if there is one.  This handles the
1037      // case where an "if (..\n..) {" statement continues over multiple
1038      // lines -- webb
1039      ptr = ml_get(pos->lnum);
1040      i = pos->col;
1041      if (i > 0) {              // skip blanks before '{'
1042        while (--i > 0 && ascii_iswhite(ptr[i])) {}
1043      }
1044      curwin->w_cursor.lnum = pos->lnum;
1045      curwin->w_cursor.col = i;
1046      if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) {
1047        curwin->w_cursor = *pos;
1048      }
1049      i = get_indent();
1050      curwin->w_cursor = old_pos;
1051      if (State & VREPLACE_FLAG) {
1052        change_indent(INDENT_SET, i, false, true);
1053      } else {
1054        set_indent(i, SIN_CHANGED);
1055      }
1056    } else if (curwin->w_cursor.col > 0) {
1057      // when inserting '{' after "O" reduce indent, but not
1058      // more than indent of previous line
1059      temp = true;
1060      if (c == '{' && Ins.can_si_back && curwin->w_cursor.lnum > 1) {
1061        old_pos = curwin->w_cursor;
1062        i = get_indent();
1063        while (curwin->w_cursor.lnum > 1) {
1064          ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
1065
1066          // ignore empty lines and lines starting with '#'.
1067          if (*ptr != '#' && *ptr != NUL) {
1068            break;
1069          }
1070        }
1071        if (get_indent() >= i) {
1072          temp = false;
1073        }
1074        curwin->w_cursor = old_pos;
1075      }
1076      if (temp) {
1077        shift_line(true, false, 1, true);
1078      }
1079    }
1080  }
1081
1082  // set indent of '#' always to 0
1083  if (curwin->w_cursor.col > 0 && Ins.can_si && c == '#' && inindent(0)) {
1084    // remember current indent for next line
1085    old_indent = get_indent();
1086    set_indent(0, SIN_CHANGED);
1087  }
1088
1089  // Adjust Ins.ai_col, the char at this position can be deleted.
1090  Ins.ai_col = MIN(Ins.ai_col, curwin->w_cursor.col);
1091}
1092
1093/// Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1094/// Keep the cursor on the same character.
1095/// type == INDENT_INC   increase indent (for CTRL-T or <Tab>)
1096/// type == INDENT_DEC   decrease indent (for CTRL-D)
1097/// type == INDENT_SET   set indent to "amount"
1098///
1099/// @param round               if true, round the indent to 'shiftwidth' (only with _INC and _Dec).
1100/// @param call_changed_bytes  call changed_bytes()
1101void change_indent(int type, int amount, int round, bool call_changed_bytes)
1102{
1103  int insstart_less;                    // reduction for Ins.start.col
1104  colnr_T orig_col = 0;                 // init for GCC
1105  char *orig_line = NULL;     // init for GCC
1106
1107  // MODE_VREPLACE state needs to know what the line was like before changing
1108  if (State & VREPLACE_FLAG) {
1109    orig_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
1110    orig_col = curwin->w_cursor.col;
1111  }
1112
1113  // for the following tricks we don't want list mode
1114  int save_p_list = curwin->w_p_list;
1115  curwin->w_p_list = false;
1116  colnr_T vc = getvcol_nolist(&curwin->w_cursor);
1117  int vcol = vc;
1118
1119  // For Replace mode we need to fix the replace stack later, which is only
1120  // possible when the cursor is in the indent.  Remember the number of
1121  // characters before the cursor if it's possible.
1122  int start_col = curwin->w_cursor.col;
1123
1124  // determine offset from first non-blank
1125  int new_cursor_col = curwin->w_cursor.col;
1126  beginline(BL_WHITE);
1127  new_cursor_col -= curwin->w_cursor.col;
1128
1129  insstart_less = curwin->w_cursor.col;
1130
1131  // If the cursor is in the indent, compute how many screen columns the
1132  // cursor is to the left of the first non-blank.
1133  if (new_cursor_col < 0) {
1134    vcol = get_indent() - vcol;
1135  }
1136
1137  if (new_cursor_col > 0) {         // can't fix replace stack
1138    start_col = -1;
1139  }
1140
1141  // Set the new indent.  The cursor will be put on the first non-blank.
1142  if (type == INDENT_SET) {
1143    set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1144  } else {
1145    int save_State = State;
1146
1147    // Avoid being called recursively.
1148    if (State & VREPLACE_FLAG) {
1149      State = MODE_INSERT;
1150    }
1151    shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1152    State = save_State;
1153  }
1154  insstart_less -= curwin->w_cursor.col;
1155
1156  // Try to put cursor on same character.
1157  // If the cursor is at or after the first non-blank in the line,
1158  // compute the cursor column relative to the column of the first
1159  // non-blank character.
1160  // If we are not in insert mode, leave the cursor on the first non-blank.
1161  // If the cursor is before the first non-blank, position it relative
1162  // to the first non-blank, counted in screen columns.
1163  if (new_cursor_col >= 0) {
1164    // When changing the indent while the cursor is touching it, reset
1165    // Insstart_col to 0.
1166    if (new_cursor_col == 0) {
1167      insstart_less = MAXCOL;
1168    }
1169    new_cursor_col += curwin->w_cursor.col;
1170  } else if (!(State & MODE_INSERT)) {
1171    new_cursor_col = curwin->w_cursor.col;
1172  } else {
1173    // Compute the screen column where the cursor should be.
1174    vcol = get_indent() - vcol;
1175    int const end_vcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1176    curwin->w_virtcol = end_vcol;
1177
1178    // Advance the cursor until we reach the right screen column.
1179    new_cursor_col = 0;
1180    char *const line = get_cursor_line_ptr();
1181    vcol = 0;
1182    if (*line != NUL) {
1183      CharsizeArg csarg;
1184      CSType cstype = init_charsize_arg(&csarg, curwin, 0, line);
1185      StrCharInfo ci = utf_ptr2StrCharInfo(line);
1186      while (true) {
1187        ClusterInfo cli = utf_ClusterInfo(ci);
1188        int next_vcol = vcol + win_charsize(cstype, vcol, ci.ptr, ci.chr.value, &csarg,
1189                                            cli.cells).width;
1190        if (next_vcol > end_vcol) {
1191          break;
1192        }
1193        vcol = next_vcol;
1194        ci = cli.next;
1195        if (*ci.ptr == NUL) {
1196          break;
1197        }
1198      }
1199      new_cursor_col = (int)(ci.ptr - line);
1200    }
1201
1202    // May need to insert spaces to be able to position the cursor on
1203    // the right screen column.
1204    if (vcol != (int)curwin->w_virtcol) {
1205      curwin->w_cursor.col = (colnr_T)new_cursor_col;
1206      const size_t ptrlen = (size_t)(curwin->w_virtcol - vcol);
1207      char *ptr = xmallocz(ptrlen);
1208      memset(ptr, ' ', ptrlen);
1209      new_cursor_col += (int)ptrlen;
1210      ins_str(ptr, ptrlen);
1211      xfree(ptr);
1212    }
1213
1214    // When changing the indent while the cursor is in it, reset
1215    // Insstart_col to 0.
1216    insstart_less = MAXCOL;
1217  }
1218
1219  curwin->w_p_list = save_p_list;
1220  curwin->w_cursor.col = MAX(0, (colnr_T)new_cursor_col);
1221  curwin->w_set_curswant = true;
1222  changed_cline_bef_curs(curwin);
1223
1224  // May have to adjust the start of the insert.
1225  if (State & MODE_INSERT) {
1226    if (curwin->w_cursor.lnum == Ins.start.lnum && Ins.start.col != 0) {
1227      if ((int)Ins.start.col <= insstart_less) {
1228        Ins.start.col = 0;
1229      } else {
1230        Ins.start.col -= insstart_less;
1231      }
1232    }
1233    if ((int)Ins.ai_col <= insstart_less) {
1234      Ins.ai_col = 0;
1235    } else {
1236      Ins.ai_col -= insstart_less;
1237    }
1238  }
1239
1240  // For MODE_REPLACE state, may have to fix the replace stack, if it's
1241  // possible.  If the number of characters before the cursor decreased, need
1242  // to pop a few characters from the replace stack.
1243  // If the number of characters before the cursor increased, need to push a
1244  // few NULs onto the replace stack.
1245  if (REPLACE_NORMAL(State) && start_col >= 0) {
1246    while (start_col > (int)curwin->w_cursor.col) {
1247      replace_join(0);              // remove a NUL from the replace stack
1248      start_col--;
1249    }
1250    while (start_col < (int)curwin->w_cursor.col) {
1251      replace_push_nul();
1252      start_col++;
1253    }
1254  }
1255
1256  // For MODE_VREPLACE state, we also have to fix the replace stack.  In this
1257  // case it is always possible because we backspace over the whole line and
1258  // then put it back again the way we wanted it.
1259  if (State & VREPLACE_FLAG) {
1260    // Save new line
1261    char *new_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
1262
1263    // We only put back the new line up to the cursor
1264    new_line[curwin->w_cursor.col] = NUL;
1265    int new_col = curwin->w_cursor.col;
1266
1267    // Put back original line
1268    ml_replace(curwin->w_cursor.lnum, orig_line, false);
1269    curwin->w_cursor.col = orig_col;
1270
1271    curbuf_splice_pending++;
1272
1273    // Backspace from cursor to start of line
1274    backspace_until_column(0);
1275
1276    // Insert new stuff into line again
1277    ins_bytes(new_line);
1278
1279    xfree(new_line);
1280
1281    curbuf_splice_pending--;
1282
1283    // TODO(bfredl): test for crazy edge cases, like we stand on a TAB or
1284    // something? does this even do the right text change then?
1285    int delta = orig_col - new_col;
1286    extmark_splice_cols(curbuf, (int)curwin->w_cursor.lnum - 1, new_col,
1287                        delta < 0 ? -delta : 0,
1288                        delta > 0 ? delta : 0,
1289                        kExtmarkUndo);
1290  }
1291}
1292
1293/// Copy the indent from ptr to the current line (and fill to size).
1294/// Leaves the cursor on the first non-blank in the line.
1295///
1296/// @return true if the line was changed.
1297bool copy_indent(int size, char *src)
1298{
1299  char *p = NULL;
1300  char *line = NULL;
1301  int ind_len;
1302  int line_len = 0;
1303  int tab_pad;
1304
1305  // Round 1: compute the number of characters needed for the indent
1306  // Round 2: copy the characters.
1307  for (int round = 1; round <= 2; round++) {
1308    int todo = size;
1309    ind_len = 0;
1310    int ind_done = 0;
1311    int ind_col = 0;
1312    char *s = src;
1313
1314    // Count/copy the usable portion of the source line.
1315    while (todo > 0 && ascii_iswhite(*s)) {
1316      if (*s == TAB) {
1317        tab_pad = tabstop_padding(ind_done,
1318                                  curbuf->b_p_ts,
1319                                  curbuf->b_p_vts_array);
1320
1321        // Stop if this tab will overshoot the target.
1322        if (todo < tab_pad) {
1323          break;
1324        }
1325        todo -= tab_pad;
1326        ind_done += tab_pad;
1327        ind_col += tab_pad;
1328      } else {
1329        todo--;
1330        ind_done++;
1331        ind_col++;
1332      }
1333      ind_len++;
1334
1335      if (p != NULL) {
1336        *p++ = *s;
1337      }
1338      s++;
1339    }
1340
1341    // Fill to next tabstop with a tab, if possible.
1342    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts, curbuf->b_p_vts_array);
1343
1344    if ((todo >= tab_pad) && !curbuf->b_p_et) {
1345      todo -= tab_pad;
1346      ind_len++;
1347      ind_col += tab_pad;
1348
1349      if (p != NULL) {
1350        *p++ = TAB;
1351      }
1352    }
1353
1354    // Add tabs required for indent.
1355    if (!curbuf->b_p_et) {
1356      while (true) {
1357        tab_pad = tabstop_padding(ind_col,
1358                                  curbuf->b_p_ts,
1359                                  curbuf->b_p_vts_array);
1360        if (todo < tab_pad) {
1361          break;
1362        }
1363        todo -= tab_pad;
1364        ind_len++;
1365        ind_col += tab_pad;
1366        if (p != NULL) {
1367          *p++ = TAB;
1368        }
1369      }
1370    }
1371
1372    // Count/add spaces required for indent.
1373    while (todo > 0) {
1374      todo--;
1375      ind_len++;
1376
1377      if (p != NULL) {
1378        *p++ = ' ';
1379      }
1380    }
1381
1382    if (p == NULL) {
1383      // Allocate memory for the result: the copied indent, new indent
1384      // and the rest of the line.
1385      line_len = get_cursor_line_len() + 1;
1386      assert(ind_len + line_len >= 0);
1387      size_t line_size;
1388      STRICT_ADD(ind_len, line_len, &line_size, size_t);
1389      line = xmalloc(line_size);
1390      p = line;
1391    }
1392  }
1393
1394  // Append the original line
1395  memmove(p, get_cursor_line_ptr(), (size_t)line_len);
1396
1397  // Replace the line
1398  ml_replace(curwin->w_cursor.lnum, line, false);
1399
1400  // Put the cursor after the indent.
1401  curwin->w_cursor.col = ind_len;
1402  return true;
1403}
1404
1405/// Give a "resulting text too long" error and maybe set got_int.
1406static void emsg_text_too_long(void)
1407{
1408  emsg(_(e_resulting_text_too_long));
1409  // when not inside a try/catch set got_int to break out of any loop
1410  if (trylevel == 0) {
1411    got_int = true;
1412  }
1413}
1414
1415/// ":retab".
1416void ex_retab(exarg_T *eap)
1417{
1418  bool got_tab = false;
1419  int num_spaces = 0;
1420  int start_col = 0;                   // For start of white-space string
1421  int64_t start_vcol = 0;                  // For start of white-space string
1422  char *new_line = (char *)1;  // init to non-NULL
1423  colnr_T *new_vts_array = NULL;
1424  char *new_ts_str;  // string value of tab argument
1425
1426  linenr_T first_line = 0;              // first changed line
1427  linenr_T last_line = 0;               // last changed line
1428  bool is_indent_only = false;
1429
1430  char *ptr = eap->arg;
1431  if (strncmp(ptr, "-indentonly", 11) == 0 && ascii_iswhite_or_nul(ptr[11])) {
1432    is_indent_only = true;
1433    ptr = skipwhite(ptr + 11);
1434  }
1435
1436  new_ts_str = ptr;
1437  if (!tabstop_set(ptr, &new_vts_array)) {
1438    return;
1439  }
1440  while (ascii_isdigit(*ptr) || *ptr == ',') {
1441    ptr++;
1442  }
1443
1444  // This ensures that either new_vts_array and new_ts_str are freshly
1445  // allocated, or new_vts_array points to an existing array and new_ts_str
1446  // is null.
1447  if (new_vts_array == NULL) {
1448    new_vts_array = curbuf->b_p_vts_array;
1449    new_ts_str = NULL;
1450  } else {
1451    new_ts_str = xmemdupz(new_ts_str, (size_t)(ptr - new_ts_str));
1452  }
1453
1454  int save_list = curwin->w_p_list;
1455  curwin->w_p_list = 0;             // don't want list mode here
1456
1457  for (linenr_T lnum = eap->line1; !got_int && lnum <= eap->line2; lnum++) {
1458    ptr = ml_get(lnum);
1459    int old_len = ml_get_len(lnum);
1460    int col = 0;
1461    int64_t vcol = 0;
1462    bool did_undo = false;  // called u_save for current line
1463    while (true) {
1464      if (ascii_iswhite(ptr[col])) {
1465        if (!got_tab && num_spaces == 0) {
1466          // First consecutive white-space
1467          start_vcol = vcol;
1468          start_col = col;
1469        }
1470        if (ptr[col] == ' ') {
1471          num_spaces++;
1472        } else {
1473          got_tab = true;
1474        }
1475      } else {
1476        if (got_tab || (eap->forceit && num_spaces > 1)) {
1477          // Retabulate this string of white-space
1478
1479          // len is virtual length of white string
1480          int len = num_spaces = (int)(vcol - start_vcol);
1481          int num_tabs = 0;
1482          if (!curbuf->b_p_et) {
1483            int t, s;
1484
1485            tabstop_fromto((colnr_T)start_vcol, (colnr_T)vcol,
1486                           (int)curbuf->b_p_ts, new_vts_array, &t, &s);
1487            num_tabs = t;
1488            num_spaces = s;
1489          }
1490          if (curbuf->b_p_et || got_tab
1491              || (num_spaces + num_tabs < len)) {
1492            if (did_undo == false) {
1493              did_undo = true;
1494              if (u_save((linenr_T)(lnum - 1),
1495                         (linenr_T)(lnum + 1)) == FAIL) {
1496                new_line = NULL;  // flag out-of-memory
1497                break;
1498              }
1499            }
1500
1501            // len is actual number of white characters used
1502            len = num_spaces + num_tabs;
1503            const int new_len = old_len - col + start_col + len + 1;
1504            if (new_len <= 0 || new_len >= MAXCOL) {
1505              emsg_text_too_long();
1506              break;
1507            }
1508            new_line = xmalloc((size_t)new_len);
1509
1510            if (start_col > 0) {
1511              memmove(new_line, ptr, (size_t)start_col);
1512            }
1513            memmove(new_line + start_col + len,
1514                    ptr + col, (size_t)old_len - (size_t)col + 1);
1515            ptr = new_line + start_col;
1516            for (col = 0; col < len; col++) {
1517              ptr[col] = (col < num_tabs) ? '\t' : ' ';
1518            }
1519            if (ml_replace(lnum, new_line, false) == OK) {
1520              // "new_line" may have been copied
1521              new_line = curbuf->b_ml.ml_line_ptr;
1522              extmark_splice_cols(curbuf, lnum - 1, 0, (colnr_T)old_len,
1523                                  (colnr_T)new_len - 1, kExtmarkUndo);
1524            }
1525            if (first_line == 0) {
1526              first_line = lnum;
1527            }
1528            last_line = lnum;
1529            ptr = new_line;
1530            old_len = new_len - 1;
1531            col = start_col + len;
1532          }
1533        }
1534        got_tab = false;
1535        num_spaces = 0;
1536
1537        if (is_indent_only) {
1538          break;
1539        }
1540      }
1541      if (ptr[col] == NUL) {
1542        break;
1543      }
1544      vcol += win_chartabsize(curwin, ptr + col, (colnr_T)vcol);
1545      if (vcol >= MAXCOL) {
1546        emsg_text_too_long();
1547        break;
1548      }
1549      col += utfc_ptr2len(ptr + col);
1550    }
1551    if (new_line == NULL) {                 // out of memory
1552      break;
1553    }
1554    line_breakcheck();
1555  }
1556  if (got_int) {
1557    emsg(_(e_interr));
1558  }
1559
1560  if (first_line != 0) {
1561    changed_lines(curbuf, first_line, 0, last_line + 1, 0, true);
1562  }
1563
1564  curwin->w_p_list = save_list;         // restore 'list'
1565  // Finish buffer cleanup before OptionSet can switch buffers.
1566  u_clearline(curbuf);
1567
1568  if (new_ts_str != NULL) {  // set the new tabstop
1569    const handle_T win_handle = curwin->handle;
1570    const handle_T buf_handle = curbuf->handle;
1571
1572    // If 'vartabstop' is in use or if the value given to retab has more
1573    // than one tabstop then update 'vartabstop'.
1574    if (tabstop_count(curbuf->b_p_vts_array) > 0 || tabstop_count(new_vts_array) > 1) {
1575      set_option_value(kOptVartabstop, CSTR_AS_OBJ(new_ts_str), OPT_LOCAL, true, NULL);
1576    } else {
1577      // 'vartabstop' wasn't in use and a single value was given to
1578      // retab then update 'tabstop'.
1579      set_option_value(kOptTabstop, INTEGER_OBJ(tabstop_first(new_vts_array)), OPT_LOCAL, true,
1580                       NULL);
1581    }
1582    xfree(new_vts_array);
1583    xfree(new_ts_str);
1584    // OptionSet may have left the command's window or buffer.
1585    if (curwin->handle != win_handle || curbuf->handle != buf_handle) {
1586      return;
1587    }
1588  }
1589  coladvance(curwin, curwin->w_curswant);
1590}
1591
1592/// Get indent level from 'indentexpr'.
1593int get_expr_indent(void)
1594{
1595  bool use_sandbox = was_set_insecurely(curwin, kOptIndentexpr, OPT_LOCAL);
1596  const sctx_T save_sctx = current_sctx;
1597
1598  // Save and restore cursor position and curswant, in case it was changed
1599  // * via :normal commands.
1600  pos_T save_pos = curwin->w_cursor;
1601  colnr_T save_curswant = curwin->w_curswant;
1602  bool save_set_curswant = curwin->w_set_curswant;
1603  set_vim_var_nr(VV_LNUM, (varnumber_T)curwin->w_cursor.lnum);
1604
1605  textlock++;
1606  current_sctx = curbuf->b_p_script_ctx[kBufOptIndentexpr];
1607
1608  int indent = eval_expr_option_number(&curbuf->b_p_inde, use_sandbox);
1609
1610  textlock--;
1611  current_sctx = save_sctx;
1612
1613  // Restore the cursor position so that 'indentexpr' doesn't need to.
1614  // Pretend to be in Insert mode, allow cursor past end of line for "o"
1615  // command.
1616  int save_State = State;
1617  State = MODE_INSERT;
1618  curwin->w_cursor = save_pos;
1619  curwin->w_curswant = save_curswant;
1620  curwin->w_set_curswant = save_set_curswant;
1621  check_cursor(curwin);
1622  State = save_State;
1623
1624  // Reset did_throw, unless 'debug' has "throw" and inside a try/catch.
1625  if (did_throw && (vim_strchr(p_debug, 't') == NULL || trylevel == 0)) {
1626    handle_did_throw();
1627    did_throw = false;
1628  }
1629
1630  // If there is an error, just keep the current indent.
1631  if (indent < 0) {
1632    indent = get_indent();
1633  }
1634
1635  return indent;
1636}
1637
1638// When 'p' is present in 'cpoptions, a Vi compatible method is used.
1639// The incompatible newer method is quite a bit better at indenting
1640// code in lisp-like languages than the traditional one; it's still
1641// mostly heuristics however -- Dirk van Deun, dirk@rave.org
1642
1643// TODO(unknown):
1644// Findmatch() should be adapted for lisp, also to make showmatch
1645// work correctly: now (v5.3) it seems all C/C++ oriented:
1646// - it does not recognize the #\( and #\) notations as character literals
1647// - it doesn't know about comments starting with a semicolon
1648// - it incorrectly interprets '(' as a character literal
1649// All this messes up get_lisp_indent in some rare cases.
1650// Update from Sergey Khorev:
1651// I tried to fix the first two issues.
1652int get_lisp_indent(void)
1653{
1654  pos_T *pos;
1655  pos_T paren;
1656  int amount;
1657
1658  pos_T realpos = curwin->w_cursor;
1659  curwin->w_cursor.col = 0;
1660
1661  if ((pos = findmatch(NULL, '(')) == NULL) {
1662    pos = findmatch(NULL, '[');
1663  } else {
1664    paren = *pos;
1665    pos = findmatch(NULL, '[');
1666
1667    if ((pos == NULL) || lt(*pos, paren)) {
1668      pos = &paren;
1669    }
1670  }
1671
1672  if (pos != NULL) {
1673    // Extra trick: Take the indent of the first previous non-white
1674    // line that is at the same () level.
1675    amount = -1;
1676    int parencount = 0;
1677
1678    while (--curwin->w_cursor.lnum >= pos->lnum) {
1679      if (linewhite(curwin->w_cursor.lnum)) {
1680        continue;
1681      }
1682
1683      for (char *that = get_cursor_line_ptr(); *that != NUL; that++) {
1684        if (*that == ';') {
1685          while (*(that + 1) != NUL) {
1686            that++;
1687          }
1688          continue;
1689        }
1690
1691        if (*that == '\\') {
1692          if (*(that + 1) != NUL) {
1693            that++;
1694          }
1695          continue;
1696        }
1697
1698        if ((*that == '"') && (*(that + 1) != NUL)) {
1699          while (*++that && *that != '"') {
1700            // Skipping escaped characters in the string
1701            if (*that == '\\') {
1702              if (*++that == NUL) {
1703                break;
1704              }
1705              if (that[1] == NUL) {
1706                that++;
1707                break;
1708              }
1709            }
1710          }
1711          if (*that == NUL) {
1712            break;
1713          }
1714        }
1715        if ((*that == '(') || (*that == '[')) {
1716          parencount++;
1717        } else if ((*that == ')') || (*that == ']')) {
1718          parencount--;
1719        }
1720      }
1721
1722      if (parencount == 0) {
1723        amount = get_indent();
1724        break;
1725      }
1726    }
1727
1728    if (amount == -1) {
1729      curwin->w_cursor.lnum = pos->lnum;
1730      curwin->w_cursor.col = pos->col;
1731      colnr_T col = pos->col;
1732
1733      char *line = get_cursor_line_ptr();
1734
1735      CharsizeArg csarg;
1736      CSType cstype = init_charsize_arg(&csarg, curwin, pos->lnum, line);
1737
1738      StrCharInfo sci = utf_ptr2StrCharInfo(line);
1739      amount = 0;
1740      while (*sci.ptr != NUL && col > 0) {
1741        ClusterInfo cli = utf_ClusterInfo(sci);
1742        amount += win_charsize(cstype, amount, sci.ptr, sci.chr.value, &csarg, cli.cells).width;
1743        sci = cli.next;
1744        col--;
1745      }
1746      char *that = sci.ptr;
1747
1748      // Some keywords require "body" indenting rules (the
1749      // non-standard-lisp ones are Scheme special forms):
1750      // (let ((a 1))    instead    (let ((a 1))
1751      //   (...))       of       (...))
1752      if (((*that == '(') || (*that == '[')) && lisp_match(that + 1)) {
1753        amount += 2;
1754      } else {
1755        if (*that != NUL) {
1756          that++;
1757          amount++;
1758        }
1759        colnr_T firsttry = amount;
1760
1761        while (ascii_iswhite(*that)) {
1762          amount += win_charsize(cstype, amount, that, (uint8_t)(*that), &csarg, 1).width;
1763          that++;
1764        }
1765
1766        if (*that && (*that != ';')) {
1767          // Not a comment line.
1768          // Test *that != '(' to accommodate first let/do
1769          // argument if it is more than one line.
1770          if ((*that != '(') && (*that != '[')) {
1771            firsttry++;
1772          }
1773
1774          parencount = 0;
1775
1776          CharInfo ci = utf_ptr2CharInfo(that);
1777          if (((ci.value != '"') && (ci.value != '\'') && (ci.value != '#')
1778               && ((ci.value < '0') || (ci.value > '9')))) {
1779            int quotecount = 0;
1780            while (*that && (!ascii_iswhite(ci.value) || quotecount || parencount)) {
1781              if (ci.value == '"') {
1782                quotecount = !quotecount;
1783              }
1784              if (((ci.value == '(') || (ci.value == '[')) && !quotecount) {
1785                parencount++;
1786              }
1787              if (((ci.value == ')') || (ci.value == ']')) && !quotecount) {
1788                parencount--;
1789              }
1790              if ((ci.value == '\\') && (*(that + 1) != NUL)) {
1791                ClusterInfo cli = utf_ClusterInfo((StrCharInfo){ that, ci });
1792                amount += win_charsize(cstype, amount, that, ci.value, &csarg, cli.cells).width;
1793                that = cli.next.ptr;
1794                ci = cli.next.chr;
1795              }
1796
1797              ClusterInfo cli = utf_ClusterInfo((StrCharInfo){ that, ci });
1798              amount += win_charsize(cstype, amount, that, ci.value, &csarg, cli.cells).width;
1799              that = cli.next.ptr;
1800              ci = cli.next.chr;
1801            }
1802          }
1803
1804          while (ascii_iswhite(*that)) {
1805            amount += win_charsize(cstype, amount, that, (uint8_t)(*that), &csarg, 1).width;
1806            that++;
1807          }
1808
1809          if (!*that || (*that == ';')) {
1810            amount = firsttry;
1811          }
1812        }
1813      }
1814    }
1815  } else {
1816    amount = 0;  // No matching '(' or '[' found, use zero indent.
1817  }
1818  curwin->w_cursor = realpos;
1819
1820  return amount;
1821}
1822
1823static int lisp_match(char *p)
1824{
1825  char buf[512];
1826  char *word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;
1827
1828  while (*word != NUL) {
1829    size_t len = copy_option_part(&word, buf, sizeof(buf), ",");
1830    if ((strncmp(buf, p, len) == 0) && ascii_iswhite_or_nul(p[len])) {
1831      return true;
1832    }
1833  }
1834  return false;
1835}
1836
1837/// Re-indent the current line, based on the current contents of it and the
1838/// surrounding lines. Fixing the cursor position seems really easy -- I'm very
1839/// confused what all the part that handles Control-T is doing that I'm not.
1840/// "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
1841void fixthisline(IndentGetter get_the_indent)
1842{
1843  int amount = get_the_indent();
1844
1845  if (amount < 0) {
1846    return;
1847  }
1848
1849  change_indent(INDENT_SET, amount, false, true);
1850  if (linewhite(curwin->w_cursor.lnum)) {
1851    Ins.did_ai = true;  // delete the indent if the line stays empty
1852  }
1853}
1854
1855/// Return true if 'indentexpr' should be used for Lisp indenting.
1856/// Caller may want to check 'autoindent'.
1857bool use_indentexpr_for_lisp(void)
1858{
1859  return curbuf->b_p_lisp
1860         && curbuf->b_p_inde.type != kCallbackNone
1861         && strcmp(curbuf->b_p_lop, "expr:1") == 0;
1862}
1863
1864/// Fix indent for 'lisp' and 'cindent'.
1865void fix_indent(void)
1866{
1867  if (p_paste) {
1868    return;  // no auto-indenting when 'paste' is set
1869  }
1870  if (curbuf->b_p_lisp && curbuf->b_p_ai) {
1871    if (use_indentexpr_for_lisp()) {
1872      do_c_expr_indent();
1873    } else {
1874      fixthisline(get_lisp_indent);
1875    }
1876  } else if (cindent_on()) {
1877    do_c_expr_indent();
1878  }
1879}
1880
1881/// "indent()" function
1882void f_indent(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1883{
1884  const linenr_T lnum = tv_get_lnum(argvars);
1885  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) {
1886    rettv->vval.v_number = get_indent_lnum(lnum);
1887  } else {
1888    rettv->vval.v_number = -1;
1889  }
1890}
1891
1892/// "lispindent(lnum)" function
1893void f_lispindent(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1894{
1895  const pos_T pos = curwin->w_cursor;
1896  const linenr_T lnum = tv_get_lnum(argvars);
1897  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) {
1898    curwin->w_cursor.lnum = lnum;
1899    rettv->vval.v_number = get_lisp_indent();
1900    curwin->w_cursor = pos;
1901  } else {
1902    rettv->vval.v_number = -1;
1903  }
1904}