Vim Recipes Other Uses of Vim Using Vim as a File Manager

Using Vim as a File Manager

Problem

You want to use Vim to manage your file system in a similar way to Nautilus, Midnight Commander, or Windows Explorer.

For example, you want to rename files matching a certain pattern. Or you want to compress the contents of a directory.

Solution

Browsing Directories explains the basics of working with directories in Vim, so read it first.

Marking Files

To operate on files you must first mark them (this does not have any relation to the marks feature).

You can operate on a single file or a group of them. In the latter case, you need to select files by marking them, as explained in the sidebar. You can now perform various operations on these files such as:

Discussion

Vim can be used as a pretty well-featured file manager. In fact, given that it can be scripted, key mapped, and configured in concert with Vim, as well as seamlessly operate on remote directories, it is arguably better.

Perhaps the most interesting command is mx. This allows you to pass the list of marked files to an external command. You're prompted for a command line, in which you can use the % wildcard. Vim then loops through the selected files and calls the command for each one, substituting % for the filename.

For example, using a POSIX-compatible system, select three files (foo.txt, bar.txt, and glark) with mf. Hit mx and enter cat %>>foo-bar-glark. Vim will now execute:

cat foo.txt >>foo-bar-glark
cat bar.txt >>foo-bar-glark
cat glark >>foo-bar-glark

foo-bar-glark will now contain the contents of each file in turn.

The mz command also bears further discussion. It toggles the state of the selected files between compressed and decompressed.

If a file is uncompressed, Vim attempts to compress it. By default it uses gzip, but you can change this by modifying the g:netrw_compress variable. For example, to use Bzip2: :let g:netrw_compress=bzip2.

For decompression Vim uses an extension-to-program mapping:

For example, if a filename ends with .zip Vim decompresses it by calling unzip zip-file. To add support for another format use :let g:netrw_decompress[ext] = prog.