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
An awesome Python wrapper for an awesome Docker CLI!

An awesome Python wrapper for an awesome Docker CLI!

Gabriel de Marmiesse 303 Jan 03, 2023
A CLI tool that scans through a directory and organizes all loose files into folders by file type.

Organizer CLI Organizer CLI is a python command line tool that goes through a given directory and organizes all un-folder bound files into folders by

Mulaza Jacinto 6 Dec 14, 2022
Color preview command-line tool written in python

Color preview command-line tool written in python

Arnau 1 Dec 27, 2021
A CLI for creating styled-components for React projects quickly

new-component Ian Cleary (iancleary) Description Welcome! This is a CLI for creating styled-components for React projects quickly. Note: I've rewrote

Ian Cleary (he/him/his) 1 Feb 15, 2022
Pequeno joguinho pra você rodar no seu terminal

JokenPython Pequeno joguinho pra você rodar no seu terminal Olá! Joguinho legal pra vc rodar no seu terminal!! (rode no terminal, pra melhor experienc

Scott 4 Nov 25, 2021
💥 Share files easily over your local network from the terminal!

Fileshare 📨 Share files easily over your local network from the terminal! 📨 Installation # clone the repo $ git clone https://github.com/dopevog/fil

Dopevog 11 Sep 10, 2021
Fetch is use to get information about anything on the shell using Wikipedia.

Fetch Search wikipedia article on command line [Why This?] [Support the Project] [Installation] [Configuration] Why this? Fetch helps you to quickly l

Yash Singh 340 Dec 18, 2022
Write Django management command using the click CLI library

Django Click Project information: Automated code metrics: django-click is a library to easily write Django management commands using the click command

Jonathan Stoppani 215 Dec 19, 2022
Double Pendulum visualised with fetching system information in Python.

Show off your terminal, in style. A nice relaxing double pendulum simulation using ASCII, able to simulate multiple pendulums at once, and provide tra

Nekurone 62 Dec 14, 2022
A minimal todo list for your terminal.

todo A minimal todo list for your terminal. Installation Run the following command. pip install git+https://github.com/piero-vic/todo.git Usage todo

Piero Lescano 7 Aug 08, 2022
A command line tool (and Python library) for archiving Twitter JSON

A command line tool (and Python library) for archiving Twitter JSON

Documenting the Now 1.3k Dec 28, 2022
A python CLI app that converts a mp4 file into a gif with ASCII effect added.

Video2ASCIIgif This CLI app takes in a mp4 format video, converts it to a gif with ASCII effect applied. This also includes full control over: backgro

Sriram R 6 Dec 31, 2021
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
Access hacksec.in from your command-line

Access hacksec.in from your command-line

hacksec.in 3 Oct 26, 2022
A CLI tool to disable and enable security standards controls in AWS Security Hub

Security Hub Controls CLI A CLI tool to disable and enable security standards controls in AWS Security Hub. It is designed to work together with AWS S

AWS Samples 4 Nov 14, 2022
iTerm2 Shell integration for Xonsh shell.

iTerm2 Shell Integration iTerm2 Shell integration for Xonsh shell. Installation To install use pip: xpip install xontrib-iterm2 # or: xpip install -U

Noorhteen Raja NJ 6 Dec 29, 2022
AlienFX is a CLI and GUI utility to control the lighting effects of your Alienware computer.

AlienFX is a Linux utility to control the lighting effects of your Alienware computer. At present there is a CLI version (alienfx) and a gtk GUI versi

Stephen Harris 218 Dec 26, 2022
Enlighten Progress Bar is a console progress bar library for Python.

Overview Enlighten Progress Bar is a console progress bar library for Python. The main advantage of Enlighten is it allows writing to stdout and stder

Rockhopper Technologies 265 Dec 28, 2022
A stupidly simple task list to keep you productive and focused.

StupidlySimple-TaskList A stupidly simple task list to keep you productive and focused. There is really nothing to it. This is a terminal-based script

Jack Soderstrom 1 Nov 28, 2021
🐍The nx-python plugin allows users to create a basic python application using nx commands.

🐍 NxPy: Nx Python plugin This project was generated using Nx. The nx-python plugin allows users to create a basic python application using nx command

StandUP Communications 74 Aug 31, 2022