vim - folding with more than one marker

324 views Asked by At

I have a debug file which looks like this:

==>func1:
.....
..
==>func2:
......
...
<==func2
..
<==func1
==>func3:
......
...
<==func3

Basically, I would like to be able to fold each one of the functions to eventually see something like this:

+-- x lines: ==> func1:
+-- x lines: ==> func3:

but still be able to expand func1 and see func2 folded:

==>func1:
.....
..
+-- x lines: ==> func2:
..
<==func1

is there any way to do so? thanks.

1

There are 1 answers

2
leaf On

The unmatched markers need extra handle, here's an expr solution( see :h fold-expr):

setlocal foldmethod=expr
setlocal foldexpr=GetFoldlevel(v:lnum)

function GetFoldlevel(lnum)
    let line = getline(a:lnum)

    let ret = '='
    if line[0:2] == '==>'
        let name = matchstr(line, '^==>\zs\w*')
        let has_match = HasMarkerMatch(a:lnum, name)
        if has_match
            let ret = 'a1'
        endif
    elseif line[0:2] == '<=='
        let ret ='s1'
    endif

    return ret
endfunction

function HasMarkerMatch(lnum, name)
    let endline = line('$')
    let current = a:lnum + 1

    let has_match = 0
    while current <= endline
        let line = getline(current)

        if line =~ '^<=='.a:name
            let has_match = 1
            break
        endif

        let current += 1
    endwhile

    return has_match
endfunction