top image
home  /  pages  /  tech tips  /  contact about

Filename completion with Vim's Netrw plugin

Problem

You edit files over ssh/scp by using Vim's Netrw plugin. While the remote file browser is helpful, the absence of filename completion on the command line is a bummer.

A related article discusses speeding up Vim's Netrw plugin over ssh/scp.

Keywords

Vim, Netrw, ssh, sshfs, scp, filename completion.

Solution

You combine the benefits of mounting the remote file system with the speedups that Netrw give you. You create a local path called /tmp/scp:/host.domain.com/home that we mount our remote home directory system onto. You then open scp://host.domain.com/home/username with /tmp as your current working directory.

First, create the oddly named local mount point.

# on a Mac, leave out the "username" part
mkdir -p /tmp/scp:/host.domain.com/home/username/

Then mount the remote home directory using sshfs (or ExpanDrive on a Mac).

sshfs -o follow_symlinks host.domain.com: /tmp/scp:/host.domain.com/home/username/
You may have to use the -o uid= and the -o gid= arguments to sshfs if your user IDs don't match locally and remotely.

If you're on a Mac, the remote remote file system will be mounted on /Volume/host.domain.com/; in that case you need to symlink the directory in /tmp to it:

# Mac only
ln -s /Volume/host.domain.com /tmp/scp:/host.domain.com/home/username

Now you should be able to access /tmp/scp:/host.domain.com/home/username/ and see the files in your remote home directory.

Open Vim with /tmp/ as your working directory. For example, open your remote .bashrc file.

cd /tmp && vim scp://host.domain.com//home/username/.bashrc

Note that this is relatively slow because it opens the file over the mounted file system, not via Netrw. But :Nw still uses scp to save the file, which is the speedup I personally care about most. (See also speeding up Vim's Netrw plugin over ssh/scp.)

You can now do filename completion on the command line. Since your current working directory needs to stay /tmp, it's handy to know that %:p:h refers to the path of the file you're currently editing. So typing :e %:p:h/ and then hitting tab will start filename completion in the directory of the file you're currently editing. I mapped ",ph" to ":e %:p:h/" and ",tph" to ":tabe %:p:h/

If you can't remember to use :Nw, you can map :w to :Nw with

:ca w Nw

If you want this for all filenames that start with scp:// , you can add the following to ~/.vim/filetype.vim

augroup netrwdetect
  au! BufNewFile,BufRead * so <sfile>:h/ftplugin/netrw/default.vim
augroup END
And then create ~/.vim/ftplugin/netrw/default.vim with:
if match(expand("%"), '^scp://') == 0
  ca w Nw
  " any other Netrw-specific customizations
endif

URL: https://thomer.com/howtos/netrw_completion.html
Copyright © 1994-2022 by Thomer M. Gil
Updated: 2011/04/04