Open files from remote ssh host in VSCode

Viewed 2770

I'm using using VSCode Remote SSH from my laptop (Linux) to work on projects that resides on a Linux host.

If I open an internal terminal in VSCode I can open files from the host by doing code some_file.txt. I frequently want to be able to do the same from terminals that are not originating from VSCode.

Is there anyway to open files in the VSCode-server while connected to a standard (Non VSCode internal) terminal?

2 Answers

From another StackOverflow answer, I learned that if you open an integrated terminal and find the VSCODE_IPC_HOOK_CLI environment variable, and set it to the same value in the non-integrated terminal, then run code from the code server install directory ~/.vscode-server, it will work. That article didn't mention that you can have more than one install in the ~/.vscode-server directory. The current install can be extracted from the VSCODE_GIT_ASKPASS_MODE variable, it looks like this:

$ echo $VSCODE_GIT_ASKPASS_NODE
/home/<user>/.vscode-server/bin/054a9295330880ed74ceaedda236253b4f39a335/node

Just chop off the node and add bin, and so run something like

$ /home/<user>/.vscode-server/bin/054a9295330880ed74ceaedda236253b4f39a335/bin/code myfile.txt

Edit: Here is a small script that will connect the terminal to the latest created vscode window.

❯ cat ~/.local/bin/connect_vscode.sh
export PATH="${HOME}/.vscode-server/bin/$(ls -t1 ${HOME}/.vscode-server/bin | head -n 1)/bin:${PATH}"
export VSCODE_IPC_HOOK_CLI="$(ls -t1 /run/user/$(id -u)/vscode-ipc-* | head -n 1)"
# Tell tmux to set these variables for new windows/panes.
# Remove if you don't use tmux
tmux setenv PATH "$PATH"
tmux setenv VSCODE_IPC_HOOK_CLI "$VSCODE_IPC_HOOK_CLI"

C. R. Oldham's answer covers the technical detail of why/how.

If you want a 1-liner that works as an alias in your ~/.bash_profile:

# Open file in most recently-connected remote VSCode session.
alias code=$'VSCODE_IPC_HOOK_CLI=/run/user/`id -u`/$(ls -lt /run/user/`id -u`/ | egrep \.sock$ | head -1 | awk \'END {print $NF}\') `ls -lt ~/.vscode-server/bin/** | fgrep bin/remote-cli/code | head -1 | awk \'END {print $NF}\'`'
Related