from talon import Context, Module, actions, settings ctx = Context() mod = Module() ctx.matches = r""" tag: user.terraform """ types = { "string": "string", "number": "number", "bool": "bool", "list": "list", "map": "map", "null": "null" } ctx.lists["user.code_type"] = types common_properties = { "name": "name", "type": "type", "description": "description", "default": "default", "for each": "for_each", "count": "count", "prevent destroy": "prevent_destroy", "nullable": "nullable", "sensitive": "sensitive", "depends on": "depends_on", "provider": "provider",
'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', ] selection_map = {n: i for i, n in enumerate(selection_numbers)} mod = Module() ctx = Context() mod.list('file_manager_directory_index', desc='number -> directory name') mod.list('file_manager_file_index', desc='number -> file name') mod.list('file_manager_directory_remap', desc='list of titles remapped to the absolute path') mod.list( 'file_manager_directory_exclusions', desc= 'list of titles that are excluded/disabled from the picker functionality') mod.setting('file_manager_auto_show_pickers', type=int, default=0, desc="Enable to show the file/directories pickers automatically")
from dataclasses import dataclass from typing import Dict, Generic, List, Mapping, Optional, TypeVar from collections import defaultdict import itertools from talon import actions, registry from talon import Context, Module, app, imgui, ui, fs import re from .extensions import file_extensions from .numbers import digits_map from .abbreviate import abbreviations mod = Module() # TODO: 'Whats application': 'WhatsApp' (Should keep "whats app" as well?) # TODO: 'V O X': 'VOX' (should keep "VOX" as well?) # Could handle by handling all alternatives for these, or by having hardcoded list of things that we want to handle specially DEFAULT_MINIMUM_TERM_LENGTH = 3 SMALL_WORD = r"[A-Z]?[a-z]+" # TODO: We want "AXEvery" to be ["AX", "Every"] UPPERCASE_WORD = r"[A-Z]+" FILE_EXTENSIONS_REGEX = "|".join( re.escape(file_extension) for file_extension in file_extensions.values()) DIGITS_REGEX = r"\d" FULL_REGEX = re.compile("|".join([ DIGITS_REGEX, FILE_EXTENSIONS_REGEX, SMALL_WORD,
from talon import Module module = Module() module.tag( "free_dictation", "Enable this tag when dictation should be a top-level operation.", )
from typing import Set from talon import Module, Context, actions, app import sys default_alphabet = "air bat cap drum each fine gust harp sit jury crunch look made near odd pit quench red sun trap urge vest whale plex yank zip".split( " ") letters_string = "abcdefghijklmnopqrstuvwxyz" default_digits = "zero one two three four five six seven eight nine".split(" ") numbers = [str(i) for i in range(10)] default_f_digits = "one two three four five six seven eight nine ten eleven twelve".split( " ") mod = Module() mod.list("letter", desc="The spoken phonetic alphabet") mod.list("symbol_key", desc="All symbols from the keyboard") mod.list("arrow_key", desc="All arrow keys") mod.list("number_key", desc="All number keys") mod.list("modifier_key", desc="All modifier keys") mod.list("function_key", desc="All function keys") mod.list("special_key", desc="All special keys") mod.list("punctuation", desc="words for inserting punctuation into text") @mod.capture(rule="{self.modifier_key}+") def modifiers(m) -> str: "One or more modifier keys" return "-".join(m.modifier_key_list)
from talon import Context, Module, speech_system, actions speech = actions.speech module = Module() @module.action_class class Actions: def sleep(): """Sleep speech recognition.""" speech.disable() def wake(): """Wake speech recognition.""" speech.enable() def engine_mimic(phrase: str): """Force the engine to mimic a phrase""" speech_system.engine_mimic(phrase) dragon_context = Context("user.dragon_context") dragon_context.matches = r""" tag: user.dragon """ @dragon_context.action_class("self") class DragonActions: def sleep():
from talon import Context, Module mod = Module() ctx = Context() mod.list('latex-prefix', desc='Prefix for all latex commands') ctx.lists['self.latex-prefix'] = ["lad"] mod.list('small-greek-prefix', desc='Prefix for latex Greek letters') ctx.lists['self.small-greek-prefix'] = ["greeky"]
from talon import Context, Module, app, imgui, ui, fs, actions from glob import glob from itertools import islice from pathlib import Path import subprocess # Construct at startup a list of overides for application names (similar to how homophone list is managed) # ie for a given talon recognition word set `one note`, recognized this in these switcher functions as `ONENOTE` # the list is a comma seperated `<Recognized Words>, <Overide>` # TODO: Consider put list csv's (homophones.csv, app_name_overrides.csv) files together in a seperate directory,`knausj_talon/lists` cwd = os.path.dirname(os.path.realpath(__file__)) overrides_directory = os.path.join(cwd, "app_names") override_file_name = f"app_name_overrides.{talon.app.platform}.csv" override_file_path = os.path.join(overrides_directory, override_file_name) mod = Module() mod.list("running", desc="all running applications") mod.list("launch", desc="all launchable applications") ctx = Context() # a list of the current overrides overrides = {} # a list of the currently running application names running_application_dict = {} mac_application_directories = [ "/Applications", "/Applications/Utilities", "/System/Applications", "/System/Applications/Utilities",
import re from talon import Context, Module, actions, settings mod = Module() ctx = Context() ctx.matches = r""" tag: user.python """ ctx.lists["user.code_common_function"] = { "enumerate": "enumerate", "integer": "int", "length": "len", "list": "list", "print": "print", "range": "range", "set": "set", "split": "split", "string": "str", "update": "update", } """a set of fields used in python docstrings that will follow the reStructuredText format""" docstring_fields = { "class": ":class:", "function": ":func:", "parameter": ":param:", "raise": ":raise:", "returns": ":return:", "type": ":type:", "return type": ":rtype:",
import glob import os import pathlib import subprocess import sys from typing import List, Set from talon import Context, Module, actions, app, fs, imgui, settings, ui from talon_init import TALON_HOME mod = Module() mod.mode("replay_picker_open") class _RecordingReplayer(object): """A class that manages finding the most recent recordings, in making them available for replay""" def __init__(self, count=10): """Specify the number of default recording to list in the picker""" self.count = count self.recordings = pathlib.Path(TALON_HOME, "recordings/") if settings.get("speech.record_all") != 1: app.notify("Recording appears to be disabled") def last_recordings(self) -> List: """Checks the last number of recordings from the recording directory, :returns: a list of the most recent self.count recordings :rtype: List """ list_of_files = sorted(self.recordings.iterdir(), key=os.path.getmtime)
from typing import Set from talon import Module, Context, actions import sys default_alphabet = "air bat cap drum each fine gust harp sit jury crunch look made near odd pit quench red sun trap urge vest whale plex yank zip".split( " ") letters_string = "abcdefghijklmnopqrstuvwxyz" default_digits = "zero one two three four five six seven eight nine".split(" ") numbers = [str(i) for i in range(10)] default_f_digits = "one two three four five six seven eight nine ten eleven twelve".split( " ") mod = Module() mod.list("letter", desc="The spoken phonetic alphabet") mod.list("symbol_key", desc="All symbols from the keyboard") mod.list("arrow_key", desc="All arrow keys") mod.list("number_key", desc="All number keys") mod.list("modifier_key", desc="All modifier keys") mod.list("function_key", desc="All function keys") mod.list("special_key", desc="All special keys") @mod.capture def modifiers(m) -> str: "One or more modifier keys" @mod.capture def arrow_key(m) -> str:
from talon import imgui, Module, speech_system, actions, app # We keep command_history_size lines of history, but by default display only # command_history_display of them. mod = Module() setting_command_history_size = mod.setting("command_history_size", int, default=50) setting_command_history_display = mod.setting( "command_history_display", int, default=10 ) hist_more = False history = [] def parse_phrase(word_list): return " ".join(word.split("\\")[0] for word in word_list) def on_phrase(j): global history try: val = parse_phrase(getattr(j["parsed"], "_unmapped", j["phrase"])) except: val = parse_phrase(j["phrase"]) if val != "": history.append(val) history = history[-setting_command_history_size.get() :]
from talon import Module from ..primitive_target import BASE_TARGET mod = Module() mod.list("cursorless_swap_action", desc="Cursorless swap action") mod.list( "cursorless_swap_connective", desc="The connective used to separate swap targets", ) @mod.capture(rule=( "[<user.cursorless_target>] {user.cursorless_swap_connective} <user.cursorless_target>" )) def cursorless_swap_targets(m) -> list[dict]: target_list = m.cursorless_target_list if len(target_list) == 1: target_list = [BASE_TARGET] + target_list return target_list
from talon import Context, Module ctx = Context() mod = Module() mod.tag("code_operators_bitwise", desc="Tag for enabling bitwise operator commands") @mod.action_class class Actions: def code_operator_bitwise_and(): """code_operator_bitwise_and""" def code_operator_bitwise_or(): """code_operator_bitwise_or""" def code_operator_bitwise_exclusive_or(): """code_operator_bitwise_exclusive_or""" def code_operator_bitwise_left_shift(): """code_operator_bitwise_left_shift""" def code_operator_bitwise_right_shift(): """code_operator_bitwise_right_shift"""
from talon import Context, Module ctx = Context() mod = Module() mod.tag( "code_imperative", desc= "Tag for enabling basic imperative programming commands (loops, functions, etc)", ) @mod.action_class class Actions: def code_block(): """Inserts equivalent of {\n} for the active language, and places the cursor appropriately""" def code_state_if(): """Inserts if statement""" def code_state_else_if(): """Inserts else if statement""" def code_state_else(): """Inserts else statement""" def code_state_do(): """Inserts do statement""" def code_state_switch(): """Inserts switch statement"""
'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', ] selection_map = {n: i for i, n in enumerate(selection_numbers)} mod = Module() ctx = Context() mod.list('file_manager_directory_remap', desc='list of titles remapped to the absolute path') mod.list( 'file_manager_directory_exclusions', desc= 'list of titles that are excluded/disabled from the picker functionality') setting_auto_show_pickers = mod.setting( 'file_manager_auto_show_pickers', type=int, default=0, desc="Enable to show the file/directories pickers automatically") setting_folder_limit = mod.setting( 'file_manager_folder_limit',
"snake": formatters_dict["SNAKE_CASE"], "convoy": formatters_dict["UPSNAKE_CASE"], # "speak": formatters_dict["NOOP"], # "string": formatters_dict["SINGLE_QUOTED_STRING"], "title": formatters_dict["CAPITALIZE_ALL_WORDS"], # disable a few formatters for now # "tree": formatters_dict["FIRST_THREE"], # "quad": formatters_dict["FIRST_FOUR"], # "fiver": formatters_dict["FIRST_FIVE"], } all_formatters = {} all_formatters.update(formatters_dict) all_formatters.update(formatters_words) mod = Module() mod.list("formatters", desc="list of formatters") mod.list( "prose_formatter", desc="words to start dictating prose, and the formatter they apply", ) @mod.capture(rule="{self.formatters}+") def formatters(m) -> str: "Returns a comma-separated string of formatters e.g. 'SNAKE,DUBSTRING'" return ",".join(m.formatters_list) @mod.capture( # Note that if the user speaks something like "snake dot", it will
from talon import speech_system, ui, cron, registry, Module in_command_context = False mod = Module() mod.tag("command_mode") def check_context(): global in_command_context if speech_system.engine and speech_system.engine.name == "dragon": if "user.command_mode" in registry.tags: if in_command_context: return speech_system.engine_mimic("switch to command mode") in_command_context = True else: if not in_command_context: return speech_system.engine_mimic("switch to normal mode") in_command_context = False cron.interval("1s", check_context)
90: "times ninety", } tens_words = "zero ten twenty thirty forty fifty sixty seventy eighty ninety".split( ) # dictionaries map multiplier words into their corresponding numbers. multiplier_numbers = {} multiplier_small = {} for n in range(1, 100): if n in multiplier_words: word = multiplier_words[n] if n <= 20: multiplier_small[word] = n multiplier_numbers[word] = n mod = Module() ctx = Context() mod.list("multipliers", desc="list of multipliers") mod.list("multipliers_small", desc="list of multipliers small (1-20)") ctx.lists["self.multipliers"] = multiplier_numbers.keys() ctx.lists["self.multipliers_small"] = multiplier_small.keys() @mod.capture(rule="{self.multipliers}") def multipliers(m) -> int: """Returns a single ordinal as a digit""" return int(multiplier_numbers[m[0]]) @mod.capture(rule="{self.multipliers_small}")
from talon import app, Module, Context, actions, ui, imgui from talon.voice import Capture import re import time import os import platform app_cache = {} overrides = {'grip': 'DataGrip', 'term': 'iTerm2'} mod = Module() mod.list('running', desc='all running applications') mod.list('launch', desc='all launchable applications') @mod.capture def running_applications(m) -> str: "Returns a single application name" @mod.capture def launch_applications(m) -> Capture: "Returns a single application name" ctx = Context() @ctx.capture(rule='{self.running}') def running_applications(m): return m.running
from .user_settings import get_list_from_csv from talon import Module, Context from urllib.parse import quote_plus import webbrowser mod = Module() mod.list("website", desc="A website.") mod.list( "search_engine", desc="A search engine. Any instance of %s will be replaced by query text", ) website_defaults = { "amazon": "https://www.amazon.com/", "dropbox": "https://dropbox.com/", "google": "https://www.google.com/", "google calendar": "https://calendar.google.com", "google maps": "https://maps.google.com/", "google scholar": "https://scholar.google.com/", "gmail": "https://mail.google.com/", "github": "https://github.com/", "gist": "https://gist.github.com/", "wikipedia": "https://en.wikipedia.org/", "youtube": "https://www.youtube.com/", } _search_engine_defaults = { "amazon": "https://www.amazon.com/s/?field-keywords=%s", "google": "https://www.google.com/search?q=%s", "map": "https://maps.google.com/maps?q=%s", "scholar": "https://scholar.google.com/scholar?q=%s",
from talon import Module, Context mod = Module() mod.list("types", desc="Typescript Commands") ctx = Context() ctx.matches = r""" mode: user.typescript mode: user.auto_lang and code.language: typescript """ # tbd ctx.lists["user.code_functions"] = { "integer": "int.TryParse", "print": "Console.WriteLine", "string": ".ToString", "log": "console.log", } ctx.lists["user.types"] = { "number": "number", "string": "string", } @ctx.action_class("user") class UserActions: def code_is_not_null(): actions.auto_insert(" !== null") def code_is_null(): actions.auto_insert(" === null")
from talon import Context, Module, actions, app, imgui, registry, settings ctx = Context() mod = Module() mod.list("code_functions", desc="List of functions for active language") mod.list("code_types", desc="List of types for active language") mod.list("code_libraries", desc="List of libraries for active language") setting_private_function_formatter = mod.setting( "code_private_function_formatter", str) setting_protected_function_formatter = mod.setting( "code_protected_function_formatter", str) setting_public_function_formatter = mod.setting( "code_public_function_formatter", str) setting_private_variable_formatter = mod.setting( "code_private_variable_formatter", str) setting_protected_variable_formatter = mod.setting( "code_protected_variable_formatter", str) setting_public_variable_formatter = mod.setting( "code_public_variable_formatter", str) mod.tag("code_comment", desc="Tag for enabling generic comment commands") mod.tag("code_block_comment", desc="Tag for enabling generic block comment commands") mod.tag("code_operators", desc="Tag for enabling generic operator commands") mod.tag( "code_generic", desc= "Tag for enabling other basic programming commands (loops, functions, etc)", )
from talon import Context, Module from .user_settings import get_list_from_csv mod = Module() ctx = Context() mod.list("vocabulary", desc="additional vocabulary words") # Default words that will need to be capitalized (particularly under w2l). # NB. These defaults and those later in this file are ONLY used when # auto-creating the corresponding settings/*.csv files. Those csv files # determine the contents of user.vocabulary and dictate.word_map. Once they # exist, the contents of the lists/dictionaries below are irrelevant. _capitalize_defaults = [ "I", "I'm", "I've", "I'll", "I'd", "Monday", "Mondays", "Tuesday", "Tuesdays", "Wednesday", "Wednesdays", "Thursday", "Thursdays", "Friday", "Fridays", "Saturday", "Saturdays",
from talon import Context, Module, actions, settings mod = Module() mod.setting( "use_stdint_datatypes ", type=int, default=1, desc="Use the stdint datatype naming in commands by default", ) ctx = Context() ctx.matches = r""" mode: user.c mode: user.auto_lang and code.language: c """ ctx.lists["self.c_pointers"] = { "pointer": "*", "pointer to pointer": "**", } ctx.lists["self.stdint_signed"] = { "signed": "", "unsigned": "u", } ctx.lists["self.c_signed"] = { "signed": "signed ", "unsigned": "unsigned ", }
# XXX - would be nice to be able pipe these through formatters from talon import Context, Module mod = Module() mod.list("abbreviation", desc="Common abbreviation") ctx = Context() ctx.lists["user.abbreviation"] = { "address": "addr", "administrator": "admin", "administrators": "admins", "advance": "adv", "advanced": "adv", "alberta": "ab", "alternative": "alt", "application": "app", "applications": "apps", "argument": "arg", "arguments": "args", "as far as i can tell": "afaict", "as far as i know": "afaik", "assembly": "asm", "at the moment": "atm", "attribute": "attr", "attributes": "attrs", "authenticate": "auth", "authentication": "auth", "away from keyboard": "afk", "binary": "bin", "boolean": "bool",
"smash": formatters_dict["NO_SPACES"], "snake": formatters_dict["SNAKE_CASE"], # "speak": formatters_dict["NOOP"], "string": formatters_dict["SINGLE_QUOTED_STRING"], "title": formatters_dict["CAPITALIZE_ALL_WORDS"], # disable a few formatters for now # "tree": formatters_dict["FIRST_THREE"], # "quad": formatters_dict["FIRST_FOUR"], # "fiver": formatters_dict["FIRST_FIVE"], } all_formatters = {} all_formatters.update(formatters_dict) all_formatters.update(formatters_words) mod = Module() mod.list("formatters", desc="list of formatters") @mod.capture(rule="{self.formatters}+") def formatters(m) -> str: "Returns a comma-separated string of formatters e.g. 'SNAKE,DUBSTRING'" return ",".join(m.formatters_list) @mod.capture( # Note that if the user speaks something like "snake dot", it will # insert "dot" - otherwise, they wouldn't be able to insert punctuation # words directly. rule="<self.formatters> <user.text> (<user.text> | <user.formatter_immune>)*" )
) def number_scaled(m): return fuse_num(fuse_scale(fuse_num(fuse_scale(list(m), 3))))[0] # This rule offers more colloquial number speaking when combined with a command # like: "go to line <number>" # Example: " one one five " == 115 # " one fifteen " == 115 # " one hundred and fifteen " == 115 @ctx.capture("number", rule=f"(<digits> | [<digits>] <user.number_scaled>)") def number(m): return int("".join(str(i) for i in list(m))) @ctx.capture("number_signed", rule=f"[negative] <number>") def number_signed(m): number = m[-1] if m[0] == "negative": return -number return number mod = Module() mod.list("number_scaled", desc="Mix of numbers and digits") @mod.capture def number_scaled(m) -> str: "Returns a series of numbers as a string"
from talon import Context, Module, actions, app ctx = Context() mod = Module() key = actions.key extension_lang_map = { ".asm": "assembly", ".bat": "batch", ".c": "c", ".cmake": "cmake", ".cpp": "cplusplus", ".cs": "csharp", ".gdb": "gdb", ".go": "go", ".h": "c", ".hpp": "cplusplus", ".ipynb": "python", ".java": "java", ".js": "javascript", ".jsx": "javascript", ".json": "json", ".lua": "lua", ".md": "markdown", ".pl": "perl", ".ps1": "powershell", ".py": "python", ".r": "r", ".R": "r", ".rb": "ruby", ".s": "assembly",
from collections import defaultdict import itertools import math from typing import Dict, List, Iterable, Set, Tuple, Union from talon import Module, Context, actions, imgui, Module, registry, ui, app from talon.grammar import Phrase mod = Module() mod.list("help_contexts", desc="list of available contexts") mod.mode("help", "mode for commands that are available only when help is visible") setting_help_max_contexts_per_page = mod.setting( "help_max_contexts_per_page", type=int, default=20, desc="Max contexts to display per page in help", ) setting_help_max_command_lines_per_page = mod.setting( "help_max_command_lines_per_page", type=int, default=50, desc="Max lines of command to display per page in help", ) ctx = Context() # context name -> commands context_command_map = {} # rule word -> Set[(context name, rule)] rule_word_map: Dict[str, Set[Tuple[str, str]]] = defaultdict(set)