且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Vim中遍历跳转列表时如何防止离开当前缓冲区?

更新时间:2023-11-13 10:20:22

尝试以下跳转列表遍历功能.它一步一步地走从一个跳转列表位置转到另一个位置(使用 Ctrl + O Ctrl + I ,具体取决于提供给它的 back forw 参数),如果当前该位置与其开始所在的缓冲区在同一缓冲区中.如果找不到属于当前缓冲区,函数返回到跳转列表中的位置那是调用该函数之前的当前代码.

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 the values that are supplied to its back and forw arguments), 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 that belongs to the current buffer, the function returns to the position in the jump list that was the current one before the function was called.

function! JumpWithinFile(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

将此功能用作 Ctrl + O / Ctrl + I -替换锁定到当前缓冲区,创建如下所示的映射.

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

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