47

Is it possible to change the name of a buffer in vim?

Specifically, I'm using Conque Shell to open shells in vim (each shell is in a buffer) and with multiple shells, I see:

10: bash - 1
11: bash - 2

in my buffer list. I would like to rename these buffers with more meaningful names (e.g., "mercurial" instead of "bash - 2"). Is it possible?

2
  • Why do you want to change name of buffer?@Barthelemy
    – Pie
    Commented Aug 30, 2019 at 2:11
  • 1
    The reason is stated in the question Commented Sep 2, 2021 at 2:00

4 Answers 4

66

You can use :file newname to change the buffer name.

From :help :file_f:

Sets the current file name to {name}. The optional ! avoids truncating the message, as with :file.
If the buffer did have a name, that name becomes the alternate-file name. An unlisted buffer is created to hold the old name.

4
  • 4
    Thank you. But, to me, it was surprising because I could not find that command using various google searches.
    – Barthelemy
    Commented Nov 13, 2010 at 10:59
  • 9
    its important to note that this basically changes the file's save path. I was hoping for something like screen's naming of windows but it doesnt work like that
    – JonnyRaa
    Commented Mar 19, 2015 at 11:03
  • so this is renaming the file like mv a b Commented Nov 9, 2021 at 17:15
  • It may be better to do :silent keepalt noautocmd file instead to limit side effects. In the case of a buffer created with :term or term_start(), the original buffer name could be any string, but :file name forces the buffer name to be the name of a file, which is apparently given by fnamemodify(name, ':p'). The command also creates a swap file even if there was none before, but that can be suppressed with :noswapfile. Commented Mar 29, 2023 at 19:12
7

If the buffer already has a filename, :file will not change the filename and will only change the alternate filename. You'll need to clear the name of the buffer with :0f[ile] to be able to put one.

:e foo

:0f
:file bar
4

Rename the current buffer with :file <new-name> (or :f <new-name>):

:f[ile][!] {name}

Sets the current file name to {name}. The optional ! avoids truncating the message, as with :file. If the buffer did have a name, that name becomes the alternate-file name. An unlisted buffer is created to hold the old name.

2

If you are trying to do that from a vim function using a variable, you can do like that:

function! MyFunc()
  let file_name = 'Some data here'
  execute 'file ' . file_name
endfunction

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .