28Folding

Structured text can be separated in sections. And sections in sub-sections. Folding allows you to display a section as one line, providing an overview. This chapter explains the different ways this can be done.

    Table of contents

  1. What is folding?
  2. Manual folding
  3. Working with folds
  4. Saving and restoring folds
  5. Folding by indent
  6. Folding with markers
  7. Folding by syntax
  8. Folding by expression
  9. Folding unchanged lines
  10. Which fold method to use?

28.1What is folding?

Folding is used to show a range of lines in the buffer as a single line on the screen. Like a piece of paper which is folded to make it shorter:

+------------------------+
| line 1		 |
| line 2		 |
| line 3		 |
|_______________________ |
\			 \
 \________________________\
 / folded lines		  /
/________________________/
| line 12		 |
| line 13		 |
| line 14		 |
+------------------------+

The text is still in the buffer, unchanged. Only the way lines are displayed is affected by folding.

The advantage of folding is that you can get a better overview of the structure of text, by folding lines of a section and replacing it with a line that indicates that there is a section.

28.2Manual folding

Try it out: Position the cursor in a paragraph and type:

zfap

You will see that the paragraph is replaced by a highlighted line. You have created a fold. zf is an operator and ap a text object selection. You can use the zf operator with any movement command to create a fold for the text that it moved over. zf also works in Visual mode.

To view the text again, open the fold by typing:

zo

And you can close the fold again with:

zc

All the folding commands start with z. With some fantasy, this looks like a folded piece of paper, seen from the side. The letter after the z has a mnemonic meaning to make it easier to remember the commands:

zfF-old creation
zoO-pen a fold
zcC-lose a fold

Folds can be nested: A region of text that contains folds can be folded again. For example, you can fold each paragraph in this section, and then fold all the sections in this chapter. Try it out. You will notice that opening the fold for the whole chapter will restore the nested folds as they were, some may be open and some may be closed.

Suppose you have created several folds, and now want to view all the text. You could go to each fold and type zo. To do this faster, use this command:

zr

This will R-educe the folding. The opposite is:

zm

This folds M-ore. You can repeat zr and zm to open and close nested folds of several levels.

If you have nested several levels deep, you can open all of them with:

zR

This R-educes folds until there are none left. And you can close all folds with:

zM

This folds M-ore and M-ore.

You can quickly disable the folding with the zn command. Then zN brings back the folding as it was. zi toggles between the two. This is a useful way of working:

More about manual folding in the reference manual: fold‑manual

28.3Working with folds

When some folds are closed, movement commands like j and k move over a fold like it was a single, empty line. This allows you to quickly move around over folded text.

You can yank, delete and put folds as if it was a single line. This is very useful if you want to reorder functions in a program. First make sure that each fold contains a whole function (or a bit less) by selecting the right foldmethod. Then delete the function with dd, move the cursor and put it with p. If some lines of the function are above or below the fold, you can use Visual selection:

It is sometimes difficult to see or remember where a fold is located, thus where a zo command would actually work. To see the defined folds:

:set foldcolumn=4

This will show a small column on the left of the window to indicate folds. A + is shown for a closed fold. A - is shown at the start of each open fold and | at following lines of the fold.

You can use the mouse to open a fold by clicking on the + in the foldcolumn. Clicking on the - or a | below it will close an open fold.

To open all folds at the cursor line use zO. To close all folds at the cursor line use zC. To delete a fold at the cursor line use zd. To delete all folds at the cursor line use zD.

When in Insert mode, the fold at the cursor line is never closed. That allows you to see what you type!

Folds are opened automatically when jumping around or moving the cursor left or right. For example, the 0 command opens the fold under the cursor (if foldopen contains hor, which is the default). The foldopen option can be changed to open folds for specific commands. If you want the line under the cursor always to be open, do this:

:set foldopen=all

Warning: You won't be able to move onto a closed fold then. You might want to use this only temporarily and then set it back to the default:

:set foldopen&

You can make folds close automatically when you move out of it:

:set foldclose=all

This will re-apply foldlevel to all folds that don't contain the cursor. You have to try it out if you like how this feels. Use zm to fold more and zr to fold less (reduce folds).

The folding is local to the window. This allows you to open two windows on the same buffer, one with folds and one without folds. Or one with all folds closed and one with all folds open.

28.4Saving and restoring folds

When you abandon a file (starting to edit another one), the state of the folds is lost. If you come back to the same file later, all manually opened and closed folds are back to their default. When folds have been created manually, all folds are gone! To save the folds use the :mkview command:

:mkview

This will store the settings and other things that influence the view on the file. You can change what is stored with the viewoptions option. When you come back to the same file later, you can load the view again:

:loadview

You can store up to ten views on one file. For example, to save the current setup as the third view and load the second view:

:mkview 3
:loadview 2

Note that when you insert or delete lines the views might become invalid. Also check out the viewdir option, which specifies where the views are stored. You might want to delete old views now and then.

28.5Folding by indent

Defining folds with zf is a lot of work. If your text is structured by giving lower level items a larger indent, you can use the indent folding method. This will create folds for every sequence of lines with the same indent. Lines with a larger indent will become nested folds. This works well with many programming languages.

Try this by setting the foldmethod option:

:set foldmethod=indent

Then you can use the zm and zr commands to fold more and reduce folding. It's easy to see on this example text:

This line is not indented

This line is indented once
	This line is indented twice
	This line is indented twice
This line is indented once

This line is not indented

This line is indented once
This line is indented once

