36

Is it possible to rename the file I'm editing from within Vim? Currently what I do is exit Vim, rename the file and open from Vim again.

31

You could save the file under a different name using :w. But this operation won't remove the old file and the 'old' file stays in your buffer, so any changes will be applied to your 'old' file.

:saveas saves your new file and opens it in a new buffer. But it doesn't delete the old file.

I use tpope/vim-eneuch to :Move files.

:Move: Rename a buffer and the file on disk simultaneously.

10

You could drop to Netrw and rename the file there.

If the file you're editing is in the current directory, then do:

:edit .

Navigate to the file, press R, and change the name. Press Enter to edit the file.

There's a caveat though: the original buffer remains in the list of buffers. If you switch to it, it's empty.

If the file you're editing is in a different directory, you can change to the file's directory with:

:cd %:p:h

If you don't want to change the directory for the entire Vim session but only for the current buffer, then you can do instead:

:lcd %:p:h
  • 2
    Typing straight :edit %:p:h also seems to work. – Mladen Jablanović Feb 11 '16 at 8:13
6

I've been using the Rename2 plugin for this for years. It renames both the current buffer, and the file on disk:

:Rename {newname}

EDIT: I found this a .vimrc file on github:

function! RenameFile()
    let old_name = expand('%')
    let new_name = input('New file name: ', expand('%'), 'file')
    if new_name != '' && new_name != old_name
        exec ':saveas ' . new_name
        exec ':silent !rm ' . old_name
        redraw!
    endif
endfunction
map <leader>n :call RenameFile()<cr>
3

The best way is to use :Move, as OrangTux said. For completeness, you can also perform terminal commands in vi editors using a bang (!) in command mode.

:!mv {current_file} {new_name}
:e {new_name}

However, this method doesn't remove the old buffer from your buffer list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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