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