← Keyhac crftwr/keyhac on GitHub · craftware

API reference

Every class and function a config.py can reach, generated from the docstrings. It answers “what are the arguments of X”; for “how do I do Y”, read Configuration first — it introduces these APIs in the order you meet them, with worked examples.

An entry opening with “Preview” may change in any release. One opening with “Deprecated” still works, says what replaces it, and goes in a later major release. PREVIEW_APIS and DEPRECATED_APIS list them.

Contents: Keymap · KeyTable · KeyCondition · FocusCondition · InputContext · Focus · KeyEvent · Window · ThreadedAction · InputText · LaunchApplication · ActivateApplication · ActivateWindow · MoveWindow · SnapWindow · MouseMove · MouseButtonDown · MouseButtonUp · MouseButtonClick · MouseWheel · MouseHorizontalWheel · StartRecordingKeys · StopRecordingKeys · ToggleRecordingKeys · PlaybackRecordedKeys · ClipboardHistory · ChooserAction · ShowCandidates · Candidate · CandidatePreview · CandidateSource · CallableSource · ChooserPage · ActionsSource · ApplicationsSource · BrowserBookmarksSource · BrowserTabsSource · ClipboardHistorySource · KeyBindingsSource · MenuItemsSource · WindowControlsSource · SnippetsSource · ClipboardToolsSource · ShowClipboardHistory · ShowClipboardSnippets · ShowClipboardTools · DateTimeSnippet · getLogger · Console · ReportCaretAnchor

class Keymap

Manages key tables and executes key action translations.

One Keymap exists per Keyhac process. The configuration file receives it as configure(keymap)’s argument; code outside configure() reaches the same object through Keymap.get_instance().

Attributes:


property Keymap.clipboard

The OS clipboard - get_text() / set_text(), or None if unwired.

The history’s provider, exposed directly because actions that paste need to read and restore the clipboard around what they do, which is not a history operation.

Safe from ThreadedAction.run(): the provider puts each call on the event-loop thread itself. It has to - NSPasteboard segfaults when it is touched from a worker, and this is the one API that is handed to actions precisely so they can call it from one. A call raises WaitTimeout if the loop is blocked, where it used to take the process down.


property Keymap.clipboard_history

The ClipboardHistory object (None while running without one, e.g. under –no-ui).


property Keymap.config_path

The configuration script this run loads.

lazydocs: ignore


property Keymap.extensions_dir

extensions/ beside config.py: on sys.path, and re-imported on every reload.

lazydocs: ignore


property Keymap.focus

Portable snapshot of the current keyboard focus (a Focus), or None before the first key event.

Always the real focus. While a chooser is open the key tables are matched against the chooser instead (see define_keytable), but this stays the application underneath - the one a paste, a window move or an IME change acts on.


property Keymap.ui

The action-facing UI API - see doc/action-api.md.

Reading and driving another application’s elements: finding windows, searching trees, waiting for the screen to change, filling fields. Deliberately a separate namespace from the configuration API, and deliberately method-style, so from keyhac import * does not acquire a dozen generic verbs that only mean something inside an action.


method Keymap.call_on_main_thread

call_on_main_thread(callback) → None

Run a callback on the thread that owns the event loop.

Thread-safe. Keyhac’s own API does not need it from a worker - elements, windows and the verbs run on the calling thread, and what cannot takes itself to the loop - so this is for a platform call of your own that must run on the event-loop thread, or for touching Keyhac’s own UI.

Args:

Note:

With no loop wired - Keyhac used as a library, or under test - the callback runs inline on the calling thread, which is what the code did everywhere before a dispatcher existed.


method Keymap.configure

configure() → bool

Load (or reload) the configuration file and rebuild the keymap.

A configuration that fails to load leaves the previous keymap active and reports the traceback to the console.

Returns: True when the configuration loaded, False when it failed and the previous keymap was kept.


method Keymap.define_keytable

define_keytable(
    name: str = None,
    focus_path_pattern: str = None,
    custom_condition_func: Callable[[keyhac.platform.base.Focus], bool] = None,
    app: str = None,
    title: str = None,
    class_name: str = None
) → KeyTable

Define a key table.

With any focus condition (focus_path_pattern / app / title / class_name / custom_condition_func) the table is added to the keymap and activates automatically whenever the condition is met. Every matching table is active at once, merged in definition order, so a table defined later overrides exactly the keys it binds.

With no condition the table is not added to the keymap: assign it to a key to make that key a multi-stroke prefix.

Args:

Returns: The KeyTable created.

Note:

app, title and class_name patterns are case-insensitive, take fnmatch wildcards (, ?, []) and “|” alternation, and all the conditions given must match. focus_path_pattern is re-evaluated on every key event, so focus moving *inside one window - an item in a list, a tab, a field on a Chromium / Electron / WPF / WinUI page - selects the table it should. While the application in front is not responding, the path is the window-level one until it answers again. While a chooser popup is open (ShowClipboardHistory, ShowCandidates, …), the conditions are checked against the chooser rather than the application underneath: app_name “Keyhac”, window_title “Chooser”, path “/Keyhac/Chooser”. A table that applies everywhere - focus_path_pattern="*" - applies there too, so a remap such as “Ctrl-J” to “Down” moves the selection; a table defined with app="Keyhac", title="Chooser" applies only there. Keys no table binds keep their usual meaning in the chooser. keymap.focus stays the application underneath.


method Keymap.define_modifier

define_modifier(key: str | int, mod: str | int) → None

Define a user modifier key.

While defined, the key loses its original meaning entirely: a User0..User3 modifier is never emitted, so assignments hanging off it cannot collide with anything an application understands.

A Windows key cannot be one, and the call is refused with an error in the log. Defining it does not take the key away from the OS: Keyhac consumes the key-down, so no application ever receives it and the Start menu stays shut, but anything watching the keyboard ahead of Keyhac still sees the physical key held - the Xbox Game Bar opens on Win+G either way, and it swallows that keystroke, including one Keyhac itself injected. A modifier that is invisible to applications but not to the shell is not what this promises, so it is not offered.

