VSCode Remote and the command line

Published:

I use Visual Studio Code in conjunction with terminal windows. I'm very used to using source control, building and running tests from the command-line and I tend to work on sufficiently weird things that VSCode's ideas about what a build is don't map well.

When poking around my source tree, building or running tests I often want to open an interesting file in my editor. Locally I just run code path/to/file and that works great, but with Visual Studio Code Remote it does not. I've been working from home since March 2020 and both the workstation in my office and the cloud machines at my disposal are much more powerful than my laptop. I wanted to get this same functionality working in this setup.

I looked at how running code within VSCode's integrated terminal works. Each remote instance creates a uniquely named directory under ~/.vscode-server/bin/ that contains a copy of node, the installed extensions, helper scripts (including one called bin/code) and other state. There's a UNIX domain socket called /run/user/UID/vscode-ipc-SOME-UUID.sock that's put in the integrated terminal shell's environment variable $VSCODE_IPC_HOOK_CLI.

I only tend to run a single VSCode remote instance per server so I wrote a Zsh function that simply looks for the most recent helper script and runs it with the most recent socket:

code () {
     local script=$(echo ~/.vscode-server/bin/*/bin/code(*ocNY1)) 
     if [[ -z ${script} ]]
     then
         echo "VSCode remote script not found"
         exit 1
     fi
     local socket=$(echo /run/user/$UID/vscode-ipc-*.sock(=ocNY1))
     if [[ -z ${socket} ]]
     then
         echo "VSCode IPC socket not found"
         exit 1
     fi
     export VSCODE_IPC_HOOK_CLI=${socket}
     ${script} $*
 }

This uses some Zsh-specific globbing but I'm sure the same thing could be implemented for bash or tcsh or fish or whatever the kids are using these days.