Open a file in your locally running Visual Studio Code instance from arbitrary terminal connections.

Overview

code-connect

GitHub release (latest SemVer)

Open a file in your locally running Visual Studio Code instance from arbitrary terminal connections.

Motivation

VS Code supports opening files with the terminal using code /path/to/file. While this is possible in WSL sessions and remote SSH sessions if the integrated terminal is used, it is currently not possible for arbitrary terminal sessions.

Say, you have just SSH'd into a remote server using your favorite terminal and would like to open a webserver config file in your local VS Code instance. So you type code nginx.conf, which doesn't work in this terminal. If you try to run code nginx.conf in the integrated terminal however, VS Code opens it the file just fine.

The aim of this project is to make the code cli available to any terminal, not only to VS Code's integrated terminal.

Prerequisites

  • Linux - we make assumptions on where VS Code stores it data based on Linux

    Macs could also support everything out of the box, confirmation needed. Please don't hesitate to come into contact if you have any information to share.

  • Python 3 - tested under Python 3.8, but slightly older versions should work fine

  • socat - used for pinging UNIX sockets

    apt-get install socat

VS Code Server

You need to set up VS Code Server before using this utility. For this, connect to your target in a remote SSH session.
Afterwards, you should have a folder .vscode-server in your home directory.

Installation

Fish

With fisher

fisher install chvolkmann/code-connect

This downloads code_connect.py and sets up an alias for you. See functions/code.fish

Bash