Any other key may be redefined, including one that already is a modifier - define_modifier("RAlt", "RUser0") works - but prefer a key that is not one: the key stops being Alt (or Ctrl, or Shift) for everything, everywhere, and that is a large thing to give up by accident. Redefining a modifier is noted in the log.

Args:


method Keymap.edit_config

edit_config() → None

Open the configuration file in a text editor.

keymap.editor chooses the editor: an application name or path the OS can resolve, or a callable receiving the config path. Left empty, a platform default is used (Visual Studio Code / Xcode / TextEdit on macOS, Notepad on Windows). The tray menu’s “Edit Config” item calls this.


method Keymap.find_window

find_window(app: str = None, title: str = None, class_name: str = None)

Find the first visible window matching the given patterns.

Matching is exactly define_keytable’s: case-insensitive, fnmatch wildcards, “ ” alternation, “.exe” optional, and all the conditions given must match.

Args:

Returns: A Window, or None when nothing matches.

Note:

Safe from any thread. Keyhac’s own windows never match.


method Keymap.get_active_window

get_active_window()

Get the frontmost window.

Returns: A Window, or None when there is none (or the platform has no window support).

Note:

Safe from any thread. Keyhac’s own windows do not exist here: with one of them in front, this answers None.


method Keymap.get_ime_status

get_ime_status() → bool | None

Get whether the IME is on for whatever holds the input focus.

There is no window argument on purpose: macOS can only ever address the current input source, so naming a window would mean two different contracts on the two OSes.

Returns: True when the IME is on, False when it is off, or None when the state cannot be determined - no IME is installed or reachable, or (Windows) a TSF-only IME does not answer the IMM32 query.

Note:

Safe from any thread; it is taken to the event-loop thread, where macOS’s input-source API has to run. “Off” is the same answer for two different situations, on both OSes: an IME that is installed and closed, and no IME in the picture at all - a plain keyboard layout on Windows, a plain layout or an input method’s Roman mode on macOS.


method Keymap.get_input_context

get_input_context(replay: bool = False) → InputContext

Get a key input context to send a batch of virtual key events.

with keymap.get_input_context() as ctx:
     ctx.send_key("Ctrl-C")

Args:

Returns: An InputContext, to be used as a context manager.


method Keymap.get_instance

get_instance() → Keymap

Get the Keymap singleton.

Returns: The Keymap instance, or None before one has been created.


method Keymap.list_windows

list_windows() → list

List the visible top-level windows.

Returns: Window objects, front-most first where the OS says so.

Note:

Safe from any thread. Keyhac’s own windows are not listed.


method Keymap.reload_config

reload_config() → None

Reload the configuration file.

The keyhac-win name for configure(), kept because configurations and documentation refer to it. The tray menu’s “Reload Config” item calls this.


method Keymap.replace_key

replace_key(src: str | int, dst: str | int) → None

Replace a key with a different key.

The substitution runs before everything else, so the rest of the configuration only ever sees dst.

Args:


method Keymap.screen_frames

screen_frames() → list

Get the frame of every screen.

Returns: One (x, y, w, h) tuple per screen, primary first, in the shared top-left-origin coordinate space.

Note:

Thread-safe - callable from a ThreadedAction.run().


method Keymap.screen_work_frames

screen_work_frames() → list

Get the work area of every screen.

Returns: screen_frames() minus the menu bar and Dock (macOS) or the taskbar (Windows), in the same order.

Note:

Safe from any thread. The macOS implementation is an AppKit query, so it is taken to the event-loop thread.


method Keymap.set_ime_status

set_ime_status(on: bool) → bool

Turn the IME on or off for whatever holds the input focus.

Args:

Returns: Whether the requested state was actually reached - the result is read back rather than assumed, so False means the IME declined or there was none to ask.

Note:

Safe from any thread, like get_ime_status(). It takes effect at once - unlike key output, which InputContext only queues for the application. Wrapping a send_key batch in “off … back on” therefore does not work: the restore lands before the keys do and they are composed anyway. Use InputContext.send_text for literal text, which the IME does not intercept. The two OSes differ in how far “on” reaches: macOS selects a Japanese input source even from a US layout, while Windows only opens an IME that the focused window is already typing under - asking for “on” while a plain layout like en-US is active returns False rather than switching the input language, which is the user’s own Win+Space to give. Whether a change also affects other applications is the user’s OS setting (“Let me use a different input method for each app window” on Windows, “Automatically switch to a document’s input source” on macOS), not something Keyhac decides.


method Keymap.window_frames

window_frames() → list

Get the frames of all normal on-screen windows.

Returns: One (x, y, w, h) tuple per window, in the same coordinate space as screen_frames().

Note:

Thread-safe, and cheaper than list_windows(): no window is asked anything.


class KeyTable

Dict-like table assigning input key conditions to output actions.

Subscript it with a key expression to bind a key. Values may be:

keymap.define_keytable() creates them.

kt["Fn-J"] = "Left"                  # key -> key
kt["Fn-N"] = "Cmd-1", "Cmd-2"        # key -> sequence
kt["Fn-A"] = some_callable           # key -> function / action object
kt["Ctrl-X"] = kt_ctrlx              # key -> multi-stroke table

Attributes:


class KeyCondition

A single key stroke condition - the parsed form of a key expression.

Assigning to a key table parses the expression for you, so configurations rarely build one directly; KeyCondition.from_str() is the way in when they do.

Attributes:


method KeyCondition.from_str

from_str(s: str) → KeyCondition

Parse a key expression.

Args:

Returns: The KeyCondition it describes.

Raises:


class FocusCondition

Condition deciding whether a key table is active for the current focus.

keymap.define_keytable() builds one from the focus arguments it is given, so configurations do not normally construct it themselves.

All specified conditions must match (AND). Within app/title/ class_name patterns, “ ” separates alternatives (OR) and fnmatch wildcards (*, ?, []) are available.

app, title, class_name and focus_path_pattern are all re-evaluated on every key event - see define_keytable().

method FocusCondition.__init__

__init__(
    focus_path_pattern: str = None,
    custom_condition_func: Callable[[keyhac.platform.base.Focus], bool] = None,
    app: str = None,
    title: str = None,
    class_name: str = None
)

