Last active
August 2, 2025 22:12
-
-
Save smeech/05854b2ebe52fbd4485933f4139609ec to your computer and use it in GitHub Desktop.
[Espanso add] Python script to add Espanso `trigger:`/`replace:` pairs, checking for duplicate triggers #espanso
This file contains hidden or 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
| # Python script to add Espanso trigger:/replace: pairs | |
| # Usage: python espanso_add.py <trigger> <replace> [filename] | |
| import subprocess | |
| import sys | |
| import os | |
| def append_to_file(trigger, replace, filename): | |
| # Set default filename if not provided | |
| if not filename: | |
| filename = "add.yml" | |
| # Set path to the output file | |
| config_path = os.path.expanduser("~/.config/espanso/match/") | |
| output_file = os.path.join(config_path, filename) | |
| # Check if the file exists, if not, create it including "matches:" line | |
| if not os.path.isfile(output_file): | |
| with open(output_file, "w") as file: | |
| file.write("matches:\n") | |
| # Execute espanso match list command and capture its output | |
| try: | |
| output = subprocess.check_output(["espanso", "match", "list"], text=True) | |
| except subprocess.CalledProcessError as e: | |
| print("Error executing espanso command:", e) | |
| sys.exit() | |
| # Check if any line matches the condition | |
| existing_match = None | |
| for line in output.split('\n'): | |
| if line.startswith(trigger + " - "): | |
| existing_match = line | |
| break | |
| # If existing match found, print it and exit | |
| if existing_match: | |
| print("Found existing match for the trigger:") | |
| print(existing_match) | |
| sys.exit() | |
| # Append content to the file | |
| with open(output_file, "a") as file: | |
| file.write(f" - trigger: {trigger}\n") | |
| file.write(f" replace: {replace}\n") | |
| print(f"Content appended successfully to {output_file}.") | |
| if __name__ == "__main__": | |
| # Check if trigger and replace are provided | |
| if len(sys.argv) < 3: | |
| print("Usage: python espanso_add.py <trigger> <replace> [filename]") | |
| sys.exit(1) | |
| trigger = sys.argv[1] | |
| replace = sys.argv[2] | |
| filename = sys.argv[3] if len(sys.argv) > 3 else None | |
| append_to_file(trigger, replace, filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment