From time to time I want to rename a file while editing it. For example from .html to .xhtml or so.

To do that in Vim, I must do

:saveas new_file
:!rm old_file

Is there a built-in command, that allows me to get rid of the :!rm part? It's annoying to re-type the old path and filename.

link|improve this question

feedback

4 Answers

up vote 3 down vote accepted

You could always define your own. E.g., put this in your .vimrc:

" First define a function
function! MoveFunction(newname)
    " get the current file name
    let a:oldname = expand("%:p")
    " save under the new name
    exec "saveas " . a:newname 
    " delete the old file
    call delete(a:oldname) 
endfunction
" Next define a command
command! -nargs=1 MoveTo call MoveFunction(<f-args>)

then:

:MoveTo <new-name>

should do what you want.

link|improve this answer
1  
Yes, I feared, that I'd have to. Thanks for the solution! – Boldewyn Sep 24 '10 at 11:57
feedback

No, there is no command that will rename both the file on-disk and the buffer at the same time. There are some ways to reduce the amount of typing you have to do, though. For example, Vim will expand % to the name of the current buffer/file, so you could use

:!mv % new_file

If new_file has the same root name as old_file, you could do this to change just the extension:

:!mv % %:r.xhtml

where %:r expands to the name of the current buffer/file without the extension. See

:help filename-modifiers

Once you have the file name changed on-disk, you can change your buffer to that name with

:e new_file

or

:f new_file

Both commands have file name completion, so you can type just the first few letters of the file name, then <tab> to have Vim complete the name.

link|improve this answer
1  
Thanks for the explanation. – Boldewyn Sep 24 '10 at 11:58
feedback

You can just use

:!mv old_file new_file

You have to save current buffer first, btw!

link|improve this answer
feedback

There's also the Rename.vim plugin: http://www.vim.org/scripts/script.php?script_id=1928

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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