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
Python-Stock-Info-CLI: Get stock info through CLI by passing stock ticker.

Python-Stock-Info-CLI Get stock info through CLI by passing stock ticker. Installation Use the following command to install the required modules at on

Ayush Soni 1 Nov 05, 2021
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
Command-line script to upload videos to Youtube using theYoutube APIv3.

Introduction Command-line script to upload videos to Youtube using theYoutube APIv3. It should work on any platform (GNU/Linux, BSD, OS X, Windows, ..

Arnau Sanchez 1.9k Jan 09, 2023
A fantasy life simulator and role-playing game hybrid distributed as CLI, written in Python 3.

Life is Fantasy Epic (LIFE) A fantasy life simulator and role-playing game hybrid distributed as CLI, written in Python 3. This repository will be pro

Pawitchaya Chaloeijanya 2 Oct 24, 2021
🪛 A simple pydantic to Form FastAPI model converter.

pyfa-converter Makes it pretty easy to create a model based on Field [pydantic] and use the model for www-form-data. How to install? pip install pyfa_

20 Dec 22, 2022
This is a repository for collecting global custom management extensions for the Django Framework.

Django Extensions Django Extensions is a collection of custom extensions for the Django Framework. Getting Started The easiest way to figure out what

Django Extensions 6k Jan 03, 2023
Dynamically Generate GitHub Stats as like Terminal Interface

GitHub Stats Terminal Style Dynamically Generate GitHub Stats as like Terminal Interface Usage Create a New Repository using this Template or click he

YOGESHWARAN R 63 Jan 03, 2023
A minimalist Vim plugin manager.

A minimalist Vim plugin manager. Pros. Easy to set up: Single file. No boilerplate code required. Easy to use: Concise, intuitive syntax Super-fast pa

Junegunn Choi 30.2k Jan 08, 2023
Command-line tool for downloading and extending the RedCaps dataset.

Command-line tool for downloading and extending the RedCaps dataset.

RedCaps dataset 33 Dec 14, 2022
YouCompleteMe: a code-completion engine for Vim

YouCompleteMe: a code-completion engine for Vim Help, Advice, Support Looking for help, advice or support? Having problems getting YCM to work? First

24.5k Jan 06, 2023
Basic python tools to generate shellcode runner in vba

vba_bin_runner Basic python tools to generate shellcode runner in vba. The stub use ZwAllocateVirtualMemory to allocate memory, RtlMoveMemory to write

4 Aug 24, 2021
Fun project to generate The Matrix Code effect on you terminal.

Fun project to generate The Matrix Code effect on you terminal.

Henrique Bastos 11 Jul 13, 2022
Features terminal for python

Features Terminal V1.0 (23/10/2021) Um programa para linux com diferentes ferramentas! Recursos: Criador de QR code Gerador de senhas Teste de velocid

1 Oct 26, 2021
img-proof (IPA) provides a command line utility to test images in the Public Cloud

overview img-proof (IPA) provides a command line utility to test images in the Public Cloud (AWS, Azure, GCE, etc.). With img-proof you can now test c

13 Jan 07, 2022
googler is a power tool to Google (web, news, videos and site search) from the command-line.

googler is a power tool to Google (web, news, videos and site search) from the command-line.

Terminator X 5.9k Jan 04, 2023
Tidier - a simple command line tool that helps you make your files tidy up

Tidier - a simple command line tool that helps you make your files tidy up

AmirMohammad Hosseini Nasab 8 Aug 16, 2022
A python library for parsing multiple types of config files, envvars & command line arguments that takes the headache out of setting app configurations.

parse_it A python library for parsing multiple types of config files, envvars and command line arguments that takes the headache out of setting app co

Naor Livne 97 Oct 22, 2022
Format click help output nicely with rich.

rich-click Format click help output nicely with Rich. Click is a "Python package for creating beautiful command line interfaces". Rich is a "Python li

Phil Ewels 333 Jan 02, 2023
pyGinit is a command line tools that help you to initialize your current project a local git repo and remote repo

pyGinit pyGinit is a command line tools that help you to initialize your current project a local git repo and remote repo Requirements Requirements be

AlphaBeta 15 Feb 26, 2022
Multifunctional library for creating progress bars.

👋 Content Installation Using github Using pypi Quickstart Flags Useful links Documentation Pypi Changelog TODO Contributing FAQ Bar structure ⚙️ Inst

DenyS 27 Jan 01, 2023