source <(curl https://raw.githubusercontent.com/chvolkmann/code-connect/main/install.sh)

This downloads code_connect.py and sets up an alias for you. See install.sh.

To uninstall, delete the alias from you ~/.bashrc and remove ~/.code-connect.

Manually

Set up an alias for code, pointing to code_connect.py by placing the following line in your shell's rcfile (bash: ~/.bashrc, fish: ~/.config/fish/fuctions/code.fish).

alias code="/path/to/code_connect.py"

Usage

Just use code like you normally would!

Usage: code [options][paths...]

To read from stdin, append '-' (e.g. 'ps aux | grep code | code -')

Options
  -d --diff             Compare two files with each other.
  -a --add                  Add folder(s) to the last active window.
  -g --goto  Open a file at the path on the specified line and character position.
  -n --new-window                   Force to open a new window.
  -r --reuse-window                 Force to open a file or folder in an already opened window.
  -w --wait                         Wait for the files to be closed before returning.
  -h --help                         Print usage.

Troubleshooting
  -v --version Print version.
  -s --status  Print process usage and diagnostics information.

Changelog

See CHANGELOG.md

How it works

VS Code uses datagram sockets to communicate between a terminal and the rendering window.

The integrated terminal as well as the WSL terminal spawn an IPC socket. You also create one when manually attaching a remote SSH session. These sockets can be found in the folder VS Code Server.

Each time you connect remotely, the VS Code client instructs the server to fetch the newest version of itself. All versions are stored by commit id in ~/.vscode-server/bin. code-connect uses the version that has been most recently accessed. The corresponding binary can be found in ~/.vscode-server/bin//bin/code.

A similar method is used to list all of VS Code's IPC sockets, which are located under /run/user//vscode-ipc-.sock, where is the current user's UID and is a unique ID. VS Code does not seem to clean up all stale connections, so some of these sockets are active, some are not.

So the socket that is listening and that was accessed within a timeframe of 4 hours by default is chosen.

VS Code communicates the presence of an active IPC connection with the environment variable VSCODE_IPC_HOOK_CLI which stores the path to the socket.
You can verify this by opening a connection to your remote machine. In one case, you use VS Code's integrated terminal. In the other case, you use any other terminal.

Run

echo $VSCODE_IPC_HOOK_CLI

which displays an output in the integrated terminal, but not on the other one.

In order, every socket is checked to see if it is listening. For this, the following snippet based on this answer on StackOverflow was used.

socat -u OPEN:/dev/null UNIX-CONNECT:/path/to/socket

This returns 0 if and only if there's something listening.

The script code_connect.py performs all of the above steps and runs the VS Code code executable as a child process with VSCODE_IPC_HOOK_CLI set properly.

Contributing

Credit

Comments
  • feat: use runtime alias strategy

    feat: use runtime alias strategy

    The existing shell init strategy lends itself to frequent state errors as VSCode sessions start and stop. It also carries the limitation of having to restart the shell after you start the VSCode session.

    Executing the code_connect.py script before every call to code ensures that the proper socket is detected without fail. The latency drawback is nearly imperceivable, clocking in between 30-60 ms.

    With this approach, we can do away with activate.sh and activate.fish... instead all we need is a simple alias like so

    function code
      ~/.local/share/code-connect/code_connect.py $argv
    end
    
    enhancement 
    opened by cmoog 4
  • Bugfixes & Expanded Environment Support

    Bugfixes & Expanded Environment Support

    Hi @chvolkmann. Your code-connect utility has been incredibly useful! Thanks for taking the time to put this together. Here are a few updates that I hope you will find valuable. Please let me know if you need anything changed or have any questions.

    A change in the March 2022 (version 1.66) release of VS Code broke an assumption code-connect was making about the location of the code binary. This pull request fixes that issue.

    This pull request also expands code-connect's supported environments to include CentOS Stream 8 machines running GNU which v2.21 and Python 3.5 or newer.

    Finally, I've fixed a small formatting bug with an if statement in code.fish & I've updated the README/CHANGELOG/VERSION documents to note these changes.

    opened by frecks 3
  • No such file or directory: .vscode-server/bin/ ... /bin/code

    No such file or directory: .vscode-server/bin/ ... /bin/code

    I am getting the following error:

    ➜ code .
    Traceback (most recent call last):
      File "/home/sruiz/.code-connect/bin/code_connect.py", line 121, in <module>
        main()
      File "/home/sruiz/.code-connect/bin/code_connect.py", line 114, in main
        proc = sp.run(args)
      File "/home/sruiz/anaconda3/lib/python3.9/subprocess.py", line 505, in run
        with Popen(*popenargs, **kwargs) as process:
      File "/home/sruiz/anaconda3/lib/python3.9/subprocess.py", line 951, in __init__
        self._execute_child(args, executable, preexec_fn, close_fds,
      File "/home/sruiz/anaconda3/lib/python3.9/subprocess.py", line 1821, in _execute_child
        raise child_exception_type(errno_num, err_msg, err_filename)
    FileNotFoundError: [Errno 2] No such file or directory: '/home/sruiz/.vscode-server/bin/c3511e6c69bb39013c4a4b7b9566ec1ca73fc4d5/bin/code'
    

    and

    ➜ ls .vscode-server/bin/c3511e6c69bb39013c4a4b7b9566ec1ca73fc4d5/bin
    code-server  helpers  remote-cli
    

    For some reason code is missing?

    I have vscode running and connected to the server that I am SSH'ed into.

    opened by sebastian-ruiz 1
  • Unify installers

    Unify installers

    Resolves #9

    Currently, we use fisher's simplicity for an easy install of code-connect. Fisher just copies over code_connect.py into the fish functions folder and we're done.

    Unifying this with the bash installer, fisher should install code_connect.py to ~/.code-connect/lib (and maybe add symlinks to ~/code-connect/lib for the .fish files for added clarity).

    opened by chvolkmann 0
  • Proper fish installer

    Proper fish installer

    Currently, we use fisher's simplicity for an easy install of code-connect. Fisher just copies over code_connect.py into the fish functions folder and we're done.

    Unifying this with the bash installer, fisher should install code_connect.py to ~/.code-connect/lib (and maybe add symlinks to ~/code-connect/lib for the .fish files for added clarity).

    Fisher hooks

    opened by chvolkmann 0
  • Don't use code-connect when code is installed

    Don't use code-connect when code is installed

    Summary

    • Redirect arguments directly to a locally installed code binary if detected in PATH. Useful in the integrated terminal as PATH will be populated with a code binary (set up beforehand by VS Code). We already have an executable available, no need to find it ourselves with code_connect.py.
    • Add function code-connect to connect through IPCs explicitly
    • Add fancy bash installer
    • Add bash uninstaller
    • Move bash-related files

    Fixes #7

    Checklist

    • [x] fish
    • [x] bash
    • [x] docs
    enhancement fix 
    opened by chvolkmann 0
  • Don't use code-connect when in integrated terminal

    Don't use code-connect when in integrated terminal

    When using the integrated terminal, VS Code sets up the IPC itself - this shouldn't be meddled with. Connections can sometimes not work when masked with code_connect.py.

    code_connect.py should detect whether it's being run in the integrated terminal by checking if $TERM_PROGRAM == ' vscode'

    bug 
    opened by chvolkmann 0
  • Fisher compatibility

    Fisher compatibility

    Apart from this repo, there's also code-connect-fish-plugin which is used for quick installation through

    fisher install chvolkmann/code-connect-fish-plugin
    

    I believe fisher supports repos that do not adhere to its expected structure. It's preferable to put the fisher integration into this repo as well, so you can simply run

    fisher install chvolkmann/code-connect
    

    instead. Also maintaining two repos is annoying.

    Resolves #3

    This puts code_connect.py into the functions folder, so fisher can discover it automatically. Along with it, code.fish sets up the alias to code_connect.py

    enhancement 
    opened by chvolkmann 0
  • Merge separate fish plugin repo

    Merge separate fish plugin repo

    Apart from this repo, there's also code-connect-fish-plugin which is used for quick installation through

    fisher install chvolkmann/code-connect-fish-plugin
    

    I believe fisher supports repos that do not adhere to its expected structure. It's preferable to put the fisher integration into this repo as well, so you can simply run

    fisher install chvolkmann/code-connect
    

    instead. Also maintaining two repos is annoying.

    enhancement 
    opened by chvolkmann 0
  • Could not find an open VS Code IPC socket. (path /run/user/{UID} does not exist)

    Could not find an open VS Code IPC socket. (path /run/user/{UID} does not exist)

    Hi! Thanks for this repo, it is exactly what I was looking for. Unfortunately it does not work for me as I'm getting this error:

    Could not find an open VS Code IPC socket.
    
    Please make sure to connect to this machine with a standard VS Code remote SSH session before using this tool.
    

    I tried killing all instances of vscode server linked to my user on the remote then launched vscode-server again by connecting to remote inside local vscode again, to no avail.

    I checked what the script is doing and it seems like the path /run/user/{UID} does not exist on my remote system. I don't know enough of Linux to know more, do you?

    Distrib is Debian 10 (buster), Linux kernel 4.19.0-6-amd64

    There's only one directory under /run/user on the remote machine, it is named "0" and is not accessible for non root user. echo $UID for my user returns 1006

    Thanks again

    opened by badaz 1
  • feat: add zsh plugin

    feat: add zsh plugin

    Thank you for maintaining this useful project. I created this PR to add a zsh plugin that may make it easier for zsh users to use this project.

    The main ideas is to use the zsh autoload builtin to define the code and code-connect functions.

    I see that you add a unified install script in #10. However, a common way to install a zsh plugin is to git clone and source it in the .zshrc manually, or use a framework like oh-my-zsh and update the plugin list. Framework can also use git pull to upgrade the project automatically. So currently I directly added bin/ to $PATH to make code_connect.py callable instead of telling user to use the script to install and upgrade manually.

    Welcome your feedback and suggestions.

    opened by qq88976321 0
Releases(v0.3.2)
  • v0.3.2(Jul 4, 2022)

  • v0.3.1(Jun 26, 2022)

    [0.3.1] - 2022-04-04

    Integrates PR #11 by @frecks

    Changed

    • Updated to reflect the VS Code binary location change from ~/.vscode-server/bin/<commit-id>/bin/code to ~/.vscode-server/bin/<commit-id>/bin/remote-cli/code in commit f4ba7dd12b684b144457c6fc6ccc9f4fe71bde3c, which was released in March 2022 (version 1.66).
    • Updated to support Python 3.5 and up.
    • Silence the which command's stderr stream, because the GNU which v2.21 command found on CentOS Stream 8 produces unnecessary error messages when we test for a locally installed VS Code binary.
    • Fixed a small formatting bug with an if statement in code.fish.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Feb 18, 2021)

    Added

    • bash uninstaller

    Changed

    • code-connect is now not just one alias anymore, but two aliases.

      • The code-connect alias is added functionality of this repo, it points to code_connect.py

      • The code alias checks whether code is in the PATH and omits using code-connect in this case. This is useful for the integrated terminal as a code executable is injected by VS Code into the PATH. Thus, code should just run that existing executable, not code-connect instead.

        See #8

    • bash installer is now fancy

    • All bash-related files are now in the bash/ folder

    • All code_connect.py is now in the bin/ folder

    • Fisher installation logic (#10)

    Source code(tar.gz)
    Source code(zip)
  • v0.2.2(Feb 16, 2021)

    Added

    • Code styling with black, isort and flake8
    • Poetry for managing code style dev dependencies
    • CI with Github Actions
    • Bash installation script
    • More docs on code_connect.py
    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Feb 15, 2021)

    • Integrates #4

    Changed

    • Created a functions folder and put code_connect.py into it. This lets fisher discover it and copy it when installing. code.fish provides the alias.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Feb 15, 2021)

    • Integrates #2

    Changed

    • source was used to make code available through code_connect.py, which only output a shell string.

      Now, code_connect.py is a direct wrapper around code and calls it as a subprocess. Thus, code_connect.py can ne be used as an alias for code. No need to activate anything first.

    • Scanning for a valid IPC socket is now done any time code is called.

    Fixed

    • code doesn't use stale IPC sockets anymore
    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Feb 15, 2021)

  • v0.1.0(Feb 15, 2021)

