blob: 5becb04685c3f6338027e9ab5798a6385560ed81 [file] [log] [blame]
Bram Moolenaar91f84f62018-07-29 15:07:52 +02001" Author: Antony Lee <anntzer.lee@gmail.com>
2" Description: Helper functions for reStructuredText syntax folding
3" Last Modified: 2018-01-07
4
5function s:CacheRstFold()
6 let closure = {'header_types': {}, 'max_level': 0, 'levels': {}}
7 function closure.Process(match) dict
8 let curline = getcurpos()[1]
9 if has_key(self.levels, curline - 1)
10 " For over+under-lined headers, the regex will match both at the
11 " overline and at the title itself; in that case, skip the second match.
12 return
13 endif
14 let lines = split(a:match, '\n')
15 let key = repeat(lines[-1][0], len(lines))
16 if !has_key(self.header_types, key)
17 let self.max_level += 1
18 let self.header_types[key] = self.max_level
19 endif
20 let self.levels[curline] = self.header_types[key]
21 endfunction
22 let save_cursor = getcurpos()
23 silent keeppatterns %s/\v^%(%(([=`:.'"~^_*+#-])\1+\n)?.{1,2}\n([=`:.'"~^_*+#-])\2+)|%(%(([=`:.''"~^_*+#-])\3{2,}\n)?.{3,}\n([=`:.''"~^_*+#-])\4{2,})$/\=closure.Process(submatch(0))/gn
24 call setpos('.', save_cursor)
25 let b:RstFoldCache = closure.levels
26endfunction
27
28function RstFold#GetRstFold()
29 if !has_key(b:, 'RstFoldCache')
30 call s:CacheRstFold()
31 endif
32 if has_key(b:RstFoldCache, v:lnum)
33 return '>' . b:RstFoldCache[v:lnum]
34 else
35 return '='
36 endif
37endfunction
38
39function RstFold#GetRstFoldText()
40 if !has_key(b:, 'RstFoldCache')
41 call s:CacheRstFold()
42 endif
43 let indent = repeat(' ', b:RstFoldCache[v:foldstart] - 1)
44 let thisline = getline(v:foldstart)
45 " For over+under-lined headers, skip the overline.
46 let text = thisline =~ '^\([=`:.''"~^_*+#-]\)\1\+$' ? getline(v:foldstart + 1) : thisline
47 return indent . text
48endfunction