How should I rename my current file in Vim?
For example:
person.html_erb_spec.rb
person
There’s a function in Gary Bernhardt’s .vimrc that handles this.
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>
For renaming existing file without using plugins you should use command
:Explore
This command allow you explore files in.directory, delete or rename them. than you should navigate to neccessary file in explorer than type R
command which will allow you to rename file name
This little script isn't perfect (the extra carriage-return you have to press) but it get's the job done.
function Rename()
let new_file_name = input('New filename: ')
let full_path_current_file = expand("%:p")
let new_full_path = expand("%:p:h")."/".new_file_name
bd
execute "!mv ".full_path_current_file." ".new_full_path
execute "e ".new_full_path
endfunction
command! Rename :call Rename()
nmap RN :Rename<CR>
If you use git and already have the tpope's plugin fugitive.vim then simply:
:Gmove newname
This will:
If your file was not yet added to a git repo then first add it:
:Gwrite
You can also do it using netrw
The explore command opens up netrw in the directory of the open file
:E
Move the cursor over the file you want to rename:
R
Type in the new name, press enter, press y.
I don't know if this is the "easiest" method, but assuming you've already saved your file (:w) I would invoke the shell (:sh) and do a simple cp foo foo.bak To go back to editor use Ctrl-D/Exit. Useful list of vi editor commands on this link