Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Runs the last-modified script (if its format is a runner_map key) found in search_dir in the event of an esc key press followed by a tab key press.
- # Meant to be used alongside Vim, mapping a tab press while on normal mode to :w or :update using vimscript (e.g. nnoremap <buffer> <tab> :w <CR>).
- import os
- import subprocess
- from time import time, sleep
- from pynput import keyboard
- search_dir = "/home/tomo/Documents"
- runner_map = {"py": lambda path: f"time python -u '{path}'",
- "hs": lambda path: f"time runghc '{path}'",}
- def path_to_last_mod_in_dir(search_dir: str, file_formats: list[str]) -> str:
- fmt_regex = r".*\.\(" + r"\|".join(file_formats) + r"\)"
- find_cmd = ["find", search_dir, "-regex", fmt_regex]
- path_list = subprocess.run(find_cmd, stdout=subprocess.PIPE).stdout.decode("utf-8").split("\n")[:-1]
- return sorted(path_list, key = os.path.getmtime)[-1]
- def run_file(path: str, runner_map: dict, print_timestamp: bool = False) -> None:
- fmt = path.split(".")[-1]
- if print_timestamp: os.system("printf '\n--- %(%H:%M:%S)T ---\n\n'")
- if path != os.path.abspath(__file__): os.system(runner_map[fmt](path))
- def on_press(key):
- global pressed_esc
- global search_dir
- global runner_map
- global path
- if pressed_esc and key == keyboard.Key.tab:
- sleep(1) # Waits for Vim to finish saving
- if not path or os.path.getmtime(path) < time() - 10:
- path = path_to_last_mod_in_dir(search_dir, runner_map.keys())
- run_file(path, runner_map, print_timestamp=True)
- pressed_esc = key == keyboard.Key.esc
- path = ""
- pressed_esc = False
- k_listener = keyboard.Listener(on_press = on_press)
- k_listener.start()
- while True: pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement