如何仅对<afile>?</afile>中指定的模块执行某些命令

时间:2013-01-21 15:06:28

标签: vim

我想执行需要MyCommand访问b:somevar的{​​{1}}缓冲区<afile>指定的缓冲区。 现在我正在做类似于

的事情
function F()
    let l:a = bufnr(expand("%"))
    let l:b = bufnr(expand("<afile>"))
    execute "bufdo call G(" . l:b . ")"
    execute "buffer " . a
endfunction

function G(d)
    let l:a = bufnr(expand("%"))
    if l:a == a:d
        execute 'MyCommand'
    endif
endfunction

autocmd BufDelete *.hs :call F()

所以F()检查每个加载的缓冲区是否为<afile>中的缓冲区。它有效,但感觉相当疯狂,应该有更好的方法。

1 个答案:

答案 0 :(得分:2)

MyCommand只需要访问b:somevar(可能是getbufline()的缓冲内容)时,它就可以使用getbufvar(expand('<abuf>'), 'somevar')


另一方面,如果需要直接在缓冲区上执行命令,则需要在窗口中临时显示缓冲区,如下所示:

function! ExecuteInVisibleBuffer( bufnr, command )
    let l:winnr = bufwinnr(a:bufnr)
    if l:winnr == -1
        " The buffer is hidden. Make it visible to execute the passed function.
        let l:originalWindowLayout = winrestcmd()
            execute 'noautocmd silent keepalt leftabove sbuffer' a:bufnr
        try
            execute a:command
        finally
            noautocmd silent close
            silent! execute l:originalWindowLayout
        endtry
    else
        " The buffer is visible in at least one window on this tab page.
        let l:currentWinNr = winnr()
        execute l:winnr . 'wincmd w'
        try
            execute a:command
        finally
            execute l:currentWinNr . 'wincmd w'
        endtry
    endif
endfunction