Is it possible to jump to the next closed fold in Vim?

前端 未结 2 717
旧时难觅i
旧时难觅i 2020-12-13 18:55

In Vim, I often find myself wanting to do a quick zk or zj to jump to the previous or next fold in a file. The problem is, I freq

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 19:40

    Let me propose the following implementation of the described behavior.

    nnoremap  zj :call NextClosedFold('j')
    nnoremap  zk :call NextClosedFold('k')
    
    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
    

    If it is desirable for the mappings to accept a count for the number of repetitions of the corresponding movement, one can implement a simple function for repeating any given command:

    function! RepeatCmd(cmd) range abort
        let n = v:count < 1 ? 1 : v:count
        while n > 0
            exe a:cmd
            let n -= 1
        endwhile
    endfunction
    

    and then redefine the above mappings as follows:

    nnoremap  zj :call RepeatCmd('call NextClosedFold("j")')
    nnoremap  zk :call RepeatCmd('call NextClosedFold("k")')
    

提交回复
热议问题