Last active
August 7, 2024 04:44
-
-
Save derek-shnosh/32eb8842f31e4b51cb29a3b0f54256f7 to your computer and use it in GitHub Desktop.
Gnome Files (Nautilus) Context Menu - Open in VScode/Open VScode Here
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: UTF-8 -*- | |
# This script is based on Tilix's "open_tilix.py" by Gerald Nunn | |
# - https://github.com/gnunn1/tilix/blob/master/data/nautilus/open-tilix.py | |
# Modified for VScode, references: | |
# - https://gnome.pages.gitlab.gnome.org/nautilus-python/class-nautilus-python-menu-provider.html | |
# - https://askubuntu.com/a/301205/643965 | |
from gettext import gettext, textdomain | |
from subprocess import Popen | |
import shutil | |
from gi.repository import Gio, GObject, Nautilus | |
TERMINAL = shutil.which("code") | |
textdomain("code") | |
_ = gettext | |
def _checkdecode(s): | |
"""Decode string assuming utf encoding if it's bytes, else return unmodified""" | |
return s.decode("utf-8") if isinstance(s, bytes) else s | |
def open_terminal_in_file(filename): | |
Popen([TERMINAL, filename]) | |
class OpenVscodeExtension(GObject.GObject, Nautilus.MenuProvider): | |
def _open_terminal(self, file_): | |
filename = Gio.File.new_for_uri(file_.get_uri()).get_path() | |
open_terminal_in_file(filename) | |
def _menu_activate_cb(self, menu, file_): | |
self._open_terminal(file_) | |
def _menu_background_activate_cb(self, menu, file_): | |
self._open_terminal(file_) | |
def get_file_items(self, *args): | |
files = args[-1] | |
if len(files) != 1: | |
return | |
items = [] | |
file_ = files[0] | |
if file_.is_directory(): | |
filename = _checkdecode(file_.get_name()) | |
item = Nautilus.MenuItem( | |
name="NautilusPython::open_file_item", | |
label=_("Open In VScode"), | |
tip=_("Open VScode In {}").format(filename), | |
) | |
item.connect("activate", self._menu_activate_cb, file_) | |
items.append(item) | |
return items | |
def get_background_items(self, *args): | |
file_ = args[-1] | |
items = [] | |
item = Nautilus.MenuItem( | |
name="NautilusPython::open_bg_file_item", | |
label=_("Open VScode Here"), | |
tip=_("Open VScode In This Directory"), | |
) | |
item.connect("activate", self._menu_background_activate_cb, file_) | |
items.append(item) | |
return items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment