Millet Porridge

English version of https://corvo.myseu.cn

0%

Adding Markdown Folding to Vim

No amount of words beats simply pasting the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
" Markdown folding
" https://stackoverflow.com/questions/3828606/vim-markdown-folding
function! MarkdownLevel()
let curline = getline(v:lnum)
if curline =~ '^# .*$'
return ">1"
endif
if curline =~ '^## .*$'
return ">2"
endif
if curline =~ '^### .*$'
return ">3"
endif
if curline =~ '^#### .*$'
return ">4"
endif
if curline =~ '^##### .*$'
return ">5"
endif
if curline =~ '^###### .*$'
return ">6"
endif
return "="
endfunction

function! MarkdownFoldText()
let foldsize = v:foldend - v:foldstart
return getline(v:foldstart).' ('.foldsize.' lines)'
endfunction

au BufEnter *.md setlocal foldexpr=MarkdownLevel()
au BufEnter *.md setlocal foldmethod=expr
au BufEnter *.md setlocal foldtext=MarkdownFoldText()

The MarkdownLevel function is responsible for finding fold lines and their current level.

  • Why does it return symbols like “>4” or “=”?

Check the documentation with : help fold

1
2
3
4
5
6
7
8
9
10
11
12
13
value         meaning
0 the line is not in a fold
1, 2, the line is in a fold with this level
-1 the fold level is undefined, use the fold level of a
line before or after this line, whichever is the
lowest.
"=" use fold level from the previous line
"a1", "a2", add one, two, .. to the fold level of the previous
line, use the result for the current line
"s1", "s2", subtract one, two, .. from the fold level of the
previous 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

Here “=” means the current line uses the same fold level as the previous line; “>1” and friends mean a first-level fold starts at the current line, and correspondingly “>2” means a second-level fold starts here.

  • MarkdownFoldText defines the text shown on the single line after folding.

Final effect

pic

References

Several approaches on StackOverFlow Video: how to create and use a simple fold?