usr_28.txt ForVim version 9.2. Last change: 2026 Feb 14 VIM USER MANUALbyBramMoolenaarFoldingStructured text can be separated in sections. And sections in sub-sections.Folding allows you to displayasectionas one line, providing an overview.This chapter explains the different ways this can be done.28.1 Whatis folding?28.2 Manualfolding28.3 Working withfolds28.4 Saving and restoringfolds28.5Folding by indent28.6Folding with markers28.7Folding bysyntax28.8Folding byexpression28.9Folding unchanged lines28.10 Which foldmethod to use? Next chapter:usr_29.txt Moving through programs Previous chapter:usr_27.txt Search commands and patternsTable of contents:usr_toc.txt==============================================================================28.1 Whatis folding?Foldingis used to showa range of lines in the bufferasa single line on thescreen. Likea piece of paper whichis folded to makeit shorter:+------------------------+| line 1 || line 2 || line 3 ||_______________________ |\ \ \________________________\/ folded lines//________________________/| line 12 || line 13 || line 14 |+------------------------+The textis still in the buffer, unchanged. Only the way lines are displayedis affected by folding.The advantage offoldingis that you can geta better overview of thestructure of text, byfolding lines ofasection andreplacingit witha linethat indicates that thereisa section.==============================================================================28.2 ManualfoldingTryit out: Position the cursor inaparagraph and type:zfapYou will see that theparagraphis replaced bya highlighted line. You havecreateda fold.zfis anoperator andapa textobject selection. Youcan use thezfoperator with anymovement command to createa fold for thetext thatit moved over.zf also works inVisual mode.Toview the text again, open the fold by typing:zoAnd you can close the fold again with:zcAll thefolding commands start with "z". With some fantasy, this looks likeafolded piece of paper, seen from the side. Theletter after the "z" hasamnemonic meaning to makeit easier to remember the commands:zfF-old creationzoO-pena foldzcC-losea foldFolds can be nested:A region of text that containsfolds can be foldedagain. For example, you can fold eachparagraph in this section, and thenfold all the sections in this chapter. Tryit out. You will notice thatopening the fold for the whole chapter will restore the nestedfoldsas theywere, some may be open and some may be closed.Suppose you have created several folds, and now want toview all the text.You couldgo to each fold and type "zo". Todo this faster, use this command:zrThis will R-educe the folding. The opposite is:zmThisfolds M-ore. You can repeat "zr" and "zm" to open and close nestedfoldsof several levels.If you have nested several levels deep, you can open all of them with:zRThis R-educesfolds until there are none left. And you can close allfoldswith:zMThisfolds M-ore and M-ore.You can quickly disable thefolding with thezn command. ThenzN bringsback thefoldingasit was.zi toggles between the two. Thisisa usefulway of working:- createfolds to get overview on your file- move around to where you want todo your work-dozi to lookat the text and editit-dozi again togo back to moving aroundMore about manualfolding in thereference manual:fold-manual==============================================================================28.3 Working withfoldsWhen somefolds are closed,movement commands like "j" and "k" move overafold likeit wasa single, empty line. This allows you to quickly move aroundover folded text.You can yank, delete andputfoldsas ifit wasa single line. Thisis veryuseful if you want to reorderfunctions ina program. First make sure thateach fold containsa whole function (ora bit less) by selecting the right'foldmethod'. Then delete the function with "dd", move the cursor andputitwith "p". If some lines of the function are above or below the fold, you canuseVisual selection:-put the cursor on the first line to be moved- hit "V" to startVisual mode-put the cursor on the last line to be moved- hit "d" to delete the selected lines.- move the cursor to the new position and "p"ut the lines there.Itis sometimes difficult to see or remember wherea foldis located, thuswhereazo command would actually work. To see the defined folds::set foldcolumn=4This will showa small column on the left of thewindow to indicate folds.A "+"is shown fora closed fold.A "-"is shownat the start of each openfold and "|"at following lines of the fold.You can use the mouse to opena fold by clicking on the "+" in the foldcolumn.Clicking on the "-" ora "|" belowit will close an open fold.To open allfoldsat the cursor line usezO.To close allfoldsat the cursor line usezC.To deletea foldat the cursor line usezd.To delete allfoldsat the cursor line usezD.When inInsert mode, the foldat the cursor lineis never closed. That allowsyou to see what you type!Folds are opened automatically when jumping around or moving the cursor leftor right. For example, the "0" command opens the fold under the cursor(if'foldopen' contains "hor", whichis the default). The'foldopen' optioncan be changed to openfolds for specific commands. If you want the lineunder the cursor always to be open,do this::set foldopen=allWarning: You won't be able to move ontoa closed fold then. You might want touse this only temporarily and then setit back to the default::set foldopen&You can makefolds close automatically when you move out of it::set foldclose=allThis will re-apply'foldlevel' to allfolds that don't contain the cursor.You have to tryit out if you like how this feels. Usezm to fold more andzr to foldless (reduce folds).Thefoldingis local to the window. This allows you to open twowindows onthe same buffer, one withfolds and one without folds. Or one with allfoldsclosed and one with allfolds open.==============================================================================28.4 Saving and restoringfoldsWhen youabandona file (starting to edit another one), the state of thefoldsis lost. If you come back to the same file later, all manually opened andclosedfolds are back to their default. Whenfolds have been createdmanually, allfolds are gone! To save thefolds use the:mkview command::mkviewThis will store the settings and other things that influence theview on thefile. You can change whatis stored with the'viewoptions' option.When you come back to the same file later, you can load theview again::loadviewYou can store up to ten views on one file. For example, to save the currentsetupas the thirdview and load the second view::mkview 3:loadview 2Note that when youinsert or delete lines the views might become invalid.Also check out the'viewdir' option, whichspecifies where the views arestored. You might want to delete old views now and then.==============================================================================28.5Folding by indentDefiningfolds withzfisa lot of work. If your textis structured bygiving lower level itemsa larger indent, you can use the indentfoldingmethod. This will createfolds for every sequence of lines with the sameindent. Lines witha larger indent will become nested folds. This works wellwith many programming languages.Try this by setting the'foldmethod' option::set foldmethod=indentThen you can use thezm andzr commands to fold more and reduce folding.It'seasy to see on this example text:This lineis not indentedThis lineis indented onceThis lineis indented twiceThis lineis indented twiceThis lineis indented onceThis lineis not indentedThis lineis indented onceThis lineis indented onceNote that the relation between the amount of indent and the fold depth dependson the'shiftwidth' option. Each'shiftwidth' worth of indent adds one to thedepth of the fold. Thisis calleda fold level.When you use thezr andzm commands you actually increase or decrease the'foldlevel' option. You could also setit directly::set foldlevel=3This means that allfolds with three timesa'shiftwidth' indent or more willbe closed. The lower the foldlevel, the morefolds will be closed. When'foldlevel'is zero, allfolds are closed.zM does set'foldlevel' to zero.The opposite commandzR sets'foldlevel' to the deepest fold level thatispresent in the file.Thus there are two ways to open and close the folds:(A) By setting the fold level. This givesa very quick way of "zooming out" toview the structure of the text, move the cursor, and "zoom in" on the text again.(B) By usingzo andzc commands to open or close specific folds. This allows opening only thosefolds that you want to be open, while otherfolds remain closed.This can be combined: You can first close mostfolds by usingzma few timesand then opena specific fold withzo. Or open allfolds withzR andthen close specificfolds withzc.But you cannot manually definefolds when'foldmethod'is "indent",as thatwould conflict with the relation between the indent and the fold level.More aboutfolding by indent in thereference manual:fold-indent==============================================================================28.6Folding with markersMarkers in the text are used to specify the start andend ofa fold region.This gives precisecontrol over which lines are included ina fold. Thedisadvantageis that the text needs to be modified.Try it::set foldmethod=markerExample text,asit could appear inaC program:/* foobar (){{{ */int foobar(){/* returna value{{{ */return 42;/*}}} */}/*}}} */Notice that the folded line will display the text before the marker. Thisisvery useful to tell what the fold contains.It's quite annoying when the markers don't pair up correctly after moving somelines around. This can be avoided by using numbered markers. Example:/* globalvariables {{{1 */int varA, varB;/*functions {{{1 *//* funcA() {{{2 */void funcA(){}/* funcB() {{{2 */void funcB(){}/* }}}1 */At every numbered markera foldat the specified level begins. This will makeany foldata higher level stop here. You can just use numbered start markersto define all folds. Only when you want to explicitly stopa fold beforeanother starts you need to add anend marker.More aboutfolding with markers in thereference manual:fold-marker==============================================================================28.7Folding bysyntaxFor each language Vim usesa differentsyntax file. This defines the colorsforvarious items in the file. If you are reading this in Vim, inaterminalthat supports colors, the colors you see are made with the "help"syntax file. In thesyntax filesitis possible to addsyntax items that have the "fold"argument. These definea fold region. This requireswritingasyntax fileand adding these items in it. That's not soeasy to do. But once it's done,allfolding happens automatically. Here we'll assume you are using an existingsyntax file. Then thereisnothing more to explain. You can open and closefoldsas explained above.Thefolds will be created and deleted automatically when you edit the file.More aboutfolding bysyntax in thereference manual:fold-syntax==============================================================================28.8Folding byexpressionThisis similar tofolding by indent, but instead of using the indent ofalinea user functionis called to compute the fold level ofa line. You canuse this for text where something in the text indicates which lines belongtogether. An exampleis an e-mail message where the quoted textis indicatedbya ">" before the line. To fold thesequotes use this::set foldmethod=expr:set foldexpr=strlen(substitute(substitute(getline(v:lnum),'\\s','',\"g\"),'[^>].*','',''))You can tryit out on this text:> quoted text he wrote> quoted text he wrote>> double quoted textI wrote>> double quoted textI wroteExplanation for the'foldexpr' used in the example (inside out): getline(v:lnum)gets the current line substitute(...,'\\s','','g')removes all whitespace from the line substitute(...,'[^>].*','','')removes everything after leading '>'s strlen(...)counts the length of the string, whichis the number of '>'s foundNote thatabackslashmust be inserted before every space, doublequote andbackslash for the ":set" command. If this confuses you,do:set foldexprto check the actual resulting value. To correcta complicated expression, usethe command-line completion::set foldexpr=<Tab>Where<Tab>isa real Tab. Vim will fill in the previous value, which you canthen edit.When theexpression gets more complicated you shouldputit ina function andset'foldexpr' to call that function.More aboutfolding byexpression in thereference manual:fold-expr==============================================================================28.9Folding unchanged linesThisis useful when you set the'diff' option in the same window. Thevimdiff command does this for you. Example::setlocal diff foldmethod=diff scrollbind nowrap foldlevel=1Do this in everywindow that showsa different version of the same file. Youwill clearly see the differences between the files, while the text that didn'tchangeis folded.For more details seefold-diff.==============================================================================28.10 Which foldmethod to use?All these possibilities make you wonder whichmethod you should choose.Unfortunately, thereis no golden rule. Here are some hints.If thereisasyntax file withfolding for the language you are editing, thatis probably the best choice. If there isn't one, you might try to write it.This requiresa good knowledge of search patterns. It's not easy, but whenit's working you will not have to definefolds 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 markermethod requires you to change the file. If you are sharing thefiles with other people or you have to meet company standards, you might notbe allowed to add them. The main advantage of markersis that you canput them exactly where youwant them. That avoids thata few lines are missed when you cut and pastefolds. And you can adda comment about whatis contained in the fold.Folding by indentis something that works in many files, but not always verywell. Useit when you can't use one of the other methods. However,itisvery useful for outlining. Then you specifically use one'shiftwidth' foreach nesting level.Folding with expressions can makefolds in almost any structured text. Itisquite simple to specify, especially if the start andend ofa fold can easilybe recognized. If you use the "expr"method to define folds, but they are not exactly howyou want them, you could switch to the "manual" method. This will not removethe defined folds. Then you can delete or addfolds manually.==============================================================================Next chapter:usr_29.txt Moving through programsCopyright: seemanual-copyright vim:tw=78:ts=8:noet:ft=help:norl: