home *** CD-ROM | disk | FTP | other *** search
/ vim.ftp.fu-berlin.de / 2015-02-03.vim.ftp.fu-berlin.de.tar / vim.ftp.fu-berlin.de / unix / vim-6.2.tar.bz2 / vim-6.2.tar / vim62 / src / fold.c < prev    next >
Encoding:
C/C++ Source or Header  |  2003-04-18  |  77.0 KB  |  3,141 lines

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