Build a focus condition.

Args:


class InputContext

A context manager to send virtual key strokes.

Key events are accumulated and sent as one batch when the context exits. Physically held modifiers are released around the batch and restored afterwards, so ctx.send_key("Ctrl-C") works even while the modifiers of the binding that triggered it are still down.

Sending is where the batch ends, not where it arrives: the events are queued for the application to pick up later. So anything the action does after the context exits - changing the IME state, activating another window - takes effect while the keys are still in flight, and lands first. keymap.set_ime_status(False) around a send_key batch is the trap this makes: the matching restore wins the race and the keys are composed by the IME after all. Send literal text with send_text(), which the IME does not intercept, and leave IME changes standing rather than undoing them in the same action.

keymap.get_input_context() creates one. It is safe to use from a ThreadedAction worker thread.

with keymap.get_input_context() as ctx:
     ctx.send_key("Cmd-Left")
     ctx.send_key("Cmd-Shift-Right")

method InputContext.send_key

send_key(s: str) → None

Send a key stroke from a key expression.

Args:

Raises:


method InputContext.send_key_by_vk

send_key_by_vk(vk: int, down: bool = True) → None

Send a key stroke by virtual key code.

Args:

Raises:


method InputContext.send_mouse_button

send_mouse_button(button: str = 'left', down: bool | None = None) → None

Press, release or click a mouse button.

Held modifiers are released first and restored when the context exits, so a modifier-bound click does not turn into a modified click (keyhac-win behavior).

Args:

Raises:


method InputContext.send_mouse_horizontal_wheel

send_mouse_horizontal_wheel(notches: float) → None

Turn the horizontal mouse wheel.

Args:

Raises:


method InputContext.send_mouse_move

send_mouse_move(dx: int, dy: int) → None

Move the mouse cursor by a relative offset.

Injected as an absolute position, so pointer acceleration cannot distort the distance. Unlike buttons and wheels, held modifiers stay held (keyhac-win behavior).

Args:

Raises:


method InputContext.send_mouse_wheel

send_mouse_wheel(notches: float) → None

Turn the vertical mouse wheel.

Held modifiers are released first, like send_mouse_button.

Args:

Raises:


method InputContext.send_text

send_text(s: str) → None

Type a literal string, whatever characters it holds.

Like an unmodified send_key, held modifiers are released first (and restored when the context exits) - otherwise e.g. a physically held Fn turns the injected keystrokes into macOS system shortcuts (Fn/Globe-A opens the Dock).

Args:

Raises:


class Focus

Portable snapshot of the current keyboard focus.

Available as keymap.focus, and passed to every custom_condition_func.

Attributes:

