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