I know I can use the :file command to change the name of the current buffer. Is there some way to change the name of an arbitrary buffer without switching to that buffer?


1 Answer 1


You could use the following function which is pretty simple:

  • First we save the current buffer and the cursor position to be able to restore them later
  • Then we show the result of buffers to help the user decide what buffer they want to change (this could be commented out)
  • Then we get the user input of the buffer to change (by it's number) and the new name to use
  • Once we have this information we can switch to the buffer to rename and rename it
  • Finally we go back to the previous position.

So technically, it is not changing the buffer name without switching to that buffer, but the switch is made invisible to the user.

The code is the following and can be used with call ChangeBufferName():

function! ChangeBufferName() abort
    " Save the current cursor position and the current buffer number
    let saveBuffer = bufnr('')
    let saveCursor = getpos('.')

    " List the available buffers

    " Get the buffer to change and its new name
    let bufferToChange = input('buffer to rename ')
    let newName = input('new buffer name ')

    " Change the buffer name
    execute 'b' . bufferToChange
    execute 'file ' . newName

    " Return to the previous position
    execute 'b' . saveBuffer
    call setpos('.', saveCursor)

Note that we could easily change the function to take some arguments instead of waiting for user input.

  • 1
    Thanks -- I didn't realize that switching to another buffer in the background would be invisible to the user. I was able to adapt your solution to do what I want. May 8, 2018 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.