I picked up this handy function for skipping up and down closed folds in vim:
let mapleader = ","
nnoremap <silent> <leader>zj :call NextClosedFold('j')<cr>
nnoremap <silent> <leader>zk :call NextClosedFold('k')<cr>
function! NextClosedFold(dir)
let cmd = 'norm!z' . a:dir
let view = winsaveview()
let [l0, l, open] = [0, view.lnum, 1]
while l != l0 && open
exe cmd
let [l0, l] = [l, line('.')]
let open = foldclosed(l) < 0
endwhile
if open
call winrestview(view)
endif
endfunction
As you can see, my leader
key is set to ,
.
So now if I issue the command ,zj
my cursor is moved to the next closed fold. However, what I want is to have the zj
command defaulted to moving to the next closed fold, and I want ,zj
to move to the next fold (open or closed).
What is the most elegant way to write the remapping so my vim behaves the way I want it to?
It sounds like you want this.
nnoremap <silent> <leader>zj zj
nnoremap <silent> <leader>zk zk
nnoremap <silent> zj :call NextClosedFold('j')<cr>
nnoremap <silent> zk :call NextClosedFold('k')<cr>
function! NextClosedFold(dir)
let cmd = 'norm!z' . a:dir
let view = winsaveview()
let [l0, l, open] = [0, view.lnum, 1]
while l != l0 && open
exe cmd
let [l0, l] = [l, line('.')]
let open = foldclosed(l) < 0
endwhile
if open
call winrestview(view)
endif
endfunction
nnoremap
makes mapping non recursive so even if you redefine what zj
and zk
do you can always get back their default behavior. Then we just map zj
and zk
to the behavior you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.