Movatterモバイル変換


[0]ホーム

URL:


Fold

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Foldingfoldingfolds
You can find an introduction on folding in chapter 28 of the user manual.usr_28.txt

1. Fold methodsfold-methods

The folding method can be set with the'foldmethod' option.
When setting'foldmethod' to a value other than "manual", all folds aredeleted and new ones created. Switching to the "manual" method doesn't removethe existing folds. This can be used to first define the folds automaticallyand then change them manually.
There are six methods to select folds:manualmanually define foldsindentmore indent means a higher fold levelexprspecify an expression to define foldssyntaxfolds defined by syntax highlightingdifffolds for unchanged textmarkerfolds defined by markers in the text

MANUALfold-manual

Use commands to manually define the fold regions. This can also be used by ascript that parses text to find folds.
The level of a fold is only defined by its nesting. To increase the foldlevel of a fold for a range of lines, define a fold inside it that has thesame lines.
The manual folds are lost when you abandon the file. To save the folds usethe:mkview command. The view can be restored later with:loadview.

INDENTfold-indent

The folds are automatically defined by the indent of the lines.
The foldlevel is computed from the indent of the line, divided by the'shiftwidth' (rounded down). A sequence of lines with the same or higher foldlevel form a fold, with the lines with a higher level forming a nested fold.
The nesting of folds is limited with'foldnestmax'.
Some lines are ignored and get the fold level of the line above or below it,whichever is lower. These are empty or white lines and lines startingwith a character in'foldignore'. White space is skipped before checking forcharacters in'foldignore'. For C use "#" to ignore preprocessor lines.
When you want to ignore lines in another way, use the "expr" method. Theindent() function can be used in'foldexpr' to get the indent of a line.

EXPRfold-expr

The folds are automatically defined by their foldlevel, like with the "indent"method. The value of the'foldexpr' option is evaluated to get the foldlevelof a line. Examples:This will create a fold for all consecutive lines that start with a tab:
:set foldexpr=getline(v:lnum)[0]==\"\\t\"
This will make a fold out of paragraphs separated by blank lines:
:set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
This does the same:
:set foldexpr=getline(v:lnum-1)=~'^\\s*$'&&getline(v:lnum)=~'\\S'?'>1':1
Note that backslashes must be used to escape characters that ":set" handlesdifferently (space, backslash, double quote, etc., seeoption-backslash).
The most efficient is to call a function without arguments:
:set foldexpr=MyFoldLevel()
The function must use v:lnum. Seeexpr-option-function.
These are the conditions with which the expression is evaluated:
The current buffer and window are set for the line.
The variable "v:lnum" is set to the line number.
The result of foldexpr then determines the fold level as follows:
valuemeaning
0the line is not in a fold 1, 2, ..the line is in a fold with this level -1the fold level is undefined, use the fold level of aline before or after this line, whichever is thelowest. "="use fold level from the previous line "a1", "a2", ..add one, two, .. to the fold level of the previousline, use the result for the current line "s1", "s2", ..subtract one, two, .. from the fold level of theprevious line, use the result for the next line "<1", "<2", ..a fold with this level ends at this line ">1", ">2", ..a fold with this level starts at this line
The result values "=", "s" and "a" are more expensive, please seefold-expr-slow.
It is not required to mark the start (end) of a fold with ">1" ("<1"), a foldwill also start (end) when the fold level is higher (lower) than the foldlevel of the previous line.
There must be no side effects from the expression. The text in the buffer,cursor position, the search patterns, options etc. must not be changed.You can change and restore them if you are careful.
If there is some error in the expression, or the resulting value isn'trecognized, there is no error message and the fold level will be zero.For debugging the'debug' option can be set to "msg", the error messages willbe visible then.
If the'foldexpr' expression starts with s: or<SID>, then it is replacedwith the script ID (local-function). Examples:
set foldexpr=s:MyFoldExpr()set foldexpr=<SID>SomeFoldExpr()
An example of using "a1" and "s1": For a multi-line C comment, a linecontaining "/*" would return "a1" to start a fold, and a line containing "*/"would return "s1" to end the fold after that line:
if match(thisline, '/\*') >= 0  return 'a1'elseif match(thisline, '\*/') >= 0  return 's1'else  return '='endif
However, this won't work for single line comments, strings, etc.
foldlevel() can be useful to compute a fold level relative to a previousfold level. But note that foldlevel() may return -1 if the level is not knownyet. And it returns the level at the start of the line, while a fold mightend in that line.
It may happen that folds are not updated properly. You can usezx orzXto force updating folds.

