I think I do not have a very clear idea of the use case for foldmethod=expr
, so for folding my C,C++ and Verilog code for which I use use the following indentations:
C,C++
if (a_condition) {
// a code
} else if ((b_condition) ||
(c_condition)) {
// b or c code
} else {
// code
}
Verilog
if (a_condition) begin
// a_code
end else if ((b_condition) ||
(c_condition)) begin
// b or c code
end else begin
// code
end
I have written the following functions which seem to fit my needs, given set foldmethod=manual
:
C,C++ fold
function! Fold()
call search('{')
let l:stline = line('.')+1
normal! %
let l:fnline = line('.')-1
silent! exec ":".l:stline.",".l:fnline."fold"
silent! exec ":".l:stline
normal! zz
endfunction
Verilog fold
function! Fold()
let l:diff = 0
let l:cLine = line('.')
let l:itLine = l:cLine
let l:lastLine = line('$')
while l:itLine != l:lastLine
let l:beginCnt = count(getline(l:itLine), 'begin')
let l:beginIdx = stridx(getline(l:itLine), 'begin')
let l:endCnt = count(getline(l:itLine), 'end')
let l:endIdx = stridx(getline(l:itLine), 'end')
let l:commIdx = stridx(getline(l:itLine), '//')
" begin
if l:beginCnt > 0 && l:endCnt == 0
if (l:commIdx == -1) || (l:beginIdx < l:commIdx)
let l:diff = l:diff + 1
end
" end
elseif l:endCnt > 0 && l:beginCnt == 0
if (l:commIdx == -1) || (l:endIdx < l:commIdx)
let l:diff = l:diff - 1
end
" end else begin
elseif l:beginCnt > 0 && l:endCnt > 0
if (l:commIdx == -1)
if l:diff == 1
let l:diff = l:diff - 1
endif
else
" end else begin //
if (l:beginIdx < l:commIdx) && (l:endIdx < l:commIdx)
if l:diff == 1
let l:diff = l:diff - 1
endif
endif
endif
endif
" echo getline(l:itLine)." --- l:diff = ".l:diff
if l:diff == 0
break
endif
let l:itLine = l:itLine+1
endwhile
if (l:itLine > l:cLine)
let l:cLine = l:cLine+1
let l:itLine = l:itLine-1
" echom ":".l:cLine.",".l:itLine."fold"
silent! exec ":".l:cLine.",".l:itLine."fold"
endif
normal! zz
endfunction
Do these functions can be implemented more efficiently and|or with less code lines using the foldmethod=expr
?
If so, what is the right way to do it?