May be None, so check before using it:

    - while one of Keyhac's own windows is in front. Keyhac's own  windows do not exist to its API (issue #173), and the rest of  the Focus is still filled in for key tables to match on; 
    - on Windows, when UI Automation could not say - unavailable, or  a call into an application that stopped answering timed out  (issue #171); 
    - on macOS, only when not even the front application could be  named. An unreadable control falls back to its window, then to  the application element, so this is otherwise never None -  but it is not always the control itself.   - <b>`native`</b>:  The platform power object - a UIElement (macOS) or  NativeWindow, an HWND wrapper (Windows). 

class KeyEvent

A normalized key event delivered by the OS hook.

Attributes:


class Window

A top-level OS window.

The portable half of keyhac-win’s pyauto.Window and keyhac-mac’s AXWindow element: window operations unify cleanly across both OSes (find, activate, move, restore, title, process), unlike element introspection, whose attribute vocabularies do not - see Focus.element.

keymap.get_active_window(), list_windows() and find_window() hand these out; configurations never construct one.

Note:

Usable from any thread, because no Window is ever one of Keyhac’s own (issue #173): the lookups skip our process before asking it anything. That is the whole of the rule. On macOS these are Accessibility calls, and AX into our own process off the main thread crashes with SIGTRAP - but AX into another application is safe from a worker, which is how the candidate window walks a menu bar (doc/dev/design-notes.md, “Streaming a source”) and how an action’s run() reads and moves windows. On Windows, reading another process’s window title does not message it.


property Window.app_name

Process base name without extension (Windows) / localized application name (macOS).


property Window.class_name

Win32 window class. None on macOS, which has no such concept.


property Window.element

This window as an element, for searching inside it.

The bridge from window operations to element introspection: an action finds a window portably (keymap.find_window) and then has to look into it, which until now meant reaching for a platform-specific entry point. macOS already holds the AX element; Windows resolves the HWND through UI Automation.


property Window.native

The underlying platform object (HWND wrapper / AX UIElement).


property Window.pid

Process id of the application owning the window.


property Window.title

The window’s title.


method Window.activate

activate() → bool

Bring this window and its application to the front.

Returns: Whether the activation succeeded.


method Window.enter_full_screen

enter_full_screen() → bool

Put the window in the OS’s full-screen mode.

Leave it with restore(). macOS only; on Windows it does nothing and returns False (see is_full_screen()). It brings the window’s application to the front, and a minimized window is restored first.

The transition animates for about half a second, and a restore() made meanwhile is accepted and then ignored - a full-screen toggle bound to a key will not take a second press straight after the first:

if window.is_full_screen():
     window.restore()
else:
     window.enter_full_screen()

Returns: False when the window was already in full screen; otherwise whether the request was accepted.


method Window.get_frame

get_frame() → tuple[float, float, float, float] | None

Get the window’s frame.

The frame is the window as drawn: invisible padding around it (the resize border Windows keeps outside the visible edge) is excluded, so these are the coordinates the OS itself positions windows in.

Returns: (x, y, w, h) in global top-left-origin screen coordinates, or None when the window has no readable frame.


method Window.is_full_screen

is_full_screen() → bool

Whether the window is in the OS’s full-screen mode.

macOS only. Windows has no such mode - full screen there is something each application draws for itself, and nothing marks it - so this is always False on Windows.

Returns: Whether the window is in full screen.


method Window.is_maximized

is_maximized() → bool

Whether the window is currently maximized.

False while the window is minimized or in full screen, even when it will come back maximized: this reports what is on screen now, so at most one of is_minimized(), is_maximized() and is_full_screen() is true.

On macOS a window counts as maximized when it fills the work area of its screen - the screen less the menu bar and the Dock - which is what Window > Fill gives it. macOS keeps no maximized flag that another application can read, so a window the user sized to exactly that frame by hand counts too.

Returns: Whether the window is maximized.


method Window.is_minimized

is_minimized() → bool

Whether the window is currently minimized.


method Window.maximize

maximize() → bool

Maximize the window.

On macOS this is Window > Fill: the window fills the work area and the OS remembers its previous size for restore(). It brings the window’s application to the front, which Fill needs, and the window animates into place for about a third of a second: is_maximized() turns true only at the end of it. For about half a second more the OS is still finishing Fill and puts back any frame written to the window, so a SnapWindow straight after a maximize() does not stick.

A minimized window is restored first. On macOS a window in full screen leaves it and is placed over the work area instead of filled

Returns: False when the window was already maximized; otherwise whether it was maximized - on macOS, whether Fill was accepted, since the animation leaves nothing to check yet.


method Window.minimize

minimize() → bool

Minimize the window.

On macOS a window in full screen cannot be minimized; restore() it first.

Returns: False when the window was already minimized or cannot be minimized; otherwise whether it was.


method Window.restore

restore() → bool

Take the window back one state - the way out of all of them.

A minimized window comes back as it was before - maximized, if it was. A full-screen window leaves full screen, again returning to what it was before. A maximized window returns to the size it had before it was maximized. To leave one particular state and nothing else, ask first:

if window.is_full_screen():
     window.restore()

On macOS, returning from maximized brings the window’s application to the front, and works only for a window the OS filled (Window > Fill, or maximize() on a window that was not in full screen); one sized to the work area any other way has no previous size to return to, and stays as it is. The way back animates like the way there (see maximize()).

Returns: False when the window was in none of the three states. Otherwise whether the change was made - on macOS, coming back from maximized, whether it was accepted, since the animation leaves nothing to check yet.


method Window.set_frame

set_frame(x: float, y: float, w: float = None, h: float = None) → bool

Move the window, and optionally resize it.

The coordinates are the visible frame get_frame reports, so a frame read from one window can be given to another unchanged.

A maximized window is taken out of the maximized state by being placed, so it does not spring back to filling the screen. A window in full screen or minimized cannot be placed; leave those states first with restore().

Args:

Returns: Whether the window accepted the change.


class ThreadedAction

Base class for time-consuming key actions.

Anything slow - network, subprocess, sleeping, heavy computation - must not run inline, because a bound function executes inside the keyboard hook’s deadline. Derive from this and implement starting(), run() and finished() instead.

Three threads, and which one you are on decides what you may touch. starting() and finished() run on the event-loop thread under the engine lock: they should stay light-weight because they hold the lock the keyboard hook needs. run() executes on a worker, and that is where the pipeline goes: input contexts, self.ui and every element read and wait work there, reading the other application directly, so a slow or hung application stalls this action and not the keyboard. The same goes for Window objects and the geometry and IME calls on keymap; the few platform calls that cannot run off the main thread take themselves there. Keyhac’s own windows are not visible to any of it.

Actions run concurrently, so a run() that takes minutes no longer holds up every other one. What is still serialized is what has to be: injected keystrokes (one with ctx: batch at a time) and the clipboard save and restore around a paste.

There is no __init__ here to extend. The base keeps no per-instance state - a running action is tracked in a class-level set - so a subclass’s constructor does not need super().__init__(), and one that omits it loses nothing.

The user can stop a running action with Esc, and an action needs to write nothing for that: wait_for raises ActionCancelled, and a long action spends nearly all its time waiting. Use check_cancelled() in a stretch of work that has no wait in it.

class Fetch(ThreadedAction):
     def starting(self):          # main thread, before run
         logger.info("fetching...")
     def run(self):               # worker thread - the slow part
         return do_network_call()
     def finished(self, result):  # main thread, after run
         logger.info(f"got {result}")

property ThreadedAction.keymap

The running Keymap, so an action need not import and look it up.


property ThreadedAction.ui

The action-facing UI API (keymap.ui) - see doc/action-api.md.

An action’s most-used object, so it is one attribute away rather than two lines of lookup at the top of every run().


method ThreadedAction.cancelled

cancelled() → bool

True once the user has asked this action to stop.

Check it in a loop that does not wait - wait_for already raises ActionCancelled on its own, and a loop built out of waits needs nothing else.


method ThreadedAction.check_cancelled

check_cancelled() → None

Raise ActionCancelled if the user has asked this action to stop.

For a stretch of work with no wait in it - a long parse, a big write - where cancellation would otherwise not be noticed until the next wait.


method ThreadedAction.finished

finished(result: Any) → None

Called on the event-loop thread once run() has returned.

Not called when run() raised - the error is logged with its traceback and get_action_result reports the run as failed - nor when it was cancelled. What must happen either way, such as recording where the run stopped, belongs in a finally inside run().

Args:


method ThreadedAction.run

run() → Any

Called in the thread pool; may block.

Returns: Anything; it is handed to finished().


method ThreadedAction.starting

starting() → None

Called on the event-loop thread the moment the action triggers.

It runs under the engine lock, inside the keyboard hook, so keep it light - capture what the key press names (keymap.focus, already read), log intent, and leave reading the screen to run(). A read here into an application that does not answer raises Unresponsive, and the action does not start.


class InputText

Type a literal string into the focused application.

method InputText.__init__

__init__(text: str)

Build the action.

Args:


class LaunchApplication

Launch (or activate) an application by name.

method LaunchApplication.__init__

__init__(app_name: str)

Build the action.

Args:


property LaunchApplication.keymap

The running Keymap, so an action need not import and look it up.


property LaunchApplication.ui

The action-facing UI API (keymap.ui) - see doc/action-api.md.

An action’s most-used object, so it is one attribute away rather than two lines of lookup at the top of every run().


class ActivateApplication

Go to an application: bring it forward, walk its windows, launch it.

One key for the whole of “take me to my terminal”. What a press does depends on where the application already is:

kt["O-RCmd"] = ActivateApplication(app="Terminal|ターミナル",
                                    launch="Terminal.app")

The rotation keeps no state. Which window is current is read from the z-order on each press, and the order walked is where the windows sit on screen, so it survives a configuration reload, windows opening and closing, and the user dragging one somewhere else.

method ActivateApplication.__init__

__init__(
    app: str,
    launch: str = None,
    cycle: bool = True,
    reverse: bool = False
)

Build the action.

Args:

Raises:


property ActivateApplication.keymap

The running Keymap, so an action need not import and look it up.


property ActivateApplication.ui

The action-facing UI API (keymap.ui) - see doc/action-api.md.

An action’s most-used object, so it is one attribute away rather than two lines of lookup at the top of every run().


class ActivateWindow

Bring an application’s window to the front, by name pattern.

The front-most window of the first application that matches, restored first if it was minimized. An application that is running but shows no window the platform can enumerate is activated by pid instead.

ActivateWindow(app="code|Visual Studio Code")

ActivateApplication is this with the rest of “go to that application” attached: it walks the windows on a second press, and launches what is not running.

method ActivateWindow.__init__

__init__(app: str)

Build the action.

Args:


property ActivateWindow.keymap

The running Keymap, so an action need not import and look it up.


property ActivateWindow.ui

The action-facing UI API (keymap.ui) - see doc/action-api.md.

An action’s most-used object, so it is one attribute away rather than two lines of lookup at the top of every run().


class MoveWindow

Move the focused window.

It nudges the window by distance pixels, or - with window_edge / screen_edge - travels until it meets another window’s edge or the edge of the screen. A window already at the screen edge hops to the adjacent monitor instead.

MoveWindow(direction="left", distance=20)
MoveWindow(direction="left", distance=9999, window_edge=True)

method MoveWindow.__init__

__init__(
    x: int = None,
    y: int = None,
    direction: str = '',
    distance: float = 10,
    window_edge: bool = False,
    screen_edge: bool = True
)

Build the action.

Args:


property MoveWindow.keymap

The running Keymap, so an action need not import and look it up.


property MoveWindow.ui

The action-facing UI API (keymap.ui) - see doc/action-api.md.

An action’s most-used object, so it is one attribute away rather than two lines of lookup at the top of every run().


class SnapWindow

Snap the focused window to a region of its screen (tiling).

The region is the screen’s work area, so the menu bar and Dock (macOS) and the taskbar (Windows) stay uncovered. “Its screen” is the one the window overlaps most, so repeated snaps keep a window on the monitor it is already on.

This places the window itself; it does not enter the OS’s own snap state. The window lands where Windows’ snap would put it, but Snap Assist does not offer to fill the other half, no snap group is formed, dragging the window away does not restore its previous size, and dragging the shared edge does not resize the neighbour. Likewise “full” covers the work area without maximizing the window; for the OS’s maximized state (Window > Fill on macOS) call Window.maximize().

A minimized window is restored and a full-screen one leaves full screen before it is placed; a maximized one stops being maximized.

SnapWindow("left")               # left half
SnapWindow("left", ratio=2/3)    # left two thirds
SnapWindow("full")

method SnapWindow.__init__

__init__(position: str, ratio: float = 0.5)

Build the action.

Args:

Raises:


class MouseMove

Move the mouse cursor by a relative offset.

Held modifiers stay held, unlike the button and wheel actions. The move is injected acceleration-proof, so the distance is exactly what you ask for (keyhac-win MouseMoveCommand).

method MouseMove.__init__

__init__(dx: int, dy: int)

Build the action.

Args:


class MouseButtonDown

Press a mouse button and hold it.

Held modifiers are released first, so a modifier-bound press does not become a modified one (keyhac-win MouseButtonDownCommand).

method MouseButtonDown.__init__

__init__(button: str = 'left')

Build the action.

Args:

Raises:


class MouseButtonUp

Release a held mouse button (keyhac-win MouseButtonUpCommand).

method MouseButtonUp.__init__

__init__(button: str = 'left')

Build the action.

Args:

Raises:


class MouseButtonClick

Click a mouse button.

Held modifiers are released first, and rapid synthetic clicks register as double-clicks (keyhac-win MouseButtonClickCommand).

method MouseButtonClick.__init__

__init__(button: str = 'left')

Build the action.

Args:

Raises:


class MouseWheel

Turn the vertical mouse wheel (keyhac-win MouseWheelCommand).

method MouseWheel.__init__

__init__(wheel: float)

Build the action.

Args:


class MouseHorizontalWheel

Turn the horizontal mouse wheel (keyhac-win MouseHorizontalWheelCommand).

method MouseHorizontalWheel.__init__

__init__(wheel: float)

Build the action.

Args:


class StartRecordingKeys

Start recording keystrokes into the replay buffer.

Bind it to a key; the recording is played back by PlaybackRecordedKeys.


class StopRecordingKeys

Stop recording and normalize the buffer.


class ToggleRecordingKeys

Toggle keystroke recording.


class PlaybackRecordedKeys

Play back the recorded keystrokes.

The replayed keys run back through the keymap, so recorded bindings expand again on playback.


class ClipboardHistory

Automatically captures historical clipboard content.

Text is kept across restarts, and so are copied files (as their paths). Rich text and images are kept for the session: choosing such an entry puts the formatting or the image back.

Content the copying app marked as concealed or transient - what password managers do with a copied password - is never recorded.

Reached from a configuration as keymap.clipboard_history, and shown by the ShowClipboardHistory action.

Attributes:


method ClipboardHistory.add_item

add_item(s: str) → None

Add text to the history without touching the OS clipboard.

Args:


method ClipboardHistory.get_current

get_current() → str | None

Get the most recent clipboard text.

Returns: The newest history entry with text, or None when there is none.


method ClipboardHistory.items

items()

Iterate the history’s text.

Entries without text - an image, files copied in Explorer - are not included; the chooser lists them.

Yields: (text, label) pairs, latest first. The label is the text collapsed onto one line for display.


method ClipboardHistory.remove_item

remove_item(s: str) → None

Remove text from the history, without touching the OS clipboard.

Args:


method ClipboardHistory.set_current

set_current(s: str) → None

Set text to the OS clipboard and the front of the history.

Args:


class ChooserAction

Base class for actions that open the chooser window.

Derive from it to build your own popup: implement list_items() and on_chosen(), and inherit the whole open / filter / refocus flow. Only one chooser is open at a time - pressing the same action’s key again closes it, and a different chooser action replaces it.

class PickBranch(ChooserAction):
     def list_items(self):
         return [("🌱", name) for name in git_branches()]
     def on_chosen(self, item, modifier_flags):
         checkout(item[1])

method ChooserAction.list_items

list_items()

Build the list the chooser shows. Override this.

Returns: A list of (icon, label) or (icon, label, …) tuples. Anything after the label is yours; on_chosen() receives the whole tuple.


method ChooserAction.on_chosen

on_chosen(item, modifier_flags: int) → None

Handle the chosen item. Override this.

Args:


class ShowCandidates

Open the candidate window over one or more sources.

The hotkey is the scarce resource, not the code: an action class per kind of row means a key per kind of row, and there are only so many a person can hold. This takes sources as values, so several kinds share one key and one incremental search - and each row is labelled with where it came from, so a mixed list stays readable.

kt["Fn-V"] = ShowCandidates([ClipboardHistorySource(), SnippetsSource(mine)])
kt["Fn-B"] = ShowCandidates(git_branches, on_chosen=checkout)
kt["Fn-P"] = ShowCandidates([ChooserPage("All", every), ChooserPage("Clipboard", clip)])

Enter runs whatever the chosen row’s source says to do, so rows from different sources can mean different things in the same window - paste this, activate that, press the other.

method ShowCandidates.__init__

__init__(sources, on_chosen=None, matcher=None, activates=None, anchor=None)

Build the action.

Args:


class Candidate

One row a source offers a view.

Attributes:


property Candidate.label

Icon and display text as one line, the way a list view draws it.


method Candidate.from_item

from_item(item) → Candidate

Adapt the (icon, label, *payload) tuple ChooserAction.list_items returns. The whole tuple becomes the payload, so on_chosen still receives exactly what it received before.


class CandidatePreview

What the chooser’s preview window shows for the selected row.

Returned from CandidateSource.preview(). Three kinds of content, any mix of them; the window draws whichever are present, top to bottom: the image, then the text, then the fields.

Attributes:


class CandidateSource

A named set of candidates, and what choosing one does.

Named for what it is a source of: keyhac import * is flat, and a config writes class Branches(CandidateSource) with no surrounding call to say which kind of source is meant. ChooserPage keeps the shorter name because it is only ever written inside ShowCandidates([...]), where the context is right there.

background says whether the generator candidates() returns may be drained on a worker thread. False by default - a source touching the UI or the keymap is only correct on the main thread - and True is for one whose work is entirely outside this process: another application’s accessibility tree, a file, a subprocess, the network. The difference is not marginal. A main-thread generator is drained in 2 ms slices on a 10 Hz tick, so a walk that takes a quarter of a second to read takes ten seconds to appear; on a worker it takes the quarter second.


method CandidateSource.badge

badge(candidate: keyhac.core.candidate.Candidate) → str

What to show quietly at the right of this row, when the window is showing only this source.

With several sources the window shows which one a row came from, because that is the thing a mixed list hides. With one there is no such question, and the slot is free for whatever this source thinks annotates a row - the menu source puts the keyboard shortcut there, so choosing a command from the list twice teaches the key the third time.


method CandidateSource.candidates

candidates()

The rows this source offers right now. Override this.

Called on every invocation rather than cached: a source reading the screen - the windows that exist, the controls in the front window - is describing something that has already moved on by the time it is asked again.

Return a list, or - for a source with real work to do - yield. A generator is drained as it goes, so its first rows are on screen while it is still finding the rest, and abandoning it (the window closed, the page changed) simply stops pulling.

This method runs on the main thread. The generator it returns runs there too unless the source sets background (below), in which case only the generator moves to a worker. On the main thread, yield often and do not block: the drain gets 2 ms per turn, and a slice that does not come back holds the keyboard as surely as any other main-thread work would.


method CandidateSource.on_chosen

on_chosen(
    candidate: keyhac.core.candidate.Candidate,
    modifier_flags: int
) → None

Act on the chosen row. Override this.

Args:


method CandidateSource.preview

preview(
    candidate: keyhac.core.candidate.Candidate
) → keyhac.core.candidate.CandidatePreview | None

What to show beside this row while it is selected, or None.

Asked only once the selection has rested on the row, never while the list is built, so a preview may cost real work - but on the main thread it holds the keyboard while it runs, so a slow one sets preview_background. Return None for rows the label already says everything about; the window then shows nothing.

Args:

Returns: A CandidatePreview, or None for no preview.


method CandidateSource.remove

remove(candidate: keyhac.core.candidate.Candidate) → bool

Remove a row for good - Shift-Delete in the chooser’s list.

Override this for a source whose rows are a record the user keeps (a history, a list of favourites), and return True once it is gone; the window then drops the row. The default says the row cannot be removed, and the key does nothing.

Args:

Returns: True if the row was removed.


class CallableSource

A source built from a plain callable, so anything that can produce a list can be one without subclassing - SSH hosts, git branches, records out of a line-of-business system.

branches = CallableSource(git_branches, "Branches", on_chosen=checkout)

The callable returns Candidate objects, or the (icon, label, *rest) tuples ChooserAction.list_items has always returned - those are adapted, and on_chosen then receives a candidate whose payload is the tuple.

A callable that yields is a streaming source and stays one; one that returns a list stays a list.


class ChooserPage

A named set of sources the candidate window can switch between.

One key opens the window; Left and Right move between pages, and the query comes with you - type kensaku, then look for the same thing on another page without retyping it.

Three is the number to aim for, with what you reach for most in the middle - the window opens there, so it costs nothing to reach and both neighbours cost one press. Three is about as many as anyone holds without looking. Pages are not how you narrow to one kind of row - @ and a source name does that, inside whichever page you are on - so a page is a place, and there are few places.

More than three, and it stops being a place and becomes a ring you count around. If you want more, the answer is another key bound to another ShowCandidates: a key is the scarce thing here, but it is yours to spend.

Scopes are also how an expensive source stays affordable. A source that walks the accessibility tree costs a real traversal every time the window opens; put it in its own page and it is paid for only when the user asks for it, instead of on every invocation of a merged everything-page.

keymap_global["Fn-P"] = ShowCandidates([
     ChooserPage("All", [clipboard, snippets, windows]),
     ChooserPage("Clipboard", [clipboard, snippets]),
     ChooserPage("Windows", [windows]),
])

method ChooserPage.__init__

__init__(name: str, sources)

Build a page.

Args:


class ActionsSource

Every action in ~/.keyhac/extensions/, startable without a key.

The half of the authoring loop a key binding never covered: a class lands in extensions/, works, and is runnable from here - the config.py edit that binds it to a key comes later, or never, for something used once a month. That is also the answer to running out of keys, from the other side to KeyBindingsSource: one asks what the keys do, this asks what there is to run.

Listing does not import. The catalogue is an AST parse (keyhac.mcp.extensions.discover), so a file is read and never executed to find out what is in it, and a module no config.py imports stays inert on disk. A class here runs at exactly one moment: when the operator picks it.

What is offered is a ThreadedAction subclass, transitively and across files - not every callable class. The main thread services the keyboard hook and every window, so a list whose rows might block it is a list that can freeze the keyboard.

A class needing constructor arguments is listed and says so rather than being hidden: an action missing from the list reads as Keyhac not seeing the file, which is a much worse thing to debug than a row that explains itself.

method ActionsSource.__init__

__init__(name: str = None)

Build the source.

Args:


class ApplicationsSource

Every installed application, and a way to launch one.

On macOS these are the .app bundles in the Applications folders, listed by the name Finder shows. On Windows they are what the Start menu lists, including Microsoft Store applications, and also whatever else it holds there, such as uninstallers.

Choosing a row launches the application. On macOS an application already running comes to the front. On Windows it depends on the application, and many open another window; ActivateApplication goes to a running one.

method ApplicationsSource.__init__

__init__(name: str = None)

Build the source.

Args:


class BrowserBookmarksSource

The bookmarks of Chrome, Edge and Safari.

Choosing a row opens the bookmark in a new tab of the browser it came from.

On macOS they are read from each browser’s Bookmarks menu, because macOS protects the browsers’ files. A browser’s rows appear only while it is running, and Chrome and Edge list the profile of their last active window. Rows can be found by title or folder: the menu does not say the URL.

On Windows they are read from the default browser’s files, for every profile, whether or not it is running. That browser must be Chrome or Edge: with any other as the default there are no rows. Rows can be found by title, URL or folder.

Bookmarks are read each time and are not stored.

method BrowserBookmarksSource.__init__

__init__(name: str = None)

Build the source.

Args:


method BrowserBookmarksSource.preview

preview(candidate)

The bookmark’s URL, where it is known, and its folder.


class BrowserTabsSource

The tabs open in Chrome, Edge and Safari, across all their windows.

Choosing a row selects the tab and brings its window to the front.

Tabs are read from each browser’s own window through accessibility, so no extension or browser permission is needed. A row shows the tab’s title: the URL is not available for a tab that is not selected.

Only tabs visible in the tab bar are listed. Chrome leaves a tab it has no room to show out of what it exposes, so widening the window brings it back.

Every browser window is read each time the page opens, so this belongs in a ChooserPage you go to deliberately.

method BrowserTabsSource.__init__

__init__(name: str = None)

Build the source.

Args:


class ClipboardHistorySource

Everything the clipboard has held, most recent first.

Enter pastes the entry with the formatting or image it was copied with, Option(Alt)-Enter pastes its text alone, and Shift sets the clipboard without pasting. When the clipboard holds something the history does not keep - a password manager’s copy, or a format it cannot read - a “Current clipboard” row comes first, and pastes it untouched.


class KeyBindingsSource

Every key binding in effect right now, and a way to run one.

The one source nothing outside Keyhac can offer: it is the engine’s own tables, resolved the way the hook resolves them - the tables whose focus condition matches where the user is standing, merged in definition order, or the armed multi-stroke table when there is one. Re-deriving that from the configuration would be a second implementation of the rule, and the two would drift.

It is also the cheap one. There is no traversal and no other process to ask; the answer is a dict the engine already keeps up to date.

A multi-stroke prefix is expanded to its leaves, the way the menu source expands submenus - Fn-X › A is the sequence you would type, and those are exactly the bindings nobody remembers. Rows show what the binding does, with the keys themselves right-aligned, so the list reads as a reference: what can I press here, and what would it do.

Choosing a row runs it, which is the point rather than a bonus - a binding you can run from a list is one that does not need a key of its own, and running out of keys is what the candidate window exists to fix.

method KeyBindingsSource.__init__

__init__(name: str = None)

Build the source.

Args:


method KeyBindingsSource.preview

preview(candidate)

What the binding does in full, its docstring, and what else follows a multi-stroke prefix.


class MenuItemsSource

Every command in the front application’s menus, as one flat list.

This is the long tail the candidate window is for: the commands that have no keyboard shortcut, in an application whose menus you do not know by heart. Rows read as the path to them - File › Export › As PDF… - and carry the shortcut where there is one, so choosing from here twice teaches the key the third time.

Only leaves are offered. A row that merely opens another menu is not a command, and a list of them would be a worse menu bar rather than a better one. Disabled items are skipped: they are visible in the menu for the shape of it, and unchoosable here.

It costs a real traversal. Measured on macOS: 79 ms for a small application, 396 ms for Chrome, for 161 and 331 items - so this belongs in a ChooserPage of its own, where it is paid for when asked for, rather than in a merged page opened on every keystroke.

macOS only. There the menu bar is an OS-level part: one per application, always at the top of the screen, and readable in full while it is closed. A Windows menu belongs to a window, may not be there at all, and is populated only when it opens - so this source finds no menu bar there and yields nothing. Nothing is lost: a menu’s top-level items are UI elements of the window like any other, and WindowControlsSource lists them with everything else clickable.

method MenuItemsSource.__init__

__init__(name: str = None)

Build the source.

Args:


method MenuItemsSource.preview

preview(candidate)

The item’s full menu path and its keyboard shortcut.


class WindowControlsSource

Everything you could click in the front window, reachable by name.

Discussion #112’s original target, and the reason the window had to stop taking the keyboard focus: a list of “what is actionable here” that changes what is actionable by opening is no use to anybody.

It streams, because it is expensive. Measured on macOS: a heavy application’s tree is 3000 nodes and 460 ms, and filtering by role does not help - the walk is the cost, and reporting less of it changes nothing. So the walk yields as it goes and the first controls are on screen while the rest are still being found. Put it in a ChooserPage of its own all the same; it has real work to do on every invocation.

Only controls with a name are offered. An icon-only button with no label, no description and no tooltip cannot be typed for - there is no text to filter on - so listing it would add a row nobody can reach. Where a name comes from is recorded on the candidate (provenance), because it decides what else can find the element: a control reachable only through its tooltip cannot be found by find(name=...) in an action either.

It has no preview, deliberately. The outline on the real control is what says which row is which, and a window beside the chooser could only add a way to cover it.

method WindowControlsSource.__init__

__init__(name: str = None)

Build the source.

Args:


class SnippetsSource

Fixed text you paste often.

SnippetsSource([("📧", "me@example.com"), ("🕒", "Date", DateTimeSnippet("%Y-%m-%d"))])

method SnippetsSource.__init__

__init__(snippets, name: str = None)

Build the source.

Args:


class ClipboardToolsSource

Transformations applied to whatever the clipboard holds now.

method ClipboardToolsSource.__init__

__init__(tools, name: str = None)

Build the source.

Args:


class ShowClipboardHistory

Show the clipboard history in the chooser window.

Type to filter, Enter pastes into the application you came from, Shift-Enter only sets the clipboard, Escape cancels.

A preset: ShowCandidates(ClipboardHistorySource()). Reach for ShowCandidates directly to put the history in one window alongside other sources rather than on a hotkey of its own.


class ShowClipboardSnippets

Show fixed snippets in the chooser window.

Choosing one pastes it, exactly like the clipboard history.

ShowClipboardSnippets([
     ("📧", "me@example.com"),                          # (icon, text)
     ("📮", "Mailing address", "400 Broad St, ..."),    # (icon, label, text)
     ("🕒", "Date", DateTimeSnippet("%Y-%m-%d")),       # (icon, label, callable)
])

A preset over SnippetsSource.

method ShowClipboardSnippets.__init__

__init__(snippets)

Build the action.

Args:


class ShowClipboardTools

Show clipboard conversion tools in the chooser window.

Each tool takes the current clipboard text and returns its replacement.

ShowClipboardTools([
     ("🔄", "Quote", ShowClipboardTools.quote),
     ("🔄", "Upper case", str.upper),
])

A preset over ClipboardToolsSource.

Attributes:

method ShowClipboardTools.__init__

__init__(tools)

Build the action.

Args:


method ShowClipboardTools.quote

quote(s)

Prefix every line with quote_mark.

Args:

Returns: The quoted text.


method ShowClipboardTools.to_full_width

to_full_width(s)

Convert half-width characters to their full-width forms.

Args:

Returns: The converted text.


method ShowClipboardTools.to_half_width

to_half_width(s)

Convert full-width characters to their half-width forms.

Args:

Returns: The converted text.


method ShowClipboardTools.to_plain

to_plain(s)

Return the text unchanged (the identity converter).

Args:

Returns: The same text.


method ShowClipboardTools.unindent

unindent(s)

Remove the common leading whitespace from every line.

Args:

Returns: The dedented text.


class DateTimeSnippet

A ShowClipboardSnippets value that produces the current date and time.

ShowClipboardSnippets([("🕒", "Date", DateTimeSnippet("%Y-%m-%d"))])

method DateTimeSnippet.__init__

__init__(fmt: str)

Build the snippet.

Args:


function getLogger

getLogger(name: str) → Logger

Get a logger wired to the Keyhac console.

logger = getLogger("Config")
logger.info("loaded")

Args:

Returns: A standard logging.Logger whose output lands in the console window (and on stderr).


class Console

The console window’s backing store: a ring buffer of log lines plus the named text slots it displays (“lastKey”, “focusPath”).

A configuration reaches the console through print() and getLogger(), not through this object.

Attributes:


classmethod Console.get_instance

get_instance() → Console

Get the Console singleton.

Returns: The Console instance, creating it on first use.


method Console.lines

lines() → list[tuple[str, int]]

Get the buffered console lines.

Returns: (text, log level) pairs, oldest first, up to max_lines of them.


class ReportCaretAnchor

Say where a popup would open right now, and why.

Bind it to a key and press it inside the application you are asking about. The report goes to the console at INFO - no debug logging to turn on - and a balloon appears at the place it found, so the numbers and the result are visible together.

kt["Fn-Ctrl-C"] = ReportCaretAnchor()

Why a key rather than a command-line tool. tools/caret_probe.py asks about whatever is in front, and while it runs that is the terminal. Reaching the application under test means switching to it and racing a timer, and the Accessibility permission it needs belongs to the terminal rather than to Keyhac - a second grant, in a second place, easy to have given to a different terminal last time. Pressed as a key, none of that applies: Keyhac is already trusted and the application under test already has the focus.

What it reports is the chain keyhac.core.anchor walks - the caret, then the focused control if it is small enough to be a place, then the window - and, above it, what each way of asking the caret question answered. That last part is what tells a control with no caret from one whose caret cannot be believed, and those want opposite things done about them.


Generated from the docstrings by make api-reference. Edit the docstrings, not this file.