Skip to content
Justin M. Keyes edited this page Mar 11, 2019 · 4 revisions

There are a couple ways to attach to a remote neovim session. Most snippets I have seen so far use TCP sockets but openssh actually supports UNIX sockets. The hard part is figuring out the needed ssh options and compromises

On the host

Here is a shell script to start nvim on the host side. This one creates the nvim socket in $HOME/.local/nvimsock.

#!/bin/sh
set -eu
SOCK_FOLDER=$HOME/.local/
mkdir -p $SOCK_FOLDER
SOCK=$SOCK_FOLDER/nvimsock
if [ -e "$SOCK" ]; then
	echo "Listening socket $SOCK already exists"
	ps ax | grep nvim
	return 1
fi
export NVIM_LISTEN_ADDRESS=$SOCK
# https://stackoverflow.com/questions/10408816/how-do-i-use-the-nohup-command-without-getting-nohup-out
nohup nvim --headless </dev/null >/dev/null 2>&1 &

This example refuses to start nvim if the socket already exists. If you are running this at startup it might be better to simply remove the socket.

On the client

Setup your connection in .ssh/config with a local UNIX socket forward

Host work
	# the .nvim_remotes folder MUST exist or binding will fail
	LocalForward /home/raf/.local/nvim_remotes/work /home/raf/.local/nvimsock
	StreamLocalBindUnlink yes

This creates a local socket at /home/raf/.local/nvim_remotes/work, connections to this socket are forwarded to /home/raf/.local/nvimsock (in the remote machine).

The StreamLocalBindUnlink yes option removes the local socket if it already exists. This means that if you open a new ssh connection the socket will be replaced.

To connect to a remote instance you connect to the remote host using ssh

$ ssh work

and then call nvim-qt on the local socket

$ nvim-qt --server $HOME/.local/nvim_remotes/work

Ephemeral sessions

If you are really confident your connection will not die, and you just want to do some quick editing.

$ nvim-qt --spawn ssh -- work -o BatchMode=yes nvim --embed

But because ssh is called through nvim-qt there is no place to insert your passwords. So this only works when authentication is handled by the ssh-agent.

  • it should be possible to combine this with the previous examples (e.g. remote socat, netcat), but nvim-qt --spawn socat -- ... is not working

Automatic spawn new nvim server without ssh access

Run socat daemon on the host

socat tcp-listen:$port,reuseaddr,fork "exec:'nvim --embed --headless',stderr,sigint"

Then connect using nvim-qt --server $addr:$port