Reputation: 7719
I’m looking for an advice on how to programmatically detect whether the current buffer in Vim has at least one fold — regardless of whether the fold is open or closed.
I need this functionality to define an autocommand for calling mkview
when a buffer is saved only if there is a fold defined in it:
autocmd BufWrite ?* if FoldDefined() | mkview | endif
function FoldDefined()
???
endfunction
Upvotes: 2
Views: 510
Reputation: 29004
func! CurrentWindowHasFolds()
let view = winsaveview()
for move in ['zj', 'zk']
sil! exec 'keepjumps norm!' move
if foldlevel('.') > 0
call winrestview(view)
return 1
endif
endfor
return 0
endfunc
Upvotes: 4
Reputation: 7733
function! FoldDefined()
return len(filter(range(1, line('$')), 'foldlevel(v:val)>1'))>0
endfunction
Upvotes: 0
Reputation: 7719
Based on perreal's advice, I did wrote one of possible solutions to my question:
" Detect presence of fold definition in the current buffer
function FoldDefined()
let result = 0
let save_cursor = getpos('.')
call cursor(1,1)
let scanline = line('.')
let lastline = line('$')
while scanline <= lastline
if foldlevel(scanline) > 0
let result = 1
break
endif
let scanline = scanline + 1
endwhile
call setpos('.', save_cursor)
return result
endfunction
Upvotes: 0