Pages

Wednesday, November 5, 2014

Starting a text editor from inside a Virtual Machine

Using Vagrant, Docker or other virtual development environment is becoming quite popular. However, a drawback of this is that you cannot start a visual text editor on your main machine because heh, the files are not there. Purist may tell you that you should be using Vim or Emacs, but I like Sublime, I want to keep using it.

A simple trick I came up with it to call my text editor by SSH using path translation. Of course, you will need to translate the paths and otherwise adapt it to your needs, but this should get you started:

#!/bin/bash
# Starting Sublime Text from inside a Virtual Machine
# @link https://gist.github.com/lavoiesl/c01b16b5f875906a6d82
# You may require to install realpath
path="$(realpath "$1")"
if echo "${path}" | grep -q "^/media/data/projects"; then
path="$(echo "${path}" | sed 's/^\/media\/data\/projects\//~\/projects\//')"
elif echo "${path}" | grep -q "^/media/home"; then
path="$(echo "${path}" | sed 's/^\/media\/home\//~\//')"
else
echo "Only paths inside /media/data/projects and /media/home are supported" >&2
exit 1
fi
ssh seb@10.10.10.1 subl "${path}"
view raw subl.sh hosted with ❤ by GitHub
In this example, /media/data/projects on the Guest exists as ~/projects on the Host and ~ on the Host exists as /media/home on the Guest.

Make sure you have ~/.ssh/authorized_keys and ForwardAgent properly setup to avoid password prompts each time.

You could also use this trick to open a webpage by using the “open” program on Mac. Equivalent exists on most Linux distros.