Vim: how to prevent jumps out of current buffer?

大兔子大兔子 提交于 2019-12-09 09:54:14

问题


I frequently have several buffers open in my Vim session. This means that my jumplist stores locations from several buffers. However, frequently when I use Ctrl-o to jump to a previous location, I do not want to leave the buffer and want to jump to previous locations "local" to the current buffer. How do I do this?

Example: If my jumplist looks like to following:

4   10   1 ~/aaa.m
3   20   1 ~/aaa.m
2   12   2 ~/xxx.m
1   15   1 ~/aaa.m

I want to jump to line 15 of file aaa.m the first time I press Ctrl-o. Importantly, the next time I press Ctrl-o, I do not want to jump to file xxx.m. Rather, I want to jump to line 20 of file aaa.m; that is, my previous location within the "current" buffer. The default behaviour of Vim is to take me to to line 12 of file xxx.m. Any ideas on how I can achieve this?


回答1:


Try the following jump-list traversing function. It steps successively from one jump-list location to another (using Ctrl+O or Ctrl+I depending on what values its back and forw arguments have) and stops if the current location is in the same buffer as that buffer it has started from. If it is not possible to find a jump-list location relating to the buffer, the function returns to the position that jump-list has before start.

function! JumpInFile(back, forw)
    let [n, i] = [bufnr('%'), 1]
    let p = [n] + getpos('.')[1:]
    sil! exe 'norm!1' . a:forw
    while 1
        let p1 = [bufnr('%')] + getpos('.')[1:]
        if n == p1[0] | break | endif
        if p == p1
            sil! exe 'norm!' . (i-1) . a:back
            break
        endif
        let [p, i] = [p1, i+1]
        sil! exe 'norm!1' . a:forw
    endwhile
endfunction

To use this function as a Ctrl+O/Ctrl+I-replacement locked to the current buffer, create mappings as it shown below.

nnoremap <silent> <c-k> :call JumpInFile("\<c-i>", "\<c-o>")<cr>
nnoremap <silent> <c-j> :call JumpInFile("\<c-o>", "\<c-i>")<cr>



回答2:


Maybe the EnhancedJumps plugin will help.

With this plugin installed, the jump to another buffer is only done if the same jump command is repeated once more immediately afterwards.



来源:https://stackoverflow.com/questions/7066456/vim-how-to-prevent-jumps-out-of-current-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!