xref: /vim-8.2.3635/runtime/doc/fold.txt (revision 53f7fccc)
1*fold.txt*      For Vim version 8.2.  Last change: 2021 Jul 13
2
3
4		  VIM REFERENCE MANUAL    by Bram Moolenaar
5
6
7Folding						*Folding* *folding* *folds*
8
9You can find an introduction on folding in chapter 28 of the user manual.
10|usr_28.txt|
11
121. Fold methods		|fold-methods|
132. Fold commands	|fold-commands|
143. Fold options		|fold-options|
154. Behavior of folds	|fold-behavior|
16
17{not available when compiled without the |+folding| feature}
18
19==============================================================================
201. Fold methods					*fold-methods*
21
22The folding method can be set with the 'foldmethod' option.
23
24When setting 'foldmethod' to a value other than "manual", all folds are
25deleted and new ones created.  Switching to the "manual" method doesn't remove
26the existing folds.  This can be used to first define the folds automatically
27and then change them manually.
28
29There are six methods to select folds:
30	manual		manually define folds
31	indent		more indent means a higher fold level
32	expr		specify an expression to define folds
33	syntax		folds defined by syntax highlighting
34	diff		folds for unchanged text
35	marker		folds defined by markers in the text
36
37
38MANUAL						*fold-manual*
39
40Use commands to manually define the fold regions.  This can also be used by a
41script that parses text to find folds.
42
43The level of a fold is only defined by its nesting.  To increase the fold
44level of a fold for a range of lines, define a fold inside it that has the
45same lines.
46
47The manual folds are lost when you abandon the file.  To save the folds use
48the |:mkview| command.  The view can be restored later with |:loadview|.
49
50
51INDENT						*fold-indent*
52
53The folds are automatically defined by the indent of the lines.
54
55The foldlevel is computed from the indent of the line, divided by the
56'shiftwidth' (rounded down).  A sequence of lines with the same or higher fold
57level form a fold, with the lines with a higher level forming a nested fold.
58
59The nesting of folds is limited with 'foldnestmax'.
60
61Some lines are ignored and get the fold level of the line above or below it,
62whichever is lower.  These are empty or white lines and lines starting
63with a character in 'foldignore'.  White space is skipped before checking for
64characters in 'foldignore'.  For C use "#" to ignore preprocessor lines.
65
66When you want to ignore lines in another way, use the "expr" method.  The
67|indent()| function can be used in 'foldexpr' to get the indent of a line.
68
69
70EXPR						*fold-expr*
71
72The folds are automatically defined by their foldlevel, like with the "indent"
73method.  The value of the 'foldexpr' option is evaluated to get the foldlevel
74of a line.  Examples:
75This will create a fold for all consecutive lines that start with a tab: >
76	:set foldexpr=getline(v:lnum)[0]==\"\\t\"
77This will call a function to compute the fold level: >
78	:set foldexpr=MyFoldLevel(v:lnum)
79This will make a fold out of paragraphs separated by blank lines: >
80	:set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
81This does the same: >
82	:set foldexpr=getline(v:lnum-1)=~'^\\s*$'&&getline(v:lnum)=~'\\S'?'>1':1
83
84Note that backslashes must be used to escape characters that ":set" handles
85differently (space, backslash, double quote, etc., see |option-backslash|).
86
87These are the conditions with which the expression is evaluated:
88- The current buffer and window are set for the line.
89- The variable "v:lnum" is set to the line number.
90- The result is used for the fold level in this way:
91  value			meaning ~
92  0			the line is not in a fold
93  1, 2, ..		the line is in a fold with this level
94  -1			the fold level is undefined, use the fold level of a
95			line before or after this line, whichever is the
96			lowest.
97  "="			use fold level from the previous line
98  "a1", "a2", ..	add one, two, .. to the fold level of the previous
99			line, use the result for the current line
100  "s1", "s2", ..	subtract one, two, .. from the fold level of the
101			previous line, use the result for the next line
102  "<1", "<2", ..	a fold with this level ends at this line
103  ">1", ">2", ..	a fold with this level starts at this line
104
105It is not required to mark the start (end) of a fold with ">1" ("<1"), a fold
106will also start (end) when the fold level is higher (lower) than the fold
107level of the previous line.
108
109There must be no side effects from the expression.  The text in the buffer,
110cursor position, the search patterns, options etc. must not be changed.
111You can change and restore them if you are careful.
112
113If there is some error in the expression, or the resulting value isn't
114recognized, there is no error message and the fold level will be zero.
115For debugging the 'debug' option can be set to "msg", the error messages will
116be visible then.
117
118Note: Since the expression has to be evaluated for every line, this fold
119method can be very slow!
120
121Try to avoid the "=", "a" and "s" return values, since Vim often has to search
122backwards for a line for which the fold level is defined.  This can be slow.
123
124An example of using "a1" and "s1": For a multi-line C comment, a line
125containing "/*" would return "a1" to start a fold, and a line containing "*/"
126would return "s1" to end the fold after that line: >
127  if match(thisline, '/\*') >= 0
128    return 'a1'
129  elseif match(thisline, '\*/') >= 0
130    return 's1'
131  else
132    return '='
133  endif
134However, this won't work for single line comments, strings, etc.
135
136|foldlevel()| can be useful to compute a fold level relative to a previous
137fold level.  But note that foldlevel() may return -1 if the level is not known
138yet.  And it returns the level at the start of the line, while a fold might
139end in that line.
140
141It may happen that folds are not updated properly.  You can use |zx| or |zX|
142to force updating folds.
143
144
145SYNTAX						*fold-syntax*
146
147A fold is defined by syntax items that have the "fold" argument. |:syn-fold|
148
149The fold level is defined by nesting folds.  The nesting of folds is limited
150with 'foldnestmax'.
151
152Be careful to specify proper syntax syncing.  If this is not done right, folds
153may differ from the displayed highlighting.  This is especially relevant when
154using patterns that match more than one line.  In case of doubt, try using
155brute-force syncing: >
156	:syn sync fromstart
157
158
159DIFF						*fold-diff*
160
161The folds are automatically defined for text that is not part of a change or
162close to a change.
163
164This method only works properly when the 'diff' option is set for the current
165window and changes are being displayed.  Otherwise the whole buffer will be
166one big fold.
167
168The 'diffopt' option can be used to specify the context.  That is, the number
169of lines between the fold and a change that are not included in the fold.  For
170example, to use a context of 8 lines: >
171	:set diffopt=filler,context:8
172The default context is six lines.
173
174When 'scrollbind' is also set, Vim will attempt to keep the same folds open in
175other diff windows, so that the same text is visible.
176
177
178MARKER						*fold-marker*
179
180Markers in the text tell where folds start and end.  This allows you to
181precisely specify the folds.  This will allow deleting and putting a fold,
182without the risk of including the wrong lines.  The 'foldtext' option is
183normally set such that the text before the marker shows up in the folded line.
184This makes it possible to give a name to the fold.
185
186Markers can have a level included, or can use matching pairs.  Including a
187level is easier, you don't have to add end markers and avoid problems with
188non-matching marker pairs.  Example: >
189	/* global variables {{{1 */
190	int varA, varB;
191
192	/* functions {{{1 */
193	/* funcA() {{{2 */
194	void funcA() {}
195
196	/* funcB() {{{2 */
197	void funcB() {}
198
199A fold starts at a "{{{" marker.  The following number specifies the fold
200level.  What happens depends on the difference between the current fold level
201and the level given by the marker:
2021. If a marker with the same fold level is encountered, the previous fold
203   ends and another fold with the same level starts.
2042. If a marker with a higher fold level is found, a nested fold is started.
2053. If a marker with a lower fold level is found, all folds up to and including
206   this level end and a fold with the specified level starts.
207
208The number indicates the fold level.  A zero cannot be used (a marker with
209level zero is ignored).  You can use "}}}" with a digit to indicate the level
210of the fold that ends.  The fold level of the following line will be one less
211than the indicated level.  Note that Vim doesn't look back to the level of the
212matching marker (that would take too much time).  Example: >
213
214	{{{1
215	fold level here is 1
216	{{{3
217	fold level here is 3
218	}}}3
219	fold level here is 2
220
221You can also use matching pairs of "{{{" and "}}}" markers to define folds.
222Each "{{{" increases the fold level by one, each "}}}" decreases the fold
223level by one.  Be careful to keep the markers matching!  Example: >
224
225	{{{
226	fold level here is 1
227	{{{
228	fold level here is 2
229	}}}
230	fold level here is 1
231
232You can mix using markers with a number and without a number.  A useful way of
233doing this is to use numbered markers for large folds, and unnumbered markers
234locally in a function.  For example use level one folds for the sections of
235your file like "structure definitions", "local variables" and "functions".
236Use level 2 markers for each definition and function,  Use unnumbered markers
237inside functions.  When you make changes in a function to split up folds, you
238don't have to renumber the markers.
239
240The markers can be set with the 'foldmarker' option.  It is recommended to
241keep this at the default value of "{{{,}}}", so that files can be exchanged
242between Vim users.  Only change it when it is required for the file (e.g., it
243contains markers from another folding editor, or the default markers cause
244trouble for the language of the file).
245
246							*fold-create-marker*
247"zf" can be used to create a fold defined by markers.  Vim will insert the
248markers for you.  Vim will append the start and end marker, as specified with
249'foldmarker'.  The markers are appended to the end of the line.
250'commentstring' is used if it isn't empty.
251This does not work properly when:
252- The line already contains a marker with a level number.  Vim then doesn't
253  know what to do.
254- Folds nearby use a level number in their marker which gets in the way.
255- The line is inside a comment, 'commentstring' isn't empty and nested
256  comments don't work.  For example with C: adding /* {{{ */ inside a comment
257  will truncate the existing comment.  Either put the marker before or after
258  the comment, or add the marker manually.
259Generally it's not a good idea to let Vim create markers when you already have
260markers with a level number.
261
262							*fold-delete-marker*
263"zd" can be used to delete a fold defined by markers.  Vim will delete the
264markers for you.  Vim will search for the start and end markers, as specified
265with 'foldmarker', at the start and end of the fold.  When the text around the
266marker matches with 'commentstring', that text is deleted as well.
267This does not work properly when:
268- A line contains more than one marker and one of them specifies a level.
269  Only the first one is removed, without checking if this will have the
270  desired effect of deleting the fold.
271- The marker contains a level number and is used to start or end several folds
272  at the same time.
273
274==============================================================================
2752. Fold commands				*fold-commands* *E490*
276
277All folding commands start with "z".  Hint: the "z" looks like a folded piece
278of paper, if you look at it from the side.
279
280
281CREATING AND DELETING FOLDS ~
282							*zf* *E350*
283zf{motion}  or
284{Visual}zf	Operator to create a fold.
285		This only works when 'foldmethod' is "manual" or "marker".
286		The new fold will be closed for the "manual" method.
287		'foldenable' will be set.
288		Also see |fold-create-marker|.
289
290							*zF*
291zF		Create a fold for [count] lines.  Works like "zf".
292
293:{range}fo[ld]						*:fold* *:fo*
294		Create a fold for the lines in {range}.  Works like "zf".
295
296							*zd* *E351*
297zd		Delete one fold at the cursor.  When the cursor is on a folded
298		line, that fold is deleted.  Nested folds are moved one level
299		up.  In Visual mode one level of all folds (partially) in the
300		selected area are deleted.
301		Careful: This easily deletes more folds than you expect and
302		there is no undo for manual folding.
303		This only works when 'foldmethod' is "manual" or "marker".
304		Also see |fold-delete-marker|.
305
306							*zD*
307zD		Delete folds recursively at the cursor.  In Visual mode all
308		folds (partially) in the selected area and all nested folds in
309		them are deleted.
310		This only works when 'foldmethod' is "manual" or "marker".
311		Also see |fold-delete-marker|.
312
313							*zE* *E352*
314zE		Eliminate all folds in the window.
315		This only works when 'foldmethod' is "manual" or "marker".
316		Also see |fold-delete-marker|.
317
318
319OPENING AND CLOSING FOLDS ~
320
321A fold smaller than 'foldminlines' will always be displayed like it was open.
322Therefore the commands below may work differently on small folds.
323
324							*zo*
325zo		Open one fold under the cursor.  When a count is given, that
326		many folds deep will be opened.  In Visual mode one level of
327		folds is opened for all lines in the selected area.
328
329							*zO*
330zO		Open all folds under the cursor recursively.  Folds that don't
331		contain the cursor line are unchanged.
332		In Visual mode it opens all folds that are in the selected
333		area, also those that are only partly selected.
334
335							*zc*
336zc		Close one fold under the cursor.  When a count is given, that
337		many folds deep are closed.  In Visual mode one level of folds
338		is closed for all lines in the selected area.
339		'foldenable' will be set.
340
341							*zC*
342zC		Close all folds under the cursor recursively.  Folds that
343		don't contain the cursor line are unchanged.
344		In Visual mode it closes all folds that are in the selected
345		area, also those that are only partly selected.
346		'foldenable' will be set.
347
348							*za*
349za		When on a closed fold: open it.  When folds are nested, you
350		may have to use "za" several times.  When a count is given,
351		that many closed folds are opened.
352		When on an open fold: close it and set 'foldenable'.  This
353		will only close one level, since using "za" again will open
354		the fold.  When a count is given that many folds will be
355		closed (that's not the same as repeating "za" that many
356		times).
357
358							*zA*
359zA		When on a closed fold: open it recursively.
360		When on an open fold: close it recursively and set
361		'foldenable'.
362
363							*zv*
364zv		View cursor line: Open just enough folds to make the line in
365		which the cursor is located not folded.
366
367							*zx*
368zx		Update folds: Undo manually opened and closed folds: re-apply
369		'foldlevel', then do "zv": View cursor line.
370		Also forces recomputing folds.  This is useful when using
371		'foldexpr' and the buffer is changed in a way that results in
372		folds not to be updated properly.
373
374							*zX*
375zX		Undo manually opened and closed folds: re-apply 'foldlevel'.
376		Also forces recomputing folds, like |zx|.
377
378							*zm*
379zm		Fold more: Subtract |v:count1| from 'foldlevel'.  If 'foldlevel' was
380		already zero nothing happens.
381		'foldenable' will be set.
382
383							*zM*
384zM		Close all folds: set 'foldlevel' to 0.
385		'foldenable' will be set.
386
387							*zr*
388zr		Reduce folding: Add |v:count1| to 'foldlevel'.
389
390							*zR*
391zR		Open all folds.  This sets 'foldlevel' to highest fold level.
392
393							*:foldo* *:foldopen*
394:{range}foldo[pen][!]
395		Open folds in {range}.  When [!] is added all folds are
396		opened.  Useful to see all the text in {range}.  Without [!]
397		one level of folds is opened.
398
399							*:foldc* *:foldclose*
400:{range}foldc[lose][!]
401		Close folds in {range}.  When [!] is added all folds are
402		closed.  Useful to hide all the text in {range}.  Without [!]
403		one level of folds is closed.
404
405							*zn*
406zn		Fold none: reset 'foldenable'.  All folds will be open.
407
408							*zN*
409zN		Fold normal: set 'foldenable'.  All folds will be as they
410		were before.
411
412							*zi*
413zi		Invert 'foldenable'.
414
415
416MOVING OVER FOLDS ~
417							*[z*
418[z		Move to the start of the current open fold.  If already at the
419		start, move to the start of the fold that contains it.  If
420		there is no containing fold, the command fails.
421		When a count is used, repeats the command [count] times.
422
423							*]z*
424]z		Move to the end of the current open fold.  If already at the
425		end, move to the end of the fold that contains it.  If there
426		is no containing fold, the command fails.
427		When a count is used, repeats the command [count] times.
428
429							*zj*
430zj		Move downwards to the start of the next fold.  A closed fold
431		is counted as one fold.
432		When a count is used, repeats the command [count] times.
433		This command can be used after an |operator|.
434
435							*zk*
436zk		Move upwards to the end of the previous fold.  A closed fold
437		is counted as one fold.
438		When a count is used, repeats the command [count] times.
439		This command can be used after an |operator|.
440
441
442EXECUTING COMMANDS ON FOLDS ~
443
444:[range]foldd[oopen] {cmd}			*:foldd* *:folddo* *:folddoopen*
445		Execute {cmd} on all lines that are not in a closed fold.
446		When [range] is given, only these lines are used.
447		Each time {cmd} is executed the cursor is positioned on the
448		line it is executed for.
449		This works like the ":global" command: First all lines that
450		are not in a closed fold are marked.  Then the {cmd} is
451		executed for all marked lines.  Thus when {cmd} changes the
452		folds, this has no influence on where it is executed (except
453		when lines are deleted, of course).
454		Example: >
455			:folddoopen s/end/loop_end/ge
456<		Note the use of the "e" flag to avoid getting an error message
457		where "end" doesn't match.
458
459:[range]folddoc[losed] {cmd}			*:folddoc* *:folddoclosed*
460		Execute {cmd} on all lines that are in a closed fold.
461		Otherwise like ":folddoopen".
462
463==============================================================================
4643. Fold options					*fold-options*
465
466COLORS							*fold-colors*
467
468The colors of a closed fold are set with the Folded group |hl-Folded|.  The
469colors of the fold column are set with the FoldColumn group |hl-FoldColumn|.
470Example to set the colors: >
471
472	:highlight Folded guibg=grey guifg=blue
473	:highlight FoldColumn guibg=darkgrey guifg=white
474
475
476FOLDLEVEL						*fold-foldlevel*
477
478'foldlevel' is a number option: The higher the more folded regions are open.
479When 'foldlevel' is 0, all folds are closed.
480When 'foldlevel' is positive, some folds are closed.
481When 'foldlevel' is very high, all folds are open.
482'foldlevel' is applied when it is changed.  After that manually folds can be
483opened and closed.
484When increased, folds above the new level are opened.  No manually opened
485folds will be closed.
486When decreased, folds above the new level are closed.  No manually closed
487folds will be opened.
488
489
490FOLDTEXT						*fold-foldtext*
491
492'foldtext' is a string option that specifies an expression.  This expression
493is evaluated to obtain the text displayed for a closed fold.  Example: >
494
495    :set foldtext=v:folddashes.substitute(getline(v:foldstart),'/\\*\\\|\\*/\\\|{{{\\d\\=','','g')
496
497This shows the first line of the fold, with "/*", "*/" and "{{{" removed.
498Note the use of backslashes to avoid some characters to be interpreted by the
499":set" command.  It's simpler to define a function and call that: >
500
501    :set foldtext=MyFoldText()
502    :function MyFoldText()
503    :  let line = getline(v:foldstart)
504    :  let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g')
505    :  return v:folddashes . sub
506    :endfunction
507
508Evaluating 'foldtext' is done in the |sandbox|.  The current window is set to
509the window that displays the line.  Errors are ignored.
510
511The default value is |foldtext()|.  This returns a reasonable text for most
512types of folding.  If you don't like it, you can specify your own 'foldtext'
513expression.  It can use these special Vim variables:
514	v:foldstart	line number of first line in the fold
515	v:foldend	line number of last line in the fold
516	v:folddashes	a string that contains dashes to represent the
517			foldlevel.
518	v:foldlevel	the foldlevel of the fold
519
520In the result a TAB is replaced with a space and unprintable characters are
521made into printable characters.
522
523The resulting line is truncated to fit in the window, it never wraps.
524When there is room after the text, it is filled with the character specified
525by 'fillchars'.
526
527Note that backslashes need to be used for characters that the ":set" command
528handles differently: Space, backslash and double-quote. |option-backslash|
529
530
531FOLDCOLUMN						*fold-foldcolumn*
532
533'foldcolumn' is a number, which sets the width for a column on the side of the
534window to indicate folds.  When it is zero, there is no foldcolumn.  A normal
535value is 4 or 5.  The minimal useful value is 2, although 1 still provides
536some information.  The maximum is 12.
537
538An open fold is indicated with a column that has a '-' at the top and '|'
539characters below it.  This column stops where the open fold stops.  When folds
540nest, the nested fold is one character right of the fold it's contained in.
541
542A closed fold is indicated with a '+'.
543
544These characters can be changed with the 'fillchars' option.
545
546Where the fold column is too narrow to display all nested folds, digits are
547shown to indicate the nesting level.
548
549The mouse can also be used to open and close folds by clicking in the
550fold column:
551- Click on a '+' to open the closed fold at this row.
552- Click on any other non-blank character to close the open fold at this row.
553
554
555OTHER OPTIONS
556
557'foldenable'  'fen':	Open all folds while not set.
558'foldexpr'    'fde':	Expression used for "expr" folding.
559'foldignore'  'fdi':	Characters used for "indent" folding.
560'foldmarker'  'fmr':	Defined markers used for "marker" folding.
561'foldmethod'  'fdm':	Name of the current folding method.
562'foldminlines' 'fml':	Minimum number of screen lines for a fold to be
563			displayed closed.
564'foldnestmax' 'fdn':	Maximum nesting for "indent" and "syntax" folding.
565'foldopen'    'fdo':	Which kinds of commands open closed folds.
566'foldclose'   'fcl':	When the folds not under the cursor are closed.
567
568==============================================================================
5694. Behavior of folds					*fold-behavior*
570
571When moving the cursor upwards or downwards and when scrolling, the cursor
572will move to the first line of a sequence of folded lines.  When the cursor is
573already on a folded line, it moves to the next unfolded line or the next
574closed fold.
575
576While the cursor is on folded lines, the cursor is always displayed in the
577first column.  The ruler does show the actual cursor position, but since the
578line is folded, it cannot be displayed there.
579
580Many movement commands handle a sequence of folded lines like an empty line.
581For example, the "w" command stops once in the first column.
582
583When in Insert mode, the cursor line is never folded.  That allows you to see
584what you type!
585
586When using an operator, a closed fold is included as a whole.  Thus "dl"
587deletes the whole closed fold under the cursor.
588
589For Ex commands that work on buffer lines the range is adjusted to always
590start at the first line of a closed fold and end at the last line of a closed
591fold.  Thus this command: >
592	:s/foo/bar/g
593when used with the cursor on a closed fold, will replace "foo" with "bar" in
594all lines of the fold.
595This does not happen for |:folddoopen| and |:folddoclosed|.
596
597When editing a buffer that has been edited before, the last used folding
598settings are used again.  For manual folding the defined folds are restored.
599For all folding methods the manually opened and closed folds are restored.
600If this buffer has been edited in this window, the values from back then are
601used.  Otherwise the values from the window where the buffer was edited last
602are used.
603
604==============================================================================
605 vim:tw=78:ts=8:noet:ft=help:norl:
606