Renaming the Current File in Vim
How Should I Rename My Current File in Vim? for Example: I Am Editing Person. Html_Erb_Spec. Rb I Would Like It Renamed to Person. Haml_Spec. Rb I Would Like...
How should I rename my current file in Vim?
For example:
- I am editing
person.html_erb_spec.rb - I would like it renamed to
person.haml_spec.rb - I would like to continue editing
person.haml_spec.rb
How would I go about doing this, elegantly?
22 Answers
The command is called :saveas, but unfortunately it will not delete your old file, you'll have to do that manually. see :help saveas for more info.
EDIT:
Most vim installations have an integrated file explorer, which you can use for such operations. Try :Explore in command mode (I would actually map that to a function key, it's very handy). You can rename files with R or delete them with D, for example. But pressing <F1> in the explorer will give you a better overview.
If you use git and already have the tpope's plugin fugitive.vim then simply:
:Gmove newname
This will:
- Rename your file on disk.
- Rename the file in git repo.
- Reload the file into the current buffer.
- Preserve undo history.
If your file was not yet added to a git repo then first add it:
:Gwrite
I'm doing it with NERDTree plugin:
:NERDTreeFind
then press m
To rename you can choose (m)ove the current node and change file name. Also there are options like delete, copy, move, etc...
There's a little plugin that lets you do this.
- Write the file while editing -
:w newname- to create a copy. - Start editing the new copy -
:e#. - (Optionally) remove the old copy -
:!rm oldname.
On Windows, the optional 3rd step changes a little:
- (Optionally) remove old Windows copy -
:!del oldname.
Short, secure, without plugin:
:sav new_name
:!rm <C-R># // or !del <C-R># for windows
control + R, # will instantly expand to an alternate-file (previously edited path in current window) before pressing Enter. That allows us to review what exactly we're going to delete.
Using pipe | in such a case is not secure, because if sav fails for any reason, # will still point to another place (or to nothing). That means !rm # or delete(expand(#)) may delete completely different file!
So do it by hand carefully or use good script (they are mentioned in many answers here).