Note that the relation between the amount of indent and the fold depth depends on the shiftwidth option. Each shiftwidth worth of indent adds one to the depth of the fold. This is called a fold level.

When you use the zr and zm commands you actually increase or decrease the foldlevel option. You could also set it directly:

:set foldlevel=3

This means that all folds with three times a shiftwidth indent or more will be closed. The lower the foldlevel, the more folds will be closed. When foldlevel is zero, all folds are closed. zM does set foldlevel to zero. The opposite command zR sets foldlevel to the deepest fold level that is present in the file.

Thus there are two ways to open and close the folds: (A) By setting the fold level.

This gives a very quick way of "zooming out" to view the structure of the

text, move the cursor, and "zoom in" on the text again.

(B) By using zo and zc commands to open or close specific folds.

This allows opening only those folds that you want to be open, while other

folds remain closed.

This can be combined: You can first close most folds by using zm a few times and then open a specific fold with zo. Or open all folds with zR and then close specific folds with zc.

But you cannot manually define folds when foldmethod is indent, as that would conflict with the relation between the indent and the fold level.

More about folding by indent in the reference manual: fold‑indent

28.6Folding with markers

Markers in the text are used to specify the start and end of a fold region. This gives precise control over which lines are included in a fold. The disadvantage is that the text needs to be modified.

Try it:

:set foldmethod=marker

Example text, as it could appear in a C program:

/* foobar () {{{ */
int foobar()
{
	/* return a value {{{ */
	return 42;
	/* }}} */
}
/* }}} */

Notice that the folded line will display the text before the marker. This is very useful to tell what the fold contains.

It's quite annoying when the markers don't pair up correctly after moving some lines around. This can be avoided by using numbered markers. Example:

/* global variables {{{1 */
int varA, varB;
/* functions {{{1 */
/* funcA() {{{2 */
void funcA() {}
/* funcB() {{{2 */
void funcB() {}
/* }}}1 */

At every numbered marker a fold at the specified level begins. This will make any fold at a higher level stop here. You can just use numbered start markers to define all folds. Only when you want to explicitly stop a fold before another starts you need to add an end marker.

More about folding with markers in the reference manual: fold‑marker

28.7Folding by syntax

For each language Vim uses a different syntax file. This defines the colors for various items in the file. If you are reading this in Vim, in a terminal that supports colors, the colors you see are made with the help syntax file.

In the syntax files it is possible to add syntax items that have the fold argument. These define a fold region. This requires writing a syntax file and adding these items in it. That's not so easy to do. But once it's done, all folding happens automatically.

Here we'll assume you are using an existing syntax file. Then there is nothing more to explain. You can open and close folds as explained above. The folds will be created and deleted automatically when you edit the file.

More about folding by syntax in the reference manual: fold‑syntax

28.8Folding by expression

This is similar to folding by indent, but instead of using the indent of a line a user function is called to compute the fold level of a line. You can use this for text where something in the text indicates which lines belong together. An example is an e-mail message where the quoted text is indicated by a > before the line. To fold these quotes use this:

:set foldmethod=expr
:set foldexpr=strlen(substitute(substitute(getline(v:lnum),'\\s','',\"g\"),'[^>].*','',''))

You can try it out on this text:

> quoted text he wrote > quoted text he wrote > > double quoted text I wrote > > double quoted text I wrote

Explanation for the foldexpr used in the example (inside out):

getline(v:lnum) gets the current line

substitute(...,'\\s','','g')removes all white space from the line
substitute(...,'[^>].*','','')removes everything after leading '>'s
strlen(...)counts the length of the string, which is the number of '>'s found

Note that a backslash must be inserted before every space, double quote and backslash for the :set command. If this confuses you, do

:set foldexpr

to check the actual resulting value. To correct a complicated expression, use the command-line completion:

:set foldexpr=<Tab>

Where <Tab> is a real Tab. Vim will fill in the previous value, which you can then edit.

When the expression gets more complicated you should put it in a function and set foldexpr to call that function.

More about folding by expression in the reference manual: fold‑expr

28.9Folding unchanged lines

This is useful when you set the diff option in the same window. The vimdiff command does this for you. Example:

:setlocal diff foldmethod=diff scrollbind nowrap foldlevel=1

Do this in every window that shows a different version of the same file. You will clearly see the differences between the files, while the text that didn't change is folded.

For more details see fold‑diff.

28.10Which fold method to use?

All these possibilities make you wonder which method you should choose. Unfortunately, there is no golden rule. Here are some hints.

If there is a syntax file with folding for the language you are editing, that is probably the best choice. If there isn't one, you might try to write it. This requires a good knowledge of search patterns. It's not easy, but when it's working you will not have to define folds manually.

Typing commands to manually fold regions can be used for unstructured text. Then use the :mkview command to save and restore your folds.

The marker method requires you to change the file. If you are sharing the files with other people or you have to meet company standards, you might not be allowed to add them.

The main advantage of markers is that you can put them exactly where you want them. That avoids that a few lines are missed when you cut and paste folds. And you can add a comment about what is contained in the fold.

Folding by indent is something that works in many files, but not always very well. Use it when you can't use one of the other methods. However, it is very useful for outlining. Then you specifically use one shiftwidth for each nesting level.

Folding with expressions can make folds in almost any structured text. It is quite simple to specify, especially if the start and end of a fold can easily be recognized.

If you use the expr method to define folds, but they are not exactly how you want them, you could switch to the manual method. This will not remove the defined folds. Then you can delete or add folds manually.