How to execute some command only for the module specified in <afile>?

I want to execute MyCommand

which needs access to b:somevar

for the buffer specified <afile>

. Right now I'm doing something similar to

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()

      

So, F()

checks every loaded buffer if it is in <afile>

. It works, but it feels completely insane, there must be a better way.

+3


source to share


1 answer


When MyCommand

you just need access to b:somevar

(and possibly the contents of the buffer through getbufline()

), then it can use getbufvar(expand('<abuf>'), 'somevar')

.




If, on the other hand, it needs to directly execute commands in the buffer, you need to temporarily display the buffer in the window, for example:

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

      

+2


source







All Articles