VIM: How to open new file in current buffer?

:e thefile | bd#

This solution has the advantage that it will preserve windows.

  1. Open "thefile" in a new buffer
  2. Delete the most recent buffer (# is the alternate buffer)

you cannot "re-use" a buffer, a buffer in vim is

a file loaded into memory for editing.

You could delete the current buffer then open a new, so that keep your buffers count:

:bd!|e /path/file

note that with !, changes on current buffer would be discarded.


:bd!|e file

is the most intuitive way, but it will kill your window if you have a split. So...

function! ReplaceBuffer(bang, newfile)
  let curbuf = bufnr('%')
  exec "e " . a:newfile
  exec "bd" . a:bang . " " . curbuf
endfunction
command! -nargs=1 -complete=file -bang -bar BDE call ReplaceBuffer('<bang>', <f-args>)

Then you can do

:BDE ~/.vimrc

or

:BDE! ~/.vimrc

to load up your .vimrc and kill off the buffer you were in, without messing with windows.

Tags:

Vim