Owner
Christian Volkmann
software dude
Christian Volkmann
Personal and work vim 8 configuration with submodules

vimfiles Windows Vim 8 configuration files based on the recommendations of Ruslan Osipov, Keep Your vimrc file clean and The musings of bluz71. :help

1 Aug 27, 2022
NudeNet wrapper made to provide a simple cli interface to the library

Nudenet Wrapper. Small warpper script for NudeNet Made to provide a small and easy to use cli interface with the library. You can indicate a single im

1 Oct 20, 2021
:computer: tmux session manager. built on libtmux

tmuxp, tmux session manager. built on libtmux. We need help! tmuxp is a trusted session manager for tmux. If you could lend your time to helping answe

python utilities for tmux 3.6k Jan 01, 2023
Python API and CLI for the ikea IDÅSEN desk.

idasen This is a heavily modified fork of rhyst/idasen-controller. The IDÅSEN is an electric sitting standing desk with a Linak controller sold by ike

Alex 79 Dec 14, 2022
An question and answer shell environment based on xonsh using ansible for setup

An question and answer shell environment based on xonsh using ansible for setup

Steven Hollingsworth 2 Jan 11, 2022
Animefetch is an anime command-line system information tool written in python

Animefetch - v0.0.3 An anime command-line system information tool written in python. Description Animefetch is an anime command-line system informatio

