Vim

再多的话语也不如贴代码来的简便

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的折叠
" 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()

MarkdownLevel函数负责找出折叠行以及当前层级

  • 为什么返回的是”>4”或是”=”这种符号呢?

可以通过: 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

这里”=”表示当前行与上一行使用相同的折叠层级, “>1”这些表示从当前行开始 作为第一层折叠, 相应的”>2”表示从当前开始的第二层折叠

  • MarkdownFoldText 表示折叠之后的一行所显示的文字.

最终效果

pic

参考资料

StackOverFlow上的几种方案 视频: 如何创建简易的fold以及使用?