robin/laufey

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

robinmerge: 8c77b5be50c50ab119

master
97.4 KiB3229 linesraw
1// vim: set fdm=marker fdl=1 fdc=3
2
3// fold.c: code for folding
4
5#include <assert.h>
6#include <inttypes.h>
7#include <stdbool.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include "klib/kvec.h"
13#include "nvim/api/extmark.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/helpers.h"
16#include "nvim/ascii_defs.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/buffer_updates.h"
19#include "nvim/change.h"
20#include "nvim/charset.h"
21#include "nvim/cursor.h"
22#include "nvim/decoration.h"
23#include "nvim/diff.h"
24#include "nvim/drawscreen.h"
25#include "nvim/errors.h"
26#include "nvim/eval.h"
27#include "nvim/eval/typval.h"
28#include "nvim/eval/vars.h"
29#include "nvim/ex_session.h"
30#include "nvim/extmark.h"
31#include "nvim/extmark_defs.h"
32#include "nvim/fold.h"
33#include "nvim/garray.h"
34#include "nvim/garray_defs.h"
35#include "nvim/gettext_defs.h"
36#include "nvim/globals.h"
37#include "nvim/indent.h"
38#include "nvim/mark.h"
39#include "nvim/mark_defs.h"
40#include "nvim/mbyte.h"
41#include "nvim/mcursor.h"
42#include "nvim/memline.h"
43#include "nvim/memory.h"
44#include "nvim/message.h"
45#include "nvim/move.h"
46#include "nvim/ops.h"
47#include "nvim/option_defs.h"
48#include "nvim/option_vars.h"
49#include "nvim/os/input.h"
50#include "nvim/plines.h"
51#include "nvim/pos_defs.h"
52#include "nvim/search.h"
53#include "nvim/state_defs.h"
54#include "nvim/strings.h"
55#include "nvim/syntax.h"
56#include "nvim/types_defs.h"
57#include "nvim/undo.h"
58#include "nvim/vim_defs.h"
59
60// local declarations. {{{1
61
62// The toplevel folds for each window are stored in the w_folds growarray.
63// Each toplevel fold can contain an array of second level folds in the
64// fd_nested growarray.
65// The info stored in both growarrays is the same: An array of fold_T.
66
67typedef struct {
68  linenr_T fd_top;              // first line of fold; for nested fold
69                                // relative to parent
70  linenr_T fd_len;              // number of lines in the fold
71  garray_T fd_nested;           // array of nested folds
72  char fd_flags;                // see below
73  TriState fd_small;            // kTrue, kFalse, or kNone: fold smaller than
74                                // 'foldminlines'; kNone applies to nested
75                                // folds too
76} fold_T;
77
78enum {
79  FD_OPEN = 0,    // fold is open (nested ones can be closed)
80  FD_CLOSED = 1,  // fold is closed
81  FD_LEVEL = 2,   // depends on 'foldlevel' (nested folds too)
82};
83
84#define MAX_LEVEL       20      // maximum fold depth
85
86// Define "fline_T", passed to get fold level for a line.
87typedef struct {
88  win_T *wp;              // window
89  linenr_T lnum;                // current line number
90  linenr_T off;                 // offset between lnum and real line number
91  linenr_T lnum_save;           // line nr used by foldUpdateIEMSRecurse()
92  int lvl;                      // current level (-1 for undefined)
93  int lvl_next;                 // level used for next line
94  int start;                    // number of folds that are forced to start at
95                                // this line.
96  int end;                      // level of fold that is forced to end below
97                                // this line
98  int had_end;                  // level of fold that is forced to end above
99                                // this line (copy of "end" of prev. line)
100} fline_T;
101
102// Flag is set when redrawing is needed.
103static bool fold_changed;
104
105// Function used by foldUpdateIEMSRecurse
106typedef void (*LevelGetter)(fline_T *);
107
108// static functions
109
110#include "fold.c.generated.h"
111static const char *e_nofold = N_("E490: No fold found");
112
113// While updating the folds lines between invalid_top and invalid_bot have an
114// undefined fold level.  Only used for the window currently being updated.
115static linenr_T invalid_top = 0;
116static linenr_T invalid_bot = 0;
117
118// When using 'foldexpr' we sometimes get the level of the next line, which
119// calls foldlevel() to get the level of the current line, which hasn't been
120// stored yet.  To get around this chicken-egg problem the level of the
121// previous line is stored here when available.  prev_lnum is zero when the
122// level is not available.
123static linenr_T prev_lnum = 0;
124static int prev_lnum_lvl = -1;
125
126// Flags used for "done" argument of setManualFold.
127#define DONE_NOTHING    0
128#define DONE_ACTION     1       // did close or open a fold
129#define DONE_FOLD       2       // did find a fold
130
131static size_t foldstartmarkerlen;
132static char *foldendmarker;
133static size_t foldendmarkerlen;
134
135//
136// Exported folding functions. {{{1
137//
138
139/// Copy that folding state from window "wp_from" to window "wp_to".
140void copyFoldingState(win_T *wp_from, win_T *wp_to)
141{
142  wp_to->w_fold_manual = wp_from->w_fold_manual;
143  wp_to->w_foldinvalid = wp_from->w_foldinvalid;
144  cloneFoldGrowArray(&wp_from->w_folds, &wp_to->w_folds);
145}
146
147/// True if there may be folded lines in window `win`. Decides how closed folds are treated: if
148/// false, operations/motions act as if all folds were open.
149int hasAnyFolding(win_T *win)
150{
151  return !win->w_buffer->terminal && win->w_p_fen && !mc_replaying()
152         && (!foldmethodIsManual(win) || !GA_EMPTY(&win->w_folds));
153}
154
155/// When returning true, *firstp and *lastp are set to the first and last
156/// lnum of the sequence of folded lines (skipped when NULL).
157///
158/// @return  true if line "lnum" in window "win" is part of a closed fold.
159bool hasFolding(win_T *win, linenr_T lnum, linenr_T *firstp, linenr_T *lastp)
160{
161  return hasFoldingWin(win, lnum, firstp, lastp, true, NULL);
162}
163
164/// Search folds starting at lnum
165/// @param lnum first line to search
166/// @param[out] first first line of fold containing lnum
167/// @param[out] lastp last line with a fold
168/// @param cache when true: use cached values of window
169/// @param[out] infop where to store fold info
170///
171/// @return true if range contains folds
172bool hasFoldingWin(win_T *const win, const linenr_T lnum, linenr_T *const firstp,
173                   linenr_T *const lastp, const bool cache, foldinfo_T *const infop)
174{
175  checkupdate(win);
176
177  // Return quickly when there is no folding at all in this window.
178  if (!hasAnyFolding(win)) {
179    if (infop != NULL) {
180      infop->fi_level = 0;
181    }
182    return false;
183  }
184
185  bool had_folded = false;
186  linenr_T first = 0;
187  linenr_T last = 0;
188
189  if (cache) {
190    // First look in cached info for displayed lines.  This is probably
191    // the fastest, but it can only be used if the entry is still valid.
192    const int x = find_wl_entry(win, lnum);
193    if (x >= 0) {
194      first = win->w_lines[x].wl_lnum;
195      last = win->w_lines[x].wl_foldend;
196      had_folded = win->w_lines[x].wl_folded;
197    }
198  }
199
200  linenr_T lnum_rel = lnum;
201  int level = 0;
202  int low_level = 0;
203  fold_T *fp;
204  bool maybe_small = false;
205  bool use_level = false;
206
207  if (first == 0) {
208    // Recursively search for a fold that contains "lnum".
209    garray_T *gap = &win->w_folds;
210    while (true) {
211      if (!foldFind(gap, lnum_rel, &fp)) {
212        break;
213      }
214
215      // Remember lowest level of fold that starts in "lnum".
216      if (lnum_rel == fp->fd_top && low_level == 0) {
217        low_level = level + 1;
218      }
219
220      first += fp->fd_top;
221      last += fp->fd_top;
222
223      // is this fold closed?
224      had_folded = check_closed(win, fp, &use_level, level,
225                                &maybe_small, lnum - lnum_rel);
226      if (had_folded) {
227        // Fold closed: Set last and quit loop.
228        last += fp->fd_len - 1;
229        break;
230      }
231
232      // Fold found, but it's open: Check nested folds.  Line number is
233      // relative to containing fold.
234      gap = &fp->fd_nested;
235      lnum_rel -= fp->fd_top;
236      level++;
237    }
238  }
239
240  if (!had_folded) {
241    if (infop != NULL) {
242      infop->fi_level = level;
243      infop->fi_lnum = lnum - lnum_rel;
244      infop->fi_low_level = low_level == 0 ? level : low_level;
245    }
246    return false;
247  }
248
249  last = MIN(last, win->w_buffer->b_ml.ml_line_count);
250  if (lastp != NULL) {
251    *lastp = last;
252  }
253  if (firstp != NULL) {
254    *firstp = first;
255  }
256  if (infop != NULL) {
257    infop->fi_level = level + 1;
258    infop->fi_lnum = first;
259    infop->fi_low_level = low_level == 0 ? level + 1 : low_level;
260  }
261  return true;
262}
263
264/// @return  fold level at line number "lnum" in the current window.
265static int foldLevel(linenr_T lnum)
266{
267  // While updating the folds lines between invalid_top and invalid_bot have
268  // an undefined fold level.  Otherwise update the folds first.
269  if (invalid_top == 0) {
270    checkupdate(curwin);
271  } else if (lnum == prev_lnum && prev_lnum_lvl >= 0) {
272    return prev_lnum_lvl;
273  } else if (lnum >= invalid_top && lnum <= invalid_bot) {
274    return -1;
275  }
276
277  // Return quickly when there is no folding at all in this window.
278  if (!hasAnyFolding(curwin)) {
279    return 0;
280  }
281
282  return foldLevelWin(curwin, lnum);
283}
284
285/// Low level function to check if a line is folded.  Doesn't use any caching.
286///
287/// @return  true if line is folded or,
288///          false if line is not folded.
289bool lineFolded(win_T *const win, const linenr_T lnum)
290{
291  return fold_info(win, lnum).fi_lines != 0;
292}
293
294/// Count the number of lines that are folded at line number "lnum".
295/// Normally "lnum" is the first line of a possible fold, and the returned
296/// number is the number of lines in the fold.
297/// Doesn't use caching from the displayed window.
298///
299/// @return with the fold level info.
300///         fi_lines = number of folded lines from "lnum",
301///                    or 0 if line is not folded.
302foldinfo_T fold_info(win_T *win, linenr_T lnum)
303{
304  foldinfo_T info;
305  linenr_T last;
306
307  if (hasFoldingWin(win, lnum, NULL, &last, false, &info)) {
308    info.fi_lines = (last - lnum + 1);
309  } else {
310    info.fi_lines = 0;
311  }
312
313  return info;
314}
315
316/// @return  true if 'foldmethod' is "manual"
317bool foldmethodIsManual(win_T *wp)
318{
319  return (wp->w_p_fdm[0] != NUL && wp->w_p_fdm[3] == 'u');
320}
321
322/// @return  true if 'foldmethod' is "indent"
323bool foldmethodIsIndent(win_T *wp)
324{
325  return wp->w_p_fdm[0] == 'i';
326}
327
328/// @return  true if 'foldmethod' is "expr"
329bool foldmethodIsExpr(win_T *wp)
330{
331  return (wp->w_p_fdm[0] != NUL && wp->w_p_fdm[1] == 'x');
332}
333
334/// @return  true if 'foldmethod' is "marker"
335bool foldmethodIsMarker(win_T *wp)
336{
337  return (wp->w_p_fdm[0] != NUL && wp->w_p_fdm[2] == 'r');
338}
339
340/// @return  true if 'foldmethod' is "syntax"
341bool foldmethodIsSyntax(win_T *wp)
342{
343  return wp->w_p_fdm[0] == 's';
344}
345
346/// @return  true if 'foldmethod' is "diff"
347bool foldmethodIsDiff(win_T *wp)
348{
349  return wp->w_p_fdm[0] == 'd';
350}
351
352/// Close fold for current window at position "pos".
353/// Repeat "count" times.
354void closeFold(pos_T pos, int count)
355{
356  setFoldRepeat(pos, count, false);
357}
358
359/// Close fold for current window at position `pos` recursively.
360void closeFoldRecurse(pos_T pos)
361{
362  setManualFold(pos, false, true, NULL);
363}
364
365/// Open or Close folds for current window in lines "first" to "last".
366/// Used for "zo", "zO", "zc" and "zC" in Visual mode.
367///
368/// @param opening     true to open, false to close
369/// @param recurse     true to do it recursively
370/// @param had_visual  true when Visual selection used
371void opFoldRange(pos_T firstpos, pos_T lastpos, int opening, int recurse, bool had_visual)
372{
373  int done = DONE_NOTHING;              // avoid error messages
374  linenr_T first = firstpos.lnum;
375  linenr_T last = lastpos.lnum;
376  linenr_T lnum_next;
377
378  for (linenr_T lnum = first; lnum <= last; lnum = lnum_next + 1) {
379    pos_T temp = { lnum, 0, 0 };
380    lnum_next = lnum;
381    // Opening one level only: next fold to open is after the one going to
382    // be opened.
383    if (opening && !recurse) {
384      hasFolding(curwin, lnum, NULL, &lnum_next);
385    }
386    setManualFold(temp, opening, recurse, &done);
387    // Closing one level only: next line to close a fold is after just
388    // closed fold.
389    if (!opening && !recurse) {
390      hasFolding(curwin, lnum, NULL, &lnum_next);
391    }
392  }
393  if (done == DONE_NOTHING) {
394    emsg(_(e_nofold));
395  }
396  // Force a redraw to remove the Visual highlighting.
397  if (had_visual) {
398    redraw_curbuf_later(UPD_INVERTED);
399  }
400}
401
402/// Open fold for current window at position "pos".
403/// Repeat "count" times.
404void openFold(pos_T pos, int count)
405{
406  setFoldRepeat(pos, count, true);
407}
408
409/// Open fold for current window at position `pos` recursively.
410void openFoldRecurse(pos_T pos)
411{
412  setManualFold(pos, true, true, NULL);
413}
414
415/// Open folds until the cursor line is not in a closed fold.
416void foldOpenCursor(void)
417{
418  checkupdate(curwin);
419  if (hasAnyFolding(curwin)) {
420    while (true) {
421      int done = DONE_NOTHING;
422      setManualFold(curwin->w_cursor, true, false, &done);
423      if (!(done & DONE_ACTION)) {
424        break;
425      }
426    }
427  }
428}
429
430/// Set new foldlevel for current window.
431void newFoldLevel(void)
432{
433  newFoldLevelWin(curwin);
434
435  if (foldmethodIsDiff(curwin) && curwin->w_p_scb) {
436    // Set the same foldlevel in other windows in diff mode.
437    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
438      if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb) {
439        wp->w_p_fdl = curwin->w_p_fdl;
440        newFoldLevelWin(wp);
441      }
442    }
443  }
444}
445
446static void newFoldLevelWin(win_T *wp)
447{
448  checkupdate(wp);
449  if (wp->w_fold_manual) {
450    // Set all flags for the first level of folds to FD_LEVEL.  Following
451    // manual open/close will then change the flags to FD_OPEN or
452    // FD_CLOSED for those folds that don't use 'foldlevel'.
453    fold_T *fp = (fold_T *)wp->w_folds.ga_data;
454    for (int i = 0; i < wp->w_folds.ga_len; i++) {
455      fp[i].fd_flags = FD_LEVEL;
456    }
457    wp->w_fold_manual = false;
458  }
459  changed_window_setting(wp);
460}
461
462/// Apply 'foldlevel' to all folds that don't contain the cursor.
463void foldCheckClose(void)
464{
465  if (*p_fcl == NUL) {
466    return;
467  }
468
469  // 'foldclose' can only be "all" right now
470  checkupdate(curwin);
471  if (checkCloseRec(&curwin->w_folds, curwin->w_cursor.lnum,
472                    (int)curwin->w_p_fdl)) {
473    changed_window_setting(curwin);
474  }
475}
476
477static bool checkCloseRec(garray_T *gap, linenr_T lnum, int level)
478{
479  bool retval = false;
480
481  fold_T *fp = (fold_T *)gap->ga_data;
482  for (int i = 0; i < gap->ga_len; i++) {
483    // Only manually opened folds may need to be closed.
484    if (fp[i].fd_flags == FD_OPEN) {
485      if (level <= 0 && (lnum < fp[i].fd_top
486                         || lnum >= fp[i].fd_top + fp[i].fd_len)) {
487        fp[i].fd_flags = FD_LEVEL;
488        retval = true;
489      } else {
490        retval |= checkCloseRec(&fp[i].fd_nested, lnum - fp[i].fd_top,
491                                level - 1);
492      }
493    }
494  }
495  return retval;
496}
497
498/// @return  true if it's allowed to manually create or delete a fold or,
499///          give an error message and return false if not.
500int foldManualAllowed(bool create)
501{
502  if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) {
503    return true;
504  }
505  if (create) {
506    emsg(_("E350: Cannot create fold with current 'foldmethod'"));
507  } else {
508    emsg(_("E351: Cannot delete fold with current 'foldmethod'"));
509  }
510  return false;
511}
512
513/// Create a fold from line "start" to line "end" (inclusive) in the current
514/// window.
515void foldCreate(win_T *wp, pos_T start, pos_T end)
516{
517  bool use_level = false;
518  bool closed = false;
519  int level = 0;
520  pos_T start_rel = start;
521  pos_T end_rel = end;
522
523  if (start.lnum > end.lnum) {
524    // reverse the range
525    end = start_rel;
526    start = end_rel;
527    start_rel = start;
528    end_rel = end;
529  }
530
531  // When 'foldmethod' is "marker" add markers, which creates the folds.
532  if (foldmethodIsMarker(wp)) {
533    foldCreateMarkers(wp, start, end);
534    return;
535  }
536
537  checkupdate(wp);
538
539  int i;
540
541  // Find the place to insert the new fold
542  garray_T *gap = &wp->w_folds;
543  if (gap->ga_len == 0) {
544    i = 0;
545  } else {
546    fold_T *fp;
547    while (true) {
548      if (!foldFind(gap, start_rel.lnum, &fp)) {
549        break;
550      }
551      if (fp->fd_top + fp->fd_len > end_rel.lnum) {
552        // New fold is completely inside this fold: Go one level deeper.
553        gap = &fp->fd_nested;
554        start_rel.lnum -= fp->fd_top;
555        end_rel.lnum -= fp->fd_top;
556        if (use_level || fp->fd_flags == FD_LEVEL) {
557          use_level = true;
558          if (level >= wp->w_p_fdl) {
559            closed = true;
560          }
561        } else if (fp->fd_flags == FD_CLOSED) {
562          closed = true;
563        }
564        level++;
565      } else {
566        // This fold and new fold overlap: Insert here and move some folds
567        // inside the new fold.
568        break;
569      }
570    }
571    if (gap->ga_len == 0) {
572      i = 0;
573    } else {
574      i = (int)(fp - (fold_T *)gap->ga_data);
575    }
576  }
577
578  ga_grow(gap, 1);
579  {
580    fold_T *fp = (fold_T *)gap->ga_data + i;
581    garray_T fold_ga;
582    ga_init(&fold_ga, (int)sizeof(fold_T), 10);
583
584    // Count number of folds that will be contained in the new fold.
585    int cont;
586    for (cont = 0; i + cont < gap->ga_len; cont++) {
587      if (fp[cont].fd_top > end_rel.lnum) {
588        break;
589      }
590    }
591    if (cont > 0) {
592      ga_grow(&fold_ga, cont);
593      // If the first fold starts before the new fold, let the new fold
594      // start there.  Otherwise the existing fold would change.
595      start_rel.lnum = MIN(start_rel.lnum, fp->fd_top);
596
597      // When last contained fold isn't completely contained, adjust end
598      // of new fold.
599      end_rel.lnum = MAX(end_rel.lnum, fp[cont - 1].fd_top + fp[cont - 1].fd_len - 1);
600      // Move contained folds to inside new fold
601      memmove(fold_ga.ga_data, fp, sizeof(fold_T) * (size_t)cont);
602      fold_ga.ga_len += cont;
603      i += cont;
604
605      // Adjust line numbers in contained folds to be relative to the
606      // new fold.
607      for (int j = 0; j < cont; j++) {
608        ((fold_T *)fold_ga.ga_data)[j].fd_top -= start_rel.lnum;
609      }
610    }
611    // Move remaining entries to after the new fold.
612    if (i < gap->ga_len) {
613      memmove(fp + 1, (fold_T *)gap->ga_data + i,
614              sizeof(fold_T) * (size_t)(gap->ga_len - i));
615    }
616    gap->ga_len = gap->ga_len + 1 - cont;
617
618    // insert new fold
619    fp->fd_nested = fold_ga;
620    fp->fd_top = start_rel.lnum;
621    fp->fd_len = end_rel.lnum - start_rel.lnum + 1;
622
623    // We want the new fold to be closed.  If it would remain open because
624    // of using 'foldlevel', need to adjust fd_flags of containing folds.
625    if (use_level && !closed && level < wp->w_p_fdl) {
626      closeFold(start, 1);
627    }
628    if (!use_level) {
629      wp->w_fold_manual = true;
630    }
631    fp->fd_flags = FD_CLOSED;
632    fp->fd_small = kNone;
633
634    // redraw
635    changed_window_setting(wp);
636  }
637}
638
639/// @param start delete all folds from start to end when not 0
640/// @param end delete all folds from start to end when not 0
641/// @param recursive delete recursively if true
642/// @param had_visual true when Visual selection used
643void deleteFold(win_T *const wp, const linenr_T start, const linenr_T end, const int recursive,
644                const bool had_visual)
645{
646  fold_T *found_fp = NULL;
647  linenr_T found_off = 0;
648  bool maybe_small = false;
649  int level = 0;
650  linenr_T lnum = start;
651  bool did_one = false;
652  linenr_T first_lnum = MAXLNUM;
653  linenr_T last_lnum = 0;
654
655  checkupdate(wp);
656
657  while (lnum <= end) {
658    // Find the deepest fold for "start".
659    garray_T *gap = &wp->w_folds;
660    garray_T *found_ga = NULL;
661    linenr_T lnum_off = 0;
662    bool use_level = false;
663    while (true) {
664      fold_T *fp;
665      if (!foldFind(gap, lnum - lnum_off, &fp)) {
666        break;
667      }
668      // lnum is inside this fold, remember info
669      found_ga = gap;
670      found_fp = fp;
671      found_off = lnum_off;
672
673      // if "lnum" is folded, don't check nesting
674      if (check_closed(wp, fp, &use_level, level,
675                       &maybe_small, lnum_off)) {
676        break;
677      }
678
679      // check nested folds
680      gap = &fp->fd_nested;
681      lnum_off += fp->fd_top;
682      level++;
683    }
684    if (found_ga == NULL) {
685      lnum++;
686    } else {
687      lnum = found_fp->fd_top + found_fp->fd_len + found_off;
688
689      if (foldmethodIsManual(wp)) {
690        deleteFoldEntry(wp, found_ga,
691                        (int)(found_fp - (fold_T *)found_ga->ga_data),
692                        recursive);
693      } else {
694        first_lnum = MIN(first_lnum, found_fp->fd_top + found_off);
695        last_lnum = MAX(last_lnum, lnum);
696        if (!did_one) {
697          parseMarker(wp);
698        }
699        deleteFoldMarkers(wp, found_fp, recursive, found_off);
700      }
701      did_one = true;
702
703      // redraw window
704      changed_window_setting(wp);
705    }
706  }
707  if (!did_one) {
708    emsg(_(e_nofold));
709    // Force a redraw to remove the Visual highlighting.
710    if (had_visual) {
711      redraw_buf_later(wp->w_buffer, UPD_INVERTED);
712    }
713  } else {
714    // Deleting markers may make cursor column invalid
715    check_cursor_col(wp);
716  }
717
718  if (last_lnum > 0) {
719    changed_lines(wp->w_buffer, first_lnum, 0, last_lnum, 0, false);
720
721    // send one nvim_buf_lines_event at the end
722    // last_lnum is the line *after* the last line of the outermost fold
723    // that was modified. Note also that deleting a fold might only require
724    // the modification of the *first* line of the fold, but we send through a
725    // notification that includes every line that was part of the fold
726    int64_t num_changed = last_lnum - first_lnum;
727    buf_updates_send_changes(wp->w_buffer, first_lnum, num_changed, num_changed);
728  }
729}
730
731/// Remove all folding for window "win".
732void clearFolding(win_T *win)
733{
734  deleteFoldRecurse(win->w_buffer, &win->w_folds);
735  win->w_foldinvalid = false;
736}
737
738/// Update folds for changes in the buffer of a window.
739/// Note that inserted/deleted lines must have already been taken care of by
740/// calling foldMarkAdjust().
741/// The changes in lines from top to bot (inclusive).
742void foldUpdate(win_T *wp, linenr_T top, linenr_T bot)
743{
744  if (disable_fold_update || (State & MODE_INSERT && !foldmethodIsIndent(wp))) {
745    return;
746  }
747
748  if (need_diff_redraw) {
749    // will update later
750    return;
751  }
752
753  if (wp->w_folds.ga_len > 0) {
754    // Mark all folds from top to bot (or bot to top) as maybe-small.
755    linenr_T maybe_small_start = MIN(top, bot);
756    linenr_T maybe_small_end = MAX(top, bot);
757
758    fold_T *fp;
759    foldFind(&wp->w_folds, maybe_small_start, &fp);
760    while (fp < (fold_T *)wp->w_folds.ga_data + wp->w_folds.ga_len
761           && fp->fd_top <= maybe_small_end) {
762      fp->fd_small = kNone;
763      fp++;
764    }
765  }
766
767  if (foldmethodIsIndent(wp)
768      || foldmethodIsExpr(wp)
769      || foldmethodIsMarker(wp)
770      || foldmethodIsDiff(wp)
771      || foldmethodIsSyntax(wp)) {
772    int save_got_int = got_int;
773
774    // reset got_int here, otherwise it won't work
775    got_int = false;
776    foldUpdateIEMS(wp, top, bot);
777    got_int |= save_got_int;
778  }
779}
780
781/// Updates folds when leaving insert-mode.
782void foldUpdateAfterInsert(void)
783{
784  if (foldmethodIsManual(curwin)  // foldmethod=manual: No need to update.
785      // These foldmethods are too slow, do not auto-update on insert-leave.
786      || foldmethodIsSyntax(curwin) || foldmethodIsExpr(curwin)) {
787    return;
788  }
789
790  foldUpdateAll(curwin);
791  foldOpenCursor();
792}
793
794/// Update all lines in a window for folding.
795/// Used when a fold setting changes or after reloading the buffer.
796/// The actual updating is postponed until fold info is used, to avoid doing
797/// every time a setting is changed or a syntax item is added.
798void foldUpdateAll(win_T *win)
799{
800  win->w_foldinvalid = true;
801  redraw_later(win, UPD_NOT_VALID);
802}
803
804/// If "updown" is false: Move to the start or end of the fold.
805/// If "updown" is true: move to fold at the same level.
806/// @return FAIL if not moved.
807///
808/// @param dir  FORWARD or BACKWARD
809int foldMoveTo(const bool updown, const int dir, const int count)
810{
811  int retval = FAIL;
812  fold_T *fp;
813
814  checkupdate(curwin);
815
816  // Repeat "count" times.
817  for (int n = 0; n < count; n++) {
818    // Find nested folds.  Stop when a fold is closed.  The deepest fold
819    // that moves the cursor is used.
820    linenr_T lnum_off = 0;
821    garray_T *gap = &curwin->w_folds;
822    if (gap->ga_len == 0) {
823      break;
824    }
825    bool use_level = false;
826    bool maybe_small = false;
827    linenr_T lnum_found = curwin->w_cursor.lnum;
828    int level = 0;
829    bool last = false;
830    while (true) {
831      if (!foldFind(gap, curwin->w_cursor.lnum - lnum_off, &fp)) {
832        if (!updown || gap->ga_len == 0) {
833          break;
834        }
835
836        // When moving up, consider a fold above the cursor; when
837        // moving down consider a fold below the cursor.
838        if (dir == FORWARD) {
839          if (fp - (fold_T *)gap->ga_data >= gap->ga_len) {
840            break;
841          }
842          fp--;
843        } else {
844          if (fp == (fold_T *)gap->ga_data) {
845            break;
846          }
847        }
848        // don't look for contained folds, they will always move
849        // the cursor too far.
850        last = true;
851      }
852
853      if (!last) {
854        // Check if this fold is closed.
855        if (check_closed(curwin, fp, &use_level, level,
856                         &maybe_small, lnum_off)) {
857          last = true;
858        }
859
860        // "[z" and "]z" stop at closed fold
861        if (last && !updown) {
862          break;
863        }
864      }
865
866      if (updown) {
867        if (dir == FORWARD) {
868          // to start of next fold if there is one
869          if (fp + 1 - (fold_T *)gap->ga_data < gap->ga_len) {
870            linenr_T lnum = fp[1].fd_top + lnum_off;
871            if (lnum > curwin->w_cursor.lnum) {
872              lnum_found = lnum;
873            }
874          }
875        } else {
876          // to end of previous fold if there is one
877          if (fp > (fold_T *)gap->ga_data) {
878            linenr_T lnum = fp[-1].fd_top + lnum_off + fp[-1].fd_len - 1;
879            if (lnum < curwin->w_cursor.lnum) {
880              lnum_found = lnum;
881            }
882          }
883        }
884      } else {
885        // Open fold found, set cursor to its start/end and then check
886        // nested folds.
887        if (dir == FORWARD) {
888          linenr_T lnum = fp->fd_top + lnum_off + fp->fd_len - 1;
889          if (lnum > curwin->w_cursor.lnum) {
890            lnum_found = lnum;
891          }
892        } else {
893          linenr_T lnum = fp->fd_top + lnum_off;
894          if (lnum < curwin->w_cursor.lnum) {
895            lnum_found = lnum;
896          }
897        }
898      }
899
900      if (last) {
901        break;
902      }
903
904      // Check nested folds (if any).
905      gap = &fp->fd_nested;
906      lnum_off += fp->fd_top;
907      level++;
908    }
909    if (lnum_found != curwin->w_cursor.lnum) {
910      if (retval == FAIL) {
911        setpcmark();
912      }
913      curwin->w_cursor.lnum = lnum_found;
914      curwin->w_cursor.col = 0;
915      retval = OK;
916    } else {
917      break;
918    }
919  }
920
921  return retval;
922}
923
924/// Init the fold info in a new window.
925void foldInitWin(win_T *new_win)
926{
927  ga_init(&new_win->w_folds, (int)sizeof(fold_T), 10);
928}
929
930/// Find an entry in the win->w_lines[] array for buffer line "lnum".
931/// Only valid entries are considered (for entries where wl_valid is false the
932/// line number can be wrong).
933///
934/// @return  index of entry or -1 if not found.
935int find_wl_entry(win_T *win, linenr_T lnum)
936{
937  for (int i = 0; i < win->w_lines_valid; i++) {
938    if (win->w_lines[i].wl_valid) {
939      if (lnum < win->w_lines[i].wl_lnum) {
940        return -1;
941      }
942      if (lnum <= win->w_lines[i].wl_foldend) {
943        return i;
944      }
945    }
946  }
947  return -1;
948}
949
950/// Adjust the Visual area to include any fold at the start or end completely.
951void foldAdjustVisual(void)
952{
953  if (!Visual.active || !hasAnyFolding(curwin)) {
954    return;
955  }
956
957  pos_T *start, *end;
958
959  if (ltoreq(Visual.start, curwin->w_cursor)) {
960    start = &Visual.start;
961    end = &curwin->w_cursor;
962  } else {
963    start = &curwin->w_cursor;
964    end = &Visual.start;
965  }
966  if (hasFolding(curwin, start->lnum, &start->lnum, NULL)) {
967    start->col = 0;
968  }
969
970  if (!hasFolding(curwin, end->lnum, NULL, &end->lnum)) {
971    return;
972  }
973
974  end->col = ml_get_len(end->lnum);
975  if (end->col > 0 && *p_sel == 'o') {
976    end->col--;
977  }
978  // prevent cursor from moving on the trail byte
979  mb_adjust_cursor();
980}
981
982/// Move the cursor to the first line of a closed fold.
983void foldAdjustCursor(win_T *wp)
984{
985  hasFolding(wp, wp->w_cursor.lnum, &wp->w_cursor.lnum, NULL);
986}
987
988// Internal functions for "fold_T" {{{1
989/// Will "clone" (i.e deep copy) a garray_T of folds.
990void cloneFoldGrowArray(garray_T *from, garray_T *to)
991{
992  ga_init(to, from->ga_itemsize, from->ga_growsize);
993
994  if (GA_EMPTY(from)) {
995    return;
996  }
997
998  ga_grow(to, from->ga_len);
999
1000  fold_T *from_p = (fold_T *)from->ga_data;
1001  fold_T *to_p = (fold_T *)to->ga_data;
1002
1003  for (int i = 0; i < from->ga_len; i++) {
1004    to_p->fd_top = from_p->fd_top;
1005    to_p->fd_len = from_p->fd_len;
1006    to_p->fd_flags = from_p->fd_flags;
1007    to_p->fd_small = from_p->fd_small;
1008    cloneFoldGrowArray(&from_p->fd_nested, &to_p->fd_nested);
1009    to->ga_len++;
1010    from_p++;
1011    to_p++;
1012  }
1013}
1014
1015/// Search for line "lnum" in folds of growarray "gap".
1016/// Set "*fpp" to the fold struct for the fold that contains "lnum" or
1017/// the first fold below it (careful: it can be beyond the end of the array!).
1018///
1019/// @return  false when there is no fold that contains "lnum".
1020static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp)
1021{
1022  if (gap->ga_len == 0) {
1023    *fpp = NULL;
1024    return false;
1025  }
1026
1027  // Perform a binary search.
1028  // "low" is lowest index of possible match.
1029  // "high" is highest index of possible match.
1030  fold_T *fp = (fold_T *)gap->ga_data;
1031  linenr_T low = 0;
1032  linenr_T high = gap->ga_len - 1;
1033  while (low <= high) {
1034    linenr_T i = (low + high) / 2;
1035    if (fp[i].fd_top > lnum) {
1036      // fold below lnum, adjust high
1037      high = i - 1;
1038    } else if (fp[i].fd_top + fp[i].fd_len <= lnum) {
1039      // fold above lnum, adjust low
1040      low = i + 1;
1041    } else {
1042      // lnum is inside this fold
1043      *fpp = fp + i;
1044      return true;
1045    }
1046  }
1047  *fpp = fp + low;
1048  return false;
1049}
1050
1051/// @return  fold level at line number "lnum" in window "wp".
1052static int foldLevelWin(win_T *wp, linenr_T lnum)
1053{
1054  fold_T *fp;
1055  linenr_T lnum_rel = lnum;
1056  int level = 0;
1057
1058  // Recursively search for a fold that contains "lnum".
1059  garray_T *gap = &wp->w_folds;
1060  while (true) {
1061    if (!foldFind(gap, lnum_rel, &fp)) {
1062      break;
1063    }
1064    // Check nested folds.  Line number is relative to containing fold.
1065    gap = &fp->fd_nested;
1066    lnum_rel -= fp->fd_top;
1067    level++;
1068  }
1069
1070  return level;
1071}
1072
1073/// Check if the folds in window "wp" are invalid and update them if needed.
1074static void checkupdate(win_T *wp)
1075{
1076  if (!wp->w_foldinvalid) {
1077    return;
1078  }
1079
1080  foldUpdate(wp, 1, (linenr_T)MAXLNUM);     // will update all
1081  wp->w_foldinvalid = false;
1082}
1083
1084/// Open or close fold for current window at position `pos`.
1085/// Repeat "count" times.
1086static void setFoldRepeat(pos_T pos, int count, int do_open)
1087{
1088  for (int n = 0; n < count; n++) {
1089    int done = DONE_NOTHING;
1090    setManualFold(pos, do_open, false, &done);
1091    if (!(done & DONE_ACTION)) {
1092      // Only give an error message when no fold could be opened.
1093      if (n == 0 && !(done & DONE_FOLD)) {
1094        emsg(_(e_nofold));
1095      }
1096      break;
1097    }
1098  }
1099}
1100
1101/// Open or close the fold in the current window which contains "lnum".
1102/// Also does this for other windows in diff mode when needed.
1103///
1104/// @param opening  true when opening, false when closing
1105/// @param recurse  true when closing/opening recursive
1106static linenr_T setManualFold(pos_T pos, bool opening, bool recurse, int *donep)
1107{
1108  if (foldmethodIsDiff(curwin) && curwin->w_p_scb) {
1109    linenr_T dlnum;
1110
1111    // Do the same operation in other windows in diff mode.  Calculate the
1112    // line number from the diffs.
1113    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1114      if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb) {
1115        dlnum = diff_lnum_win(curwin->w_cursor.lnum, wp);
1116        if (dlnum != 0) {
1117          setManualFoldWin(wp, dlnum, opening, recurse, NULL);
1118        }
1119      }
1120    }
1121  }
1122
1123  return setManualFoldWin(curwin, pos.lnum, opening, recurse, donep);
1124}
1125
1126/// Open or close the fold in window "wp" which contains "lnum".
1127/// "donep", when not NULL, points to flag that is set to DONE_FOLD when some
1128/// fold was found and to DONE_ACTION when some fold was opened or closed.
1129/// When "donep" is NULL give an error message when no fold was found for
1130/// "lnum", but only if "wp" is "curwin".
1131///
1132/// @param opening  true when opening, false when closing
1133/// @param recurse  true when closing/opening recursive
1134///
1135/// @return         the line number of the next line that could be closed.
1136///                 It's only valid when "opening" is true!
1137static linenr_T setManualFoldWin(win_T *wp, linenr_T lnum, bool opening, bool recurse, int *donep)
1138{
1139  fold_T *fp;
1140  fold_T *fp2;
1141  fold_T *found = NULL;
1142  int level = 0;
1143  bool use_level = false;
1144  bool found_fold = false;
1145  linenr_T next = MAXLNUM;
1146  linenr_T off = 0;
1147  int done = 0;
1148
1149  checkupdate(wp);
1150
1151  // Find the fold, open or close it.
1152  garray_T *gap = &wp->w_folds;
1153  while (true) {
1154    if (!foldFind(gap, lnum, &fp)) {
1155      // If there is a following fold, continue there next time.
1156      if (fp != NULL && fp < (fold_T *)gap->ga_data + gap->ga_len) {
1157        next = fp->fd_top + off;
1158      }
1159      break;
1160    }
1161
1162    // lnum is inside this fold
1163    found_fold = true;
1164
1165    // If there is a following fold, continue there next time.
1166    if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len) {
1167      next = fp[1].fd_top + off;
1168    }
1169
1170    // Change from level-dependent folding to manual.
1171    if (use_level || fp->fd_flags == FD_LEVEL) {
1172      use_level = true;
1173      fp->fd_flags = level >= wp->w_p_fdl ? FD_CLOSED : FD_OPEN;
1174      fp2 = (fold_T *)fp->fd_nested.ga_data;
1175      for (int j = 0; j < fp->fd_nested.ga_len; j++) {
1176        fp2[j].fd_flags = FD_LEVEL;
1177      }
1178    }
1179
1180    // Simple case: Close recursively means closing the fold.
1181    if (!opening && recurse) {
1182      if (fp->fd_flags != FD_CLOSED) {
1183        done |= DONE_ACTION;
1184        fp->fd_flags = FD_CLOSED;
1185      }
1186    } else if (fp->fd_flags == FD_CLOSED) {
1187      // When opening, open topmost closed fold.
1188      if (opening) {
1189        fp->fd_flags = FD_OPEN;
1190        done |= DONE_ACTION;
1191        if (recurse) {
1192          foldOpenNested(fp);
1193        }
1194      }
1195      break;
1196    }
1197
1198    // fold is open, check nested folds
1199    found = fp;
1200    gap = &fp->fd_nested;
1201    lnum -= fp->fd_top;
1202    off += fp->fd_top;
1203    level++;
1204  }
1205  if (found_fold) {
1206    // When closing and not recurse, close deepest open fold.
1207    if (!opening && found != NULL) {
1208      found->fd_flags = FD_CLOSED;
1209      done |= DONE_ACTION;
1210    }
1211    wp->w_fold_manual = true;
1212    if (done & DONE_ACTION) {
1213      changed_window_setting(wp);
1214    }
1215    done |= DONE_FOLD;
1216  } else if (donep == NULL && wp == curwin) {
1217    emsg(_(e_nofold));
1218  }
1219
1220  if (donep != NULL) {
1221    *donep |= done;
1222  }
1223
1224  return next;
1225}
1226
1227/// Open all nested folds in fold "fpr" recursively.
1228static void foldOpenNested(fold_T *fpr)
1229{
1230  fold_T *fp = (fold_T *)fpr->fd_nested.ga_data;
1231  for (int i = 0; i < fpr->fd_nested.ga_len; i++) {
1232    foldOpenNested(&fp[i]);
1233    fp[i].fd_flags = FD_OPEN;
1234  }
1235}
1236
1237/// Delete fold "idx" from growarray "gap".
1238///
1239/// @param recursive  when true, also delete all the folds contained in it.
1240///                   when false, contained folds are moved one level up.
1241static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx,
1242                            const bool recursive)
1243{
1244  fold_T *fp = (fold_T *)gap->ga_data + idx;
1245  if (recursive || GA_EMPTY(&fp->fd_nested)) {
1246    // recursively delete the contained folds
1247    deleteFoldRecurse(wp->w_buffer, &fp->fd_nested);
1248    gap->ga_len--;
1249    if (idx < gap->ga_len) {
1250      memmove(fp, fp + 1, sizeof(*fp) * (size_t)(gap->ga_len - idx));
1251    }
1252  } else {
1253    // Move nested folds one level up, to overwrite the fold that is
1254    // deleted.
1255    int moved = fp->fd_nested.ga_len;
1256    ga_grow(gap, moved - 1);
1257    {
1258      // Get "fp" again, the array may have been reallocated.
1259      fp = (fold_T *)gap->ga_data + idx;
1260
1261      // adjust fd_top and fd_flags for the moved folds
1262      fold_T *nfp = (fold_T *)fp->fd_nested.ga_data;
1263      for (int i = 0; i < moved; i++) {
1264        nfp[i].fd_top += fp->fd_top;
1265        if (fp->fd_flags == FD_LEVEL) {
1266          nfp[i].fd_flags = FD_LEVEL;
1267        }
1268        if (fp->fd_small == kNone) {
1269          nfp[i].fd_small = kNone;
1270        }
1271      }
1272
1273      // move the existing folds down to make room
1274      if (idx + 1 < gap->ga_len) {
1275        memmove(fp + moved, fp + 1,
1276                sizeof(*fp) * (size_t)(gap->ga_len - (idx + 1)));
1277      }
1278      // move the contained folds one level up
1279      memmove(fp, nfp, sizeof(*fp) * (size_t)moved);
1280      xfree(nfp);
1281      gap->ga_len += moved - 1;
1282    }
1283  }
1284}
1285
1286/// Delete nested folds in a fold.
1287void deleteFoldRecurse(buf_T *bp, garray_T *gap)
1288{
1289#define DELETE_FOLD_NESTED(fd) deleteFoldRecurse(bp, &((fd)->fd_nested))
1290  GA_DEEP_CLEAR(gap, fold_T, DELETE_FOLD_NESTED);
1291}
1292
1293/// Update line numbers of folds for inserted/deleted lines.
1294///
1295/// We are adjusting the folds in the range from line1 til line2,
1296/// make sure that line2 does not get smaller than line1
1297void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, linenr_T amount,
1298                    linenr_T amount_after)
1299{
1300  // If deleting marks from line1 to line2, but not deleting all those
1301  // lines, set line2 so that only deleted lines have their folds removed.
1302  if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after) {
1303    line2 = line1 - amount_after - 1;
1304  }
1305  if (line2 < line1) {
1306    line2 = line1;
1307  }
1308  // If appending a line in Insert mode, it should be included in the fold
1309  // just above the line.
1310  if ((State & MODE_INSERT) && amount == 1 && line2 == MAXLNUM) {
1311    line1--;
1312  }
1313  foldMarkAdjustRecurse(wp, &wp->w_folds, line1, line2, amount, amount_after);
1314}
1315
1316static void foldMarkAdjustRecurse(win_T *wp, garray_T *gap, linenr_T line1, linenr_T line2,
1317                                  linenr_T amount, linenr_T amount_after)
1318{
1319  if (gap->ga_len == 0) {
1320    return;
1321  }
1322
1323  // In Insert mode an inserted line at the top of a fold is considered part
1324  // of the fold, otherwise it isn't.
1325  linenr_T top = ((State & MODE_INSERT) && amount == 1 && line2 == MAXLNUM)
1326                 ? line1 + 1
1327                 : line1;
1328
1329  // Find the fold containing or just below "line1".
1330  fold_T *fp;
1331  foldFind(gap, line1, &fp);
1332
1333  // Adjust all folds below "line1" that are affected.
1334  for (int i = (int)(fp - (fold_T *)gap->ga_data); i < gap->ga_len; i++, fp++) {
1335    // Check for these situations:
1336    //    1  2  3
1337    //    1  2  3
1338    // line1     2      3  4  5
1339    //       2  3  4  5
1340    //       2  3  4  5
1341    // line2     2      3  4  5
1342    //          3     5  6
1343    //          3     5  6
1344
1345    linenr_T last = fp->fd_top + fp->fd_len - 1;     // last line of fold
1346
1347    // 1. fold completely above line1: nothing to do
1348    if (last < line1) {
1349      continue;
1350    }
1351
1352    // 6. fold below line2: only adjust for amount_after
1353    if (fp->fd_top > line2) {
1354      if (amount_after == 0) {
1355        break;
1356      }
1357      fp->fd_top += amount_after;
1358    } else {
1359      if (fp->fd_top >= top && last <= line2) {
1360        // 4. fold completely contained in range
1361        if (amount == MAXLNUM) {
1362          // Deleting lines: delete the fold completely
1363          deleteFoldEntry(wp, gap, i, true);
1364          i--;              // adjust index for deletion
1365          fp--;
1366        } else {
1367          fp->fd_top += amount;
1368        }
1369      } else {
1370        if (fp->fd_top < top) {
1371          // 2 or 3: need to correct nested folds too
1372          foldMarkAdjustRecurse(wp, &fp->fd_nested, line1 - fp->fd_top,
1373                                line2 - fp->fd_top, amount, amount_after);
1374          if (last <= line2) {
1375            // 2. fold contains line1, line2 is below fold
1376            if (amount == MAXLNUM) {
1377              fp->fd_len = line1 - fp->fd_top;
1378            } else {
1379              fp->fd_len += amount;
1380            }
1381          } else {
1382            // 3. fold contains line1 and line2
1383            fp->fd_len += amount_after;
1384          }
1385        } else {
1386          // 5. fold is below line1 and contains line2; need to
1387          // correct nested folds too
1388          if (amount == MAXLNUM) {
1389            foldMarkAdjustRecurse(wp, &fp->fd_nested, 0, line2 - fp->fd_top,
1390                                  amount, amount_after + (fp->fd_top - top));
1391            fp->fd_len -= line2 - fp->fd_top + 1;
1392            fp->fd_top = line1;
1393          } else {
1394            foldMarkAdjustRecurse(wp, &fp->fd_nested, 0, line2 - fp->fd_top,
1395                                  amount, amount_after - amount);
1396            fp->fd_len += amount_after - amount;
1397            fp->fd_top += amount;
1398          }
1399        }
1400      }
1401    }
1402  }
1403}
1404
1405/// Get the lowest 'foldlevel' value that makes the deepest nested fold in
1406/// window `wp`.
1407int getDeepestNesting(win_T *wp)
1408{
1409  checkupdate(wp);
1410  return getDeepestNestingRecurse(&wp->w_folds);
1411}
1412
1413static int getDeepestNestingRecurse(garray_T *gap)
1414{
1415  int maxlevel = 0;
1416
1417  fold_T *fp = (fold_T *)gap->ga_data;
1418  for (int i = 0; i < gap->ga_len; i++) {
1419    int level = getDeepestNestingRecurse(&fp[i].fd_nested) + 1;
1420    maxlevel = MAX(maxlevel, level);
1421  }
1422
1423  return maxlevel;
1424}
1425
1426/// Check if a fold is closed and update the info needed to check nested folds.
1427///
1428/// @param[in,out] use_levelp true: outer fold had FD_LEVEL
1429/// @param[in,out] fp fold to check
1430/// @param level folding depth
1431/// @param[out] maybe_smallp true: outer this had fd_small == kNone
1432/// @param lnum_off line number offset for fp->fd_top
1433/// @return true if fold is closed
1434static bool check_closed(win_T *const wp, fold_T *const fp, bool *const use_levelp, const int level,
1435                         bool *const maybe_smallp, const linenr_T lnum_off)
1436{
1437  bool closed = false;
1438
1439  // Check if this fold is closed.  If the flag is FD_LEVEL this
1440  // fold and all folds it contains depend on 'foldlevel'.
1441  if (*use_levelp || fp->fd_flags == FD_LEVEL) {
1442    *use_levelp = true;
1443    if (level >= wp->w_p_fdl) {
1444      closed = true;
1445    }
1446  } else if (fp->fd_flags == FD_CLOSED) {
1447    closed = true;
1448  }
1449
1450  // Small fold isn't closed anyway.
1451  if (fp->fd_small == kNone) {
1452    *maybe_smallp = true;
1453  }
1454  if (closed) {
1455    if (*maybe_smallp) {
1456      fp->fd_small = kNone;
1457    }
1458    checkSmall(wp, fp, lnum_off);
1459    if (fp->fd_small == kTrue) {
1460      closed = false;
1461    }
1462  }
1463  return closed;
1464}
1465
1466/// Update fd_small field of fold "fp".
1467///
1468/// @param lnum_off  offset for fp->fd_top
1469static void checkSmall(win_T *const wp, fold_T *const fp, const linenr_T lnum_off)
1470{
1471  if (fp->fd_small != kNone) {
1472    return;
1473  }
1474
1475  // Mark any nested folds to maybe-small
1476  setSmallMaybe(&fp->fd_nested);
1477
1478  if (fp->fd_len > wp->w_p_fml) {
1479    fp->fd_small = kFalse;
1480  } else {
1481    int count = 0;
1482    for (int n = 0; n < fp->fd_len; n++) {
1483      count += plines_win_nofold(wp, fp->fd_top + lnum_off + n);
1484      if (count > wp->w_p_fml) {
1485        fp->fd_small = kFalse;
1486        return;
1487      }
1488    }
1489    fp->fd_small = kTrue;
1490  }
1491}
1492
1493/// Set small flags in "gap" to kNone.
1494static void setSmallMaybe(garray_T *gap)
1495{
1496  fold_T *fp = (fold_T *)gap->ga_data;
1497  for (int i = 0; i < gap->ga_len; i++) {
1498    fp[i].fd_small = kNone;
1499  }
1500}
1501
1502/// Create a fold from line "start" to line "end" (inclusive) in window `wp`
1503/// by adding markers.
1504static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end)
1505{
1506  buf_T *buf = wp->w_buffer;
1507  if (!MODIFIABLE(buf)) {
1508    emsg(_(e_modifiable));
1509    return;
1510  }
1511  parseMarker(wp);
1512
1513  foldAddMarker(buf, start, wp->w_p_fmr, foldstartmarkerlen);
1514  foldAddMarker(buf, end, foldendmarker, foldendmarkerlen);
1515
1516  // Update both changes here, to avoid all folds after the start are
1517  // changed when the start marker is inserted and the end isn't.
1518  changed_lines(buf, start.lnum, 0, end.lnum, 0, false);
1519
1520  // Note: foldAddMarker() may not actually change start and/or end if
1521  // u_save() is unable to save the buffer line, but we send the
1522  // nvim_buf_lines_event anyway since it won't do any harm.
1523  int64_t num_changed = 1 + end.lnum - start.lnum;
1524  buf_updates_send_changes(buf, start.lnum, num_changed, num_changed);
1525}
1526
1527/// Add "marker[markerlen]" in 'commentstring' to position `pos`.
1528static void foldAddMarker(buf_T *buf, pos_T pos, const char *marker, size_t markerlen)
1529{
1530  char *cms = buf->b_p_cms;
1531  char *p = strstr(buf->b_p_cms, "%s");
1532  bool line_is_comment = false;
1533  linenr_T lnum = pos.lnum;
1534
1535  // Allocate a new line: old-line + 'cms'-start + marker + 'cms'-end
1536  char *line = ml_get_buf(buf, lnum);
1537  size_t line_len = (size_t)ml_get_buf_len(buf, lnum);
1538  size_t added = 0;
1539
1540  if (u_save(lnum - 1, lnum + 1) != OK) {
1541    return;
1542  }
1543
1544  // Check if the line ends with an unclosed comment
1545  skip_comment(line, false, false, &line_is_comment);
1546  char *newline = xmalloc(line_len + markerlen + strlen(cms) + 1);
1547  STRCPY(newline, line);
1548  // Append the marker to the end of the line
1549  if (p == NULL || line_is_comment) {
1550    xmemcpyz(newline + line_len, marker, markerlen);
1551    added = markerlen;
1552  } else {
1553    STRCPY(newline + line_len, cms);
1554    memcpy(newline + line_len + (p - cms), marker, markerlen);
1555    STRCPY(newline + line_len + (p - cms) + markerlen, p + 2);
1556    added = markerlen + strlen(cms) - 2;
1557  }
1558  ml_replace_buf(buf, lnum, newline, false, false);
1559  if (added) {
1560    extmark_splice_cols(buf, (int)lnum - 1, (int)line_len,
1561                        0, (int)added, kExtmarkUndo);
1562  }
1563}
1564
1565/// Delete the markers for a fold, causing it to be deleted.
1566///
1567/// @param lnum_off  offset for fp->fd_top
1568static void deleteFoldMarkers(win_T *wp, fold_T *fp, bool recursive, linenr_T lnum_off)
1569{
1570  if (recursive) {
1571    for (int i = 0; i < fp->fd_nested.ga_len; i++) {
1572      deleteFoldMarkers(wp, (fold_T *)fp->fd_nested.ga_data + i, true,
1573                        lnum_off + fp->fd_top);
1574    }
1575  }
1576  foldDelMarker(wp->w_buffer, fp->fd_top + lnum_off, wp->w_p_fmr,
1577                foldstartmarkerlen);
1578  foldDelMarker(wp->w_buffer, fp->fd_top + lnum_off + fp->fd_len - 1,
1579                foldendmarker, foldendmarkerlen);
1580}
1581
1582/// Delete marker "marker[markerlen]" at the end of line "lnum".
1583/// Delete 'commentstring' if it matches.
1584/// If the marker is not found, there is no error message.  Could be a missing
1585/// close-marker.
1586static void foldDelMarker(buf_T *buf, linenr_T lnum, char *marker, size_t markerlen)
1587{
1588  // end marker may be missing and fold extends below the last line
1589  if (lnum > buf->b_ml.ml_line_count) {
1590    return;
1591  }
1592
1593  char *cms = buf->b_p_cms;
1594  char *line = ml_get_buf(buf, lnum);
1595  for (char *p = line; *p != NUL; p++) {
1596    if (strncmp(p, marker, markerlen) != 0) {
1597      continue;
1598    }
1599    // Found the marker, include a digit if it's there.
1600    size_t len = markerlen;
1601    if (ascii_isdigit(p[len])) {
1602      len++;
1603    }
1604    if (*cms != NUL) {
1605      // Also delete 'commentstring' if it matches.
1606      char *cms2 = strstr(cms, "%s");
1607      if (cms2 != NULL && p - line >= cms2 - cms
1608          && strncmp(p - (cms2 - cms), cms, (size_t)(cms2 - cms)) == 0
1609          && strncmp(p + len, cms2 + 2, strlen(cms2 + 2)) == 0) {
1610        p -= cms2 - cms;
1611        len += strlen(cms) - 2;
1612      }
1613    }
1614    if (u_save(lnum - 1, lnum + 1) == OK) {
1615      // Make new line: text-before-marker + text-after-marker
1616      char *newline = xmalloc((size_t)ml_get_buf_len(buf, lnum) - len + 1);
1617      assert(p >= line);
1618      memcpy(newline, line, (size_t)(p - line));
1619      STRCPY(newline + (p - line), p + len);
1620      ml_replace_buf(buf, lnum, newline, false, false);
1621      extmark_splice_cols(buf, (int)lnum - 1, (int)(p - line),
1622                          (int)len, 0, kExtmarkUndo);
1623    }
1624    break;
1625  }
1626}
1627
1628/// Generates text to display
1629///
1630/// @param buf allocated memory of length FOLD_TEXT_LEN. Used when 'foldtext'
1631///            isn't set puts the result in "buf[FOLD_TEXT_LEN]".
1632/// @param at line "lnum", with last line "lnume".
1633/// @return the text for a closed fold
1634///
1635/// Otherwise the result is in allocated memory.
1636char *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldinfo, char *buf,
1637                   VirtText *vt)
1638  FUNC_ATTR_NONNULL_ALL
1639{
1640  char *text = NULL;
1641  // an error occurred when evaluating 'fdt' setting
1642  static bool got_fdt_error = false;
1643  int save_did_emsg = did_emsg;
1644  static win_T *last_wp = NULL;
1645  static linenr_T last_lnum = 0;
1646
1647  if (last_wp == NULL || last_wp != wp || last_lnum > lnum || last_lnum == 0) {
1648    // window changed, try evaluating foldtext setting once again
1649    got_fdt_error = false;
1650  }
1651
1652  if (!got_fdt_error) {
1653    // a previous error should not abort evaluating 'foldexpr'
1654    did_emsg = false;
1655  }
1656
1657  if (wp->w_p_fdt.type != kCallbackNone) {
1658    char dashes[MAX_LEVEL + 2];
1659
1660    // Set "v:foldstart" and "v:foldend".
1661    set_vim_var_nr(VV_FOLDSTART, (varnumber_T)lnum);
1662    set_vim_var_nr(VV_FOLDEND, (varnumber_T)lnume);
1663
1664    // Set "v:folddashes" to a string of "level" dashes.
1665    // Set "v:foldlevel" to "level".
1666    int level = MIN(foldinfo.fi_level, (int)sizeof(dashes) - 1);
1667    memset(dashes, '-', (size_t)level);
1668    dashes[level] = NUL;
1669    set_vim_var_string(VV_FOLDDASHES, dashes, level);
1670    set_vim_var_nr(VV_FOLDLEVEL, (varnumber_T)level);
1671
1672    // skip evaluating 'foldtext' on errors
1673    if (!got_fdt_error) {
1674      win_T *const save_curwin = curwin;
1675      const sctx_T saved_sctx = current_sctx;
1676
1677      curwin = wp;
1678      curbuf = wp->w_buffer;
1679      current_sctx = wp->w_p_script_ctx[kWinOptFoldtext];
1680
1681      emsg_off++;  // handle exceptions, but don't display errors
1682
1683      Object obj = eval_foldtext(wp);
1684      if (obj.type == kObjectTypeArray) {
1685        Error err = ERROR_INIT;
1686        *vt = parse_virt_text(obj.data.array, &err, NULL, false);
1687        if (!ERROR_SET(&err)) {
1688          *buf = NUL;
1689          text = buf;
1690        }
1691        api_clear_error(&err);
1692      } else if (obj.type == kObjectTypeString) {
1693        text = obj.data.string.data;
1694        obj = NIL;
1695      }
1696      api_free_object(obj);
1697
1698      emsg_off--;
1699
1700      if (text == NULL || did_emsg) {
1701        got_fdt_error = true;
1702      }
1703
1704      curwin = save_curwin;
1705      curbuf = curwin->w_buffer;
1706      current_sctx = saved_sctx;
1707    }
1708    last_lnum = lnum;
1709    last_wp = wp;
1710    set_vim_var_string(VV_FOLDDASHES, NULL, -1);
1711
1712    if (!did_emsg && save_did_emsg) {
1713      did_emsg = save_did_emsg;
1714    }
1715
1716    if (text != NULL) {
1717      // Replace unprintable characters, if there are any.  But
1718      // replace a TAB with a space.
1719      char *p;
1720      for (p = text; *p != NUL; p++) {
1721        int len = utfc_ptr2len(p);
1722
1723        if (len > 1) {
1724          if (!vim_isprintc(utf_ptr2char(p))) {
1725            break;
1726          }
1727          p += len - 1;
1728        } else if (*p == TAB) {
1729          *p = ' ';
1730        } else if (ptr2cells(p) > 1) {
1731          break;
1732        }
1733      }
1734      if (*p != NUL) {
1735        p = transstr(text, true);
1736        xfree(text);
1737        text = p;
1738      }
1739    }
1740  }
1741  if (text == NULL) {
1742    int count = lnume - lnum + 1;
1743
1744    vim_snprintf(buf, FOLD_TEXT_LEN,
1745                 NGETTEXT("+--%3d line folded",
1746                          "+--%3d lines folded ", count),
1747                 count);
1748    text = buf;
1749  }
1750  return text;
1751}
1752
1753/// Remove 'foldmarker' and 'commentstring' from "str" (in-place).
1754static void foldtext_cleanup(char *str)
1755{
1756  // Ignore leading and trailing white space in 'commentstring'.
1757  char *cms_start = skipwhite(curbuf->b_p_cms);
1758  size_t cms_slen = strlen(cms_start);
1759  while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) {
1760    cms_slen--;
1761  }
1762
1763  // locate "%s" in 'commentstring', use the part before and after it.
1764  char *cms_end = strstr(cms_start, "%s");
1765  size_t cms_elen = 0;
1766  if (cms_end != NULL) {
1767    cms_elen = cms_slen - (size_t)(cms_end - cms_start);
1768    cms_slen = (size_t)(cms_end - cms_start);
1769
1770    // exclude white space before "%s"
1771    while (cms_slen > 0 && ascii_iswhite(cms_start[cms_slen - 1])) {
1772      cms_slen--;
1773    }
1774
1775    // skip "%s" and white space after it
1776    char *s = skipwhite(cms_end + 2);
1777    cms_elen -= (size_t)(s - cms_end);
1778    cms_end = s;
1779  }
1780  parseMarker(curwin);
1781
1782  bool did1 = false;
1783  bool did2 = false;
1784
1785  for (char *s = str; *s != NUL;) {
1786    size_t len = 0;
1787    if (strncmp(s, curwin->w_p_fmr, foldstartmarkerlen) == 0) {
1788      len = foldstartmarkerlen;
1789    } else if (strncmp(s, foldendmarker, foldendmarkerlen) == 0) {
1790      len = foldendmarkerlen;
1791    }
1792    if (len > 0) {
1793      if (ascii_isdigit(s[len])) {
1794        len++;
1795      }
1796
1797      // May remove 'commentstring' start.  Useful when it's a double
1798      // quote and we already removed a double quote.
1799      char *p;
1800      for (p = s; p > str && ascii_iswhite(p[-1]); p--) {}
1801      if (p >= str + cms_slen
1802          && strncmp(p - cms_slen, cms_start, cms_slen) == 0) {
1803        len += (size_t)(s - p) + cms_slen;
1804        s = p - cms_slen;
1805      }
1806    } else if (cms_end != NULL) {
1807      if (!did1 && cms_slen > 0 && strncmp(s, cms_start, cms_slen) == 0) {
1808        len = cms_slen;
1809        did1 = true;
1810      } else if (!did2 && cms_elen > 0
1811                 && strncmp(s, cms_end, cms_elen) == 0) {
1812        len = cms_elen;
1813        did2 = true;
1814      }
1815    }
1816    if (len != 0) {
1817      while (ascii_iswhite(s[len])) {
1818        len++;
1819      }
1820      STRMOVE(s, s + len);
1821    } else {
1822      MB_PTR_ADV(s);
1823    }
1824  }
1825}
1826
1827// Folding by indent, expr, marker and syntax. {{{1
1828// Function declarations. {{{2
1829
1830/// Update the folding for window "wp", at least from lines "top" to "bot".
1831/// IEMS = "Indent Expr Marker Syntax"
1832static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot)
1833{
1834  // Avoid problems when being called recursively.
1835  if (invalid_top != 0) {
1836    return;
1837  }
1838
1839  if (wp->w_foldinvalid) {
1840    // Need to update all folds.
1841    top = 1;
1842    bot = wp->w_buffer->b_ml.ml_line_count;
1843    wp->w_foldinvalid = false;
1844
1845    // Mark all folds as maybe-small.
1846    setSmallMaybe(&wp->w_folds);
1847  }
1848
1849  // add the context for "diff" folding
1850  if (foldmethodIsDiff(wp)) {
1851    if (top > diff_context) {
1852      top -= diff_context;
1853    } else {
1854      top = 1;
1855    }
1856    bot += diff_context;
1857  }
1858
1859  // When deleting lines at the end of the buffer "top" can be past the end
1860  // of the buffer.
1861  top = MIN(top, wp->w_buffer->b_ml.ml_line_count);
1862
1863  fline_T fline;
1864
1865  fold_changed = false;
1866  fline.wp = wp;
1867  fline.off = 0;
1868  fline.lvl = 0;
1869  fline.lvl_next = -1;
1870  fline.start = 0;
1871  fline.end = MAX_LEVEL + 1;
1872  fline.had_end = MAX_LEVEL + 1;
1873
1874  invalid_top = top;
1875  invalid_bot = bot;
1876
1877  LevelGetter getlevel = NULL;
1878
1879  if (foldmethodIsMarker(wp)) {
1880    getlevel = foldlevelMarker;
1881
1882    // Init marker variables to speed up foldlevelMarker().
1883    parseMarker(wp);
1884
1885    // Need to get the level of the line above top, it is used if there is
1886    // no marker at the top.
1887    if (top > 1) {
1888      // Get the fold level at top - 1.
1889      const int level = foldLevelWin(wp, top - 1);
1890
1891      // The fold may end just above the top, check for that.
1892      fline.lnum = top - 1;
1893      fline.lvl = level;
1894      getlevel(&fline);
1895
1896      // If a fold started here, we already had the level, if it stops
1897      // here, we need to use lvl_next.  Could also start and end a fold
1898      // in the same line.
1899      if (fline.lvl > level) {
1900        fline.lvl = level - (fline.lvl - fline.lvl_next);
1901      } else {
1902        fline.lvl = fline.lvl_next;
1903      }
1904    }
1905    fline.lnum = top;
1906    getlevel(&fline);
1907  } else {
1908    fline.lnum = top;
1909    if (foldmethodIsExpr(wp)) {
1910      getlevel = foldlevelExpr;
1911      // start one line back, because a "<1" may indicate the end of a
1912      // fold in the topline
1913      if (top > 1) {
1914        fline.lnum--;
1915      }
1916    } else if (foldmethodIsSyntax(wp)) {
1917      getlevel = foldlevelSyntax;
1918    } else if (foldmethodIsDiff(wp)) {
1919      getlevel = foldlevelDiff;
1920    } else {
1921      getlevel = foldlevelIndent;
1922      // Start one line back, because if the line above "top" has an
1923      // undefined fold level, folding it relies on the line under it,
1924      // which is "top".
1925      if (top > 1) {
1926        fline.lnum--;
1927      }
1928    }
1929
1930    // Backup to a line for which the fold level is defined.  Since it's
1931    // always defined for line one, we will stop there.
1932    fline.lvl = -1;
1933    for (; !got_int; fline.lnum--) {
1934      // Reset lvl_next each time, because it will be set to a value for
1935      // the next line, but we search backwards here.
1936      fline.lvl_next = -1;
1937      getlevel(&fline);
1938      if (fline.lvl >= 0) {
1939        break;
1940      }
1941    }
1942  }
1943
1944  // If folding is defined by the syntax, it is possible that a change in
1945  // one line will cause all sub-folds of the current fold to change (e.g.,
1946  // closing a C-style comment can cause folds in the subsequent lines to
1947  // appear). To take that into account we should adjust the value of "bot"
1948  // to point to the end of the current fold:
1949  if (foldlevelSyntax == getlevel) {
1950    garray_T *gap = &wp->w_folds;
1951    fold_T *fpn = NULL;
1952    int current_fdl = 0;
1953    linenr_T fold_start_lnum = 0;
1954    linenr_T lnum_rel = fline.lnum;
1955
1956    while (current_fdl < fline.lvl) {
1957      if (!foldFind(gap, lnum_rel, &fpn)) {
1958        break;
1959      }
1960      current_fdl++;
1961
1962      fold_start_lnum += fpn->fd_top;
1963      gap = &fpn->fd_nested;
1964      lnum_rel -= fpn->fd_top;
1965    }
1966    if (fpn != NULL && current_fdl == fline.lvl) {
1967      linenr_T fold_end_lnum = fold_start_lnum + fpn->fd_len;
1968
1969      bot = MAX(bot, fold_end_lnum);
1970    }
1971  }
1972
1973  linenr_T start = fline.lnum;
1974  linenr_T end = bot;
1975  // Do at least one line.
1976  if (start > end && end < wp->w_buffer->b_ml.ml_line_count) {
1977    end = start;
1978  }
1979
1980  fold_T *fp;
1981
1982  while (!got_int) {
1983    // Always stop at the end of the file ("end" can be past the end of
1984    // the file).
1985    if (fline.lnum > wp->w_buffer->b_ml.ml_line_count) {
1986      break;
1987    }
1988    if (fline.lnum > end) {
1989      // For "marker", "expr"  and "syntax"  methods: If a change caused
1990      // a fold to be removed, we need to continue at least until where
1991      // it ended.
1992      if (getlevel != foldlevelMarker
1993          && getlevel != foldlevelSyntax
1994          && getlevel != foldlevelExpr) {
1995        break;
1996      }
1997      if ((start <= end
1998           && foldFind(&wp->w_folds, end, &fp)
1999           && fp->fd_top + fp->fd_len - 1 > end)
2000          || (fline.lvl == 0
2001              && foldFind(&wp->w_folds, fline.lnum, &fp)
2002              && fp->fd_top < fline.lnum)) {
2003        end = fp->fd_top + fp->fd_len - 1;
2004      } else if (getlevel == foldlevelSyntax
2005                 && foldLevelWin(wp, fline.lnum) != fline.lvl) {
2006        // For "syntax" method: Compare the foldlevel that the syntax
2007        // tells us to the foldlevel from the existing folds.  If they
2008        // don't match continue updating folds.
2009        end = fline.lnum;
2010      } else {
2011        break;
2012      }
2013    }
2014
2015    // A level 1 fold starts at a line with foldlevel > 0.
2016    if (fline.lvl > 0) {
2017      invalid_top = fline.lnum;
2018      invalid_bot = end;
2019      end = foldUpdateIEMSRecurse(&wp->w_folds, 1, start, &fline, getlevel, end,
2020                                  FD_LEVEL);
2021      start = fline.lnum;
2022    } else {
2023      if (fline.lnum == wp->w_buffer->b_ml.ml_line_count) {
2024        break;
2025      }
2026      fline.lnum++;
2027      fline.lvl = fline.lvl_next;
2028      getlevel(&fline);
2029    }
2030  }
2031
2032  // There can't be any folds from start until end now.
2033  foldRemove(wp, &wp->w_folds, start, end);
2034
2035  // If some fold changed, need to redraw and position cursor.
2036  if (fold_changed && wp->w_p_fen) {
2037    changed_window_setting(wp);
2038  }
2039
2040  // If we updated folds past "bot", need to redraw more lines.  Don't do
2041  // this in other situations, the changed lines will be redrawn anyway and
2042  // this method can cause the whole window to be updated.
2043  if (end != bot) {
2044    redraw_win_range_later(wp, top, end);
2045  }
2046
2047  invalid_top = 0;
2048}
2049
2050/// Update a fold that starts at "flp->lnum".  At this line there is always a
2051/// valid foldlevel, and its level >= "level".
2052///
2053/// "flp" is valid for "flp->lnum" when called and it's valid when returning.
2054/// "flp->lnum" is set to the lnum just below the fold, if it ends before
2055/// "bot", it's "bot" plus one if the fold continues and it's bigger when using
2056/// the marker method and a text change made following folds to change.
2057/// When returning, "flp->lnum_save" is the line number that was used to get
2058/// the level when the level at "flp->lnum" is invalid.
2059/// Remove any folds from "startlnum" up to here at this level.
2060/// Recursively update nested folds.
2061/// Below line "bot" there are no changes in the text.
2062/// "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the
2063/// outer fold.
2064/// "flp->off" is the offset to the real line number in the buffer.
2065///
2066/// All this would be a lot simpler if all folds in the range would be deleted
2067/// and then created again.  But we would lose all information about the
2068/// folds, even when making changes that don't affect the folding (e.g. "vj~").
2069///
2070/// @param topflags  containing fold flags
2071///
2072/// @return  bot, which may have been increased for lines that also need to be
2073/// updated as a result of a detected change in the fold.
2074static linenr_T foldUpdateIEMSRecurse(garray_T *const gap, const int level,
2075                                      const linenr_T startlnum, fline_T *const flp,
2076                                      LevelGetter getlevel, linenr_T bot, const char topflags)
2077{
2078  fold_T *fp = NULL;
2079
2080  // If using the marker method, the start line is not the start of a fold
2081  // at the level we're dealing with and the level is non-zero, we must use
2082  // the previous fold.  But ignore a fold that starts at or below
2083  // startlnum, it must be deleted.
2084  if (getlevel == foldlevelMarker && flp->start <= flp->lvl - level
2085      && flp->lvl > 0) {
2086    foldFind(gap, startlnum - 1, &fp);
2087    if (fp != NULL
2088        && (fp >= ((fold_T *)gap->ga_data) + gap->ga_len
2089            || fp->fd_top >= startlnum)) {
2090      fp = NULL;
2091    }
2092  }
2093
2094  fold_T *fp2;
2095  int lvl = level;
2096  linenr_T startlnum2 = startlnum;
2097  const linenr_T firstlnum = flp->lnum;     // first lnum we got
2098  bool finish = false;
2099  const linenr_T linecount = flp->wp->w_buffer->b_ml.ml_line_count - flp->off;
2100
2101  // Loop over all lines in this fold, or until "bot" is hit.
2102  // Handle nested folds inside of this fold.
2103  // "flp->lnum" is the current line.  When finding the end of the fold, it
2104  // is just below the end of the fold.
2105  // "*flp" contains the level of the line "flp->lnum" or a following one if
2106  // there are lines with an invalid fold level.  "flp->lnum_save" is the
2107  // line number that was used to get the fold level (below "flp->lnum" when
2108  // it has an invalid fold level).  When called the fold level is always
2109  // valid, thus "flp->lnum_save" is equal to "flp->lnum".
2110  flp->lnum_save = flp->lnum;
2111  while (!got_int) {
2112    // Updating folds can be slow, check for CTRL-C.
2113    line_breakcheck();
2114
2115    // Set "lvl" to the level of line "flp->lnum".  When flp->start is set
2116    // and after the first line of the fold, set the level to zero to
2117    // force the fold to end.  Do the same when had_end is set: Previous
2118    // line was marked as end of a fold.
2119    lvl = MIN(flp->lvl, MAX_LEVEL);
2120    if (flp->lnum > firstlnum
2121        && (level > lvl - flp->start || level >= flp->had_end)) {
2122      lvl = 0;
2123    }
2124
2125    if (flp->lnum > bot && !finish && fp != NULL) {
2126      // For "marker" and "syntax" methods:
2127      // - If a change caused a nested fold to be removed, we need to
2128      //   delete it and continue at least until where it ended.
2129      // - If a change caused a nested fold to be created, or this fold
2130      //   to continue below its original end, need to finish this fold.
2131      if (getlevel != foldlevelMarker
2132          && getlevel != foldlevelExpr
2133          && getlevel != foldlevelSyntax) {
2134        break;
2135      }
2136      int i = 0;
2137      fp2 = fp;
2138      if (lvl >= level) {
2139        // Compute how deep the folds currently are, if it's deeper
2140        // than "lvl" then some must be deleted, need to update
2141        // at least one nested fold.
2142        int ll = flp->lnum - fp->fd_top;
2143        while (foldFind(&fp2->fd_nested, ll, &fp2)) {
2144          i++;
2145          ll -= fp2->fd_top;
2146        }
2147      }
2148      if (lvl < level + i) {
2149        foldFind(&fp->fd_nested, flp->lnum - fp->fd_top, &fp2);
2150        if (fp2 != NULL) {
2151          bot = fp2->fd_top + fp2->fd_len - 1 + fp->fd_top;
2152        }
2153      } else if (fp->fd_top + fp->fd_len <= flp->lnum && lvl >= level) {
2154        finish = true;
2155      } else {
2156        break;
2157      }
2158    }
2159
2160    // At the start of the first nested fold and at the end of the current
2161    // fold: check if existing folds at this level, before the current
2162    // one, need to be deleted or truncated.
2163    if (fp == NULL
2164        && (lvl != level
2165            || flp->lnum_save >= bot
2166            || flp->start != 0
2167            || flp->had_end <= MAX_LEVEL
2168            || flp->lnum == linecount)) {
2169      // Remove or update folds that have lines between startlnum and
2170      // firstlnum.
2171      while (!got_int) {
2172        // set concat to 1 if it's allowed to concatenate this fold
2173        // with a previous one that touches it.
2174        int concat = (flp->start != 0 || flp->had_end <= MAX_LEVEL) ? 0 : 1;
2175
2176        // Find an existing fold to re-use.  Preferably one that
2177        // includes startlnum, otherwise one that ends just before
2178        // startlnum or starts after it.
2179        if (gap->ga_len > 0
2180            && (foldFind(gap, startlnum, &fp)
2181                || (fp < ((fold_T *)gap->ga_data) + gap->ga_len
2182                    && fp->fd_top <= firstlnum)
2183                || foldFind(gap, firstlnum - concat, &fp)
2184                || (fp < ((fold_T *)gap->ga_data) + gap->ga_len
2185                    && ((lvl < level && fp->fd_top < flp->lnum)
2186                        || (lvl >= level
2187                            && fp->fd_top <= flp->lnum_save))))) {
2188          if (fp->fd_top + fp->fd_len + concat > firstlnum) {
2189            // Use existing fold for the new fold.  If it starts
2190            // before where we started looking, extend it.  If it
2191            // starts at another line, update nested folds to keep
2192            // their position, compensating for the new fd_top.
2193            if (fp->fd_top == firstlnum) {
2194              // We have found a fold beginning exactly where we want one.
2195            } else if (fp->fd_top >= startlnum) {
2196              if (fp->fd_top > firstlnum) {
2197                // We will move the start of this fold up, hence we move all
2198                // nested folds (with relative line numbers) down.
2199                foldMarkAdjustRecurse(flp->wp, &fp->fd_nested,
2200                                      0, (linenr_T)MAXLNUM,
2201                                      (fp->fd_top - firstlnum), 0);
2202              } else {
2203                // Will move fold down, move nested folds relatively up.
2204                foldMarkAdjustRecurse(flp->wp, &fp->fd_nested,
2205                                      0,
2206                                      (firstlnum - fp->fd_top - 1),
2207                                      (linenr_T)MAXLNUM,
2208                                      (fp->fd_top - firstlnum));
2209              }
2210              fp->fd_len += fp->fd_top - firstlnum;
2211              fp->fd_top = firstlnum;
2212              fp->fd_small = kNone;
2213              fold_changed = true;
2214            } else if ((flp->start != 0 && lvl == level)
2215                       || (firstlnum != startlnum)) {
2216              // Before there was a fold spanning from above startlnum to below
2217              // firstlnum. This fold is valid above startlnum (because we are
2218              // not updating that range), but there is now a break in it.
2219              // If the break is because we are now forced to start a new fold
2220              // at the level "level" at line fline->lnum, then we need to
2221              // split the fold at fline->lnum.
2222              // If the break is because the range [startlnum, firstlnum) is
2223              // now at a lower indent than "level", we need to split the fold
2224              // in this range.
2225              // Any splits have to be done recursively.
2226              linenr_T breakstart;
2227              linenr_T breakend;
2228              if (firstlnum != startlnum) {
2229                breakstart = startlnum;
2230                breakend = firstlnum;
2231              } else {
2232                breakstart = flp->lnum;
2233                breakend = flp->lnum;
2234              }
2235              foldRemove(flp->wp, &fp->fd_nested, breakstart - fp->fd_top,
2236                         breakend - fp->fd_top);
2237              int i = (int)(fp - (fold_T *)gap->ga_data);
2238              foldSplit(flp->wp->w_buffer, gap, i, breakstart, breakend - 1);
2239              fp = (fold_T *)gap->ga_data + i + 1;
2240              // If using the "marker" or "syntax" method, we
2241              // need to continue until the end of the fold is
2242              // found.
2243              if (getlevel == foldlevelMarker
2244                  || getlevel == foldlevelExpr
2245                  || getlevel == foldlevelSyntax) {
2246                finish = true;
2247              }
2248            }
2249            if (fp->fd_top == startlnum && concat) {
2250              int i = (int)(fp - (fold_T *)gap->ga_data);
2251              if (i != 0) {
2252                fp2 = fp - 1;
2253                if (fp2->fd_top + fp2->fd_len == fp->fd_top) {
2254                  foldMerge(flp->wp, fp2, gap, fp);
2255                  fp = fp2;
2256                }
2257              }
2258            }
2259            break;
2260          }
2261          if (fp->fd_top >= startlnum) {
2262            // A fold that starts at or after startlnum and stops
2263            // before the new fold must be deleted.  Continue
2264            // looking for the next one.
2265            deleteFoldEntry(flp->wp, gap,
2266                            (int)(fp - (fold_T *)gap->ga_data), true);
2267          } else {
2268            // A fold has some lines above startlnum, truncate it
2269            // to stop just above startlnum.
2270            fp->fd_len = startlnum - fp->fd_top;
2271            foldMarkAdjustRecurse(flp->wp, &fp->fd_nested,
2272                                  fp->fd_len, (linenr_T)MAXLNUM,
2273                                  (linenr_T)MAXLNUM, 0);
2274            fold_changed = true;
2275          }
2276        } else {
2277          // Insert new fold.  Careful: ga_data may be NULL and it
2278          // may change!
2279          int i;
2280          if (gap->ga_len == 0) {
2281            i = 0;
2282          } else {
2283            i = (int)(fp - (fold_T *)gap->ga_data);
2284          }
2285          foldInsert(gap, i);
2286          fp = (fold_T *)gap->ga_data + i;
2287          // The new fold continues until bot, unless we find the
2288          // end earlier.
2289          fp->fd_top = firstlnum;
2290          fp->fd_len = bot - firstlnum + 1;
2291          // When the containing fold is open, the new fold is open.
2292          // The new fold is closed if the fold above it is closed.
2293          // The first fold depends on the containing fold.
2294          if (topflags == FD_OPEN) {
2295            flp->wp->w_fold_manual = true;
2296            fp->fd_flags = FD_OPEN;
2297          } else if (i <= 0) {
2298            fp->fd_flags = topflags;
2299            if (topflags != FD_LEVEL) {
2300              flp->wp->w_fold_manual = true;
2301            }
2302          } else {
2303            fp->fd_flags = (fp - 1)->fd_flags;
2304          }
2305          fp->fd_small = kNone;
2306          // If using the "marker", "expr" or "syntax" method, we
2307          // need to continue until the end of the fold is found.
2308          if (getlevel == foldlevelMarker
2309              || getlevel == foldlevelExpr
2310              || getlevel == foldlevelSyntax) {
2311            finish = true;
2312          }
2313          fold_changed = true;
2314          break;
2315        }
2316      }
2317    }
2318
2319    if (lvl < level || flp->lnum > linecount) {
2320      // Found a line with a lower foldlevel, this fold ends just above
2321      // "flp->lnum".
2322      break;
2323    }
2324
2325    // The fold includes the line "flp->lnum" and "flp->lnum_save".
2326    // Check "fp" for safety.
2327    if (lvl > level && fp != NULL) {
2328      // There is a nested fold, handle it recursively.
2329      // At least do one line (can happen when finish is true).
2330      bot = MAX(bot, flp->lnum);
2331
2332      // Line numbers in the nested fold are relative to the start of
2333      // this fold.
2334      flp->lnum = flp->lnum_save - fp->fd_top;
2335      flp->off += fp->fd_top;
2336      int i = (int)(fp - (fold_T *)gap->ga_data);
2337      bot = foldUpdateIEMSRecurse(&fp->fd_nested, level + 1,
2338                                  startlnum2 - fp->fd_top, flp, getlevel,
2339                                  bot - fp->fd_top, fp->fd_flags);
2340      fp = (fold_T *)gap->ga_data + i;
2341      flp->lnum += fp->fd_top;
2342      flp->lnum_save += fp->fd_top;
2343      flp->off -= fp->fd_top;
2344      bot += fp->fd_top;
2345      startlnum2 = flp->lnum;
2346
2347      // This fold may end at the same line, don't incr. flp->lnum.
2348    } else {
2349      // Get the level of the next line, then continue the loop to check
2350      // if it ends there.
2351      // Skip over undefined lines, to find the foldlevel after it.
2352      // For the last line in the file the foldlevel is always valid.
2353      flp->lnum = flp->lnum_save;
2354      int ll = flp->lnum + 1;
2355      while (!got_int) {
2356        // Make the previous level available to foldlevel().
2357        prev_lnum = flp->lnum;
2358        prev_lnum_lvl = flp->lvl;
2359
2360        if (++flp->lnum > linecount) {
2361          break;
2362        }
2363        flp->lvl = flp->lvl_next;
2364        getlevel(flp);
2365        if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL) {
2366          break;
2367        }
2368      }
2369      prev_lnum = 0;
2370      if (flp->lnum > linecount) {
2371        break;
2372      }
2373
2374      // leave flp->lnum_save to lnum of the line that was used to get
2375      // the level, flp->lnum to the lnum of the next line.
2376      flp->lnum_save = flp->lnum;
2377      flp->lnum = ll;
2378    }
2379  }
2380
2381  if (fp == NULL) {     // only happens when got_int is set
2382    return bot;
2383  }
2384
2385  // Get here when:
2386  // lvl < level: the folds ends just above "flp->lnum"
2387  // lvl >= level: fold continues below "bot"
2388
2389  // Current fold at least extends until lnum.
2390  if (fp->fd_len < flp->lnum - fp->fd_top) {
2391    fp->fd_len = flp->lnum - fp->fd_top;
2392    fp->fd_small = kNone;
2393    fold_changed = true;
2394  } else if (fp->fd_top + fp->fd_len > linecount) {
2395    // running into the end of the buffer (deleted last line)
2396    fp->fd_len = linecount - fp->fd_top + 1;
2397  }
2398
2399  // Delete contained folds from the end of the last one found until where
2400  // we stopped looking.
2401  foldRemove(flp->wp, &fp->fd_nested, startlnum2 - fp->fd_top,
2402             flp->lnum - 1 - fp->fd_top);
2403
2404  if (lvl < level) {
2405    // End of fold found, update the length when it got shorter.
2406    if (fp->fd_len != flp->lnum - fp->fd_top) {
2407      if (fp->fd_top + fp->fd_len - 1 > bot) {
2408        // fold continued below bot
2409        if (getlevel == foldlevelMarker
2410            || getlevel == foldlevelExpr
2411            || getlevel == foldlevelSyntax) {
2412          // marker method: truncate the fold and make sure the
2413          // previously included lines are processed again
2414          bot = fp->fd_top + fp->fd_len - 1;
2415          fp->fd_len = flp->lnum - fp->fd_top;
2416        } else {
2417          // indent or expr method: split fold to create a new one
2418          // below bot
2419          int i = (int)(fp - (fold_T *)gap->ga_data);
2420          foldSplit(flp->wp->w_buffer, gap, i, flp->lnum, bot);
2421          fp = (fold_T *)gap->ga_data + i;
2422        }
2423      } else {
2424        fp->fd_len = flp->lnum - fp->fd_top;
2425      }
2426      fold_changed = true;
2427    }
2428  }
2429
2430  // delete following folds that end before the current line
2431  while (true) {
2432    fp2 = fp + 1;
2433    if (fp2 >= (fold_T *)gap->ga_data + gap->ga_len
2434        || fp2->fd_top > flp->lnum) {
2435      break;
2436    }
2437    if (fp2->fd_top + fp2->fd_len > flp->lnum) {
2438      if (fp2->fd_top < flp->lnum) {
2439        // Make fold that includes lnum start at lnum.
2440        foldMarkAdjustRecurse(flp->wp, &fp2->fd_nested,
2441                              0, (flp->lnum - fp2->fd_top - 1),
2442                              (linenr_T)MAXLNUM, (fp2->fd_top - flp->lnum));
2443        fp2->fd_len -= flp->lnum - fp2->fd_top;
2444        fp2->fd_top = flp->lnum;
2445        fold_changed = true;
2446      }
2447
2448      if (lvl >= level) {
2449        // merge new fold with existing fold that follows
2450        foldMerge(flp->wp, fp, gap, fp2);
2451      }
2452      break;
2453    }
2454    fold_changed = true;
2455    deleteFoldEntry(flp->wp, gap, (int)(fp2 - (fold_T *)gap->ga_data), true);
2456  }
2457
2458  // Need to redraw the lines we inspected, which might be further down than
2459  // was asked for.
2460  bot = MAX(bot, flp->lnum - 1);
2461
2462  return bot;
2463}
2464
2465/// Insert a new fold in "gap" at position "i".
2466static void foldInsert(garray_T *gap, int i)
2467{
2468  ga_grow(gap, 1);
2469
2470  fold_T *fp = (fold_T *)gap->ga_data + i;
2471  if (gap->ga_len > 0 && i < gap->ga_len) {
2472    memmove(fp + 1, fp, sizeof(fold_T) * (size_t)(gap->ga_len - i));
2473  }
2474  gap->ga_len++;
2475  ga_init(&fp->fd_nested, (int)sizeof(fold_T), 10);
2476}
2477
2478/// Split the "i"th fold in "gap", which starts before "top" and ends below
2479/// "bot" in two pieces, one ending above "top" and the other starting below
2480/// "bot".
2481/// The caller must first have taken care of any nested folds from "top" to
2482/// "bot"!
2483static void foldSplit(buf_T *buf, garray_T *const gap, const int i, const linenr_T top,
2484                      const linenr_T bot)
2485{
2486  fold_T *fp2;
2487
2488  // The fold continues below bot, need to split it.
2489  foldInsert(gap, i + 1);
2490
2491  fold_T *const fp = (fold_T *)gap->ga_data + i;
2492  fp[1].fd_top = bot + 1;
2493  // check for wrap around (MAXLNUM, and 32bit)
2494  assert(fp[1].fd_top > bot);
2495  fp[1].fd_len = fp->fd_len - (fp[1].fd_top - fp->fd_top);
2496  fp[1].fd_flags = fp->fd_flags;
2497  fp[1].fd_small = kNone;
2498  fp->fd_small = kNone;
2499
2500  // Move nested folds below bot to new fold.  There can't be
2501  // any between top and bot, they have been removed by the caller.
2502  garray_T *const gap1 = &fp->fd_nested;
2503  garray_T *const gap2 = &fp[1].fd_nested;
2504  foldFind(gap1, bot + 1 - fp->fd_top, &fp2);
2505  if (fp2 != NULL) {
2506    const int len = (int)((fold_T *)gap1->ga_data + gap1->ga_len - fp2);
2507    if (len > 0) {
2508      ga_grow(gap2, len);
2509      for (int idx = 0; idx < len; idx++) {
2510        ((fold_T *)gap2->ga_data)[idx] = fp2[idx];
2511        ((fold_T *)gap2->ga_data)[idx].fd_top
2512          -= fp[1].fd_top - fp->fd_top;
2513      }
2514      gap2->ga_len = len;
2515      gap1->ga_len -= len;
2516    }
2517  }
2518  fp->fd_len = top - fp->fd_top;
2519  fold_changed = true;
2520}
2521
2522/// Remove folds within the range "top" to and including "bot".
2523/// Check for these situations:
2524///      1  2  3
2525///      1  2  3
2526/// top     2  3  4  5
2527///     2  3  4  5
2528/// bot     2  3  4  5
2529///        3     5  6
2530///        3     5  6
2531///
2532/// 1: not changed
2533/// 2: truncate to stop above "top"
2534/// 3: split in two parts, one stops above "top", other starts below "bot".
2535/// 4: deleted
2536/// 5: made to start below "bot".
2537/// 6: not changed
2538static void foldRemove(win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot)
2539{
2540  if (bot < top) {
2541    return;             // nothing to do
2542  }
2543
2544  fold_T *fp = NULL;
2545
2546  while (gap->ga_len > 0) {
2547    // Find fold that includes top or a following one.
2548    if (foldFind(gap, top, &fp) && fp->fd_top < top) {
2549      // 2: or 3: need to delete nested folds
2550      foldRemove(wp, &fp->fd_nested, top - fp->fd_top, bot - fp->fd_top);
2551      if (fp->fd_top + fp->fd_len - 1 > bot) {
2552        // 3: need to split it.
2553        foldSplit(wp->w_buffer, gap,
2554                  (int)(fp - (fold_T *)gap->ga_data), top, bot);
2555      } else {
2556        // 2: truncate fold at "top".
2557        fp->fd_len = top - fp->fd_top;
2558      }
2559      fold_changed = true;
2560      continue;
2561    }
2562    if (gap->ga_data == NULL
2563        || fp >= (fold_T *)(gap->ga_data) + gap->ga_len
2564        || fp->fd_top > bot) {
2565      // 6: Found a fold below bot, can stop looking.
2566      break;
2567    }
2568    if (fp->fd_top >= top) {
2569      // Found an entry below top.
2570      fold_changed = true;
2571      if (fp->fd_top + fp->fd_len - 1 > bot) {
2572        // 5: Make fold that includes bot start below bot.
2573        foldMarkAdjustRecurse(wp, &fp->fd_nested,
2574                              0, (bot - fp->fd_top),
2575                              (linenr_T)MAXLNUM, (fp->fd_top - bot - 1));
2576        fp->fd_len -= bot - fp->fd_top + 1;
2577        fp->fd_top = bot + 1;
2578        break;
2579      }
2580
2581      // 4: Delete completely contained fold.
2582      deleteFoldEntry(wp, gap, (int)(fp - (fold_T *)gap->ga_data), true);
2583    }
2584  }
2585}
2586
2587static void foldReverseOrder(garray_T *gap, const linenr_T start_arg, const linenr_T end_arg)
2588{
2589  linenr_T start = start_arg;
2590  linenr_T end = end_arg;
2591  for (; start < end; start++, end--) {
2592    fold_T *left = (fold_T *)gap->ga_data + start;
2593    fold_T *right = (fold_T *)gap->ga_data + end;
2594    fold_T tmp = *left;
2595    *left = *right;
2596    *right = tmp;
2597  }
2598}
2599
2600static void truncate_fold(win_T *const wp, fold_T *fp, linenr_T end)
2601{
2602  // I want to stop *at here*, foldRemove() stops *above* top
2603  end += 1;
2604  foldRemove(wp, &fp->fd_nested, end - fp->fd_top, MAXLNUM);
2605  fp->fd_len = end - fp->fd_top;
2606}
2607
2608#define FOLD_END(fp) ((fp)->fd_top + (fp)->fd_len - 1)
2609#define VALID_FOLD(fp, gap) \
2610  ((gap)->ga_len > 0 && (fp) < ((fold_T *)(gap)->ga_data + (gap)->ga_len))
2611#define FOLD_INDEX(fp, gap) ((size_t)((fp) - ((fold_T *)(gap)->ga_data)))
2612
2613/// Move folds within the inclusive range "line1" to "line2" to after "dest"
2614/// require "line1" <= "line2" <= "dest"
2615///
2616/// There are the following situations for the first fold at or below line1 - 1.
2617///       1  2  3  4
2618///       1  2  3  4
2619/// line1    2  3  4
2620///          2  3  4  5  6  7
2621/// line2       3  4  5  6  7
2622///             3  4     6  7  8  9
2623/// dest           4        7  8  9
2624///                4        7  8    10
2625///                4        7  8    10
2626///
2627/// In the following descriptions, "moved" means moving in the buffer, *and* in
2628/// the fold array.
2629/// Meanwhile, "shifted" just means moving in the buffer.
2630/// 1. not changed
2631/// 2. truncated above line1
2632/// 3. length reduced by  line2 - line1, folds starting between the end of 3 and
2633///    dest are truncated and shifted up
2634/// 4. internal folds moved (from [line1, line2] to dest)
2635/// 5. moved to dest.
2636/// 6. truncated below line2 and moved.
2637/// 7. length reduced by line2 - dest, folds starting between line2 and dest are
2638///    removed, top is moved down by move_len.
2639/// 8. truncated below dest and shifted up.
2640/// 9. shifted up
2641/// 10. not changed
2642void foldMoveRange(win_T *const wp, garray_T *gap, const linenr_T line1, const linenr_T line2,
2643                   const linenr_T dest)
2644{
2645  fold_T *fp;
2646  const linenr_T range_len = line2 - line1 + 1;
2647  const linenr_T move_len = dest - line2;
2648  const bool at_start = foldFind(gap, line1 - 1, &fp);
2649
2650  if (at_start) {
2651    if (FOLD_END(fp) > dest) {
2652      // Case 4 -- don't have to change this fold, but have to move nested
2653      // folds.
2654      foldMoveRange(wp, &fp->fd_nested, line1 - fp->fd_top, line2 -
2655                    fp->fd_top, dest - fp->fd_top);
2656      return;
2657    } else if (FOLD_END(fp) > line2) {
2658      // Case 3 -- Remove nested folds between line1 and line2 & reduce the
2659      // length of fold by "range_len".
2660      // Folds after this one must be dealt with.
2661      foldMarkAdjustRecurse(wp, &fp->fd_nested, line1 - fp->fd_top,
2662                            line2 - fp->fd_top, MAXLNUM, -range_len);
2663      fp->fd_len -= range_len;
2664    } else {
2665      // Case 2 -- truncate fold *above* line1.
2666      // Folds after this one must be dealt with.
2667      truncate_fold(wp, fp, line1 - 1);
2668    }
2669    // Look at the next fold, and treat that one as if it were the first after
2670    // "line1" (because now it is).
2671    fp = fp + 1;
2672  }
2673
2674  if (!VALID_FOLD(fp, gap) || fp->fd_top > dest) {
2675    // No folds after "line1" and before "dest"
2676    // Case 10.
2677    return;
2678  } else if (fp->fd_top > line2) {
2679    for (; VALID_FOLD(fp, gap) && FOLD_END(fp) <= dest; fp++) {
2680      // Case 9. (for all case 9's) -- shift up.
2681      fp->fd_top -= range_len;
2682    }
2683    if (VALID_FOLD(fp, gap) && fp->fd_top <= dest) {
2684      // Case 8. -- ensure truncated at dest, shift up
2685      truncate_fold(wp, fp, dest);
2686      fp->fd_top -= range_len;
2687    }
2688    return;
2689  } else if (FOLD_END(fp) > dest) {
2690    // Case 7 -- remove nested folds and shrink
2691    foldMarkAdjustRecurse(wp, &fp->fd_nested, line2 + 1 - fp->fd_top,
2692                          dest - fp->fd_top, MAXLNUM, -move_len);
2693    fp->fd_len -= move_len;
2694    fp->fd_top += move_len;
2695    return;
2696  }
2697
2698  // Case 5 or 6: changes rely on whether there are folds between the end of
2699  // this fold and "dest".
2700  size_t move_start = FOLD_INDEX(fp, gap);
2701  size_t move_end = 0;
2702  size_t dest_index = 0;
2703  for (; VALID_FOLD(fp, gap) && fp->fd_top <= dest; fp++) {
2704    if (fp->fd_top <= line2) {
2705      // 5, or 6
2706      if (FOLD_END(fp) > line2) {
2707        // 6, truncate before moving
2708        truncate_fold(wp, fp, line2);
2709      }
2710      fp->fd_top += move_len;
2711      continue;
2712    }
2713
2714    // Record index of the first fold after the moved range.
2715    if (move_end == 0) {
2716      move_end = FOLD_INDEX(fp, gap);
2717    }
2718
2719    if (FOLD_END(fp) > dest) {
2720      truncate_fold(wp, fp, dest);
2721    }
2722
2723    fp->fd_top -= range_len;
2724  }
2725  dest_index = FOLD_INDEX(fp, gap);
2726
2727  // All folds are now correct, but not necessarily in the correct order.
2728  // We must swap folds in the range [move_end, dest_index) with those in the
2729  // range [move_start, move_end).
2730  if (move_end == 0) {
2731    // There are no folds after those moved, so none were moved out of order.
2732    return;
2733  }
2734  foldReverseOrder(gap, (linenr_T)move_start, (linenr_T)(dest_index - 1));
2735  foldReverseOrder(gap, (linenr_T)move_start,
2736                   (linenr_T)(move_start + dest_index - move_end - 1));
2737  foldReverseOrder(gap, (linenr_T)(move_start + dest_index - move_end),
2738                   (linenr_T)(dest_index - 1));
2739}
2740#undef FOLD_END
2741#undef VALID_FOLD
2742#undef FOLD_INDEX
2743
2744/// Merge two adjacent folds (and the nested ones in them).
2745/// This only works correctly when the folds are really adjacent!  Thus "fp1"
2746/// must end just above "fp2".
2747/// The resulting fold is "fp1", nested folds are moved from "fp2" to "fp1".
2748/// Fold entry "fp2" in "gap" is deleted.
2749static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2)
2750{
2751  fold_T *fp3;
2752  fold_T *fp4;
2753  garray_T *gap1 = &fp1->fd_nested;
2754  garray_T *gap2 = &fp2->fd_nested;
2755
2756  // If the last nested fold in fp1 touches the first nested fold in fp2,
2757  // merge them recursively.
2758  if (foldFind(gap1, fp1->fd_len - 1, &fp3) && foldFind(gap2, 0, &fp4)) {
2759    foldMerge(wp, fp3, gap2, fp4);
2760  }
2761
2762  // Move nested folds in fp2 to the end of fp1.
2763  if (!GA_EMPTY(gap2)) {
2764    ga_grow(gap1, gap2->ga_len);
2765    for (int idx = 0; idx < gap2->ga_len; idx++) {
2766      ((fold_T *)gap1->ga_data)[gap1->ga_len]
2767        = ((fold_T *)gap2->ga_data)[idx];
2768      ((fold_T *)gap1->ga_data)[gap1->ga_len].fd_top += fp1->fd_len;
2769      gap1->ga_len++;
2770    }
2771    gap2->ga_len = 0;
2772  }
2773
2774  fp1->fd_len += fp2->fd_len;
2775  deleteFoldEntry(wp, gap, (int)(fp2 - (fold_T *)gap->ga_data), true);
2776  fold_changed = true;
2777}
2778
2779/// Low level function to get the foldlevel for the "indent" method.
2780/// Doesn't use any caching.
2781///
2782/// @return  a level of -1 if the foldlevel depends on surrounding lines.
2783static void foldlevelIndent(fline_T *flp)
2784{
2785  linenr_T lnum = flp->lnum + flp->off;
2786
2787  buf_T *buf = flp->wp->w_buffer;
2788  char *s = skipwhite(ml_get_buf(buf, lnum));
2789
2790  // empty line or lines starting with a character in 'foldignore': level
2791  // depends on surrounding lines
2792  if (*s == NUL || vim_strchr(flp->wp->w_p_fdi, (uint8_t)(*s)) != NULL) {
2793    // first and last line can't be undefined, use level 0
2794    flp->lvl = (lnum == 1 || lnum == buf->b_ml.ml_line_count) ? 0 : -1;
2795  } else {
2796    flp->lvl = get_indent_buf(buf, lnum) / get_sw_value(buf);
2797  }
2798  flp->lvl = MIN(flp->lvl, (int)MAX(0, flp->wp->w_p_fdn));
2799}
2800
2801/// Low level function to get the foldlevel for the "diff" method.
2802/// Doesn't use any caching.
2803static void foldlevelDiff(fline_T *flp)
2804{
2805  flp->lvl = (diff_infold(flp->wp, flp->lnum + flp->off)) ? 1 : 0;
2806}
2807
2808/// Low level function to get the foldlevel for the "expr" method.
2809/// Doesn't use any caching.
2810///
2811/// @return  a level of -1 if the foldlevel depends on surrounding lines.
2812static void foldlevelExpr(fline_T *flp)
2813{
2814  linenr_T lnum = flp->lnum + flp->off;
2815
2816  win_T *win = curwin;
2817  curwin = flp->wp;
2818  curbuf = flp->wp->w_buffer;
2819  set_vim_var_nr(VV_LNUM, (varnumber_T)lnum);
2820
2821  flp->start = 0;
2822  flp->had_end = flp->end;
2823  flp->end = MAX_LEVEL + 1;
2824  if (lnum <= 1) {
2825    flp->lvl = 0;
2826  }
2827
2828  // KeyTyped may be reset to 0 when calling a function which invokes
2829  // do_cmdline().  To make 'foldopen' work correctly restore KeyTyped.
2830  const bool save_keytyped = KeyTyped;
2831
2832  int c;
2833  const int n = eval_foldexpr(flp->wp, &c);
2834  KeyTyped = save_keytyped;
2835
2836  switch (c) {
2837  // "a1", "a2", .. : add to the fold level
2838  case 'a':
2839    if (flp->lvl >= 0) {
2840      flp->lvl += n;
2841      flp->lvl_next = flp->lvl;
2842    }
2843    flp->start = n;
2844    break;
2845
2846  // "s1", "s2", .. : subtract from the fold level
2847  case 's':
2848    if (flp->lvl >= 0) {
2849      if (n > flp->lvl) {
2850        flp->lvl_next = 0;
2851      } else {
2852        flp->lvl_next = flp->lvl - n;
2853      }
2854      flp->end = flp->lvl_next + 1;
2855    }
2856    break;
2857
2858  // ">1", ">2", .. : start a fold with a certain level
2859  case '>':
2860    flp->lvl = n;
2861    flp->lvl_next = n;
2862    flp->start = 1;
2863    break;
2864
2865  // "<1", "<2", .. : end a fold with a certain level
2866  case '<':
2867    // To prevent an unexpected start of a new fold, the next
2868    // level must not exceed the level of the current fold.
2869    flp->lvl_next = MIN(flp->lvl, n - 1);
2870    flp->end = n;
2871    break;
2872
2873  // "=": No change in level
2874  case '=':
2875    flp->lvl_next = flp->lvl;
2876    break;
2877
2878  // "-1", "0", "1", ..: set fold level
2879  default:
2880    if (n < 0) {
2881      // Use the current level for the next line, so that "a1"
2882      // will work there.
2883      flp->lvl_next = flp->lvl;
2884    } else {
2885      flp->lvl_next = n;
2886    }
2887    flp->lvl = n;
2888    break;
2889  }
2890
2891  // If the level is unknown for the first or the last line in the file, use
2892  // level 0.
2893  if (flp->lvl < 0) {
2894    if (lnum <= 1) {
2895      flp->lvl = 0;
2896      flp->lvl_next = 0;
2897    }
2898    if (lnum == curbuf->b_ml.ml_line_count) {
2899      flp->lvl_next = 0;
2900    }
2901  }
2902
2903  curwin = win;
2904  curbuf = curwin->w_buffer;
2905}
2906
2907/// Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and
2908/// "foldendmarkerlen".
2909/// Relies on the option value to have been checked for correctness already.
2910static void parseMarker(win_T *wp)
2911{
2912  foldendmarker = vim_strchr(wp->w_p_fmr, ',');
2913  foldstartmarkerlen = (size_t)(foldendmarker++ - wp->w_p_fmr);
2914  foldendmarkerlen = strlen(foldendmarker);
2915}
2916
2917/// Low level function to get the foldlevel for the "marker" method.
2918/// "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been
2919/// set before calling this.
2920/// Requires that flp->lvl is set to the fold level of the previous line!
2921/// Careful: This means you can't call this function twice on the same line.
2922/// Doesn't use any caching.
2923/// Sets flp->start when a start marker was found.
2924static void foldlevelMarker(fline_T *flp)
2925{
2926  int start_lvl = flp->lvl;
2927
2928  // cache a few values for speed
2929  char *startmarker = flp->wp->w_p_fmr;
2930  char cstart = *startmarker;
2931  startmarker++;
2932  char cend = *foldendmarker;
2933
2934  // Default: no start found, next level is same as current level
2935  flp->start = 0;
2936  flp->lvl_next = flp->lvl;
2937
2938  char *s = ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off);
2939  while (*s) {
2940    if (*s == cstart
2941        && strncmp(s + 1, startmarker, foldstartmarkerlen - 1) == 0) {
2942      // found startmarker: set flp->lvl
2943      s += foldstartmarkerlen;
2944      if (ascii_isdigit(*s)) {
2945        int n = atoi(s);
2946        if (n > 0) {
2947          flp->lvl = n;
2948          flp->lvl_next = n;
2949          flp->start = MAX(n - start_lvl, 1);
2950        }
2951      } else {
2952        flp->lvl++;
2953        flp->lvl_next++;
2954        flp->start++;
2955      }
2956    } else if (*s == cend
2957               && strncmp(s + 1, foldendmarker + 1, foldendmarkerlen - 1) == 0) {
2958      // found endmarker: set flp->lvl_next
2959      s += foldendmarkerlen;
2960      if (ascii_isdigit(*s)) {
2961        int n = atoi(s);
2962        if (n > 0) {
2963          flp->lvl = n;
2964          flp->lvl_next = n - 1;
2965          // never start a fold with an end marker
2966          flp->lvl_next = MIN(flp->lvl_next, start_lvl);
2967        }
2968      } else {
2969        flp->lvl_next--;
2970      }
2971    } else {
2972      MB_PTR_ADV(s);
2973    }
2974  }
2975
2976  // The level can't go negative, must be missing a start marker.
2977  flp->lvl_next = MAX(flp->lvl_next, 0);
2978}
2979
2980/// Low level function to get the foldlevel for the "syntax" method.
2981/// Doesn't use any caching.
2982static void foldlevelSyntax(fline_T *flp)
2983{
2984  linenr_T lnum = flp->lnum + flp->off;
2985
2986  // Use the maximum fold level at the start of this line and the next.
2987  flp->lvl = syn_get_foldlevel(flp->wp, lnum);
2988  flp->start = 0;
2989  if (lnum < flp->wp->w_buffer->b_ml.ml_line_count) {
2990    int n = syn_get_foldlevel(flp->wp, lnum + 1);
2991    if (n > flp->lvl) {
2992      flp->start = n - flp->lvl;        // fold(s) start here
2993      flp->lvl = n;
2994    }
2995  }
2996}
2997
2998// functions for storing the fold state in a View {{{1
2999/// Write commands to "fd" to restore the manual folds in window "wp".
3000///
3001/// @return  FAIL if writing fails.
3002int put_folds(FILE *fd, win_T *wp)
3003{
3004  if (foldmethodIsManual(wp)) {
3005    if (put_line(fd, "silent! normal! zE") == FAIL
3006        || put_folds_recurse(fd, &wp->w_folds, 0) == FAIL
3007        || put_line(fd, "let &fdl = &fdl") == FAIL) {
3008      return FAIL;
3009    }
3010  }
3011
3012  // If some folds are manually opened/closed, need to restore that.
3013  if (wp->w_fold_manual) {
3014    return put_foldopen_recurse(fd, wp, &wp->w_folds, 0);
3015  }
3016
3017  return OK;
3018}
3019
3020/// Write commands to "fd" to recreate manually created folds.
3021///
3022/// @return  FAIL when writing failed.
3023static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off)
3024{
3025  fold_T *fp = (fold_T *)gap->ga_data;
3026  for (int i = 0; i < gap->ga_len; i++) {
3027    // Do nested folds first, they will be created closed.
3028    if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) {
3029      return FAIL;
3030    }
3031    if (fprintf(fd, "sil! %" PRId64 ",%" PRId64 "fold",
3032                (int64_t)fp->fd_top + off,
3033                (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0
3034        || put_eol(fd) == FAIL) {
3035      return FAIL;
3036    }
3037    fp++;
3038  }
3039  return OK;
3040}
3041
3042/// Write commands to "fd" to open and close manually opened/closed folds.
3043///
3044/// @return  FAIL when writing failed.
3045static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off)
3046{
3047  fold_T *fp = (fold_T *)gap->ga_data;
3048  for (int i = 0; i < gap->ga_len; i++) {
3049    if (fp->fd_flags != FD_LEVEL) {
3050      if (!GA_EMPTY(&fp->fd_nested)) {
3051        // open nested folds while this fold is open
3052        // ignore errors
3053        if (fprintf(fd, "%" PRId64, (int64_t)fp->fd_top + off) < 0
3054            || put_eol(fd) == FAIL
3055            || put_line(fd, "sil! normal! zo") == FAIL) {
3056          return FAIL;
3057        }
3058        if (put_foldopen_recurse(fd, wp, &fp->fd_nested,
3059                                 off + fp->fd_top)
3060            == FAIL) {
3061          return FAIL;
3062        }
3063        // close the parent when needed
3064        if (fp->fd_flags == FD_CLOSED) {
3065          if (put_fold_open_close(fd, fp, off) == FAIL) {
3066            return FAIL;
3067          }
3068        }
3069      } else {
3070        // Open or close the leaf according to the window foldlevel.
3071        // Do not close a leaf that is already closed, as it will close
3072        // the parent.
3073        int level = foldLevelWin(wp, off + fp->fd_top);
3074        if ((fp->fd_flags == FD_CLOSED && wp->w_p_fdl >= level)
3075            || (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level)) {
3076          if (put_fold_open_close(fd, fp, off) == FAIL) {
3077            return FAIL;
3078          }
3079        }
3080      }
3081    }
3082    fp++;
3083  }
3084
3085  return OK;
3086}
3087
3088/// Write the open or close command to "fd".
3089///
3090/// @return  FAIL when writing failed.
3091static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off)
3092{
3093  if (fprintf(fd, "%" PRIdLINENR, fp->fd_top + off) < 0
3094      || put_eol(fd) == FAIL
3095      || fprintf(fd, "sil! normal! z%c",
3096                 fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0
3097      || put_eol(fd) == FAIL) {
3098    return FAIL;
3099  }
3100
3101  return OK;
3102}
3103
3104// }}}1
3105
3106/// "foldclosed()" and "foldclosedend()" functions
3107static void foldclosed_both(typval_T *argvars, typval_T *rettv, bool end)
3108{
3109  const linenr_T lnum = tv_get_lnum(argvars);
3110  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) {
3111    linenr_T first;
3112    linenr_T last;
3113    if (hasFoldingWin(curwin, lnum, &first, &last, false, NULL)) {
3114      rettv->vval.v_number = (varnumber_T)(end ? last : first);
3115      return;
3116    }
3117  }
3118  rettv->vval.v_number = -1;
3119}
3120
3121/// "foldclosed()" function
3122void f_foldclosed(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3123{
3124  foldclosed_both(argvars, rettv, false);
3125}
3126
3127/// "foldclosedend()" function
3128void f_foldclosedend(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3129{
3130  foldclosed_both(argvars, rettv, true);
3131}
3132
3133/// "foldlevel()" function
3134void f_foldlevel(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3135{
3136  const linenr_T lnum = tv_get_lnum(argvars);
3137  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) {
3138    rettv->vval.v_number = foldLevel(lnum);
3139  }
3140}
3141
3142/// "foldtext()" function
3143void f_foldtext(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3144{
3145  rettv->v_type = VAR_STRING;
3146  rettv->vval.v_string = NULL;
3147
3148  linenr_T foldstart = (linenr_T)get_vim_var_nr(VV_FOLDSTART);
3149  linenr_T foldend = (linenr_T)get_vim_var_nr(VV_FOLDEND);
3150  char *dashes = get_vim_var_str(VV_FOLDDASHES);
3151  if (foldstart > 0 && foldend <= curbuf->b_ml.ml_line_count) {
3152    // Find first non-empty line in the fold.
3153    linenr_T lnum;
3154    for (lnum = foldstart; lnum < foldend; lnum++) {
3155      if (!linewhite(lnum)) {
3156        break;
3157      }
3158    }
3159
3160    // Find interesting text in this line.
3161    char *s = skipwhite(ml_get(lnum));
3162    // skip C comment-start
3163    if (s[0] == '/' && (s[1] == '*' || s[1] == '/')) {
3164      s = skipwhite(s + 2);
3165      if (*skipwhite(s) == NUL && lnum + 1 < foldend) {
3166        s = skipwhite(ml_get(lnum + 1));
3167        if (*s == '*') {
3168          s = skipwhite(s + 1);
3169        }
3170      }
3171    }
3172    int count = foldend - foldstart + 1;
3173    char *txt = NGETTEXT("+-%s%3d line: ", "+-%s%3d lines: ", count);
3174    size_t len = strlen(txt)
3175                 + strlen(dashes)  // for %s
3176                 + 20              // for %3ld
3177                 + strlen(s);      // concatenated
3178    char *r = xmalloc(len);
3179    snprintf(r, len, txt, dashes, count);
3180    len = strlen(r);
3181    strcat(r, s);
3182    // remove 'foldmarker' and 'commentstring'
3183    foldtext_cleanup(r + len);
3184    rettv->vval.v_string = r;
3185  }
3186}
3187
3188/// "foldtextresult(lnum)" function
3189void f_foldtextresult(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3190{
3191  char buf[FOLD_TEXT_LEN];
3192  static bool entered = false;
3193
3194  rettv->v_type = VAR_STRING;
3195  rettv->vval.v_string = NULL;
3196  if (entered) {
3197    return;  // reject recursive use
3198  }
3199  entered = true;
3200  linenr_T lnum = tv_get_lnum(argvars);
3201  // Treat illegal types and illegal string values for {lnum} the same.
3202  lnum = MAX(lnum, 0);
3203
3204  foldinfo_T info = fold_info(curwin, lnum);
3205  if (info.fi_lines > 0) {
3206    VirtText vt = VIRTTEXT_EMPTY;
3207    char *text = get_foldtext(curwin, lnum, lnum + info.fi_lines - 1, info, buf, &vt);
3208    if (text == buf) {
3209      text = xstrdup(text);
3210    }
3211    if (kv_size(vt) > 0) {
3212      assert(*text == NUL);
3213      for (size_t i = 0; i < kv_size(vt);) {
3214        int attr = 0;
3215        char *new_text = next_virt_text_chunk(vt, &i, &attr);
3216        if (new_text == NULL) {
3217          break;
3218        }
3219        new_text = concat_str(text, new_text);
3220        xfree(text);
3221        text = new_text;
3222      }
3223    }
3224    clear_virttext(&vt);
3225    rettv->vval.v_string = text;
3226  }
3227
3228  entered = false;
3229}