Run 'code' from remote and open VSCode locally to view

VSCode CLI code <dir/file> is extremely convenient to use. It will open a VSCode session from the terminal. When using sshed terminal at remote, we do want to use such convenience. This tutorial will show how to run code from remote, then VSCode that runs locally will open the remote directory.

Prerequisition

  • VSCode and Remote SSH extension installed
  • SSH connection to the remote server

Tutorial

Prepare scripts

Put the following scripts in a Path-reachable directory:

Script name: code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env zsh

local process=$(echo $HOME/.vscode-server/cli/servers/*/server/bin/remote-cli/code(*oc[1]N))
local config_dir=$HOME/.config/setcode
local ipc_file=${config_dir}/ipc
mkdir -p ${config_dir}
if [[ -z ${VSCODE_IPC_HOOK_CLI} ]]; then
if [[ -e ${ipc_file} ]]; then
export VSCODE_IPC_HOOK_CLI=$(cat ${ipc_file})
else
echo "No running vscode server found" >&2
exit 1
fi
fi
${process} $@ --new-window

Script name: setcode

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env zsh

local config_dir=$HOME/.config/setcode
local ipc_file=${config_dir}/ipc
mkdir -p ${config_dir}
if [[ -z ${VSCODE_IPC_HOOK_CLI} ]]; then
echo "No running vscode server found" >&2
exit 1
fi
echo ${VSCODE_IPC_HOOK_CLI} > ${ipc_file}

Workflow

  • Every time you want to use code from remote, firstly run VSCode to connect to the remote manually, and use the VSCode terminal to run setcode. Then you shall put this window in the background.

  • Then you can ssh using normal terminal. When you want to open a remote directory, simply run code <dir/file> at remote terminal. You can run this command multiple times to open multiple directories, as long as the initial setcode VSCode window is not closed.

References

https://stackoverflow.com/questions/62201080/is-it-possible-to-use-the-code-command-in-sshed-terminal-to-open-vs-code-on-l/68090934

PS. The method mentioned in the above reference works badly for me. It is hard to judge which socket shall I use. So I write a setcode script to set the socket manually.