Thadeuks 6 Jun 17, 2022
Chopper: An Automated Security Headers Analyzer

____ _ _ / ___| |__ ___ _ __ _ __ ___ _ __| | | | | '_ \ / _ \| '_ \| '_ \ / _ \ '__| | | |___| | | | (_) |

Kamran Saifullah (Frog Man) 2 Nov 27, 2022
Unofficial Open Corporates CLI: OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unofficial open corporates python command line tool.

Unofficial Open Corporates CLI OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unoff

Richard Mwewa 30 Sep 08, 2022
argofloats: Simple CLI for ArgoVis and Argofloats

argofloats: Simple CLI for ArgoVis and Argofloats Argo is an international program that collects information from inside the ocean using a fleet of ro

Samapriya Roy 2 Feb 13, 2022
Turdshovel is an interactive CLI tool that allows users to dump objects from .NET memory dumps

Turdshovel Description Turdshovel is an interactive CLI tool that allows users to dump objects from .NET memory dumps without having to fully understa

Leron Gray 41 Jul 27, 2022
asciinema - Terminal session recorder 📹

asciinema - Terminal session recorder 📹

asciinema 11.1k Dec 27, 2022
eBay's TSV Utilities: Command line tools for large, tabular data files. Filtering, statistics, sampling, joins and more.

Command line utilities for tabular data files This is a set of command line utilities for manipulating large tabular data files. Files of numeric and

eBay 1.4k Jan 09, 2023
Run an FFmpeg command and see the percentage progress and ETA.

Run an FFmpeg command and see the percentage progress and ETA.

25 Dec 22, 2022
sync-my-tasks is a CLI tool that copies tasks between apps.

sync-my-tasks Copy tasks between apps Report a Bug · Request a Feature . Ask a Question Table of Contents Table of Contents Getting Started Developmen

William Hutson 2 Dec 14, 2021
Tstock - Check stocks from the terminal

tstock - Check stocks from the terminal! 📈 tstock is a tool to easily generate stock charts from the command line. Just type tstock aapl to get a 3 m

Gabe Banks 502 Dec 30, 2022
Install python modules from pypi from a previous date in history

pip-rewind is a command-line tool that can rewind pypi module versions (given as command-line arguments or read from a requirements.txt file) to a previous date in time.

Amar Paul 4 Jul 03, 2021
Python Library and CLI for exporting MySQL databases

expdb Python library and CLI for exporting MySQL databases Installation Pre-requisites MySQL server Python 3.9+ Using git Clone the repository to your

Devansh Singh 1 Nov 29, 2021
OneDriveExplorer - A command line and GUI based application for reconstructing the folder structure of OneDrive from the UserCid.dat file

OneDriveExplorer - A command line and GUI based application for reconstructing the folder structure of OneDrive from the UserCid.dat file

Brian Maloney 100 Dec 13, 2022
The easiest way to create beautiful CLI for your programs.

The Yandere is a program written in Python3, allowing you to create your own beautiful CLI tool.

Billy 31 Dec 20, 2022
Wik is use to get information about anything on the shell using Wikipedia.

WIK wik is a tool to view wikipedia pages from your terminal. It also let you search for any wikipedia up to date article on one query from your termi

Yash Singh 340 Dec 18, 2022