April 26, 2020

Renaming files in Vim: A Vimscript experiment

I took an attempt at creating a Vimscript function to rename a file with a simple command. It was not that hard, but there are a few tricks that you need to learn to get started writing Vimscript.

Let’s first look at the full code for the function, with a mapping to <leader>fr

function! s:RenameCurrentFile( newName )
    let l:file = expand('%')
    let l:currentFilePath = expand('%:p:h')
    let l:newFile = l:currentFilePath . '/' . a:newName
    " Save new file
    execute "saveas " . l:newFile
    " Open new file in a new buffer
    execute "e " . l:newFile
    " Kill old buffer
    execute "bdelete " . l:file
    " Remove old file
    call delete(l:file)
endfunction
command! -nargs=1 -complete=file RenameCurrentFile call s:RenameCurrentFile(<f-args>)
nnoremap <leader>fr :RenameCurrentFile

The first thing that had me bumped was how to use saveas. You have to execute a string that you create with the proper arguments, and there is no function for that. All commands that you would type after a colon (like edit, or bdelete, in this example) will have to be executed this way.

To use a function, you cannot just write its name, and you have to actually call it.

To make use of this function, you have to create a command that can be used, which will be called using :RenameCurrentFile <new name>. To pass arguments to the command, use the -nargs=1 and <f-args> pair (:help :command-nargs, :help f-args). Using the -complete=file flag allows to complete filenames, which may be useful for a renaming function.

I quite like the idea of namespacing with the prefixes. s: for script variable, l: for function variable, a: for argument variable.

I would have liked to be able to create a mapping that got me the file name along with the command, so that I could just modify it, but I was not able to find the way to do it.

In the end, I am using Tpope’s vim-eunuch, just because I trust the plugin author, the rename function is better implemented, and there are other interesting functions to work with files. And if you still want to use this function, be aware that there are no checks here that the file was actually written before being deleted, so you may want to make a few improvements to ensure not to lose any work.

Copyright Marin Gilles 2019-2021