Autocmd-buflocal response to wrong buffer

82 Views Asked by At

I use vim open a file, and the buffer id(bufnr()) is 2, then I run a function PreviewJupyterMD in Vim commandline by call PreviewJupyterMD().

The function body is like:

function! PreviewJupyterMD()
    " creat a md file and load file name to a variable l:md_file
    ...
    ...
    exec "edit" . l:md_file
    let b:created_for_jupyter = 1
    autocmd BufUnload <buffer> call MDCleanUp()
endfunction

So what I do is use edit open a new file and load it to buffer 3(I checked it by bufnr(), too). And add a local variable to buffer 3. Then I want vim run MDCleanUp function for buffer 3 when I close Vim.

What MDCleanUp do is check whether buffer has a variable if so delete file of that buffer from disk:

function! MDCleanUp()
    if exists("b:created_for_jupyter")
        call delete(expand("<afile>:p"))
    endif
    " below 2 line use to know this function run on which buffer
    echom bufnr()
    sleep 4
endfunction

The actural behavior is MDCleanUp run twice, but all output message by echom bufnr() is 2, output 2 twice!

Would you give me some instruction or suggestion about why the output is:

2
2

and how to let it be:

2
3

Thanks in advance!

0

There are 0 best solutions below