|
| 1 | +" Author: Antony Lee <[email protected]> |
| 2 | +" Description: Helper functions for reStructuredText syntax folding |
| 3 | +" Last Modified: 2018-01-07 |
| 4 | + |
| 5 | +function 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 |
| 26 | +endfunction |
| 27 | + |
| 28 | +function 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 |
| 37 | +endfunction |
| 38 | + |
| 39 | +function 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 |
| 48 | +endfunction |
0 commit comments