I'm trying to implement a simple autocommand, which deletes a buffer when it's hidden, with a condition that the file hasn't been modified in the last N seconds. I have the following code in ~/.vim/autoload/tools.vim
:
function tools#TimeSinceModified(file)
return localtime() - getftime(a:file)
endfunction
let s:delete_buf_after_s = 1800
function tools#DeleteBuffer(bufnr)
if !&modified && tools#TimeSinceModified(bufname(a:bufnr)) > s:delete_buf_after_s
execute 'bdelete' a:bufnr
endif
endfunction
Then, in my .vimrc
, I have this autocommand:
autocmd BufHidden * call tools#DeleteBuffer(expand("<abuf>"))
This doesn't work, however. The buffer isn't deleted, and the editor prompts the following error whenever a buffer is being hidden:
Error detected while processing function tools#DeleteBuffer:
line 2:
E937: Attempt to delete a buffer that is in use
Is there some way of getting around this error? How can I get this functionality to work?
:bdelete
? If you mean to force close the buffer even if it has changes since it was last saved then just add!
after:bdelete
.:bdelete
. I think in this case the command without!
should be sufficient since we're checking that themodified
flag is0
, so there shouldn't be any unsaved changes. I also triedbdelete!
instead ofbdelete
in the function, but I still get the same error.hidden
option set, so this is triggered everytime a buffer is hidden. But do you know if there is any some other way of achieving the similar functionality I described before? Maybe settingnohidden
and setting thebufhidden
option for buffers?