python.vim (2189B)
1 vim9script 2 3 def MyFoldFunc(): string 4 if !exists('b:lasttick') 5 b:lasttick = 0 6 endif 7 if b:lasttick == b:changedtick 8 return b:foldlevels[v:lnum - 1] 9 endif 10 b:lasttick = b:changedtick 11 b:foldlevels = [] 12 13 var current_foldlevel = 0 14 var firstblock = true 15 for i_line in range(line('$') - 1) 16 const line = getline(i_line + 1) 17 const nextline = getline(i_line + 2) 18 if line =~ '^# %% \[markdown\]' 19 if nextline =~ '^# # ' 20 current_foldlevel = 1 21 firstblock = true 22 elseif nextline =~ '^# ## ' 23 current_foldlevel = 2 24 firstblock = true 25 elseif nextline =~ '^# ### ' 26 current_foldlevel = 3 27 firstblock = true 28 endif 29 b:foldlevels->add('>' .. current_foldlevel) 30 elseif line =~ '^# %%' 31 if firstblock 32 current_foldlevel = current_foldlevel + 1 33 firstblock = false 34 endif 35 b:foldlevels->add('>' .. current_foldlevel) 36 elseif nextline =~ '^# %% \[markdown\]' 37 const nextnextline = getline(i_line + 3) 38 if nextnextline =~ '^# # ' 39 b:foldlevels->add('0') 40 elseif nextnextline =~ '^# ## ' 41 b:foldlevels->add('1') 42 elseif nextnextline =~ '^# ### ' 43 b:foldlevels->add('2') 44 else 45 b:foldlevels->add('' .. current_foldlevel) 46 endif 47 else 48 b:foldlevels->add('' .. current_foldlevel) 49 endif 50 endfor 51 b:foldlevels->add('' .. current_foldlevel) 52 53 return b:foldlevels[v:lnum - 1] 54 enddef 55 56 def CustomFoldText(): string 57 const line = getline(v:foldstart + 1)->substitute('^# ', '', '') 58 const nlines = v:foldend - v:foldstart + 1 59 return '+' .. v:folddashes .. printf('%3d lines: %s', nlines, line) 60 enddef 61 62 def SetFolds() 63 setlocal foldmethod=expr 64 setlocal foldexpr=MyFoldFunc() 65 setlocal foldtext=CustomFoldText() 66 setlocal foldlevel=1 67 enddef 68 69 autocmd BufWinEnter * if &foldmethod == "manual" | call SetFolds() | endif 70 71 # vim: et sts=4 sw=4