This commit is contained in:
sankalp committed 2024-01-02 16:23:20 +05:45
1 parent 5922a32bcc
commit 1b46ee74cf
8 files changed
+2245 -382

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
[ "$1" = @selection ] && set -- .
xdg-open "$1"
+1904 -295
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -0,0 +1,9 @@
def main():
pass
def handle_result(args, result, target_window_id, boss):
boss.active_tab.neighboring_window(args[1])
handle_result.no_ui = True
+31
View File
@@ -0,0 +1,31 @@
# Directories
protocol file
mime inode/directory
xdg-open --type=os-window --cwd $FILE_PATH
# Files
protocol file
mime text/*
action launch --type=overlay $EDITOR $FILE_PATH
# Images
protocol file
mime image/*
xdg-open $FILE_PATH
# SSH Urls
protocol ssh
action launch --type=os-window ssh $URL
# Executables
action launch --hold --type=os-window $FILE_PATH
# Shell files
protocol file
ext fish,bash,zsh
action launch --hold --type=os-window kitty +shebang $FILE_PATH __ext__
# Scripts
protocol file
ext sh,command,tool
action launch --hold --type=os-window kitty +shebang $FILE_PATH $SHELL
+106
View File
@@ -0,0 +1,106 @@
import re
from kittens.tui.handler import result_handler
from kitty.key_encoding import KeyEvent, parse_shortcut
def is_window_vim(window, vim_id):
from kittens.tui.loop import debug
debug(vim_id)
fp = window.child.foreground_processes
return any(re.search(vim_id, p['cmdline'][0] if len(p['cmdline']) else '', re.I) for p in fp)
def encode_key_mapping(window, key_mapping):
mods, key = parse_shortcut(key_mapping)
event = KeyEvent(
mods=mods,
key=key,
shift=bool(mods & 1),
alt=bool(mods & 2),
ctrl=bool(mods & 4),
super=bool(mods & 8),
hyper=bool(mods & 16),
meta=bool(mods & 32),
).as_window_system_event()
return window.encoded_key(event)
def relative_resize_window(direction, amount, target_window_id, boss):
window = boss.window_id_map.get(target_window_id)
if window is None:
return
neighbors = boss.active_tab.current_layout.neighbors_for_window(window, boss.active_tab.windows)
current_window_id = boss.active_tab.active_window
left_neighbors = neighbors.get('left')
right_neighbors = neighbors.get('right')
top_neighbors = neighbors.get('top')
bottom_neighbors = neighbors.get('bottom')
# has a neighbor on both sides
if direction == 'left' and (left_neighbors and right_neighbors):
boss.active_tab.resize_window('narrower', amount)
# only has left neighbor
elif direction == 'left' and left_neighbors:
boss.active_tab.resize_window('wider', amount)
# only has right neighbor
elif direction == 'left' and right_neighbors:
boss.active_tab.resize_window('narrower', amount)
# has a neighbor on both sides
elif direction == 'right' and (left_neighbors and right_neighbors):
boss.active_tab.resize_window('wider', amount)
# only has left neighbor
elif direction == 'right' and left_neighbors:
boss.active_tab.resize_window('narrower', amount)
# only has right neighbor
elif direction == 'right' and right_neighbors:
boss.active_tab.resize_window('wider', amount)
# has a neighbor above and below
elif direction == 'up' and (top_neighbors and bottom_neighbors):
boss.active_tab.resize_window('shorter', amount)
# only has top neighbor
elif direction == 'up' and top_neighbors:
boss.active_tab.resize_window('taller', amount)
# only has bottom neighbor
elif direction == 'up' and bottom_neighbors:
boss.active_tab.resize_window('shorter', amount)
# has a neighbor above and below
elif direction == 'down' and (top_neighbors and bottom_neighbors):
boss.active_tab.resize_window('taller', amount)
# only has top neighbor
elif direction == 'down' and top_neighbors:
boss.active_tab.resize_window('shorter', amount)
# only has bottom neighbor
elif direction == 'down' and bottom_neighbors:
boss.active_tab.resize_window('taller', amount)
def main():
pass
@result_handler(no_ui=True)
def handle_result(args, result, target_window_id, boss):
window = boss.window_id_map.get(target_window_id)
action = args[1]
direction = args[2]
key_mapping = args[3] if action == 'neighboring_window' else args[4]
amount = int(args[3]) if action == 'relative_resize' else None
vim_id_idx = 4 if action == 'neighboring_window' else 5
vim_id = args[vim_id_idx] if len(args) > vim_id_idx else "n?vim"
if window is None:
return
if is_window_vim(window, vim_id):
for keymap in key_mapping.split(">"):
encoded = encode_key_mapping(window, keymap)
window.write_to_child(encoded)
elif action == 'neighboring_window':
boss.active_tab.neighboring_window(direction)
elif action == 'relative_resize':
relative_resize_window(direction, amount, target_window_id, boss)
+64
View File
@@ -0,0 +1,64 @@
# Based on MIT licensed code at https://github.com/chancez/dotfiles/blob/badc69d3895a6a942285amount26b8c372a55d77533eamount/kitty/.config/kitty/relative_resize.py
from kittens.tui.handler import result_handler
def main(args):
pass
def relative_resize_window(direction, amount, target_window_id, boss):
window = boss.window_id_map.get(target_window_id)
if window is None:
return
neighbors = boss.active_tab.current_layout.neighbors_for_window(window, boss.active_tab.windows)
current_window_id = boss.active_tab.active_window
left_neighbors = neighbors.get('left')
right_neighbors = neighbors.get('right')
top_neighbors = neighbors.get('top')
bottom_neighbors = neighbors.get('bottom')
# has a neighbor on both sides
if direction == 'left' and (left_neighbors and right_neighbors):
boss.active_tab.resize_window('narrower', amount)
# only has left neighbor
elif direction == 'left' and left_neighbors:
boss.active_tab.resize_window('wider', amount)
# only has right neighbor
elif direction == 'left' and right_neighbors:
boss.active_tab.resize_window('narrower', amount)
# has a neighbor on both sides
elif direction == 'right' and (left_neighbors and right_neighbors):
boss.active_tab.resize_window('wider', amount)
# only has left neighbor
elif direction == 'right' and left_neighbors:
boss.active_tab.resize_window('narrower', amount)
# only has right neighbor
elif direction == 'right' and right_neighbors:
boss.active_tab.resize_window('wider', amount)
# has a neighbor above and below
elif direction == 'up' and (top_neighbors and bottom_neighbors):
boss.active_tab.resize_window('shorter', amount)
# only has top neighbor
elif direction == 'up' and top_neighbors:
boss.active_tab.resize_window('taller', amount)
# only has bottom neighbor
elif direction == 'up' and bottom_neighbors:
boss.active_tab.resize_window('shorter', amount)
# has a neighbor above and below
elif direction == 'down' and (top_neighbors and bottom_neighbors):
boss.active_tab.resize_window('taller', amount)
# only has top neighbor
elif direction == 'down' and top_neighbors:
boss.active_tab.resize_window('shorter', amount)
# only has bottom neighbor
elif direction == 'down' and bottom_neighbors:
boss.active_tab.resize_window('taller', amount)
@result_handler(no_ui=True)
def handle_result(args, result, target_window_id, boss):
direction = args[1]
amount = int(args[2])
relative_resize_window(direction, amount, target_window_id, boss)
+11 -5
View File
@@ -1,12 +1,18 @@
def main(args):
from kittens.tui.handler import result_handler
from kitty.boss import Boss
def main(args: list[str]) -> None:
pass
def handle_result(args, answer, target_window_id, boss):
@result_handler(no_ui=True)
def handle_result(
args: list[str], answer: str, target_window_id: int, boss: Boss
) -> None:
w = boss.window_id_map.get(target_window_id)
if w is not None:
if len(args) > 1 and args[1] != 'prev':
if len(args) > 1 and args[1] != "prev":
w.scroll_to_mark(prev=False)
else:
w.scroll_to_mark()
handle_result.no_ui = True
+117 -82
View File
@@ -1,32 +1,42 @@
import json
import re
import subprocess
from gettext import gettext as _
from subprocess import run, PIPE
from pathlib import Path
from kitty import remote_control
from kitty.config import cached_values_for
from subprocess import PIPE, run
from kittens.tui.handler import Handler
from kittens.tui.line_edit import LineEdit
from kittens.tui.loop import Loop
from kittens.tui.operations import (
clear_screen, cursor, set_line_wrapping, set_window_title, styled
clear_screen,
cursor,
set_line_wrapping,
set_window_title,
styled,
)
from kitty.config import cached_values_for
from kitty.key_encoding import EventType
from kitty.typing import KeyEventType, ScreenSize
NON_SPACE_PATTERN = re.compile(r'\S+')
SPACE_PATTERN = re.compile(r'\s+')
SPACE_PATTERN_END = re.compile(r'\s+$')
SPACE_PATTERN_START = re.compile(r'^\s+')
NON_SPACE_PATTERN = re.compile(r"\S+")
SPACE_PATTERN = re.compile(r"\s+")
SPACE_PATTERN_END = re.compile(r"\s+$")
SPACE_PATTERN_START = re.compile(r"^\s+")
NON_ALPHANUM_PATTERN = re.compile(r'[^\w\d]+')
NON_ALPHANUM_PATTERN_END = re.compile(r'[^\w\d]+$')
NON_ALPHANUM_PATTERN_START = re.compile(r'^[^\w\d]+')
ALPHANUM_PATTERN = re.compile(r'[\w\d]+')
NON_ALPHANUM_PATTERN = re.compile(r"[^\w\d]+")
NON_ALPHANUM_PATTERN_END = re.compile(r"[^\w\d]+$")
NON_ALPHANUM_PATTERN_START = re.compile(r"^[^\w\d]+")
ALPHANUM_PATTERN = re.compile(r"[\w\d]+")
def reindex(text, pattern, right=False):
def call_remote_control(args: list[str]) -> None:
subprocess.run(["kitty", "@", *args], capture_output=True)
def reindex(
text: str, pattern: re.Pattern[str], right: bool = False
) -> tuple[int, int]:
if not right:
m = pattern.search(text)
else:
@@ -40,33 +50,37 @@ def reindex(text, pattern, right=False):
return m.span()
SCROLLMARK_FILE = Path(__file__).parent.absolute() / "scroll_mark.py"
class Search(Handler):
def __init__(self, cached_values, window_ids, error=''):
def __init__(
self, cached_values: dict[str, str], window_ids: list[int], error: str = ""
) -> None:
self.cached_values = cached_values
self.window_ids = window_ids
self.error = error
self.line_edit = LineEdit()
last_search = cached_values.get('last_search', '')
last_search = cached_values.get("last_search", "")
self.line_edit.add_text(last_search)
self.text_marked = bool(last_search)
self.mode = cached_values.get('mode', 'text')
self.mode = cached_values.get("mode", "text")
self.update_prompt()
self.mark()
def update_prompt(self):
self.prompt = '~> ' if self.mode == 'regex' else '=> '
def update_prompt(self) -> None:
self.prompt = "~> " if self.mode == "regex" else "=> "
def init_terminal_state(self):
def init_terminal_state(self) -> None:
self.write(set_line_wrapping(False))
self.write(set_window_title(_('Search')))
self.write(set_window_title(_("Search")))
def initialize(self):
def initialize(self) -> None:
self.init_terminal_state()
self.draw_screen()
def draw_screen(self):
def draw_screen(self) -> None:
self.write(clear_screen())
if self.window_ids:
input_text = self.line_edit.current_input
@@ -76,31 +90,46 @@ class Search(Handler):
self.line_edit.current_input = input_text
if self.error:
with cursor(self.write):
self.print('')
for l in self.error.split('\n'):
self.print("")
for l in self.error.split("\n"):
self.print(l)
def refresh(self):
def refresh(self) -> None:
self.draw_screen()
self.mark()
def switch_mode(self):
if self.mode == 'regex':
self.mode = 'text'
def switch_mode(self) -> None:
if self.mode == "regex":
self.mode = "text"
else:
self.mode = 'regex'
self.cached_values['mode'] = self.mode
self.mode = "regex"
self.cached_values["mode"] = self.mode
self.update_prompt()
def on_text(self, text, in_bracketed_paste):
def on_text(self, text: str, in_bracketed_paste: bool = False) -> None:
if self.text_marked:
self.text_marked = False
self.line_edit.clear()
self.line_edit.on_text(text, in_bracketed_paste)
self.refresh()
def on_key(self, key_event):
if self.text_marked and key_event.key not in ['TAB', 'LEFT_CONTROL', 'RIGHT_CONTROL', 'LEFT_ALT', 'RIGHT_ALT', 'LEFT_SHIFT', 'RIGHT_SHIFT', 'LEFT_SUPER', 'RIGHT_SUPER']:
def on_key(self, key_event: KeyEventType) -> None:
if (
self.text_marked
and key_event.type == EventType.PRESS
and key_event.key
not in [
"TAB",
"LEFT_CONTROL",
"RIGHT_CONTROL",
"LEFT_ALT",
"RIGHT_ALT",
"LEFT_SHIFT",
"RIGHT_SHIFT",
"LEFT_SUPER",
"RIGHT_SUPER",
]
):
self.text_marked = False
self.refresh()
@@ -108,16 +137,16 @@ class Search(Handler):
self.refresh()
return
if key_event.matches('ctrl+u'):
if key_event.matches("ctrl+u"):
self.line_edit.clear()
self.refresh()
elif key_event.matches('ctrl+a'):
elif key_event.matches("ctrl+a"):
self.line_edit.home()
self.refresh()
elif key_event.matches('ctrl+e'):
elif key_event.matches("ctrl+e"):
self.line_edit.end()
self.refresh()
elif key_event.matches('ctrl+backspace') or key_event.matches('ctrl+w'):
elif key_event.matches("ctrl+backspace") or key_event.matches("ctrl+w"):
before, _ = self.line_edit.split_at_cursor()
try:
@@ -126,12 +155,12 @@ class Search(Handler):
start = -1
try:
space = before[:start].rindex(' ')
space = before[:start].rindex(" ")
except ValueError:
space = 0
self.line_edit.backspace(len(before) - space)
self.refresh()
elif key_event.matches('ctrl+left') or key_event.matches('ctrl+b'):
elif key_event.matches("ctrl+left") or key_event.matches("ctrl+b"):
before, _ = self.line_edit.split_at_cursor()
try:
start, _ = reindex(before, SPACE_PATTERN_END, right=True)
@@ -139,12 +168,12 @@ class Search(Handler):
start = -1
try:
space = before[:start].rindex(' ')
space = before[:start].rindex(" ")
except ValueError:
space = 0
self.line_edit.left(len(before) - space)
self.refresh()
elif key_event.matches('ctrl+right') or key_event.matches('ctrl+f'):
elif key_event.matches("ctrl+right") or key_event.matches("ctrl+f"):
_, after = self.line_edit.split_at_cursor()
try:
_, end = reindex(after, SPACE_PATTERN_START)
@@ -152,12 +181,12 @@ class Search(Handler):
end = 0
try:
space = after[end:].index(' ') + 1
space = after[end:].index(" ") + 1
except ValueError:
space = len(after)
self.line_edit.right(space)
self.refresh()
elif key_event.matches('alt+backspace') or key_event.matches('alt+w'):
elif key_event.matches("alt+backspace") or key_event.matches("alt+w"):
before, _ = self.line_edit.split_at_cursor()
try:
@@ -178,7 +207,7 @@ class Search(Handler):
self.line_edit.backspace(len(before) - (start + 1))
self.refresh()
elif key_event.matches('alt+left') or key_event.matches('alt+b'):
elif key_event.matches("alt+left") or key_event.matches("alt+b"):
before, _ = self.line_edit.split_at_cursor()
try:
@@ -199,7 +228,7 @@ class Search(Handler):
self.line_edit.left(len(before) - (start + 1))
self.refresh()
elif key_event.matches('alt+right') or key_event.matches('alt+f'):
elif key_event.matches("alt+right") or key_event.matches("alt+f"):
_, after = self.line_edit.split_at_cursor()
try:
@@ -220,84 +249,90 @@ class Search(Handler):
self.line_edit.right(end - 1)
self.refresh()
elif key_event.matches('tab'):
elif key_event.matches("tab"):
self.switch_mode()
self.refresh()
elif key_event.matches('up'):
elif key_event.matches("up"):
for match_arg in self.match_args():
remote_control.main(['', 'kitten', match_arg, str(SCROLLMARK_FILE)])
elif key_event.matches('down'):
call_remote_control(["kitten", match_arg, str(SCROLLMARK_FILE)])
elif key_event.matches("down"):
for match_arg in self.match_args():
remote_control.main(['', 'kitten', match_arg, str(SCROLLMARK_FILE), 'next'])
elif key_event.matches('enter'):
call_remote_control(["kitten", match_arg, str(SCROLLMARK_FILE), "next"])
elif key_event.matches("enter"):
self.quit(0)
elif key_event.matches('esc'):
elif key_event.matches("esc"):
self.quit(1)
def on_interrupt(self):
def on_interrupt(self) -> None:
self.quit(1)
def on_eot(self):
def on_eot(self) -> None:
self.quit(1)
def on_resize(self, new_size):
def on_resize(self, screen_size: ScreenSize) -> None:
self.refresh()
def match_args(self):
return [f'--match=id:{window_id}' for window_id in self.window_ids]
def match_args(self) -> list[str]:
return [f"--match=id:{window_id}" for window_id in self.window_ids]
def mark(self):
def mark(self) -> None:
if not self.window_ids:
return
text = self.line_edit.current_input
if text:
match_case = 'i' if text.islower() else ''
match_case = "i" if text.islower() else ""
match_type = match_case + self.mode
for match_arg in self.match_args():
remote_control.main(['', 'create-marker', match_arg, match_type, '1', text])
try:
call_remote_control(
["create-marker", match_arg, match_type, "1", text]
)
except SystemExit:
self.remove_mark()
else:
self.remove_mark()
def remove_mark(self):
def remove_mark(self) -> None:
for match_arg in self.match_args():
remote_control.main(['', 'remove-marker', match_arg])
call_remote_control(["remove-marker", match_arg])
def quit(self, return_code):
self.cached_values['last_search'] = self.line_edit.current_input
def quit(self, return_code: int) -> None:
self.cached_values["last_search"] = self.line_edit.current_input
self.remove_mark()
if return_code:
for match_arg in self.match_args():
remote_control.main(['', 'scroll-window', match_arg, 'end'])
call_remote_control(["scroll-window", match_arg, "end"])
self.quit_loop(return_code)
def main(args):
try:
remote_control.main(['', 'resize-window', '--self', '--axis=vertical', '--increment', '-100'])
except:
pass
def main(args: list[str]) -> None:
call_remote_control(
["resize-window", "--self", "--axis=vertical", "--increment", "-100"]
)
error = ''
error = ""
if len(args) < 2 or not args[1].isdigit():
error = 'Error: Window id must be provided as the first argument.'
error = "Error: Window id must be provided as the first argument."
window_id = int(args[1])
window_ids = [window_id]
if len(args) > 2 and args[2] == '--all-windows':
ls_output = run(['kitty', '@', 'ls'], stdout=PIPE)
if len(args) > 2 and args[2] == "--all-windows":
ls_output = run(["kitty", "@", "ls"], stdout=PIPE)
ls_json = json.loads(ls_output.stdout.decode())
current_tab = None
for os_window in ls_json:
for tab in os_window['tabs']:
for kitty_window in tab['windows']:
if kitty_window['id'] == window_id:
for tab in os_window["tabs"]:
for kitty_window in tab["windows"]:
if kitty_window["id"] == window_id:
current_tab = tab
if current_tab:
window_ids = [w['id'] for w in current_tab['windows'] if not w['is_focused']]
window_ids = [
w["id"] for w in current_tab["windows"] if not w["is_focused"]
]
else:
error = 'Error: Could not find the window id provided.'
error = "Error: Could not find the window id provided."
loop = Loop()
with cached_values_for('search') as cached_values:
with cached_values_for("search") as cached_values:
handler = Search(cached_values, window_ids, error)
loop.loop(handler)