docs:vim:folding

Folding

" folding using /search/ pattern
" \z
" This folds every line that does not contain the search pattern.
" see vimtip #282 and vimtip #108
map <silent><leader>z :set foldexpr=getline(v:lnum)!~@/ foldlevel=0 foldcolumn=0 foldmethod=expr<CR>

" this folds all classes and function to create a code index.
" mnemonic: think "function fold"
map zff :/^\s*class\s\\|^\s*function\s\\|^\s*def\s/<CR>:set foldmethod=expr foldlevel=0 foldcolumn=1 foldtext=v:folddashes<CR><CR>
" space toggles the fold state under the cursor.
nnoremap <silent><space> :exe 'silent! normal! za'.(foldlevel('.')?'':'l')<cr>

The goal here is to make the file more readable by folding on logical items. The example file is an ics file from iCal, a calendar program. We want to create a fold on each event. We also want the fold to be descriptive about what the event is about, so we add the summary line contents to the fold text.

ics data from iCal program (partial data)

BEGIN:VCALENDAR
CALSCALE:GREGORIAN
PRODID:-//Apple Computer\, Inc//iCal 2.0//EN
VERSION:2.0
BEGIN:VEVENT
DTSTART;VALUE=DATE:20020527
DTEND;VALUE=DATE:20020528
SUMMARY:Memorial Day
UID:C31860C8-1ED0-11D9-A5E0-000A958A3252
DTSTAMP:20041015T171054Z
RRULE:FREQ=YEARLY;INTERVAL=1;UNTIL=20040530;BYMONTH=5;BYDAY=-1MO
END:VEVENT
BEGIN:VEVENT
DTSTART;VALUE=DATE:20041225
DTEND;VALUE=DATE:20041226
SUMMARY:Christmas Day\n(fed holiday)
UID:C318ADAA-1ED0-11D9-A5E0-000A958A3252
DTSTAMP:20041015T171054Z
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=12
END:VEVENT
BEGIN:VEVENT
DTSTART;VALUE=DATE:20020222
DTEND;VALUE=DATE:20020223
SUMMARY:Washington's Birthday
UID:C318585A-1ED0-11D9-A5E0-000A958A3252
DTSTAMP:20041015T171054Z
RRULE:FREQ=YEARLY;INTERVAL=1;UNTIL=20040221;BYMONTH=2
END:VEVENT
BEGIN:VEVENT
DTSTART;VALUE=DATE:20020704
DTEND;VALUE=DATE:20020705
SUMMARY:Independence Day
UID:C31865E4-1ED0-11D9-A5E0-000A958A3252
DTSTAMP:20041015T171054Z
RRULE:FREQ=YEARLY;INTERVAL=1;UNTIL=20040703;BYMONTH=7
END:VEVENT
BEGIN:VEVENT
DTSTART;VALUE=DATE:20040222
DTEND;VALUE=DATE:20040223
SUMMARY:Washington's Birthday (actual)
UID:C3189C32-1ED0-11D9-A5E0-000A958A3252
DTSTAMP:20041015T171054Z
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=2
END:VEVENT
...

fold at each event, adding the SUMMARY line content to the fold text

syn clear
	setl foldmethod=syntax
	syn region event start=/BEGIN:VEVENT/ end=/END:VEVENT$/ fold

	function! FoldText()
		let lines = getline(v:foldstart, v:foldend)
		let match = match(lines, 'SUMMARY:')
		let summary = ''
		if summary > -1
			let summary = getline(v:foldstart + match)
			let summary = substitute(summary, 'SUMMARY:','','')
		endif
		return foldtext() . ' (' . summary . ')'
	endfunction
	setl foldtext=FoldText()

setl fen
  • docs/vim/folding.txt
  • Last modified: 2008/08/03 00:25
  • by 127.0.0.1