MINIMIZING COMPUTATIONAL COSTfold-expr-slow

Due to its computational cost, this fold method can make Vim unresponsive,especially when the fold level of all lines have to be initially computed.Afterwards, after each change, Vim restricts the computation of foldlevelsto those lines whose fold level was affected by it (and reuses the knownfoldlevels of all the others).
The fold expression should therefore strive to minimize the number ofdependent lines needed for the computation of a given line: For example, tryto avoid the "=", "a" and "s" return values, because these will require theevaluation of the fold levels on previous lines until an independent foldlevel is found.
If this proves difficult, the next best thing could be to cache all foldlevels in a buffer-local variable (b:foldlevels) that is only updated onb:changedtick:
func MyFoldFunc()  if b:lasttick == b:changedtick    return b:foldlevels[v:lnum - 1]  endif  let b:lasttick = b:changedtick  let b:foldlevels = []  " compute foldlevels ...  return b:foldlevels[v:lnum - 1]enddefset foldexpr=s:MyFoldFunc()
In above example further speedup was gained by using a function withoutarguments (that must still use v:lnum). Seeexpr-option-function.

SYNTAXfold-syntax

A fold is defined by syntax items that have the "fold" argument.:syn-fold
The fold level is defined by nesting folds. The nesting of folds is limitedwith'foldnestmax'.
Be careful to specify proper syntax syncing. If this is not done right, foldsmay differ from the displayed highlighting. This is especially relevant whenusing patterns that match more than one line. In case of doubt, try usingbrute-force syncing:
:syn sync fromstart

DIFFfold-diff

The folds are automatically defined for text that is not part of a change orclose to a change.
This method only works properly when the'diff' option is set for the currentwindow and changes are being displayed. Otherwise the whole buffer will beone big fold.
The'diffopt' option can be used to specify the context. That is, the numberof lines between the fold and a change that are not included in the fold. Forexample, to use a context of 8 lines:
:set diffopt=filler,context:8
The default context is six lines.
When'scrollbind' is also set, Vim will attempt to keep the same folds open inother diff windows, so that the same text is visible.

MARKERfold-marker

Markers in the text tell where folds start and end. This allows you toprecisely specify the folds. This will allow deleting and putting a fold,without the risk of including the wrong lines. The'foldtext' option isnormally set such that the text before the marker shows up in the folded line.This makes it possible to give a name to the fold.
Markers can have a level included, or can use matching pairs. Including alevel is easier, you don't have to add end markers and avoid problems withnon-matching marker pairs. Example:
/* global variables {{{1 */int varA, varB;/* functions {{{1 *//* funcA() {{{2 */void funcA() {}/* funcB() {{{2 */void funcB() {}
{{{}}}A fold starts at a "{{{" marker. The following number specifies the foldlevel. What happens depends on the difference between the current fold leveland the level given by the marker:1. If a marker with the same fold level is encountered, the previous fold ends and another fold with the same level starts.2. If a marker with a higher fold level is found, a nested fold is started.3. If a marker with a lower fold level is found, all folds up to and including this level end and a fold with the specified level starts.
The number indicates the fold level. A zero cannot be used (a marker withlevel zero is ignored). You can use "}}}" with a digit to indicate the levelof the fold that ends. The fold level of the following line will be one lessthan the indicated level. Note that Vim doesn't look back to the level of thematching marker (that would take too much time). Example:
{{{1fold level here is 1{{{3fold level here is 3}}}3fold level here is 2
You can also use matching pairs of "{{{" and "}}}" markers to define folds.Each "{{{" increases the fold level by one, each "}}}" decreases the foldlevel by one. Be careful to keep the markers matching! Example:
{{{fold level here is 1{{{fold level here is 2}}}fold level here is 1
You can mix using markers with a number and without a number. A useful way ofdoing this is to use numbered markers for large folds, and unnumbered markerslocally in a function. For example use level one folds for the sections ofyour file like "structure definitions", "local variables" and "functions".Use level 2 markers for each definition and function, Use unnumbered markersinside functions. When you make changes in a function to split up folds, youdon't have to renumber the markers.
The markers can be set with the'foldmarker' option. It is recommended tokeep this at the default value of "{{{,}}}", so that files can be exchangedbetween Vim users. Only change it when it is required for the file (e.g., itcontains markers from another folding editor, or the default markers causetrouble for the language of the file).
fold-create-marker
"zf" can be used to create a fold defined by markers. Vim will insert themarkers for you. Vim will append the start and end marker, as specified with'foldmarker'. The markers are appended to the end of the line.'commentstring' is used if it isn't empty.This does not work properly when:
The line already contains a marker with a level number. Vim then doesn't know what to do.
Folds nearby use a level number in their marker which gets in the way.
The line is inside a comment,'commentstring' isn't empty and nested comments don't work. For example with C: adding/* {{{ */ inside a comment will truncate the existing comment. Either put the marker before or after the comment, or add the marker manually.Generally it's not a good idea to let Vim create markers when you already havemarkers with a level number.
fold-delete-marker
"zd" can be used to delete a fold defined by markers. Vim will delete themarkers for you. Vim will search for the start and end markers, as specifiedwith'foldmarker', at the start and end of the fold. When the text around themarker matches with'commentstring', that text is deleted as well.This does not work properly when:
A line contains more than one marker and one of them specifies a level. Only the first one is removed, without checking if this will have the desired effect of deleting the fold.
The marker contains a level number and is used to start or end several folds at the same time.

2. Fold commandsfold-commandsE490

All folding commands start with "z". Hint: the "z" looks like a folded pieceof paper, if you look at it from the side.
CREATING AND DELETING FOLDS
zfE350zf{motion} or{Visual}zfOperator to create a fold.This only works when'foldmethod' is "manual" or "marker".The new fold will be closed for the "manual" method.'foldenable' will be set.Also seefold-create-marker.
zF
zFCreate a fold for [count] lines. Works like "zf".
:{range}fo[ld]:fold:foCreate a fold for the lines in{range}. Works like "zf".
zdE351zdDelete one fold at the cursor. When the cursor is on a foldedline, that fold is deleted. Nested folds are moved one levelup. In Visual mode one level of all folds (partially) in theselected area are deleted.Careful: This easily deletes more folds than you expect andthere is no undo for manual folding.This only works when'foldmethod' is "manual" or "marker".Also seefold-delete-marker.
zD
zDDelete folds recursively at the cursor. In Visual mode allfolds (partially) in the selected area and all nested folds inthem are deleted.This only works when'foldmethod' is "manual" or "marker".Also seefold-delete-marker.
zEE352zEEliminate all folds in the window.This only works when'foldmethod' is "manual" or "marker".Also seefold-delete-marker.
OPENING AND CLOSING FOLDS
A fold smaller than'foldminlines' will always be displayed like it was open.Therefore the commands below may work differently on small folds.
zo
zoOpen one fold under the cursor. When a count is given, thatmany folds deep will be opened. In Visual mode one level offolds is opened for all lines in the selected area.
zO
zOOpen all folds under the cursor recursively. Folds that don'tcontain the cursor line are unchanged.In Visual mode it opens all folds that are in the selectedarea, also those that are only partly selected.
zc
zcClose one fold under the cursor. When a count is given, thatmany folds deep are closed. In Visual mode one level of foldsis closed for all lines in the selected area.'foldenable' will be set.
zC
zCClose all folds under the cursor recursively. Folds thatdon't contain the cursor line are unchanged.In Visual mode it closes all folds that are in the selectedarea, also those that are only partly selected.'foldenable' will be set.
za
zaSummary: Toggle the fold under the cursor.When on a closed fold: open it. When folds are nested, youmay have to use "za" several times. When a count is given,that many closed folds are opened.When on an open fold: close it and set'foldenable'. Thiswill only close one level, since using "za" again will openthe fold. When a count is given that many folds will beclosed (that's not the same as repeating "za" that manytimes).
zA
zAWhen on a closed fold: open it recursively.When on an open fold: close it recursively and set'foldenable'.
zv
zvView cursor line: Open just enough folds to make the line inwhich the cursor is located not folded.
zx
zxUpdate folds: Undo manually opened and closed folds: re-apply'foldlevel', then do "zv": View cursor line.Also forces recomputing folds. This is useful when using'foldexpr' and the buffer is changed in a way that results infolds not to be updated properly.
zX
zXUndo manually opened and closed folds: re-apply'foldlevel'.Also forces recomputing folds, likezx.
zm
zmFold more: Subtractv:count1 from'foldlevel'. If'foldlevel' was already zero nothing happens.'foldenable' will be set.
zM
zMClose all folds: set'foldlevel' to 0.'foldenable' will be set.
zr
zrReduce folding: Addv:count1 to'foldlevel'.
zR
zROpen all folds. This sets'foldlevel' to highest fold level.
:foldo:foldopen:{range}foldo[pen][!]Open folds in{range}. When [!] is added all folds areopened. Useful to see all the text in{range}. Without [!]one level of folds is opened.
:foldc:foldclose:{range}foldc[lose][!]Close folds in{range}. When [!] is added all folds areclosed. Useful to hide all the text in{range}. Without [!]one level of folds is closed.
zn
znFold none: reset'foldenable'. All folds will be open.
zN
zNFold normal: set'foldenable'. All folds will be as theywere before.
zi
ziInvert'foldenable'.
MOVING OVER FOLDS
[z
[zMove to the start of the current open fold. If already at thestart, move to the start of the fold that contains it. Ifthere is no containing fold, the command fails.When a count is used, repeats the command [count] times.
]z
]zMove to the end of the current open fold. If already at theend, move to the end of the fold that contains it. If thereis no containing fold, the command fails.When a count is used, repeats the command [count] times.
zj
zjMove downwards to the start of the next fold. A closed foldis counted as one fold.When a count is used, repeats the command [count] times.This command can be used after anoperator.
zk
zkMove upwards to the end of the previous fold. A closed foldis counted as one fold.When a count is used, repeats the command [count] times.This command can be used after anoperator.
EXECUTING COMMANDS ON FOLDS
:[range]foldd[oopen]{cmd}:foldd:folddo:folddoopenExecute{cmd} on all lines that are not in a closed fold.When [range] is given, only these lines are used.Each time{cmd} is executed the cursor is positioned on theline it is executed for.This works like the ":global" command: First all lines thatare not in a closed fold are marked. Then the{cmd} isexecuted for all marked lines. Thus when{cmd} changes thefolds, this has no influence on where it is executed (exceptwhen lines are deleted, of course).Example:
:folddoopen s/end/loop_end/ge
Note the use of the "e" flag to avoid getting an error messagewhere "end" doesn't match.
:[range]folddoc[losed]{cmd}:folddoc:folddoclosedExecute{cmd} on all lines that are in a closed fold.Otherwise like ":folddoopen".

3. Fold optionsfold-options

COLORSfold-colors

The colors of a closed fold are set with the Folded grouphl-Folded. Thecolors of the fold column are set with the FoldColumn grouphl-FoldColumn.Example to set the colors:
:highlight Folded guibg=grey guifg=blue:highlight FoldColumn guibg=darkgrey guifg=white

FOLDLEVELfold-foldlevel

'foldlevel' is a number option: The higher the more folded regions are open.When'foldlevel' is 0, all folds are closed.When'foldlevel' is positive, some folds are closed.When'foldlevel' is very high, all folds are open.'foldlevel' is applied when it is changed. After that manually folds can beopened and closed.When increased, folds above the new level are opened. No manually openedfolds will be closed.When decreased, folds above the new level are closed. No manually closedfolds will be opened.

FOLDTEXTfold-foldtext

'foldtext' is a string option that specifies an expression. This expressionis evaluated to obtain the text displayed for a closed fold. Example:
:set foldtext=v:folddashes.substitute(getline(v:foldstart),'/\\*\\\|\\*/\\\|{{{\\d\\=','','g')
This shows the first line of the fold, with "/*", "*/" and "{{{" removed.Note the use of backslashes to avoid some characters to be interpreted by the":set" command. It is much simpler to define a function and call it:
:set foldtext=MyFoldText():function MyFoldText():  let line = getline(v:foldstart):  let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g'):  return v:folddashes .. sub:endfunction
Evaluating'foldtext' is done in thesandbox. The current window is set tothe window that displays the line.
Errors are ignored. For debugging set the'debug' option to "throw".
The default value isfoldtext(). This returns a reasonable text for mosttypes of folding. If you don't like it, you can specify your own'foldtext'expression. It can use these special Vim variables:v:foldstartline number of first line in the foldv:foldendline number of last line in the foldv:folddashesa string that contains dashes to represent thefoldlevel.v:foldlevelthe foldlevel of the fold
If the result is aList, it is parsed and drawn like "overlay" virtual text(seenvim_buf_set_extmark()), otherwise the result is converted to a stringwhere a TAB is replaced with a space and unprintable characters are made intoprintable characters.
The resulting line is truncated to fit in the window, it never wraps.When there is room after the text, it is filled with the character specifiedby'fillchars'.
If the'foldtext' expression starts with s: or<SID>, then it is replacedwith the script ID (local-function). Examples:
set foldtext=s:MyFoldText()set foldtext=<SID>SomeFoldText()
Note that backslashes need to be used for characters that the ":set" commandhandles differently: Space, backslash and double-quote.option-backslash

FOLDCOLUMNfold-foldcolumn

'foldcolumn' is a number, which sets the width for a column on the side of thewindow to indicate folds. When it is zero, there is no foldcolumn. A normalvalue is auto:9. The maximum is 9.
An open fold is indicated with a column that has a '-' at the top and '|'characters below it. This column stops where the open fold stops. When foldsnest, the nested fold is one character right of the fold it's contained in.
A closed fold is indicated with a '+'.
These characters can be changed with the'fillchars' option.
Where the fold column is too narrow to display all nested folds, digits areshown to indicate the nesting level. To override this behavior you can usethe "foldinner" character of the'fillchars' option.
The mouse can also be used to open and close folds by clicking in thefold column:
Click on a '+' to open the closed fold at this row.
Click on any other non-blank character to close the open fold at this row.

OTHER OPTIONS

'foldenable''fen':Open all folds while not set.'foldexpr''fde':Expression used for "expr" folding.'foldignore''fdi':Characters used for "indent" folding.'foldmarker''fmr':Defined markers used for "marker" folding.'foldmethod''fdm':Name of the current folding method.'foldminlines''fml':Minimum number of screen lines for a fold to bedisplayed closed.'foldnestmax''fdn':Maximum nesting for "indent" and "syntax" folding.'foldopen''fdo':Which kinds of commands open closed folds.'foldclose''fcl':When the folds not under the cursor are closed.

4. Behavior of foldsfold-behavior

When moving the cursor upwards or downwards and when scrolling, the cursorwill move to the first line of a sequence of folded lines. When the cursor isalready on a folded line, it moves to the next unfolded line or the nextclosed fold.
While the cursor is on folded lines, the cursor is always displayed in thefirst column. The ruler does show the actual cursor position, but since theline is folded, it cannot be displayed there.
Many movement commands handle a sequence of folded lines like an empty line.For example, the "w" command stops once in the first column.
When starting a search in a closed fold it will not find a match in thecurrent fold. It's like a forward search always starts from the end of theclosed fold, while a backwards search starts from the start of the closedfold.
When in Insert mode, the cursor line is never folded. That allows you to seewhat you type!
When using an operator, a closed fold is included as a whole. Thus "dl"deletes the whole closed fold under the cursor.
For Ex commands that operate on buffer lines, the range is adjusted to alwaysstart at the first line of a closed fold and end at the last line of a closedfold. Thus, this command:
:s/foo/bar/g
when used with the cursor on a closed fold, will replace "foo" with "bar" inall lines of the fold.This does not happen for:folddoopen and:folddoclosed.
Note that for some Ex commands like:source the range is only adjusted whenusing a two line specifiers [range].
When editing a buffer that has been edited before, the last used foldingsettings are used again. For manual folding the defined folds are restored.For all folding methods the manually opened and closed folds are restored.If this buffer has been edited in this window, the values from back then areused. Otherwise the values from the window where the buffer was edited lastare used.
Main
Commands index
Quick reference

1. Fold methods
MANUAL
INDENT
EXPR
MINIMIZING COMPUTATIONAL COST
SYNTAX
DIFF
MARKER
2. Fold commands
3. Fold options
COLORS
FOLDLEVEL
FOLDTEXT
FOLDCOLUMN
OTHER OPTIONS
4. Behavior of folds

[8]ページ先頭

©2009-2025 Movatter.jp