xref: /vim-8.2.3635/src/fold.c (revision 12ee7ff0)
1 /* vi:set ts=8 sts=4 sw=4 noet:
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 
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 
110 /* hasAnyFolding() {{{2 */
111 /*
112  * Return TRUE if there may be folded lines in the current window.
113  */
114     int
115 hasAnyFolding(win_T *win)
116 {
117     /* very simple now, but can become more complex later */
118     return (win->w_p_fen
119 	    && (!foldmethodIsManual(win) || win->w_folds.ga_len > 0));
120 }
121 
122 /* hasFolding() {{{2 */
123 /*
124  * Return TRUE if line "lnum" in the current window is part of a closed
125  * fold.
126  * When returning TRUE, *firstp and *lastp are set to the first and last
127  * lnum of the sequence of folded lines (skipped when NULL).
128  */
129     int
130 hasFolding(linenr_T lnum, linenr_T *firstp, linenr_T *lastp)
131 {
132     return hasFoldingWin(curwin, lnum, firstp, lastp, TRUE, NULL);
133 }
134 
135 /* hasFoldingWin() {{{2 */
136     int
137 hasFoldingWin(
138     win_T	*win,
139     linenr_T	lnum,
140     linenr_T	*firstp,
141     linenr_T	*lastp,
142     int		cache,		/* when TRUE: use cached values of window */
143     foldinfo_T	*infop)		/* where to store fold info */
144 {
145     int		had_folded = FALSE;
146     linenr_T	first = 0;
147     linenr_T	last = 0;
148     linenr_T	lnum_rel = lnum;
149     int		x;
150     fold_T	*fp;
151     int		level = 0;
152     int		use_level = FALSE;
153     int		maybe_small = FALSE;
154     garray_T	*gap;
155     int		low_level = 0;
156 
157     checkupdate(win);
158 
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     if (disable_fold_update > 0)
815 	return;
816 
817     /* Mark all folds from top to bot as maybe-small. */
818     (void)foldFind(&wp->w_folds, top, &fp);
819     while (fp < (fold_T *)wp->w_folds.ga_data + wp->w_folds.ga_len
820 	    && fp->fd_top < bot)
821     {
822 	fp->fd_small = MAYBE;
823 	++fp;
824     }
825 
826     if (foldmethodIsIndent(wp)
827 	    || foldmethodIsExpr(wp)
828 	    || foldmethodIsMarker(wp)
829 #ifdef FEAT_DIFF
830 	    || foldmethodIsDiff(wp)
831 #endif
832 	    || foldmethodIsSyntax(wp))
833     {
834 	int save_got_int = got_int;
835 
836 	/* reset got_int here, otherwise it won't work */
837 	got_int = FALSE;
838 	foldUpdateIEMS(wp, top, bot);
839 	got_int |= save_got_int;
840     }
841 }
842 
843 /* foldUpdateAll() {{{2 */
844 /*
845  * Update all lines in a window for folding.
846  * Used when a fold setting changes or after reloading the buffer.
847  * The actual updating is postponed until fold info is used, to avoid doing
848  * every time a setting is changed or a syntax item is added.
849  */
850     void
851 foldUpdateAll(win_T *win)
852 {
853     win->w_foldinvalid = TRUE;
854     redraw_win_later(win, NOT_VALID);
855 }
856 
857 /* foldMoveTo() {{{2 */
858 /*
859  * If "updown" is FALSE: Move to the start or end of the fold.
860  * If "updown" is TRUE: move to fold at the same level.
861  * If not moved return FAIL.
862  */
863     int
864 foldMoveTo(
865     int		updown,
866     int		dir,	    /* FORWARD or BACKWARD */
867     long	count)
868 {
869     long	n;
870     int		retval = FAIL;
871     linenr_T	lnum_off;
872     linenr_T	lnum_found;
873     linenr_T	lnum;
874     int		use_level;
875     int		maybe_small;
876     garray_T	*gap;
877     fold_T	*fp;
878     int		level;
879     int		last;
880 
881     checkupdate(curwin);
882 
883     /* Repeat "count" times. */
884     for (n = 0; n < count; ++n)
885     {
886 	/* Find nested folds.  Stop when a fold is closed.  The deepest fold
887 	 * that moves the cursor is used. */
888 	lnum_off = 0;
889 	gap = &curwin->w_folds;
890 	use_level = FALSE;
891 	maybe_small = FALSE;
892 	lnum_found = curwin->w_cursor.lnum;
893 	level = 0;
894 	last = FALSE;
895 	for (;;)
896 	{
897 	    if (!foldFind(gap, curwin->w_cursor.lnum - lnum_off, &fp))
898 	    {
899 		if (!updown)
900 		    break;
901 
902 		/* When moving up, consider a fold above the cursor; when
903 		 * moving down consider a fold below the cursor. */
904 		if (dir == FORWARD)
905 		{
906 		    if (fp - (fold_T *)gap->ga_data >= gap->ga_len)
907 			break;
908 		    --fp;
909 		}
910 		else
911 		{
912 		    if (fp == (fold_T *)gap->ga_data)
913 			break;
914 		}
915 		/* don't look for contained folds, they will always move
916 		 * the cursor too far. */
917 		last = TRUE;
918 	    }
919 
920 	    if (!last)
921 	    {
922 		/* Check if this fold is closed. */
923 		if (check_closed(curwin, fp, &use_level, level,
924 						      &maybe_small, lnum_off))
925 		    last = TRUE;
926 
927 		/* "[z" and "]z" stop at closed fold */
928 		if (last && !updown)
929 		    break;
930 	    }
931 
932 	    if (updown)
933 	    {
934 		if (dir == FORWARD)
935 		{
936 		    /* to start of next fold if there is one */
937 		    if (fp + 1 - (fold_T *)gap->ga_data < gap->ga_len)
938 		    {
939 			lnum = fp[1].fd_top + lnum_off;
940 			if (lnum > curwin->w_cursor.lnum)
941 			    lnum_found = lnum;
942 		    }
943 		}
944 		else
945 		{
946 		    /* to end of previous fold if there is one */
947 		    if (fp > (fold_T *)gap->ga_data)
948 		    {
949 			lnum = fp[-1].fd_top + lnum_off + fp[-1].fd_len - 1;
950 			if (lnum < curwin->w_cursor.lnum)
951 			    lnum_found = lnum;
952 		    }
953 		}
954 	    }
955 	    else
956 	    {
957 		/* Open fold found, set cursor to its start/end and then check
958 		 * nested folds. */
959 		if (dir == FORWARD)
960 		{
961 		    lnum = fp->fd_top + lnum_off + fp->fd_len - 1;
962 		    if (lnum > curwin->w_cursor.lnum)
963 			lnum_found = lnum;
964 		}
965 		else
966 		{
967 		    lnum = fp->fd_top + lnum_off;
968 		    if (lnum < curwin->w_cursor.lnum)
969 			lnum_found = lnum;
970 		}
971 	    }
972 
973 	    if (last)
974 		break;
975 
976 	    /* Check nested folds (if any). */
977 	    gap = &fp->fd_nested;
978 	    lnum_off += fp->fd_top;
979 	    ++level;
980 	}
981 	if (lnum_found != curwin->w_cursor.lnum)
982 	{
983 	    if (retval == FAIL)
984 		setpcmark();
985 	    curwin->w_cursor.lnum = lnum_found;
986 	    curwin->w_cursor.col = 0;
987 	    retval = OK;
988 	}
989 	else
990 	    break;
991     }
992 
993     return retval;
994 }
995 
996 /* foldInitWin() {{{2 */
997 /*
998  * Init the fold info in a new window.
999  */
1000     void
1001 foldInitWin(win_T *new_win)
1002 {
1003     ga_init2(&new_win->w_folds, (int)sizeof(fold_T), 10);
1004 }
1005 
1006 /* find_wl_entry() {{{2 */
1007 /*
1008  * Find an entry in the win->w_lines[] array for buffer line "lnum".
1009  * Only valid entries are considered (for entries where wl_valid is FALSE the
1010  * line number can be wrong).
1011  * Returns index of entry or -1 if not found.
1012  */
1013     int
1014 find_wl_entry(win_T *win, linenr_T lnum)
1015 {
1016     int		i;
1017 
1018     for (i = 0; i < win->w_lines_valid; ++i)
1019 	if (win->w_lines[i].wl_valid)
1020 	{
1021 	    if (lnum < win->w_lines[i].wl_lnum)
1022 		return -1;
1023 	    if (lnum <= win->w_lines[i].wl_lastlnum)
1024 		return i;
1025 	}
1026     return -1;
1027 }
1028 
1029 /* foldAdjustVisual() {{{2 */
1030 /*
1031  * Adjust the Visual area to include any fold at the start or end completely.
1032  */
1033     void
1034 foldAdjustVisual(void)
1035 {
1036     pos_T	*start, *end;
1037     char_u	*ptr;
1038 
1039     if (!VIsual_active || !hasAnyFolding(curwin))
1040 	return;
1041 
1042     if (LTOREQ_POS(VIsual, curwin->w_cursor))
1043     {
1044 	start = &VIsual;
1045 	end = &curwin->w_cursor;
1046     }
1047     else
1048     {
1049 	start = &curwin->w_cursor;
1050 	end = &VIsual;
1051     }
1052     if (hasFolding(start->lnum, &start->lnum, NULL))
1053 	start->col = 0;
1054     if (hasFolding(end->lnum, NULL, &end->lnum))
1055     {
1056 	ptr = ml_get(end->lnum);
1057 	end->col = (colnr_T)STRLEN(ptr);
1058 	if (end->col > 0 && *p_sel == 'o')
1059 	    --end->col;
1060 	/* prevent cursor from moving on the trail byte */
1061 	if (has_mbyte)
1062 	    mb_adjust_cursor();
1063     }
1064 }
1065 
1066 /* cursor_foldstart() {{{2 */
1067 /*
1068  * Move the cursor to the first line of a closed fold.
1069  */
1070     void
1071 foldAdjustCursor(void)
1072 {
1073     (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL);
1074 }
1075 
1076 /* Internal functions for "fold_T" {{{1 */
1077 /* cloneFoldGrowArray() {{{2 */
1078 /*
1079  * Will "clone" (i.e deep copy) a garray_T of folds.
1080  *
1081  * Return FAIL if the operation cannot be completed, otherwise OK.
1082  */
1083     void
1084 cloneFoldGrowArray(garray_T *from, garray_T *to)
1085 {
1086     int		i;
1087     fold_T	*from_p;
1088     fold_T	*to_p;
1089 
1090     ga_init2(to, from->ga_itemsize, from->ga_growsize);
1091     if (from->ga_len == 0 || ga_grow(to, from->ga_len) == FAIL)
1092 	return;
1093 
1094     from_p = (fold_T *)from->ga_data;
1095     to_p = (fold_T *)to->ga_data;
1096 
1097     for (i = 0; i < from->ga_len; i++)
1098     {
1099 	to_p->fd_top = from_p->fd_top;
1100 	to_p->fd_len = from_p->fd_len;
1101 	to_p->fd_flags = from_p->fd_flags;
1102 	to_p->fd_small = from_p->fd_small;
1103 	cloneFoldGrowArray(&from_p->fd_nested, &to_p->fd_nested);
1104 	++to->ga_len;
1105 	++from_p;
1106 	++to_p;
1107     }
1108 }
1109 
1110 /* foldFind() {{{2 */
1111 /*
1112  * Search for line "lnum" in folds of growarray "gap".
1113  * Set *fpp to the fold struct for the fold that contains "lnum" or
1114  * the first fold below it (careful: it can be beyond the end of the array!).
1115  * Returns FALSE when there is no fold that contains "lnum".
1116  */
1117     static int
1118 foldFind(garray_T *gap, linenr_T lnum, fold_T **fpp)
1119 {
1120     linenr_T	low, high;
1121     fold_T	*fp;
1122     int		i;
1123 
1124     /*
1125      * Perform a binary search.
1126      * "low" is lowest index of possible match.
1127      * "high" is highest index of possible match.
1128      */
1129     fp = (fold_T *)gap->ga_data;
1130     low = 0;
1131     high = gap->ga_len - 1;
1132     while (low <= high)
1133     {
1134 	i = (low + high) / 2;
1135 	if (fp[i].fd_top > lnum)
1136 	    /* fold below lnum, adjust high */
1137 	    high = i - 1;
1138 	else if (fp[i].fd_top + fp[i].fd_len <= lnum)
1139 	    /* fold above lnum, adjust low */
1140 	    low = i + 1;
1141 	else
1142 	{
1143 	    /* lnum is inside this fold */
1144 	    *fpp = fp + i;
1145 	    return TRUE;
1146 	}
1147     }
1148     *fpp = fp + low;
1149     return FALSE;
1150 }
1151 
1152 /* foldLevelWin() {{{2 */
1153 /*
1154  * Return fold level at line number "lnum" in window "wp".
1155  */
1156     static int
1157 foldLevelWin(win_T *wp, linenr_T lnum)
1158 {
1159     fold_T	*fp;
1160     linenr_T	lnum_rel = lnum;
1161     int		level =  0;
1162     garray_T	*gap;
1163 
1164     /* Recursively search for a fold that contains "lnum". */
1165     gap = &wp->w_folds;
1166     for (;;)
1167     {
1168 	if (!foldFind(gap, lnum_rel, &fp))
1169 	    break;
1170 	/* Check nested folds.  Line number is relative to containing fold. */
1171 	gap = &fp->fd_nested;
1172 	lnum_rel -= fp->fd_top;
1173 	++level;
1174     }
1175 
1176     return level;
1177 }
1178 
1179 /* checkupdate() {{{2 */
1180 /*
1181  * Check if the folds in window "wp" are invalid and update them if needed.
1182  */
1183     static void
1184 checkupdate(win_T *wp)
1185 {
1186     if (wp->w_foldinvalid)
1187     {
1188 	foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); /* will update all */
1189 	wp->w_foldinvalid = FALSE;
1190     }
1191 }
1192 
1193 /* setFoldRepeat() {{{2 */
1194 /*
1195  * Open or close fold for current window at line "lnum".
1196  * Repeat "count" times.
1197  */
1198     static void
1199 setFoldRepeat(linenr_T lnum, long count, int do_open)
1200 {
1201     int		done;
1202     long	n;
1203 
1204     for (n = 0; n < count; ++n)
1205     {
1206 	done = DONE_NOTHING;
1207 	(void)setManualFold(lnum, do_open, FALSE, &done);
1208 	if (!(done & DONE_ACTION))
1209 	{
1210 	    /* Only give an error message when no fold could be opened. */
1211 	    if (n == 0 && !(done & DONE_FOLD))
1212 		emsg(_(e_nofold));
1213 	    break;
1214 	}
1215     }
1216 }
1217 
1218 /* setManualFold() {{{2 */
1219 /*
1220  * Open or close the fold in the current window which contains "lnum".
1221  * Also does this for other windows in diff mode when needed.
1222  */
1223     static linenr_T
1224 setManualFold(
1225     linenr_T	lnum,
1226     int		opening,    /* TRUE when opening, FALSE when closing */
1227     int		recurse,    /* TRUE when closing/opening recursive */
1228     int		*donep)
1229 {
1230 #ifdef FEAT_DIFF
1231     if (foldmethodIsDiff(curwin) && curwin->w_p_scb)
1232     {
1233 	win_T	    *wp;
1234 	linenr_T    dlnum;
1235 
1236 	/*
1237 	 * Do the same operation in other windows in diff mode.  Calculate the
1238 	 * line number from the diffs.
1239 	 */
1240 	FOR_ALL_WINDOWS(wp)
1241 	{
1242 	    if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb)
1243 	    {
1244 		dlnum = diff_lnum_win(curwin->w_cursor.lnum, wp);
1245 		if (dlnum != 0)
1246 		    (void)setManualFoldWin(wp, dlnum, opening, recurse, NULL);
1247 	    }
1248 	}
1249     }
1250 #endif
1251 
1252     return setManualFoldWin(curwin, lnum, opening, recurse, donep);
1253 }
1254 
1255 /* setManualFoldWin() {{{2 */
1256 /*
1257  * Open or close the fold in window "wp" which contains "lnum".
1258  * "donep", when not NULL, points to flag that is set to DONE_FOLD when some
1259  * fold was found and to DONE_ACTION when some fold was opened or closed.
1260  * When "donep" is NULL give an error message when no fold was found for
1261  * "lnum", but only if "wp" is "curwin".
1262  * Return the line number of the next line that could be closed.
1263  * It's only valid when "opening" is TRUE!
1264  */
1265     static linenr_T
1266 setManualFoldWin(
1267     win_T	*wp,
1268     linenr_T	lnum,
1269     int		opening,    /* TRUE when opening, FALSE when closing */
1270     int		recurse,    /* TRUE when closing/opening recursive */
1271     int		*donep)
1272 {
1273     fold_T	*fp;
1274     fold_T	*fp2;
1275     fold_T	*found = NULL;
1276     int		j;
1277     int		level = 0;
1278     int		use_level = FALSE;
1279     int		found_fold = FALSE;
1280     garray_T	*gap;
1281     linenr_T	next = MAXLNUM;
1282     linenr_T	off = 0;
1283     int		done = 0;
1284 
1285     checkupdate(wp);
1286 
1287     /*
1288      * Find the fold, open or close it.
1289      */
1290     gap = &wp->w_folds;
1291     for (;;)
1292     {
1293 	if (!foldFind(gap, lnum, &fp))
1294 	{
1295 	    /* If there is a following fold, continue there next time. */
1296 	    if (fp < (fold_T *)gap->ga_data + gap->ga_len)
1297 		next = fp->fd_top + off;
1298 	    break;
1299 	}
1300 
1301 	/* lnum is inside this fold */
1302 	found_fold = TRUE;
1303 
1304 	/* If there is a following fold, continue there next time. */
1305 	if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len)
1306 	    next = fp[1].fd_top + off;
1307 
1308 	/* Change from level-dependent folding to manual. */
1309 	if (use_level || fp->fd_flags == FD_LEVEL)
1310 	{
1311 	    use_level = TRUE;
1312 	    if (level >= wp->w_p_fdl)
1313 		fp->fd_flags = FD_CLOSED;
1314 	    else
1315 		fp->fd_flags = FD_OPEN;
1316 	    fp2 = (fold_T *)fp->fd_nested.ga_data;
1317 	    for (j = 0; j < fp->fd_nested.ga_len; ++j)
1318 		fp2[j].fd_flags = FD_LEVEL;
1319 	}
1320 
1321 	/* Simple case: Close recursively means closing the fold. */
1322 	if (!opening && recurse)
1323 	{
1324 	    if (fp->fd_flags != FD_CLOSED)
1325 	    {
1326 		done |= DONE_ACTION;
1327 		fp->fd_flags = FD_CLOSED;
1328 	    }
1329 	}
1330 	else if (fp->fd_flags == FD_CLOSED)
1331 	{
1332 	    /* When opening, open topmost closed fold. */
1333 	    if (opening)
1334 	    {
1335 		fp->fd_flags = FD_OPEN;
1336 		done |= DONE_ACTION;
1337 		if (recurse)
1338 		    foldOpenNested(fp);
1339 	    }
1340 	    break;
1341 	}
1342 
1343 	/* fold is open, check nested folds */
1344 	found = fp;
1345 	gap = &fp->fd_nested;
1346 	lnum -= fp->fd_top;
1347 	off += fp->fd_top;
1348 	++level;
1349     }
1350     if (found_fold)
1351     {
1352 	/* When closing and not recurse, close deepest open fold. */
1353 	if (!opening && found != NULL)
1354 	{
1355 	    found->fd_flags = FD_CLOSED;
1356 	    done |= DONE_ACTION;
1357 	}
1358 	wp->w_fold_manual = TRUE;
1359 	if (done & DONE_ACTION)
1360 	    changed_window_setting_win(wp);
1361 	done |= DONE_FOLD;
1362     }
1363     else if (donep == NULL && wp == curwin)
1364 	emsg(_(e_nofold));
1365 
1366     if (donep != NULL)
1367 	*donep |= done;
1368 
1369     return next;
1370 }
1371 
1372 /* foldOpenNested() {{{2 */
1373 /*
1374  * Open all nested folds in fold "fpr" recursively.
1375  */
1376     static void
1377 foldOpenNested(fold_T *fpr)
1378 {
1379     int		i;
1380     fold_T	*fp;
1381 
1382     fp = (fold_T *)fpr->fd_nested.ga_data;
1383     for (i = 0; i < fpr->fd_nested.ga_len; ++i)
1384     {
1385 	foldOpenNested(&fp[i]);
1386 	fp[i].fd_flags = FD_OPEN;
1387     }
1388 }
1389 
1390 /* deleteFoldEntry() {{{2 */
1391 /*
1392  * Delete fold "idx" from growarray "gap".
1393  * When "recursive" is TRUE also delete all the folds contained in it.
1394  * When "recursive" is FALSE contained folds are moved one level up.
1395  */
1396     static void
1397 deleteFoldEntry(garray_T *gap, int idx, int recursive)
1398 {
1399     fold_T	*fp;
1400     int		i;
1401     long	moved;
1402     fold_T	*nfp;
1403 
1404     fp = (fold_T *)gap->ga_data + idx;
1405     if (recursive || fp->fd_nested.ga_len == 0)
1406     {
1407 	/* recursively delete the contained folds */
1408 	deleteFoldRecurse(&fp->fd_nested);
1409 	--gap->ga_len;
1410 	if (idx < gap->ga_len)
1411 	    mch_memmove(fp, fp + 1, sizeof(fold_T) * (gap->ga_len - idx));
1412     }
1413     else
1414     {
1415 	/* Move nested folds one level up, to overwrite the fold that is
1416 	 * deleted. */
1417 	moved = fp->fd_nested.ga_len;
1418 	if (ga_grow(gap, (int)(moved - 1)) == OK)
1419 	{
1420 	    /* Get "fp" again, the array may have been reallocated. */
1421 	    fp = (fold_T *)gap->ga_data + idx;
1422 
1423 	    /* adjust fd_top and fd_flags for the moved folds */
1424 	    nfp = (fold_T *)fp->fd_nested.ga_data;
1425 	    for (i = 0; i < moved; ++i)
1426 	    {
1427 		nfp[i].fd_top += fp->fd_top;
1428 		if (fp->fd_flags == FD_LEVEL)
1429 		    nfp[i].fd_flags = FD_LEVEL;
1430 		if (fp->fd_small == MAYBE)
1431 		    nfp[i].fd_small = MAYBE;
1432 	    }
1433 
1434 	    /* move the existing folds down to make room */
1435 	    if (idx + 1 < gap->ga_len)
1436 		mch_memmove(fp + moved, fp + 1,
1437 				  sizeof(fold_T) * (gap->ga_len - (idx + 1)));
1438 	    /* move the contained folds one level up */
1439 	    mch_memmove(fp, nfp, (size_t)(sizeof(fold_T) * moved));
1440 	    vim_free(nfp);
1441 	    gap->ga_len += moved - 1;
1442 	}
1443     }
1444 }
1445 
1446 /* deleteFoldRecurse() {{{2 */
1447 /*
1448  * Delete nested folds in a fold.
1449  */
1450     void
1451 deleteFoldRecurse(garray_T *gap)
1452 {
1453     int		i;
1454 
1455     for (i = 0; i < gap->ga_len; ++i)
1456 	deleteFoldRecurse(&(((fold_T *)(gap->ga_data))[i].fd_nested));
1457     ga_clear(gap);
1458 }
1459 
1460 /* foldMarkAdjust() {{{2 */
1461 /*
1462  * Update line numbers of folds for inserted/deleted lines.
1463  */
1464     void
1465 foldMarkAdjust(
1466     win_T	*wp,
1467     linenr_T	line1,
1468     linenr_T	line2,
1469     long	amount,
1470     long	amount_after)
1471 {
1472     /* If deleting marks from line1 to line2, but not deleting all those
1473      * lines, set line2 so that only deleted lines have their folds removed. */
1474     if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after)
1475 	line2 = line1 - amount_after - 1;
1476     /* If appending a line in Insert mode, it should be included in the fold
1477      * just above the line. */
1478     if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM)
1479 	--line1;
1480     foldMarkAdjustRecurse(&wp->w_folds, line1, line2, amount, amount_after);
1481 }
1482 
1483 /* foldMarkAdjustRecurse() {{{2 */
1484     static void
1485 foldMarkAdjustRecurse(
1486     garray_T	*gap,
1487     linenr_T	line1,
1488     linenr_T	line2,
1489     long	amount,
1490     long	amount_after)
1491 {
1492     fold_T	*fp;
1493     int		i;
1494     linenr_T	last;
1495     linenr_T	top;
1496 
1497     /* In Insert mode an inserted line at the top of a fold is considered part
1498      * of the fold, otherwise it isn't. */
1499     if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM)
1500 	top = line1 + 1;
1501     else
1502 	top = line1;
1503 
1504     /* Find the fold containing or just below "line1". */
1505     (void)foldFind(gap, line1, &fp);
1506 
1507     /*
1508      * Adjust all folds below "line1" that are affected.
1509      */
1510     for (i = (int)(fp - (fold_T *)gap->ga_data); i < gap->ga_len; ++i, ++fp)
1511     {
1512 	/*
1513 	 * Check for these situations:
1514 	 *	  1  2	3
1515 	 *	  1  2	3
1516 	 * line1     2	3  4  5
1517 	 *	     2	3  4  5
1518 	 *	     2	3  4  5
1519 	 * line2     2	3  4  5
1520 	 *		3     5  6
1521 	 *		3     5  6
1522 	 */
1523 
1524 	last = fp->fd_top + fp->fd_len - 1; /* last line of fold */
1525 
1526 	/* 1. fold completely above line1: nothing to do */
1527 	if (last < line1)
1528 	    continue;
1529 
1530 	/* 6. fold below line2: only adjust for amount_after */
1531 	if (fp->fd_top > line2)
1532 	{
1533 	    if (amount_after == 0)
1534 		break;
1535 	    fp->fd_top += amount_after;
1536 	}
1537 	else
1538 	{
1539 	    if (fp->fd_top >= top && last <= line2)
1540 	    {
1541 		/* 4. fold completely contained in range */
1542 		if (amount == MAXLNUM)
1543 		{
1544 		    /* Deleting lines: delete the fold completely */
1545 		    deleteFoldEntry(gap, i, TRUE);
1546 		    --i;    /* adjust index for deletion */
1547 		    --fp;
1548 		}
1549 		else
1550 		    fp->fd_top += amount;
1551 	    }
1552 	    else
1553 	    {
1554 		if (fp->fd_top < top)
1555 		{
1556 		    /* 2 or 3: need to correct nested folds too */
1557 		    foldMarkAdjustRecurse(&fp->fd_nested, line1 - fp->fd_top,
1558 				  line2 - fp->fd_top, amount, amount_after);
1559 		    if (last <= line2)
1560 		    {
1561 			/* 2. fold contains line1, line2 is below fold */
1562 			if (amount == MAXLNUM)
1563 			    fp->fd_len = line1 - fp->fd_top;
1564 			else
1565 			    fp->fd_len += amount;
1566 		    }
1567 		    else
1568 		    {
1569 			/* 3. fold contains line1 and line2 */
1570 			fp->fd_len += amount_after;
1571 		    }
1572 		}
1573 		else
1574 		{
1575 		    /* 5. fold is below line1 and contains line2; need to
1576 		     * correct nested folds too */
1577 		    if (amount == MAXLNUM)
1578 		    {
1579 			foldMarkAdjustRecurse(&fp->fd_nested,
1580 				  line1 - fp->fd_top,
1581 				  line2 - fp->fd_top,
1582 				  amount,
1583 				  amount_after + (fp->fd_top - top));
1584 			fp->fd_len -= line2 - fp->fd_top + 1;
1585 			fp->fd_top = line1;
1586 		    }
1587 		    else
1588 		    {
1589 			foldMarkAdjustRecurse(&fp->fd_nested,
1590 				  line1 - fp->fd_top,
1591 				  line2 - fp->fd_top,
1592 				  amount,
1593 				  amount_after - amount);
1594 			fp->fd_len += amount_after - amount;
1595 			fp->fd_top += amount;
1596 		    }
1597 		}
1598 	    }
1599 	}
1600     }
1601 }
1602 
1603 /* getDeepestNesting() {{{2 */
1604 /*
1605  * Get the lowest 'foldlevel' value that makes the deepest nested fold in the
1606  * current window open.
1607  */
1608     int
1609 getDeepestNesting(void)
1610 {
1611     checkupdate(curwin);
1612     return getDeepestNestingRecurse(&curwin->w_folds);
1613 }
1614 
1615     static int
1616 getDeepestNestingRecurse(garray_T *gap)
1617 {
1618     int		i;
1619     int		level;
1620     int		maxlevel = 0;
1621     fold_T	*fp;
1622 
1623     fp = (fold_T *)gap->ga_data;
1624     for (i = 0; i < gap->ga_len; ++i)
1625     {
1626 	level = getDeepestNestingRecurse(&fp[i].fd_nested) + 1;
1627 	if (level > maxlevel)
1628 	    maxlevel = level;
1629     }
1630 
1631     return maxlevel;
1632 }
1633 
1634 /* check_closed() {{{2 */
1635 /*
1636  * Check if a fold is closed and update the info needed to check nested folds.
1637  */
1638     static int
1639 check_closed(
1640     win_T	*win,
1641     fold_T	*fp,
1642     int		*use_levelp,	    /* TRUE: outer fold had FD_LEVEL */
1643     int		level,		    /* folding depth */
1644     int		*maybe_smallp,	    /* TRUE: outer this had fd_small == MAYBE */
1645     linenr_T	lnum_off)	    /* line number offset for fp->fd_top */
1646 {
1647     int		closed = FALSE;
1648 
1649     /* Check if this fold is closed.  If the flag is FD_LEVEL this
1650      * fold and all folds it contains depend on 'foldlevel'. */
1651     if (*use_levelp || fp->fd_flags == FD_LEVEL)
1652     {
1653 	*use_levelp = TRUE;
1654 	if (level >= win->w_p_fdl)
1655 	    closed = TRUE;
1656     }
1657     else if (fp->fd_flags == FD_CLOSED)
1658 	closed = TRUE;
1659 
1660     /* Small fold isn't closed anyway. */
1661     if (fp->fd_small == MAYBE)
1662 	*maybe_smallp = TRUE;
1663     if (closed)
1664     {
1665 	if (*maybe_smallp)
1666 	    fp->fd_small = MAYBE;
1667 	checkSmall(win, fp, lnum_off);
1668 	if (fp->fd_small == TRUE)
1669 	    closed = FALSE;
1670     }
1671     return closed;
1672 }
1673 
1674 /* checkSmall() {{{2 */
1675 /*
1676  * Update fd_small field of fold "fp".
1677  */
1678     static void
1679 checkSmall(
1680     win_T	*wp,
1681     fold_T	*fp,
1682     linenr_T	lnum_off)	/* offset for fp->fd_top */
1683 {
1684     int		count;
1685     int		n;
1686 
1687     if (fp->fd_small == MAYBE)
1688     {
1689 	/* Mark any nested folds to maybe-small */
1690 	setSmallMaybe(&fp->fd_nested);
1691 
1692 	if (fp->fd_len > curwin->w_p_fml)
1693 	    fp->fd_small = FALSE;
1694 	else
1695 	{
1696 	    count = 0;
1697 	    for (n = 0; n < fp->fd_len; ++n)
1698 	    {
1699 		count += plines_win_nofold(wp, fp->fd_top + lnum_off + n);
1700 		if (count > curwin->w_p_fml)
1701 		{
1702 		    fp->fd_small = FALSE;
1703 		    return;
1704 		}
1705 	    }
1706 	    fp->fd_small = TRUE;
1707 	}
1708     }
1709 }
1710 
1711 /* setSmallMaybe() {{{2 */
1712 /*
1713  * Set small flags in "gap" to MAYBE.
1714  */
1715     static void
1716 setSmallMaybe(garray_T *gap)
1717 {
1718     int		i;
1719     fold_T	*fp;
1720 
1721     fp = (fold_T *)gap->ga_data;
1722     for (i = 0; i < gap->ga_len; ++i)
1723 	fp[i].fd_small = MAYBE;
1724 }
1725 
1726 /* foldCreateMarkers() {{{2 */
1727 /*
1728  * Create a fold from line "start" to line "end" (inclusive) in the current
1729  * window by adding markers.
1730  */
1731     static void
1732 foldCreateMarkers(linenr_T start, linenr_T end)
1733 {
1734     if (!curbuf->b_p_ma)
1735     {
1736 	emsg(_(e_modifiable));
1737 	return;
1738     }
1739     parseMarker(curwin);
1740 
1741     foldAddMarker(start, curwin->w_p_fmr, foldstartmarkerlen);
1742     foldAddMarker(end, foldendmarker, foldendmarkerlen);
1743 
1744     /* Update both changes here, to avoid all folds after the start are
1745      * changed when the start marker is inserted and the end isn't. */
1746     changed_lines(start, (colnr_T)0, end, 0L);
1747 }
1748 
1749 /* foldAddMarker() {{{2 */
1750 /*
1751  * Add "marker[markerlen]" in 'commentstring' to line "lnum".
1752  */
1753     static void
1754 foldAddMarker(linenr_T lnum, char_u *marker, int markerlen)
1755 {
1756     char_u	*cms = curbuf->b_p_cms;
1757     char_u	*line;
1758     int		line_len;
1759     char_u	*newline;
1760     char_u	*p = (char_u *)strstr((char *)curbuf->b_p_cms, "%s");
1761     int		line_is_comment = FALSE;
1762 
1763     /* Allocate a new line: old-line + 'cms'-start + marker + 'cms'-end */
1764     line = ml_get(lnum);
1765     line_len = (int)STRLEN(line);
1766 
1767     if (u_save(lnum - 1, lnum + 1) == OK)
1768     {
1769 #if defined(FEAT_COMMENTS)
1770 	/* Check if the line ends with an unclosed comment */
1771 	(void)skip_comment(line, FALSE, FALSE, &line_is_comment);
1772 #endif
1773 	newline = alloc(line_len + markerlen + STRLEN(cms) + 1);
1774 	if (newline == NULL)
1775 	    return;
1776 	STRCPY(newline, line);
1777 	/* Append the marker to the end of the line */
1778 	if (p == NULL || line_is_comment)
1779 	    vim_strncpy(newline + line_len, marker, markerlen);
1780 	else
1781 	{
1782 	    STRCPY(newline + line_len, cms);
1783 	    STRNCPY(newline + line_len + (p - cms), marker, markerlen);
1784 	    STRCPY(newline + line_len + (p - cms) + markerlen, p + 2);
1785 	}
1786 
1787 	ml_replace(lnum, newline, FALSE);
1788     }
1789 }
1790 
1791 /* deleteFoldMarkers() {{{2 */
1792 /*
1793  * Delete the markers for a fold, causing it to be deleted.
1794  */
1795     static void
1796 deleteFoldMarkers(
1797     fold_T	*fp,
1798     int		recursive,
1799     linenr_T	lnum_off)	/* offset for fp->fd_top */
1800 {
1801     int		i;
1802 
1803     if (recursive)
1804 	for (i = 0; i < fp->fd_nested.ga_len; ++i)
1805 	    deleteFoldMarkers((fold_T *)fp->fd_nested.ga_data + i, TRUE,
1806 						       lnum_off + fp->fd_top);
1807     foldDelMarker(fp->fd_top + lnum_off, curwin->w_p_fmr, foldstartmarkerlen);
1808     foldDelMarker(fp->fd_top + lnum_off + fp->fd_len - 1,
1809 					     foldendmarker, foldendmarkerlen);
1810 }
1811 
1812 /* foldDelMarker() {{{2 */
1813 /*
1814  * Delete marker "marker[markerlen]" at the end of line "lnum".
1815  * Delete 'commentstring' if it matches.
1816  * If the marker is not found, there is no error message.  Could a missing
1817  * close-marker.
1818  */
1819     static void
1820 foldDelMarker(linenr_T lnum, char_u *marker, int markerlen)
1821 {
1822     char_u	*line;
1823     char_u	*newline;
1824     char_u	*p;
1825     int		len;
1826     char_u	*cms = curbuf->b_p_cms;
1827     char_u	*cms2;
1828 
1829     line = ml_get(lnum);
1830     for (p = line; *p != NUL; ++p)
1831 	if (STRNCMP(p, marker, markerlen) == 0)
1832 	{
1833 	    /* Found the marker, include a digit if it's there. */
1834 	    len = markerlen;
1835 	    if (VIM_ISDIGIT(p[len]))
1836 		++len;
1837 	    if (*cms != NUL)
1838 	    {
1839 		/* Also delete 'commentstring' if it matches. */
1840 		cms2 = (char_u *)strstr((char *)cms, "%s");
1841 		if (p - line >= cms2 - cms
1842 			&& STRNCMP(p - (cms2 - cms), cms, cms2 - cms) == 0
1843 			&& STRNCMP(p + len, cms2 + 2, STRLEN(cms2 + 2)) == 0)
1844 		{
1845 		    p -= cms2 - cms;
1846 		    len += (int)STRLEN(cms) - 2;
1847 		}
1848 	    }
1849 	    if (u_save(lnum - 1, lnum + 1) == OK)
1850 	    {
1851 		/* Make new line: text-before-marker + text-after-marker */
1852 		newline = alloc(STRLEN(line) - len + 1);
1853 		if (newline != NULL)
1854 		{
1855 		    STRNCPY(newline, line, p - line);
1856 		    STRCPY(newline + (p - line), p + len);
1857 		    ml_replace(lnum, newline, FALSE);
1858 		}
1859 	    }
1860 	    break;
1861 	}
1862 }
1863 
1864 /* get_foldtext() {{{2 */
1865 /*
1866  * Return the text for a closed fold at line "lnum", with last line "lnume".
1867  * When 'foldtext' isn't set puts the result in "buf[FOLD_TEXT_LEN]".
1868  * Otherwise the result is in allocated memory.
1869  */
1870     char_u *
1871 get_foldtext(
1872     win_T	*wp,
1873     linenr_T	lnum,
1874     linenr_T	lnume,
1875     foldinfo_T	*foldinfo,
1876     char_u	*buf)
1877 {
1878     char_u	*text = NULL;
1879 #ifdef FEAT_EVAL
1880      /* an error occurred when evaluating 'fdt' setting */
1881     static int	    got_fdt_error = FALSE;
1882     int		    save_did_emsg = did_emsg;
1883     static win_T    *last_wp = NULL;
1884     static linenr_T last_lnum = 0;
1885 
1886     if (last_wp != wp || last_wp == NULL
1887 					|| last_lnum > lnum || last_lnum == 0)
1888 	/* window changed, try evaluating foldtext setting once again */
1889 	got_fdt_error = FALSE;
1890 
1891     if (!got_fdt_error)
1892 	/* a previous error should not abort evaluating 'foldexpr' */
1893 	did_emsg = FALSE;
1894 
1895     if (*wp->w_p_fdt != NUL)
1896     {
1897 	char_u	dashes[MAX_LEVEL + 2];
1898 	win_T	*save_curwin;
1899 	int	level;
1900 	char_u	*p;
1901 
1902 	/* Set "v:foldstart" and "v:foldend". */
1903 	set_vim_var_nr(VV_FOLDSTART, lnum);
1904 	set_vim_var_nr(VV_FOLDEND, lnume);
1905 
1906 	/* Set "v:folddashes" to a string of "level" dashes. */
1907 	/* Set "v:foldlevel" to "level". */
1908 	level = foldinfo->fi_level;
1909 	if (level > (int)sizeof(dashes) - 1)
1910 	    level = (int)sizeof(dashes) - 1;
1911 	vim_memset(dashes, '-', (size_t)level);
1912 	dashes[level] = NUL;
1913 	set_vim_var_string(VV_FOLDDASHES, dashes, -1);
1914 	set_vim_var_nr(VV_FOLDLEVEL, (long)level);
1915 
1916 	/* skip evaluating foldtext on errors */
1917 	if (!got_fdt_error)
1918 	{
1919 	    save_curwin = curwin;
1920 	    curwin = wp;
1921 	    curbuf = wp->w_buffer;
1922 
1923 	    ++emsg_silent; /* handle exceptions, but don't display errors */
1924 	    text = eval_to_string_safe(wp->w_p_fdt, NULL,
1925 			 was_set_insecurely((char_u *)"foldtext", OPT_LOCAL));
1926 	    --emsg_silent;
1927 
1928 	    if (text == NULL || did_emsg)
1929 		got_fdt_error = TRUE;
1930 
1931 	    curwin = save_curwin;
1932 	    curbuf = curwin->w_buffer;
1933 	}
1934 	last_lnum = lnum;
1935 	last_wp   = wp;
1936 	set_vim_var_string(VV_FOLDDASHES, NULL, -1);
1937 
1938 	if (!did_emsg && save_did_emsg)
1939 	    did_emsg = save_did_emsg;
1940 
1941 	if (text != NULL)
1942 	{
1943 	    /* Replace unprintable characters, if there are any.  But
1944 	     * replace a TAB with a space. */
1945 	    for (p = text; *p != NUL; ++p)
1946 	    {
1947 		int	len;
1948 
1949 		if (has_mbyte && (len = (*mb_ptr2len)(p)) > 1)
1950 		{
1951 		    if (!vim_isprintc((*mb_ptr2char)(p)))
1952 			break;
1953 		    p += len - 1;
1954 		}
1955 		else
1956 		    if (*p == TAB)
1957 			*p = ' ';
1958 		    else if (ptr2cells(p) > 1)
1959 			break;
1960 	    }
1961 	    if (*p != NUL)
1962 	    {
1963 		p = transstr(text);
1964 		vim_free(text);
1965 		text = p;
1966 	    }
1967 	}
1968     }
1969     if (text == NULL)
1970 #endif
1971     {
1972 	long count = (long)(lnume - lnum + 1);
1973 
1974 	vim_snprintf((char *)buf, FOLD_TEXT_LEN,
1975 		     NGETTEXT("+--%3ld line folded ",
1976 					       "+--%3ld lines folded ", count),
1977 		     count);
1978 	text = buf;
1979     }
1980     return text;
1981 }
1982 
1983 /* foldtext_cleanup() {{{2 */
1984 /*
1985  * Remove 'foldmarker' and 'commentstring' from "str" (in-place).
1986  */
1987     void
1988 foldtext_cleanup(char_u *str)
1989 {
1990     char_u	*cms_start;	/* first part or the whole comment */
1991     int		cms_slen = 0;	/* length of cms_start */
1992     char_u	*cms_end;	/* last part of the comment or NULL */
1993     int		cms_elen = 0;	/* length of cms_end */
1994     char_u	*s;
1995     char_u	*p;
1996     int		len;
1997     int		did1 = FALSE;
1998     int		did2 = FALSE;
1999 
2000     /* Ignore leading and trailing white space in 'commentstring'. */
2001     cms_start = skipwhite(curbuf->b_p_cms);
2002     cms_slen = (int)STRLEN(cms_start);
2003     while (cms_slen > 0 && VIM_ISWHITE(cms_start[cms_slen - 1]))
2004 	--cms_slen;
2005 
2006     /* locate "%s" in 'commentstring', use the part before and after it. */
2007     cms_end = (char_u *)strstr((char *)cms_start, "%s");
2008     if (cms_end != NULL)
2009     {
2010 	cms_elen = cms_slen - (int)(cms_end - cms_start);
2011 	cms_slen = (int)(cms_end - cms_start);
2012 
2013 	/* exclude white space before "%s" */
2014 	while (cms_slen > 0 && VIM_ISWHITE(cms_start[cms_slen - 1]))
2015 	    --cms_slen;
2016 
2017 	/* skip "%s" and white space after it */
2018 	s = skipwhite(cms_end + 2);
2019 	cms_elen -= (int)(s - cms_end);
2020 	cms_end = s;
2021     }
2022     parseMarker(curwin);
2023 
2024     for (s = str; *s != NUL; )
2025     {
2026 	len = 0;
2027 	if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0)
2028 	    len = foldstartmarkerlen;
2029 	else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0)
2030 	    len = foldendmarkerlen;
2031 	if (len > 0)
2032 	{
2033 	    if (VIM_ISDIGIT(s[len]))
2034 		++len;
2035 
2036 	    /* May remove 'commentstring' start.  Useful when it's a double
2037 	     * quote and we already removed a double quote. */
2038 	    for (p = s; p > str && VIM_ISWHITE(p[-1]); --p)
2039 		;
2040 	    if (p >= str + cms_slen
2041 			   && STRNCMP(p - cms_slen, cms_start, cms_slen) == 0)
2042 	    {
2043 		len += (int)(s - p) + cms_slen;
2044 		s = p - cms_slen;
2045 	    }
2046 	}
2047 	else if (cms_end != NULL)
2048 	{
2049 	    if (!did1 && cms_slen > 0 && STRNCMP(s, cms_start, cms_slen) == 0)
2050 	    {
2051 		len = cms_slen;
2052 		did1 = TRUE;
2053 	    }
2054 	    else if (!did2 && cms_elen > 0
2055 					&& STRNCMP(s, cms_end, cms_elen) == 0)
2056 	    {
2057 		len = cms_elen;
2058 		did2 = TRUE;
2059 	    }
2060 	}
2061 	if (len != 0)
2062 	{
2063 	    while (VIM_ISWHITE(s[len]))
2064 		++len;
2065 	    STRMOVE(s, s + len);
2066 	}
2067 	else
2068 	{
2069 	    MB_PTR_ADV(s);
2070 	}
2071     }
2072 }
2073 
2074 /* Folding by indent, expr, marker and syntax. {{{1 */
2075 /* Define "fline_T", passed to get fold level for a line. {{{2 */
2076 typedef struct
2077 {
2078     win_T	*wp;		/* window */
2079     linenr_T	lnum;		/* current line number */
2080     linenr_T	off;		/* offset between lnum and real line number */
2081     linenr_T	lnum_save;	/* line nr used by foldUpdateIEMSRecurse() */
2082     int		lvl;		/* current level (-1 for undefined) */
2083     int		lvl_next;	/* level used for next line */
2084     int		start;		/* number of folds that are forced to start at
2085 				   this line. */
2086     int		end;		/* level of fold that is forced to end below
2087 				   this line */
2088     int		had_end;	/* level of fold that is forced to end above
2089 				   this line (copy of "end" of prev. line) */
2090 } fline_T;
2091 
2092 /* Flag is set when redrawing is needed. */
2093 static int fold_changed;
2094 
2095 /* Function declarations. {{{2 */
2096 static linenr_T foldUpdateIEMSRecurse(garray_T *gap, int level, linenr_T startlnum, fline_T *flp, void (*getlevel)(fline_T *), linenr_T bot, int topflags);
2097 static int foldInsert(garray_T *gap, int i);
2098 static void foldSplit(garray_T *gap, int i, linenr_T top, linenr_T bot);
2099 static void foldRemove(garray_T *gap, linenr_T top, linenr_T bot);
2100 static void foldMerge(fold_T *fp1, garray_T *gap, fold_T *fp2);
2101 static void foldlevelIndent(fline_T *flp);
2102 #ifdef FEAT_DIFF
2103 static void foldlevelDiff(fline_T *flp);
2104 #endif
2105 static void foldlevelExpr(fline_T *flp);
2106 static void foldlevelMarker(fline_T *flp);
2107 static void foldlevelSyntax(fline_T *flp);
2108 
2109 /* foldUpdateIEMS() {{{2 */
2110 /*
2111  * Update the folding for window "wp", at least from lines "top" to "bot".
2112  * Return TRUE if any folds did change.
2113  */
2114     static void
2115 foldUpdateIEMS(win_T *wp, linenr_T top, linenr_T bot)
2116 {
2117     linenr_T	start;
2118     linenr_T	end;
2119     fline_T	fline;
2120     void	(*getlevel)(fline_T *);
2121     int		level;
2122     fold_T	*fp;
2123 
2124     /* Avoid problems when being called recursively. */
2125     if (invalid_top != (linenr_T)0)
2126 	return;
2127 
2128     if (wp->w_foldinvalid)
2129     {
2130 	/* Need to update all folds. */
2131 	top = 1;
2132 	bot = wp->w_buffer->b_ml.ml_line_count;
2133 	wp->w_foldinvalid = FALSE;
2134 
2135 	/* Mark all folds a maybe-small. */
2136 	setSmallMaybe(&wp->w_folds);
2137     }
2138 
2139 #ifdef FEAT_DIFF
2140     /* add the context for "diff" folding */
2141     if (foldmethodIsDiff(wp))
2142     {
2143 	if (top > diff_context)
2144 	    top -= diff_context;
2145 	else
2146 	    top = 1;
2147 	bot += diff_context;
2148     }
2149 #endif
2150 
2151     /* When deleting lines at the end of the buffer "top" can be past the end
2152      * of the buffer. */
2153     if (top > wp->w_buffer->b_ml.ml_line_count)
2154 	top = wp->w_buffer->b_ml.ml_line_count;
2155 
2156     fold_changed = FALSE;
2157     fline.wp = wp;
2158     fline.off = 0;
2159     fline.lvl = 0;
2160     fline.lvl_next = -1;
2161     fline.start = 0;
2162     fline.end = MAX_LEVEL + 1;
2163     fline.had_end = MAX_LEVEL + 1;
2164 
2165     invalid_top = top;
2166     invalid_bot = bot;
2167 
2168     if (foldmethodIsMarker(wp))
2169     {
2170 	getlevel = foldlevelMarker;
2171 
2172 	/* Init marker variables to speed up foldlevelMarker(). */
2173 	parseMarker(wp);
2174 
2175 	/* Need to get the level of the line above top, it is used if there is
2176 	 * no marker at the top. */
2177 	if (top > 1)
2178 	{
2179 	    /* Get the fold level at top - 1. */
2180 	    level = foldLevelWin(wp, top - 1);
2181 
2182 	    /* The fold may end just above the top, check for that. */
2183 	    fline.lnum = top - 1;
2184 	    fline.lvl = level;
2185 	    getlevel(&fline);
2186 
2187 	    /* If a fold started here, we already had the level, if it stops
2188 	     * here, we need to use lvl_next.  Could also start and end a fold
2189 	     * in the same line. */
2190 	    if (fline.lvl > level)
2191 		fline.lvl = level - (fline.lvl - fline.lvl_next);
2192 	    else
2193 		fline.lvl = fline.lvl_next;
2194 	}
2195 	fline.lnum = top;
2196 	getlevel(&fline);
2197     }
2198     else
2199     {
2200 	fline.lnum = top;
2201 	if (foldmethodIsExpr(wp))
2202 	{
2203 	    getlevel = foldlevelExpr;
2204 	    /* start one line back, because a "<1" may indicate the end of a
2205 	     * fold in the topline */
2206 	    if (top > 1)
2207 		--fline.lnum;
2208 	}
2209 	else if (foldmethodIsSyntax(wp))
2210 	    getlevel = foldlevelSyntax;
2211 #ifdef FEAT_DIFF
2212 	else if (foldmethodIsDiff(wp))
2213 	    getlevel = foldlevelDiff;
2214 #endif
2215 	else
2216 	    getlevel = foldlevelIndent;
2217 
2218 	/* Backup to a line for which the fold level is defined.  Since it's
2219 	 * always defined for line one, we will stop there. */
2220 	fline.lvl = -1;
2221 	for ( ; !got_int; --fline.lnum)
2222 	{
2223 	    /* Reset lvl_next each time, because it will be set to a value for
2224 	     * the next line, but we search backwards here. */
2225 	    fline.lvl_next = -1;
2226 	    getlevel(&fline);
2227 	    if (fline.lvl >= 0)
2228 		break;
2229 	}
2230     }
2231 
2232     /*
2233      * If folding is defined by the syntax, it is possible that a change in
2234      * one line will cause all sub-folds of the current fold to change (e.g.,
2235      * closing a C-style comment can cause folds in the subsequent lines to
2236      * appear). To take that into account we should adjust the value of "bot"
2237      * to point to the end of the current fold:
2238      */
2239     if (foldlevelSyntax == getlevel)
2240     {
2241 	garray_T *gap = &wp->w_folds;
2242 	fold_T	 *fpn = NULL;
2243 	int	  current_fdl = 0;
2244 	linenr_T  fold_start_lnum = 0;
2245 	linenr_T  lnum_rel = fline.lnum;
2246 
2247 	while (current_fdl < fline.lvl)
2248 	{
2249 	    if (!foldFind(gap, lnum_rel, &fpn))
2250 		break;
2251 	    ++current_fdl;
2252 
2253 	    fold_start_lnum += fpn->fd_top;
2254 	    gap = &fpn->fd_nested;
2255 	    lnum_rel -= fpn->fd_top;
2256 	}
2257 	if (fpn != NULL && current_fdl == fline.lvl)
2258 	{
2259 	    linenr_T fold_end_lnum = fold_start_lnum + fpn->fd_len;
2260 
2261 	    if (fold_end_lnum > bot)
2262 		bot = fold_end_lnum;
2263 	}
2264     }
2265 
2266     start = fline.lnum;
2267     end = bot;
2268     /* Do at least one line. */
2269     if (start > end && end < wp->w_buffer->b_ml.ml_line_count)
2270 	end = start;
2271     while (!got_int)
2272     {
2273 	/* Always stop at the end of the file ("end" can be past the end of
2274 	 * the file). */
2275 	if (fline.lnum > wp->w_buffer->b_ml.ml_line_count)
2276 	    break;
2277 	if (fline.lnum > end)
2278 	{
2279 	    /* For "marker", "expr"  and "syntax"  methods: If a change caused
2280 	     * a fold to be removed, we need to continue at least until where
2281 	     * it ended. */
2282 	    if (getlevel != foldlevelMarker
2283 		    && getlevel != foldlevelSyntax
2284 		    && getlevel != foldlevelExpr)
2285 		break;
2286 	    if ((start <= end
2287 			&& foldFind(&wp->w_folds, end, &fp)
2288 			&& fp->fd_top + fp->fd_len - 1 > end)
2289 		    || (fline.lvl == 0
2290 			&& foldFind(&wp->w_folds, fline.lnum, &fp)
2291 			&& fp->fd_top < fline.lnum))
2292 		end = fp->fd_top + fp->fd_len - 1;
2293 	    else if (getlevel == foldlevelSyntax
2294 		    && foldLevelWin(wp, fline.lnum) != fline.lvl)
2295 		/* For "syntax" method: Compare the foldlevel that the syntax
2296 		 * tells us to the foldlevel from the existing folds.  If they
2297 		 * don't match continue updating folds. */
2298 		end = fline.lnum;
2299 	    else
2300 		break;
2301 	}
2302 
2303 	/* A level 1 fold starts at a line with foldlevel > 0. */
2304 	if (fline.lvl > 0)
2305 	{
2306 	    invalid_top = fline.lnum;
2307 	    invalid_bot = end;
2308 	    end = foldUpdateIEMSRecurse(&wp->w_folds,
2309 				   1, start, &fline, getlevel, end, FD_LEVEL);
2310 	    start = fline.lnum;
2311 	}
2312 	else
2313 	{
2314 	    if (fline.lnum == wp->w_buffer->b_ml.ml_line_count)
2315 		break;
2316 	    ++fline.lnum;
2317 	    fline.lvl = fline.lvl_next;
2318 	    getlevel(&fline);
2319 	}
2320     }
2321 
2322     /* There can't be any folds from start until end now. */
2323     foldRemove(&wp->w_folds, start, end);
2324 
2325     /* If some fold changed, need to redraw and position cursor. */
2326     if (fold_changed && wp->w_p_fen)
2327 	changed_window_setting_win(wp);
2328 
2329     /* If we updated folds past "bot", need to redraw more lines.  Don't do
2330      * this in other situations, the changed lines will be redrawn anyway and
2331      * this method can cause the whole window to be updated. */
2332     if (end != bot)
2333     {
2334 	if (wp->w_redraw_top == 0 || wp->w_redraw_top > top)
2335 	    wp->w_redraw_top = top;
2336 	if (wp->w_redraw_bot < end)
2337 	    wp->w_redraw_bot = end;
2338     }
2339 
2340     invalid_top = (linenr_T)0;
2341 }
2342 
2343 /* foldUpdateIEMSRecurse() {{{2 */
2344 /*
2345  * Update a fold that starts at "flp->lnum".  At this line there is always a
2346  * valid foldlevel, and its level >= "level".
2347  * "flp" is valid for "flp->lnum" when called and it's valid when returning.
2348  * "flp->lnum" is set to the lnum just below the fold, if it ends before
2349  * "bot", it's "bot" plus one if the fold continues and it's bigger when using
2350  * the marker method and a text change made following folds to change.
2351  * When returning, "flp->lnum_save" is the line number that was used to get
2352  * the level when the level at "flp->lnum" is invalid.
2353  * Remove any folds from "startlnum" up to here at this level.
2354  * Recursively update nested folds.
2355  * Below line "bot" there are no changes in the text.
2356  * "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the
2357  * outer fold.
2358  * "flp->off" is the offset to the real line number in the buffer.
2359  *
2360  * All this would be a lot simpler if all folds in the range would be deleted
2361  * and then created again.  But we would lose all information about the
2362  * folds, even when making changes that don't affect the folding (e.g. "vj~").
2363  *
2364  * Returns bot, which may have been increased for lines that also need to be
2365  * updated as a result of a detected change in the fold.
2366  */
2367     static linenr_T
2368 foldUpdateIEMSRecurse(
2369     garray_T	*gap,
2370     int		level,
2371     linenr_T	startlnum,
2372     fline_T	*flp,
2373     void	(*getlevel)(fline_T *),
2374     linenr_T	bot,
2375     int		topflags)	/* flags used by containing fold */
2376 {
2377     linenr_T	ll;
2378     fold_T	*fp = NULL;
2379     fold_T	*fp2;
2380     int		lvl = level;
2381     linenr_T	startlnum2 = startlnum;
2382     linenr_T	firstlnum = flp->lnum;	/* first lnum we got */
2383     int		i;
2384     int		finish = FALSE;
2385     linenr_T	linecount = flp->wp->w_buffer->b_ml.ml_line_count - flp->off;
2386     int		concat;
2387 
2388     /*
2389      * If using the marker method, the start line is not the start of a fold
2390      * at the level we're dealing with and the level is non-zero, we must use
2391      * the previous fold.  But ignore a fold that starts at or below
2392      * startlnum, it must be deleted.
2393      */
2394     if (getlevel == foldlevelMarker && flp->start <= flp->lvl - level
2395 							      && flp->lvl > 0)
2396     {
2397 	(void)foldFind(gap, startlnum - 1, &fp);
2398 	if (fp >= ((fold_T *)gap->ga_data) + gap->ga_len
2399 						   || fp->fd_top >= startlnum)
2400 	    fp = NULL;
2401     }
2402 
2403     /*
2404      * Loop over all lines in this fold, or until "bot" is hit.
2405      * Handle nested folds inside of this fold.
2406      * "flp->lnum" is the current line.  When finding the end of the fold, it
2407      * is just below the end of the fold.
2408      * "*flp" contains the level of the line "flp->lnum" or a following one if
2409      * there are lines with an invalid fold level.  "flp->lnum_save" is the
2410      * line number that was used to get the fold level (below "flp->lnum" when
2411      * it has an invalid fold level).  When called the fold level is always
2412      * valid, thus "flp->lnum_save" is equal to "flp->lnum".
2413      */
2414     flp->lnum_save = flp->lnum;
2415     while (!got_int)
2416     {
2417 	/* Updating folds can be slow, check for CTRL-C. */
2418 	line_breakcheck();
2419 
2420 	/* Set "lvl" to the level of line "flp->lnum".  When flp->start is set
2421 	 * and after the first line of the fold, set the level to zero to
2422 	 * force the fold to end.  Do the same when had_end is set: Previous
2423 	 * line was marked as end of a fold. */
2424 	lvl = flp->lvl;
2425 	if (lvl > MAX_LEVEL)
2426 	    lvl = MAX_LEVEL;
2427 	if (flp->lnum > firstlnum
2428 		&& (level > lvl - flp->start || level >= flp->had_end))
2429 	    lvl = 0;
2430 
2431 	if (flp->lnum > bot && !finish && fp != NULL)
2432 	{
2433 	    /* For "marker" and "syntax" methods:
2434 	     * - If a change caused a nested fold to be removed, we need to
2435 	     *   delete it and continue at least until where it ended.
2436 	     * - If a change caused a nested fold to be created, or this fold
2437 	     *   to continue below its original end, need to finish this fold.
2438 	     */
2439 	    if (getlevel != foldlevelMarker
2440 		    && getlevel != foldlevelExpr
2441 		    && getlevel != foldlevelSyntax)
2442 		break;
2443 	    i = 0;
2444 	    fp2 = fp;
2445 	    if (lvl >= level)
2446 	    {
2447 		/* Compute how deep the folds currently are, if it's deeper
2448 		 * than "lvl" then some must be deleted, need to update
2449 		 * at least one nested fold. */
2450 		ll = flp->lnum - fp->fd_top;
2451 		while (foldFind(&fp2->fd_nested, ll, &fp2))
2452 		{
2453 		    ++i;
2454 		    ll -= fp2->fd_top;
2455 		}
2456 	    }
2457 	    if (lvl < level + i)
2458 	    {
2459 		(void)foldFind(&fp->fd_nested, flp->lnum - fp->fd_top, &fp2);
2460 		if (fp2 != NULL)
2461 		    bot = fp2->fd_top + fp2->fd_len - 1 + fp->fd_top;
2462 	    }
2463 	    else if (fp->fd_top + fp->fd_len <= flp->lnum && lvl >= level)
2464 		finish = TRUE;
2465 	    else
2466 		break;
2467 	}
2468 
2469 	/* At the start of the first nested fold and at the end of the current
2470 	 * fold: check if existing folds at this level, before the current
2471 	 * one, need to be deleted or truncated. */
2472 	if (fp == NULL
2473 		&& (lvl != level
2474 		    || flp->lnum_save >= bot
2475 		    || flp->start != 0
2476 		    || flp->had_end <= MAX_LEVEL
2477 		    || flp->lnum == linecount))
2478 	{
2479 	    /*
2480 	     * Remove or update folds that have lines between startlnum and
2481 	     * firstlnum.
2482 	     */
2483 	    while (!got_int)
2484 	    {
2485 		/* set concat to 1 if it's allowed to concatenated this fold
2486 		 * with a previous one that touches it. */
2487 		if (flp->start != 0 || flp->had_end <= MAX_LEVEL)
2488 		    concat = 0;
2489 		else
2490 		    concat = 1;
2491 
2492 		/* Find an existing fold to re-use.  Preferably one that
2493 		 * includes startlnum, otherwise one that ends just before
2494 		 * startlnum or starts after it. */
2495 		if (foldFind(gap, startlnum, &fp)
2496 			|| (fp < ((fold_T *)gap->ga_data) + gap->ga_len
2497 			    && fp->fd_top <= firstlnum)
2498 			|| foldFind(gap, firstlnum - concat, &fp)
2499 			|| (fp < ((fold_T *)gap->ga_data) + gap->ga_len
2500 			    && ((lvl < level && fp->fd_top < flp->lnum)
2501 				|| (lvl >= level
2502 					   && fp->fd_top <= flp->lnum_save))))
2503 		{
2504 		    if (fp->fd_top + fp->fd_len + concat > firstlnum)
2505 		    {
2506 			/* Use existing fold for the new fold.  If it starts
2507 			 * before where we started looking, extend it.  If it
2508 			 * starts at another line, update nested folds to keep
2509 			 * their position, compensating for the new fd_top. */
2510 			if (fp->fd_top == firstlnum)
2511 			{
2512 			    /* have found a fold beginning where we want */
2513 			}
2514 			else if (fp->fd_top >= startlnum)
2515 			{
2516 			    if (fp->fd_top > firstlnum)
2517 				/* like lines are inserted */
2518 				foldMarkAdjustRecurse(&fp->fd_nested,
2519 					(linenr_T)0, (linenr_T)MAXLNUM,
2520 					(long)(fp->fd_top - firstlnum), 0L);
2521 			    else
2522 				/* like lines are deleted */
2523 				foldMarkAdjustRecurse(&fp->fd_nested,
2524 					(linenr_T)0,
2525 					(long)(firstlnum - fp->fd_top - 1),
2526 					(linenr_T)MAXLNUM,
2527 					(long)(fp->fd_top - firstlnum));
2528 			    fp->fd_len += fp->fd_top - firstlnum;
2529 			    fp->fd_top = firstlnum;
2530 			    fold_changed = TRUE;
2531 			}
2532 			else if ((flp->start != 0 && lvl == level)
2533 						     || firstlnum != startlnum)
2534 			{
2535 			    linenr_T breakstart;
2536 			    linenr_T breakend;
2537 
2538 			    /*
2539 			     * Before there was a fold spanning from above
2540 			     * startlnum to below firstlnum. This fold is valid
2541 			     * above startlnum (because we are not updating
2542 			     * that range), but there should now be a break in
2543 			     * it.
2544 			     * If the break is because we are now forced to
2545 			     * start a new fold at the level "level" at line
2546 			     * fline->lnum, then we need to split the fold at
2547 			     * fline->lnum.
2548 			     * If the break is because the range
2549 			     * [startlnum, firstlnum) is now at a lower indent
2550 			     * than "level", we need to split the fold in this
2551 			     * range.
2552 			     * Any splits have to be done recursively.
2553 			     */
2554 			    if (firstlnum != startlnum)
2555 			    {
2556 				breakstart = startlnum;
2557 				breakend = firstlnum;
2558 			    }
2559 			    else
2560 			    {
2561 				breakstart = flp->lnum;
2562 				breakend = flp->lnum;
2563 			    }
2564 			    foldRemove(&fp->fd_nested, breakstart - fp->fd_top,
2565 						      breakend - fp->fd_top);
2566 			    i = (int)(fp - (fold_T *)gap->ga_data);
2567 			    foldSplit(gap, i, breakstart, breakend - 1);
2568 			    fp = (fold_T *)gap->ga_data + i + 1;
2569 
2570 			    /* If using the "marker" or "syntax" method, we
2571 			     * need to continue until the end of the fold is
2572 			     * found. */
2573 			    if (getlevel == foldlevelMarker
2574 				    || getlevel == foldlevelExpr
2575 				    || getlevel == foldlevelSyntax)
2576 				finish = TRUE;
2577 			}
2578 
2579 			if (fp->fd_top == startlnum && concat)
2580 			{
2581 			    i = (int)(fp - (fold_T *)gap->ga_data);
2582 			    if (i != 0)
2583 			    {
2584 				fp2 = fp - 1;
2585 				if (fp2->fd_top + fp2->fd_len == fp->fd_top)
2586 				{
2587 				    foldMerge(fp2, gap, fp);
2588 				    fp = fp2;
2589 				}
2590 			    }
2591 			}
2592 			break;
2593 		    }
2594 		    if (fp->fd_top >= startlnum)
2595 		    {
2596 			/* A fold that starts at or after startlnum and stops
2597 			 * before the new fold must be deleted.  Continue
2598 			 * looking for the next one. */
2599 			deleteFoldEntry(gap,
2600 				     (int)(fp - (fold_T *)gap->ga_data), TRUE);
2601 		    }
2602 		    else
2603 		    {
2604 			/* A fold has some lines above startlnum, truncate it
2605 			 * to stop just above startlnum.  */
2606 			fp->fd_len = startlnum - fp->fd_top;
2607 			foldMarkAdjustRecurse(&fp->fd_nested,
2608 				(linenr_T)fp->fd_len, (linenr_T)MAXLNUM,
2609 						       (linenr_T)MAXLNUM, 0L);
2610 			fold_changed = TRUE;
2611 		    }
2612 		}
2613 		else
2614 		{
2615 		    /* Insert new fold.  Careful: ga_data may be NULL and it
2616 		     * may change! */
2617 		    i = (int)(fp - (fold_T *)gap->ga_data);
2618 		    if (foldInsert(gap, i) != OK)
2619 			return bot;
2620 		    fp = (fold_T *)gap->ga_data + i;
2621 		    /* The new fold continues until bot, unless we find the
2622 		     * end earlier. */
2623 		    fp->fd_top = firstlnum;
2624 		    fp->fd_len = bot - firstlnum + 1;
2625 		    /* When the containing fold is open, the new fold is open.
2626 		     * The new fold is closed if the fold above it is closed.
2627 		     * The first fold depends on the containing fold. */
2628 		    if (topflags == FD_OPEN)
2629 		    {
2630 			flp->wp->w_fold_manual = TRUE;
2631 			fp->fd_flags = FD_OPEN;
2632 		    }
2633 		    else if (i <= 0)
2634 		    {
2635 			fp->fd_flags = topflags;
2636 			if (topflags != FD_LEVEL)
2637 			    flp->wp->w_fold_manual = TRUE;
2638 		    }
2639 		    else
2640 			fp->fd_flags = (fp - 1)->fd_flags;
2641 		    fp->fd_small = MAYBE;
2642 		    /* If using the "marker", "expr" or "syntax" method, we
2643 		     * need to continue until the end of the fold is found. */
2644 		    if (getlevel == foldlevelMarker
2645 			    || getlevel == foldlevelExpr
2646 			    || getlevel == foldlevelSyntax)
2647 			finish = TRUE;
2648 		    fold_changed = TRUE;
2649 		    break;
2650 		}
2651 	    }
2652 	}
2653 
2654 	if (lvl < level || flp->lnum > linecount)
2655 	{
2656 	    /*
2657 	     * Found a line with a lower foldlevel, this fold ends just above
2658 	     * "flp->lnum".
2659 	     */
2660 	    break;
2661 	}
2662 
2663 	/*
2664 	 * The fold includes the line "flp->lnum" and "flp->lnum_save".
2665 	 * Check "fp" for safety.
2666 	 */
2667 	if (lvl > level && fp != NULL)
2668 	{
2669 	    /*
2670 	     * There is a nested fold, handle it recursively.
2671 	     */
2672 	    /* At least do one line (can happen when finish is TRUE). */
2673 	    if (bot < flp->lnum)
2674 		bot = flp->lnum;
2675 
2676 	    /* Line numbers in the nested fold are relative to the start of
2677 	     * this fold. */
2678 	    flp->lnum = flp->lnum_save - fp->fd_top;
2679 	    flp->off += fp->fd_top;
2680 	    i = (int)(fp - (fold_T *)gap->ga_data);
2681 	    bot = foldUpdateIEMSRecurse(&fp->fd_nested, level + 1,
2682 				       startlnum2 - fp->fd_top, flp, getlevel,
2683 					      bot - fp->fd_top, fp->fd_flags);
2684 	    fp = (fold_T *)gap->ga_data + i;
2685 	    flp->lnum += fp->fd_top;
2686 	    flp->lnum_save += fp->fd_top;
2687 	    flp->off -= fp->fd_top;
2688 	    bot += fp->fd_top;
2689 	    startlnum2 = flp->lnum;
2690 
2691 	    /* This fold may end at the same line, don't incr. flp->lnum. */
2692 	}
2693 	else
2694 	{
2695 	    /*
2696 	     * Get the level of the next line, then continue the loop to check
2697 	     * if it ends there.
2698 	     * Skip over undefined lines, to find the foldlevel after it.
2699 	     * For the last line in the file the foldlevel is always valid.
2700 	     */
2701 	    flp->lnum = flp->lnum_save;
2702 	    ll = flp->lnum + 1;
2703 	    while (!got_int)
2704 	    {
2705 		/* Make the previous level available to foldlevel(). */
2706 		prev_lnum = flp->lnum;
2707 		prev_lnum_lvl = flp->lvl;
2708 
2709 		if (++flp->lnum > linecount)
2710 		    break;
2711 		flp->lvl = flp->lvl_next;
2712 		getlevel(flp);
2713 		if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL)
2714 		    break;
2715 	    }
2716 	    prev_lnum = 0;
2717 	    if (flp->lnum > linecount)
2718 		break;
2719 
2720 	    /* leave flp->lnum_save to lnum of the line that was used to get
2721 	     * the level, flp->lnum to the lnum of the next line. */
2722 	    flp->lnum_save = flp->lnum;
2723 	    flp->lnum = ll;
2724 	}
2725     }
2726 
2727     if (fp == NULL)	/* only happens when got_int is set */
2728 	return bot;
2729 
2730     /*
2731      * Get here when:
2732      * lvl < level: the folds ends just above "flp->lnum"
2733      * lvl >= level: fold continues below "bot"
2734      */
2735 
2736     /* Current fold at least extends until lnum. */
2737     if (fp->fd_len < flp->lnum - fp->fd_top)
2738     {
2739 	fp->fd_len = flp->lnum - fp->fd_top;
2740 	fp->fd_small = MAYBE;
2741 	fold_changed = TRUE;
2742     }
2743 
2744     /* Delete contained folds from the end of the last one found until where
2745      * we stopped looking. */
2746     foldRemove(&fp->fd_nested, startlnum2 - fp->fd_top,
2747 						  flp->lnum - 1 - fp->fd_top);
2748 
2749     if (lvl < level)
2750     {
2751 	/* End of fold found, update the length when it got shorter. */
2752 	if (fp->fd_len != flp->lnum - fp->fd_top)
2753 	{
2754 	    if (fp->fd_top + fp->fd_len - 1 > bot)
2755 	    {
2756 		/* fold continued below bot */
2757 		if (getlevel == foldlevelMarker
2758 			|| getlevel == foldlevelExpr
2759 			|| getlevel == foldlevelSyntax)
2760 		{
2761 		    /* marker method: truncate the fold and make sure the
2762 		     * previously included lines are processed again */
2763 		    bot = fp->fd_top + fp->fd_len - 1;
2764 		    fp->fd_len = flp->lnum - fp->fd_top;
2765 		}
2766 		else
2767 		{
2768 		    /* indent or expr method: split fold to create a new one
2769 		     * below bot */
2770 		    i = (int)(fp - (fold_T *)gap->ga_data);
2771 		    foldSplit(gap, i, flp->lnum, bot);
2772 		    fp = (fold_T *)gap->ga_data + i;
2773 		}
2774 	    }
2775 	    else
2776 		fp->fd_len = flp->lnum - fp->fd_top;
2777 	    fold_changed = TRUE;
2778 	}
2779     }
2780 
2781     /* delete following folds that end before the current line */
2782     for (;;)
2783     {
2784 	fp2 = fp + 1;
2785 	if (fp2 >= (fold_T *)gap->ga_data + gap->ga_len
2786 						  || fp2->fd_top > flp->lnum)
2787 	    break;
2788 	if (fp2->fd_top + fp2->fd_len > flp->lnum)
2789 	{
2790 	    if (fp2->fd_top < flp->lnum)
2791 	    {
2792 		/* Make fold that includes lnum start at lnum. */
2793 		foldMarkAdjustRecurse(&fp2->fd_nested,
2794 			(linenr_T)0, (long)(flp->lnum - fp2->fd_top - 1),
2795 			(linenr_T)MAXLNUM, (long)(fp2->fd_top - flp->lnum));
2796 		fp2->fd_len -= flp->lnum - fp2->fd_top;
2797 		fp2->fd_top = flp->lnum;
2798 		fold_changed = TRUE;
2799 	    }
2800 
2801 	    if (lvl >= level)
2802 	    {
2803 		/* merge new fold with existing fold that follows */
2804 		foldMerge(fp, gap, fp2);
2805 	    }
2806 	    break;
2807 	}
2808 	fold_changed = TRUE;
2809 	deleteFoldEntry(gap, (int)(fp2 - (fold_T *)gap->ga_data), TRUE);
2810     }
2811 
2812     /* Need to redraw the lines we inspected, which might be further down than
2813      * was asked for. */
2814     if (bot < flp->lnum - 1)
2815 	bot = flp->lnum - 1;
2816 
2817     return bot;
2818 }
2819 
2820 /* foldInsert() {{{2 */
2821 /*
2822  * Insert a new fold in "gap" at position "i".
2823  * Returns OK for success, FAIL for failure.
2824  */
2825     static int
2826 foldInsert(garray_T *gap, int i)
2827 {
2828     fold_T	*fp;
2829 
2830     if (ga_grow(gap, 1) != OK)
2831 	return FAIL;
2832     fp = (fold_T *)gap->ga_data + i;
2833     if (i < gap->ga_len)
2834 	mch_memmove(fp + 1, fp, sizeof(fold_T) * (gap->ga_len - i));
2835     ++gap->ga_len;
2836     ga_init2(&fp->fd_nested, (int)sizeof(fold_T), 10);
2837     return OK;
2838 }
2839 
2840 /* foldSplit() {{{2 */
2841 /*
2842  * Split the "i"th fold in "gap", which starts before "top" and ends below
2843  * "bot" in two pieces, one ending above "top" and the other starting below
2844  * "bot".
2845  * The caller must first have taken care of any nested folds from "top" to
2846  * "bot"!
2847  */
2848     static void
2849 foldSplit(
2850     garray_T	*gap,
2851     int		i,
2852     linenr_T	top,
2853     linenr_T	bot)
2854 {
2855     fold_T	*fp;
2856     fold_T	*fp2;
2857     garray_T	*gap1;
2858     garray_T	*gap2;
2859     int		idx;
2860     int		len;
2861 
2862     /* The fold continues below bot, need to split it. */
2863     if (foldInsert(gap, i + 1) == FAIL)
2864 	return;
2865     fp = (fold_T *)gap->ga_data + i;
2866     fp[1].fd_top = bot + 1;
2867     fp[1].fd_len = fp->fd_len - (fp[1].fd_top - fp->fd_top);
2868     fp[1].fd_flags = fp->fd_flags;
2869     fp[1].fd_small = MAYBE;
2870     fp->fd_small = MAYBE;
2871 
2872     /* Move nested folds below bot to new fold.  There can't be
2873      * any between top and bot, they have been removed by the caller. */
2874     gap1 = &fp->fd_nested;
2875     gap2 = &fp[1].fd_nested;
2876     (void)(foldFind(gap1, bot + 1 - fp->fd_top, &fp2));
2877     len = (int)((fold_T *)gap1->ga_data + gap1->ga_len - fp2);
2878     if (len > 0 && ga_grow(gap2, len) == OK)
2879     {
2880 	for (idx = 0; idx < len; ++idx)
2881 	{
2882 	    ((fold_T *)gap2->ga_data)[idx] = fp2[idx];
2883 	    ((fold_T *)gap2->ga_data)[idx].fd_top
2884 						 -= fp[1].fd_top - fp->fd_top;
2885 	}
2886 	gap2->ga_len = len;
2887 	gap1->ga_len -= len;
2888     }
2889     fp->fd_len = top - fp->fd_top;
2890     fold_changed = TRUE;
2891 }
2892 
2893 /* foldRemove() {{{2 */
2894 /*
2895  * Remove folds within the range "top" to and including "bot".
2896  * Check for these situations:
2897  *      1  2  3
2898  *      1  2  3
2899  * top     2  3  4  5
2900  *	   2  3  4  5
2901  * bot	   2  3  4  5
2902  *	      3     5  6
2903  *	      3     5  6
2904  *
2905  * 1: not changed
2906  * 2: truncate to stop above "top"
2907  * 3: split in two parts, one stops above "top", other starts below "bot".
2908  * 4: deleted
2909  * 5: made to start below "bot".
2910  * 6: not changed
2911  */
2912     static void
2913 foldRemove(garray_T *gap, linenr_T top, linenr_T bot)
2914 {
2915     fold_T	*fp = NULL;
2916 
2917     if (bot < top)
2918 	return;		/* nothing to do */
2919 
2920     for (;;)
2921     {
2922 	/* Find fold that includes top or a following one. */
2923 	if (foldFind(gap, top, &fp) && fp->fd_top < top)
2924 	{
2925 	    /* 2: or 3: need to delete nested folds */
2926 	    foldRemove(&fp->fd_nested, top - fp->fd_top, bot - fp->fd_top);
2927 	    if (fp->fd_top + fp->fd_len - 1 > bot)
2928 	    {
2929 		/* 3: need to split it. */
2930 		foldSplit(gap, (int)(fp - (fold_T *)gap->ga_data), top, bot);
2931 	    }
2932 	    else
2933 	    {
2934 		/* 2: truncate fold at "top". */
2935 		fp->fd_len = top - fp->fd_top;
2936 	    }
2937 	    fold_changed = TRUE;
2938 	    continue;
2939 	}
2940 	if (fp >= (fold_T *)(gap->ga_data) + gap->ga_len
2941 		|| fp->fd_top > bot)
2942 	{
2943 	    /* 6: Found a fold below bot, can stop looking. */
2944 	    break;
2945 	}
2946 	if (fp->fd_top >= top)
2947 	{
2948 	    /* Found an entry below top. */
2949 	    fold_changed = TRUE;
2950 	    if (fp->fd_top + fp->fd_len - 1 > bot)
2951 	    {
2952 		/* 5: Make fold that includes bot start below bot. */
2953 		foldMarkAdjustRecurse(&fp->fd_nested,
2954 			(linenr_T)0, (long)(bot - fp->fd_top),
2955 			(linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1));
2956 		fp->fd_len -= bot - fp->fd_top + 1;
2957 		fp->fd_top = bot + 1;
2958 		break;
2959 	    }
2960 
2961 	    /* 4: Delete completely contained fold. */
2962 	    deleteFoldEntry(gap, (int)(fp - (fold_T *)gap->ga_data), TRUE);
2963 	}
2964     }
2965 }
2966 
2967 /* foldReverseOrder() {{{2 */
2968     static void
2969 foldReverseOrder(garray_T *gap, linenr_T start_arg, linenr_T end_arg)
2970 {
2971     fold_T *left, *right;
2972     fold_T tmp;
2973     linenr_T start = start_arg;
2974     linenr_T end = end_arg;
2975 
2976     for (; start < end; start++, end--)
2977     {
2978 	left = (fold_T *)gap->ga_data + start;
2979 	right = (fold_T *)gap->ga_data + end;
2980 	tmp  = *left;
2981 	*left = *right;
2982 	*right = tmp;
2983     }
2984 }
2985 
2986 /* foldMoveRange() {{{2 */
2987 /*
2988  * Move folds within the inclusive range "line1" to "line2" to after "dest"
2989  * requires "line1" <= "line2" <= "dest"
2990  *
2991  * There are the following situations for the first fold at or below line1 - 1.
2992  *       1  2  3  4
2993  *       1  2  3  4
2994  * line1    2  3  4
2995  *          2  3  4  5  6  7
2996  * line2       3  4  5  6  7
2997  *             3  4     6  7  8  9
2998  * dest           4        7  8  9
2999  *                4        7  8    10
3000  *                4        7  8    10
3001  *
3002  * In the following descriptions, "moved" means moving in the buffer, *and* in
3003  * the fold array.
3004  * Meanwhile, "shifted" just means moving in the buffer.
3005  * 1. not changed
3006  * 2. truncated above line1
3007  * 3. length reduced by  line2 - line1, folds starting between the end of 3 and
3008  *    dest are truncated and shifted up
3009  * 4. internal folds moved (from [line1, line2] to dest)
3010  * 5. moved to dest.
3011  * 6. truncated below line2 and moved.
3012  * 7. length reduced by line2 - dest, folds starting between line2 and dest are
3013  *    removed, top is moved down by move_len.
3014  * 8. truncated below dest and shifted up.
3015  * 9. shifted up
3016  * 10. not changed
3017  */
3018 
3019     static void
3020 truncate_fold(fold_T *fp, linenr_T end)
3021 {
3022     end += 1;
3023     foldRemove(&fp->fd_nested, end - fp->fd_top, MAXLNUM);
3024     fp->fd_len = end - fp->fd_top;
3025 }
3026 
3027 #define fold_end(fp) ((fp)->fd_top + (fp)->fd_len - 1)
3028 #define valid_fold(fp, gap) ((fp) < ((fold_T *)(gap)->ga_data + (gap)->ga_len))
3029 #define fold_index(fp, gap) ((size_t)(fp - ((fold_T *)(gap)->ga_data)))
3030 
3031     void
3032 foldMoveRange(garray_T *gap, linenr_T line1, linenr_T line2, linenr_T dest)
3033 {
3034     fold_T *fp;
3035     linenr_T range_len = line2 - line1 + 1;
3036     linenr_T move_len = dest - line2;
3037     int at_start = foldFind(gap, line1 - 1, &fp);
3038     size_t move_start = 0, move_end = 0, dest_index = 0;
3039 
3040     if (at_start)
3041     {
3042 	if (fold_end(fp) > dest)
3043 	{
3044 	    /* Case 4
3045 	    * don't have to change this fold, but have to move nested folds.
3046 	    */
3047 	    foldMoveRange(&fp->fd_nested, line1 - fp->fd_top, line2 -
3048 		    fp->fd_top, dest - fp->fd_top);
3049 	    return;
3050 	}
3051 	else if (fold_end(fp) > line2)
3052 	{
3053 	    /* Case 3
3054 	     * Remove nested folds between line1 and line2 & reduce the
3055 	     * length of fold by "range_len".
3056 	     * Folds after this one must be dealt with.
3057 	     */
3058 	    foldMarkAdjustRecurse(&fp->fd_nested, line1 - fp->fd_top, line2 -
3059 		    fp->fd_top, MAXLNUM, -range_len);
3060 	    fp->fd_len -= range_len;
3061 	}
3062 	else
3063 	    /* Case 2 truncate fold, folds after this one must be dealt with. */
3064 	    truncate_fold(fp, line1 - 1);
3065 
3066 	/* Look at the next fold, and treat that one as if it were the first
3067 	 * after  "line1" (because now it is). */
3068 	fp = fp + 1;
3069     }
3070 
3071     if (!valid_fold(fp, gap) || fp->fd_top > dest)
3072     {
3073 	/* Case 10
3074 	 * No folds after "line1" and before "dest"
3075 	 */
3076 	return;
3077     }
3078     else if (fp->fd_top > line2)
3079     {
3080 	for (; valid_fold(fp, gap) && fold_end(fp) <= dest; fp++)
3081 	/* Case 9. (for all case 9's) -- shift up. */
3082 	    fp->fd_top -= range_len;
3083 
3084 	if (valid_fold(fp, gap) && fp->fd_top <= dest)
3085 	{
3086 	    /* Case 8. -- ensure truncated at dest, shift up */
3087 	    truncate_fold(fp, dest);
3088 	    fp->fd_top -= range_len;
3089 	}
3090 	return;
3091     }
3092     else if (fold_end(fp) > dest)
3093     {
3094 	/* Case 7 -- remove nested folds and shrink */
3095 	foldMarkAdjustRecurse(&fp->fd_nested, line2 + 1 - fp->fd_top, dest -
3096 		fp->fd_top, MAXLNUM, -move_len);
3097 	fp->fd_len -= move_len;
3098 	fp->fd_top += move_len;
3099 	return;
3100     }
3101 
3102     /* Case 5 or 6
3103      * changes rely on whether there are folds between the end of
3104      * this fold and "dest".
3105      */
3106     move_start = fold_index(fp, gap);
3107 
3108     for (; valid_fold(fp, gap) && fp->fd_top <= dest; fp++)
3109     {
3110 	if (fp->fd_top <= line2)
3111 	{
3112 	    /* 1. 2. or 3. */
3113 	    if (fold_end(fp) > line2)
3114 		/* 2. or 3., truncate before moving */
3115 		truncate_fold(fp, line2);
3116 
3117 	    fp->fd_top += move_len;
3118 	    continue;
3119 	}
3120 
3121 	/* Record index of the first fold after the moved range. */
3122 	if (move_end == 0)
3123 	    move_end = fold_index(fp, gap);
3124 
3125 	if (fold_end(fp) > dest)
3126 	    truncate_fold(fp, dest);
3127 
3128 	fp->fd_top -= range_len;
3129     }
3130 
3131     dest_index = fold_index(fp, gap);
3132 
3133     /*
3134      * All folds are now correct, but not necessarily in the correct order.  We
3135      * must swap folds in the range [move_end, dest_index) with those in the
3136      * range [move_start, move_end).
3137      */
3138     if (move_end == 0)
3139 	/* There are no folds after those moved, hence no folds have been moved
3140 	 * out of order. */
3141 	return;
3142     foldReverseOrder(gap, (linenr_T)move_start, (linenr_T)dest_index - 1);
3143     foldReverseOrder(gap, (linenr_T)move_start,
3144 			   (linenr_T)(move_start + dest_index - move_end - 1));
3145     foldReverseOrder(gap, (linenr_T)(move_start + dest_index - move_end),
3146 						   (linenr_T)(dest_index - 1));
3147 }
3148 #undef fold_end
3149 #undef valid_fold
3150 #undef fold_index
3151 
3152 /* foldMerge() {{{2 */
3153 /*
3154  * Merge two adjacent folds (and the nested ones in them).
3155  * This only works correctly when the folds are really adjacent!  Thus "fp1"
3156  * must end just above "fp2".
3157  * The resulting fold is "fp1", nested folds are moved from "fp2" to "fp1".
3158  * Fold entry "fp2" in "gap" is deleted.
3159  */
3160     static void
3161 foldMerge(fold_T *fp1, garray_T *gap, fold_T *fp2)
3162 {
3163     fold_T	*fp3;
3164     fold_T	*fp4;
3165     int		idx;
3166     garray_T	*gap1 = &fp1->fd_nested;
3167     garray_T	*gap2 = &fp2->fd_nested;
3168 
3169     /* If the last nested fold in fp1 touches the first nested fold in fp2,
3170      * merge them recursively. */
3171     if (foldFind(gap1, fp1->fd_len - 1L, &fp3) && foldFind(gap2, 0L, &fp4))
3172 	foldMerge(fp3, gap2, fp4);
3173 
3174     /* Move nested folds in fp2 to the end of fp1. */
3175     if (gap2->ga_len > 0 && ga_grow(gap1, gap2->ga_len) == OK)
3176     {
3177 	for (idx = 0; idx < gap2->ga_len; ++idx)
3178 	{
3179 	    ((fold_T *)gap1->ga_data)[gap1->ga_len]
3180 					= ((fold_T *)gap2->ga_data)[idx];
3181 	    ((fold_T *)gap1->ga_data)[gap1->ga_len].fd_top += fp1->fd_len;
3182 	    ++gap1->ga_len;
3183 	}
3184 	gap2->ga_len = 0;
3185     }
3186 
3187     fp1->fd_len += fp2->fd_len;
3188     deleteFoldEntry(gap, (int)(fp2 - (fold_T *)gap->ga_data), TRUE);
3189     fold_changed = TRUE;
3190 }
3191 
3192 /* foldlevelIndent() {{{2 */
3193 /*
3194  * Low level function to get the foldlevel for the "indent" method.
3195  * Doesn't use any caching.
3196  * Returns a level of -1 if the foldlevel depends on surrounding lines.
3197  */
3198     static void
3199 foldlevelIndent(fline_T *flp)
3200 {
3201     char_u	*s;
3202     buf_T	*buf;
3203     linenr_T	lnum = flp->lnum + flp->off;
3204 
3205     buf = flp->wp->w_buffer;
3206     s = skipwhite(ml_get_buf(buf, lnum, FALSE));
3207 
3208     /* empty line or lines starting with a character in 'foldignore': level
3209      * depends on surrounding lines */
3210     if (*s == NUL || vim_strchr(flp->wp->w_p_fdi, *s) != NULL)
3211     {
3212 	/* first and last line can't be undefined, use level 0 */
3213 	if (lnum == 1 || lnum == buf->b_ml.ml_line_count)
3214 	    flp->lvl = 0;
3215 	else
3216 	    flp->lvl = -1;
3217     }
3218     else
3219 	flp->lvl = get_indent_buf(buf, lnum) / get_sw_value(buf);
3220     if (flp->lvl > flp->wp->w_p_fdn)
3221     {
3222 	flp->lvl = flp->wp->w_p_fdn;
3223 	if (flp->lvl < 0)
3224 	    flp->lvl = 0;
3225     }
3226 }
3227 
3228 /* foldlevelDiff() {{{2 */
3229 #ifdef FEAT_DIFF
3230 /*
3231  * Low level function to get the foldlevel for the "diff" method.
3232  * Doesn't use any caching.
3233  */
3234     static void
3235 foldlevelDiff(fline_T *flp)
3236 {
3237     if (diff_infold(flp->wp, flp->lnum + flp->off))
3238 	flp->lvl = 1;
3239     else
3240 	flp->lvl = 0;
3241 }
3242 #endif
3243 
3244 /* foldlevelExpr() {{{2 */
3245 /*
3246  * Low level function to get the foldlevel for the "expr" method.
3247  * Doesn't use any caching.
3248  * Returns a level of -1 if the foldlevel depends on surrounding lines.
3249  */
3250     static void
3251 foldlevelExpr(fline_T *flp)
3252 {
3253 #ifndef FEAT_EVAL
3254     flp->start = FALSE;
3255     flp->lvl = 0;
3256 #else
3257     win_T	*win;
3258     int		n;
3259     int		c;
3260     linenr_T	lnum = flp->lnum + flp->off;
3261     int		save_keytyped;
3262 
3263     win = curwin;
3264     curwin = flp->wp;
3265     curbuf = flp->wp->w_buffer;
3266     set_vim_var_nr(VV_LNUM, lnum);
3267 
3268     flp->start = 0;
3269     flp->had_end = flp->end;
3270     flp->end = MAX_LEVEL + 1;
3271     if (lnum <= 1)
3272 	flp->lvl = 0;
3273 
3274     /* KeyTyped may be reset to 0 when calling a function which invokes
3275      * do_cmdline().  To make 'foldopen' work correctly restore KeyTyped. */
3276     save_keytyped = KeyTyped;
3277     n = (int)eval_foldexpr(flp->wp->w_p_fde, &c);
3278     KeyTyped = save_keytyped;
3279 
3280     switch (c)
3281     {
3282 	/* "a1", "a2", .. : add to the fold level */
3283 	case 'a': if (flp->lvl >= 0)
3284 		  {
3285 		      flp->lvl += n;
3286 		      flp->lvl_next = flp->lvl;
3287 		  }
3288 		  flp->start = n;
3289 		  break;
3290 
3291 	/* "s1", "s2", .. : subtract from the fold level */
3292 	case 's': if (flp->lvl >= 0)
3293 		  {
3294 		      if (n > flp->lvl)
3295 			  flp->lvl_next = 0;
3296 		      else
3297 			  flp->lvl_next = flp->lvl - n;
3298 		      flp->end = flp->lvl_next + 1;
3299 		  }
3300 		  break;
3301 
3302 	/* ">1", ">2", .. : start a fold with a certain level */
3303 	case '>': flp->lvl = n;
3304 		  flp->lvl_next = n;
3305 		  flp->start = 1;
3306 		  break;
3307 
3308 	/* "<1", "<2", .. : end a fold with a certain level */
3309 	case '<': flp->lvl_next = n - 1;
3310 		  flp->end = n;
3311 		  break;
3312 
3313 	/* "=": No change in level */
3314 	case '=': flp->lvl_next = flp->lvl;
3315 		  break;
3316 
3317 	/* "-1", "0", "1", ..: set fold level */
3318 	default:  if (n < 0)
3319 		      /* Use the current level for the next line, so that "a1"
3320 		       * will work there. */
3321 		      flp->lvl_next = flp->lvl;
3322 		  else
3323 		      flp->lvl_next = n;
3324 		  flp->lvl = n;
3325 		  break;
3326     }
3327 
3328     /* If the level is unknown for the first or the last line in the file, use
3329      * level 0. */
3330     if (flp->lvl < 0)
3331     {
3332 	if (lnum <= 1)
3333 	{
3334 	    flp->lvl = 0;
3335 	    flp->lvl_next = 0;
3336 	}
3337 	if (lnum == curbuf->b_ml.ml_line_count)
3338 	    flp->lvl_next = 0;
3339     }
3340 
3341     curwin = win;
3342     curbuf = curwin->w_buffer;
3343 #endif
3344 }
3345 
3346 /* parseMarker() {{{2 */
3347 /*
3348  * Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and
3349  * "foldendmarkerlen".
3350  * Relies on the option value to have been checked for correctness already.
3351  */
3352     static void
3353 parseMarker(win_T *wp)
3354 {
3355     foldendmarker = vim_strchr(wp->w_p_fmr, ',');
3356     foldstartmarkerlen = (int)(foldendmarker++ - wp->w_p_fmr);
3357     foldendmarkerlen = (int)STRLEN(foldendmarker);
3358 }
3359 
3360 /* foldlevelMarker() {{{2 */
3361 /*
3362  * Low level function to get the foldlevel for the "marker" method.
3363  * "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been
3364  * set before calling this.
3365  * Requires that flp->lvl is set to the fold level of the previous line!
3366  * Careful: This means you can't call this function twice on the same line.
3367  * Doesn't use any caching.
3368  * Sets flp->start when a start marker was found.
3369  */
3370     static void
3371 foldlevelMarker(fline_T *flp)
3372 {
3373     char_u	*startmarker;
3374     int		cstart;
3375     int		cend;
3376     int		start_lvl = flp->lvl;
3377     char_u	*s;
3378     int		n;
3379 
3380     /* cache a few values for speed */
3381     startmarker = flp->wp->w_p_fmr;
3382     cstart = *startmarker;
3383     ++startmarker;
3384     cend = *foldendmarker;
3385 
3386     /* Default: no start found, next level is same as current level */
3387     flp->start = 0;
3388     flp->lvl_next = flp->lvl;
3389 
3390     s = ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, FALSE);
3391     while (*s)
3392     {
3393 	if (*s == cstart
3394 		  && STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0)
3395 	{
3396 	    /* found startmarker: set flp->lvl */
3397 	    s += foldstartmarkerlen;
3398 	    if (VIM_ISDIGIT(*s))
3399 	    {
3400 		n = atoi((char *)s);
3401 		if (n > 0)
3402 		{
3403 		    flp->lvl = n;
3404 		    flp->lvl_next = n;
3405 		    if (n <= start_lvl)
3406 			flp->start = 1;
3407 		    else
3408 			flp->start = n - start_lvl;
3409 		}
3410 	    }
3411 	    else
3412 	    {
3413 		++flp->lvl;
3414 		++flp->lvl_next;
3415 		++flp->start;
3416 	    }
3417 	}
3418 	else if (*s == cend
3419 	      && STRNCMP(s + 1, foldendmarker + 1, foldendmarkerlen - 1) == 0)
3420 	{
3421 	    /* found endmarker: set flp->lvl_next */
3422 	    s += foldendmarkerlen;
3423 	    if (VIM_ISDIGIT(*s))
3424 	    {
3425 		n = atoi((char *)s);
3426 		if (n > 0)
3427 		{
3428 		    flp->lvl = n;
3429 		    flp->lvl_next = n - 1;
3430 		    /* never start a fold with an end marker */
3431 		    if (flp->lvl_next > start_lvl)
3432 			flp->lvl_next = start_lvl;
3433 		}
3434 	    }
3435 	    else
3436 		--flp->lvl_next;
3437 	}
3438 	else
3439 	    MB_PTR_ADV(s);
3440     }
3441 
3442     /* The level can't go negative, must be missing a start marker. */
3443     if (flp->lvl_next < 0)
3444 	flp->lvl_next = 0;
3445 }
3446 
3447 /* foldlevelSyntax() {{{2 */
3448 /*
3449  * Low level function to get the foldlevel for the "syntax" method.
3450  * Doesn't use any caching.
3451  */
3452     static void
3453 foldlevelSyntax(fline_T *flp)
3454 {
3455 #ifndef FEAT_SYN_HL
3456     flp->start = 0;
3457     flp->lvl = 0;
3458 #else
3459     linenr_T	lnum = flp->lnum + flp->off;
3460     int		n;
3461 
3462     /* Use the maximum fold level at the start of this line and the next. */
3463     flp->lvl = syn_get_foldlevel(flp->wp, lnum);
3464     flp->start = 0;
3465     if (lnum < flp->wp->w_buffer->b_ml.ml_line_count)
3466     {
3467 	n = syn_get_foldlevel(flp->wp, lnum + 1);
3468 	if (n > flp->lvl)
3469 	{
3470 	    flp->start = n - flp->lvl;	/* fold(s) start here */
3471 	    flp->lvl = n;
3472 	}
3473     }
3474 #endif
3475 }
3476 
3477 /* functions for storing the fold state in a View {{{1 */
3478 /* put_folds() {{{2 */
3479 #if defined(FEAT_SESSION) || defined(PROTO)
3480 static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off);
3481 static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off);
3482 static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off);
3483 
3484 /*
3485  * Write commands to "fd" to restore the manual folds in window "wp".
3486  * Return FAIL if writing fails.
3487  */
3488     int
3489 put_folds(FILE *fd, win_T *wp)
3490 {
3491     if (foldmethodIsManual(wp))
3492     {
3493 	if (put_line(fd, "silent! normal! zE") == FAIL
3494 		|| put_folds_recurse(fd, &wp->w_folds, (linenr_T)0) == FAIL)
3495 	    return FAIL;
3496     }
3497 
3498     /* If some folds are manually opened/closed, need to restore that. */
3499     if (wp->w_fold_manual)
3500 	return put_foldopen_recurse(fd, wp, &wp->w_folds, (linenr_T)0);
3501 
3502     return OK;
3503 }
3504 
3505 /* put_folds_recurse() {{{2 */
3506 /*
3507  * Write commands to "fd" to recreate manually created folds.
3508  * Returns FAIL when writing failed.
3509  */
3510     static int
3511 put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off)
3512 {
3513     int		i;
3514     fold_T	*fp;
3515 
3516     fp = (fold_T *)gap->ga_data;
3517     for (i = 0; i < gap->ga_len; i++)
3518     {
3519 	/* Do nested folds first, they will be created closed. */
3520 	if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL)
3521 	    return FAIL;
3522 	if (fprintf(fd, "%ld,%ldfold", fp->fd_top + off,
3523 					fp->fd_top + off + fp->fd_len - 1) < 0
3524 		|| put_eol(fd) == FAIL)
3525 	    return FAIL;
3526 	++fp;
3527     }
3528     return OK;
3529 }
3530 
3531 /* put_foldopen_recurse() {{{2 */
3532 /*
3533  * Write commands to "fd" to open and close manually opened/closed folds.
3534  * Returns FAIL when writing failed.
3535  */
3536     static int
3537 put_foldopen_recurse(
3538     FILE	*fd,
3539     win_T	*wp,
3540     garray_T	*gap,
3541     linenr_T	off)
3542 {
3543     int		i;
3544     int		level;
3545     fold_T	*fp;
3546 
3547     fp = (fold_T *)gap->ga_data;
3548     for (i = 0; i < gap->ga_len; i++)
3549     {
3550 	if (fp->fd_flags != FD_LEVEL)
3551 	{
3552 	    if (fp->fd_nested.ga_len > 0)
3553 	    {
3554 		/* open nested folds while this fold is open */
3555 		if (fprintf(fd, "%ld", fp->fd_top + off) < 0
3556 			|| put_eol(fd) == FAIL
3557 			|| put_line(fd, "normal! zo") == FAIL)
3558 		    return FAIL;
3559 		if (put_foldopen_recurse(fd, wp, &fp->fd_nested,
3560 							     off + fp->fd_top)
3561 			== FAIL)
3562 		    return FAIL;
3563 		/* close the parent when needed */
3564 		if (fp->fd_flags == FD_CLOSED)
3565 		{
3566 		    if (put_fold_open_close(fd, fp, off) == FAIL)
3567 			return FAIL;
3568 		}
3569 	    }
3570 	    else
3571 	    {
3572 		/* Open or close the leaf according to the window foldlevel.
3573 		 * Do not close a leaf that is already closed, as it will close
3574 		 * the parent. */
3575 		level = foldLevelWin(wp, off + fp->fd_top);
3576 		if ((fp->fd_flags == FD_CLOSED && wp->w_p_fdl >= level)
3577 			|| (fp->fd_flags != FD_CLOSED && wp->w_p_fdl < level))
3578 		if (put_fold_open_close(fd, fp, off) == FAIL)
3579 		    return FAIL;
3580 	    }
3581 	}
3582 	++fp;
3583     }
3584 
3585     return OK;
3586 }
3587 
3588 /* put_fold_open_close() {{{2 */
3589 /*
3590  * Write the open or close command to "fd".
3591  * Returns FAIL when writing failed.
3592  */
3593     static int
3594 put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off)
3595 {
3596     if (fprintf(fd, "%ld", fp->fd_top + off) < 0
3597 	    || put_eol(fd) == FAIL
3598 	    || fprintf(fd, "normal! z%c",
3599 			   fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0
3600 	    || put_eol(fd) == FAIL)
3601 	return FAIL;
3602 
3603     return OK;
3604 }
3605 #endif /* FEAT_SESSION */
3606 
3607 /* }}}1 */
3608 #endif /* defined(FEAT_FOLDING) || defined(PROTO) */
3609