Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute some command only for module specified in <afile>?

Tags:

vim

I want to execute MyCommand that needs access to b:somevar for buffer specified by <afile>. Right now I'm doing something akin 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 for every loaded buffer if it's the one in <afile>. It works but feels rather insane, there should be a better way.

like image 217
Matvey Aksenov Avatar asked Dec 14 '25 19:12

Matvey Aksenov


1 Answers

When MyCommand just need access to b:somevar (and maybe the buffer contents via getbufline()), then it can use getbufvar(expand('<abuf>'), 'somevar').


If, on the other hand, it needs to execute commands on the buffer directly, you need to temporarily show the buffer in a window, like this:

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
like image 164
Ingo Karkat Avatar answered Dec 18 '25 03:12

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!