Can I rename files in a directory with Vim?

If I open a directory in vim using vim . I will get a file-browser-type interface of the current directory. From there I am expected to browse to a file, and then start editing it.

I want to use this interface to rename files. Normal vim rename works like %s/term1/term2/, but when I try it out here, it returns: E21: Cannot make changes, 'modifiable' is off.

Is there a way to turn modifiable on in this scenario, or does this simply mean that it cannot be done like this with vim?


Solution 1:

Yes, it can't be done like that.

That "file-browser-type interface" is provided by a built-in plugin called netrw. It is read-only so yeah, you can't modify it.

You are supposed to hit R to rename the file under the cursor or the marked files.

See :help netrw, :help netrw-browse-maps and more specifically :help netrw-R.

If you want to batch-rename files using Vim you should try qmv from the renameutils package or vidir from the moreutils package (thanks to Dmitry for the heads up).

Solution 2:

Check out the renamer.vim - Use the power of vim to rename groups of files plugin (now purely maintained on GitHub). Like netrw, it presents the directory contents in a scratch buffer, and then lets you edit that buffer, and finally apply the edits to the underlying files.

Solution 3:

Netrw will allow you to apply a pattern to rename files since about v143. The procedure: mark files (use mr to mark files based on a pattern), then hit R. Upon the first renaming query, respond with the strings/-frompat-/-topat-/ where the -frompat- and -topat- are vim substitution patterns. The s/ is required for this. Example:

s/\(.*\)\.c/\1.cpp/

Solution 4:

I try to use "system()" to accomplish this task using the shell (if that is the case, of course) creating a function to accomplish this task on your ".vimrc".

func! YourFunc() range

    let l:result = system("your shell command")

    [...]

endfunc

See an use of "system()" in https://github.com/eduardolucioac/groovim/blob/master/.vimrc

[]'s