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