English | 日本語
Keyhac is configured with one Python file: ~/.keyhac/config.py (or, in Windows
portable mode, the config.py sitting next
to Keyhac.exe). On first run it is
created from a fully commented template — the template
(keyhac/_config.py in the source tree) is a working example of
everything on this page, and a good file to keep open while reading.
This page introduces the APIs in the order you meet them. For the exact arguments of any one of them, see the API reference.
from keyhac import *
def configure(keymap):
...
Keyhac calls configure(keymap) at startup and on every reload (“Reload Config” in
the tray / menu-bar menu). Errors are contained:
~/.keyhac/extensions/ is on sys.path, so you can split a large config into modules
and import them. Reloading re-imports them too, so an edit to an extension is picked
up without restarting Keyhac.
The directory is appended to sys.path, not prepended: an extension is named after
what it does, and a queue.py next to a queue-handling action would otherwise shadow
the standard library for the whole process. If you name a module after one Python
already provides, Python’s copy wins and yours is unreachable — rename it.
Your config and extensions can import the standard library and what Keyhac itself
ships. For anything else, list it in ~/.keyhac/requirements.txt, next to
config.py, and choose Advanced > Sync Python Packages in the tray / menu-bar menu:
# ~/.keyhac/requirements.txt
requests
openpyxl
The sync runs pip in the background, using the Python Keyhac itself runs on, so
compiled packages match it. pip’s output appears in the console, and the config
reloads when it finishes. If you installed Keyhac with pip, keyhac deps sync does
the same from a shell, and keyhac deps status says (offline) whether a sync is due.
It works the same for every install, the macOS app and the Windows app included. The
libraries go into ~/.keyhac/site-packages/, not into Keyhac, so upgrading Keyhac
keeps them.
extensions/, these are not
re-imported on reload, which is the right behavior for libraries. A library that was
already imported keeps its old version until Keyhac restarts. On Windows, if a
library in use can’t be replaced, the new set takes over at the next start.site-packages/3.14/). When a newer Keyhac runs on a newer Python, the console
says so, and one sync installs the same list again.requirements.txt is an ordinary pip requirements file: version specifiers,
--index-url, and paths relative to the file all work. A file it pulls in with -r
is not watched by the startup check, so sync by hand after editing one. Don’t edit
site-packages/ yourself; every sync replaces it. If you keep ~/.keyhac in a
dotfiles repository, commit requirements.txt and leave site-packages/ out: each
machine syncs its own.
“Edit Config” in the tray menu opens the file in an editor. Pick yours with:
keymap.editor = "CotEditor" # app name or path, or a callable(path)
Unset, Keyhac tries VS Code, then Xcode, then TextEdit on macOS; Notepad on Windows.
The same file runs on Windows and macOS. Where the OSes genuinely differ, branch on
keymap.platform ("windows" or "mac"). Two constants absorb most of it — this is
the pattern the template uses throughout:
mac = keymap.platform == "mac"
MOD1 = "Fn" if mac else "User0" # the modifier your bindings hang off
MOD2 = "Cmd" if mac else "Ctrl" # the OS's primary shortcut modifier
kt[f"{MOD1}-C"] = f"{MOD2}-C"
A plain Python constant is the answer here, not a built-in name: there is no Mod-
modifier in the key expression language. Modifier names mean the same thing on both
OSes, and one that quietly changed meaning per OS would not survive the round trip —
the console reports what actually fired, Cmd-C or Ctrl-C. The constant also scales
to whatever else your config wants to vary by OS, which is why MOD1 above works the
same way. The names are the template’s; a config that spells its constants
differently, or writes keymap.platform checks inline, is doing the same thing.
Config diagnostics are cross-platform aware: a key name that exists only on the other
OS says so in the error, and after loading, Keyhac warns once about bindings whose
modifiers no key on this OS can produce (for example a Cmd- binding running on
Windows — it parses, but would silently never fire).
A key table holds bindings and a condition for when they apply:
# global (matches everything)
kt = keymap.define_keytable(focus_path_pattern="*")
# portable: by application, by window title (fnmatch wildcards, "|" alternation,
# case-insensitive; ".exe" optional on Windows)
kt_term = keymap.define_keytable(app="WindowsTerminal|Terminal|iTerm2")
kt_edit = keymap.define_keytable(app="Code", title="*myproject*")
# platform extras
kt_np = keymap.define_keytable(app="notepad", class_name="Edit") # Windows
kt_area = keymap.define_keytable(focus_path_pattern="*/AXTextArea(*)") # macOS
# arbitrary logic
kt_x = keymap.define_keytable(custom_condition_func=lambda focus: ...)
# named, detached table = a multi-stroke second stroke (see below)
kt_ctrlx = keymap.define_keytable(name="Ctrl-X")
Matching:
app — process/exe base name on Windows, localized application name on macOS.title — window title.class_name — Win32 window class (Windows only).focus_path_pattern — the control hierarchy down to the focused element: the AX
tree on macOS, the UI Automation tree on Windows. Watch the console’s
“Focus path” field to see the live value while you focus things:
macOS: /AXApplication(Xcode)/AXWindow(...)/.../AXTextArea()
Windows: /Application(Code)/Window(...)/.../Edit(Message input)
Use * to skip levels: focus_path_pattern="*/Edit(*)". A component is
Role(Name), and many controls carry a name, so */Edit() matches only
unnamed ones — usually you want */Edit(*).
The focused element is read 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 — re-evaluates the condition, on both platforms. When the
application in front stops responding, the path falls back to the window
level (/Application(…)/…(title)) until it answers again.
custom_condition_func(focus) — your own test; receives the Focus
object. It is never called without a focus: while nothing
reports one, the table is simply inactive.What an application is called. app= is matched against Focus.app_name, and it
is one value everywhere you meet it: what a custom_condition_func receives as
focus.app_name, the application column of list_windows, and the focus now: line
of describe_keymap (the MCP tools), and the console’s focus path.
Focus.app_name is |
for example | |
|---|---|---|
| Windows | the executable’s name, without “.exe” | Code, WindowsTerminal, notepad, msedge, cmd |
| macOS | the application’s localized display name | Code, Terminal (ターミナル on a Japanese system), Safari, Google Chrome |
app= is forgiving — case-insensitive, wildcards and |, and on Windows the “.exe” is
optional in the pattern. Your own function is plain Python, so it compares exact
strings: focus.app_name == "WindowsTerminal", never "WindowsTerminal.exe". When in
doubt, focus the application and read the name off any of the places above rather
than guessing it.
Every matching table is active at once, merged in definition order — later tables win per key. Define your global table first and app-specific tables after it, and the specific ones override exactly the keys they bind.
There is no negated app=. Say “everywhere but here” with custom_condition_func,
and give the exception a name so it reads as what it means:
def is_terminal(focus):
return focus.app_name in ("Terminal", "ターミナル", "iTerm2", "WindowsTerminal",
"cmd", "powershell", "pwsh")
kt_emacs = keymap.define_keytable(
custom_condition_func=lambda focus: not is_terminal(focus))
kt_emacs["Ctrl-F"] = "Right"
kt_emacs["Ctrl-B"] = "Left"
If your config already has such a function (the template’s is_terminal is one),
reuse it, so “a terminal” means one thing throughout the file. If what it has is a
table for the terminals instead — define_keytable(app="Terminal|iTerm2|…") — the
names in that pattern are the list to write the function from; there is no way to
negate the pattern itself. A localized name is a separate name, so list every
spelling the machines you use report (Terminal and ターミナル).
The other route is to bind the keys in a table that applies everywhere and give them
back in a later table for the exception, with None — which passes the key through
untouched (see Assignments):
kt["Ctrl-F"] = "Right" # everywhere ...
kt_terminal["Ctrl-F"] = None # ... except here, where Ctrl-F is Ctrl-F
Both work. Prefer the first when the exception covers the whole set of keys: it lives
in one place, and a key added to the set later is excepted without a second line. The
second fits when a table that is otherwise right everywhere needs one or two keys
handed back in one application. Do not give a key back by binding it to itself
(kt_terminal["Ctrl-F"] = "Ctrl-F"): that is not a pass-through but a key Keyhac
consumes and sends again, as described below.
{O-|D-|U-}{Modifier-}...{Key} — case-insensitive.
Alt, Ctrl, Shift, User0–User3, plus Cmd and Fn on
macOS, Win on Windows. Each has L/R variants (LCtrl-, RAlt-).A-, C-, S-, W-, U0-–U3-,
and their L/R forms (LC-, RA-, …). The full names are the documented
spelling.Ctrl-A matches either Ctrl, LCtrl-A only the left one. Output goes out with
left-side modifier keys.O- one-shot (see below), D- key-down only, U- key-up only.Semicolon, Slash,
OpenBracket, …, plus JIS names like Yen and Atmark), F1–F20 (to F24
on Windows), Return (Enter also works), Escape, Tab, Space, Back
(Backspace), Delete, the navigation cluster (Left, Home, PageUp, …),
numpad (Num0, NumAdd, …), Kana/Eisu/Menu/Help (macOS — Menu is the
application key a PC keyboard sends), Section (macOS — on an ISO keyboard, the key
left of 1, whatever its legend; there the key between left Shift and Z is
BackQuote),
Apps/PrintScreen/ScrollLock/Pause (Windows), and the modifier keys
themselves as primary keys (LWin, RCmd, …). Any unmapped key is expressible
as its raw code: "(124)".Fn-Left/Right/Up/Down into
Home/End/PageUp/PageDown in hardware (the Fn modifier itself still
arrives). A Fn-…-Left binding can therefore never fire — bind Fn-…-Home
instead. The template’s MoveWindow samples show the per-OS spelling.macOS function-key row: with the top row on its media functions (the
macOS default; “Use F1, F2, etc. keys as standard function keys” off), a key
reaches applications as F1 only with Fn held, and Keyhac sees Fn-F1, not
F1 — the console’s last-key field shows LFn-F1. A binding for “the key
the application gets as F1” is then Fn-F1. Bind both to cover either
setting:
kt_vscode["F1"] = lambda: None
if keymap.platform == "mac":
kt_vscode["Fn-F1"] = lambda: None # top row on media keys: Fn+F1 is F1
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
kt["O-RCtrl"] = "Space" # one-shot
Anything callable can be bound: a plain function, a lambda, or one of the action
objects below (MoveWindow(...), ShowClipboardHistory(), … — they are all
callables).
Making a key do nothing. Bind it to a function that does nothing:
kt_vscode = keymap.define_keytable(app="Code")
kt_vscode["F1"] = lambda: None # F1 never reaches VS Code
The key is consumed and nothing is sent. Scope it with the table’s condition, as
above, and every other application still gets the key. For a function key on a
Mac, bind Fn-F1 as well — see the function-key row. The values that look as if
they might mean “nothing” mean something else:
| Bound to | What the key does |
|---|---|
lambda: None |
nothing — consumed, nothing sent. The spelling to use. |
() |
also nothing, but on Windows a held Alt or Win released afterwards can then open the menu bar or the Start menu; the function form prevents that |
None |
passes through untouched, as if no table bound it — the way to give a key back in a later table |
"" |
an error, logged to the console each time it is pressed, and the key passes through |
A key that a binding sends goes straight to the application. It is never matched
against your tables again, so a table cannot loop on its own output:
kt_cx["Ctrl-X"] = "Ctrl-X" sends Ctrl-X (Cut), it does not re-arm the prefix. The
same holds for a key bound to itself (kt["Ctrl-F"] = "Ctrl-F"): it is consumed and
sent again rather than passed through, which the application mostly cannot tell apart
— but auto-repeat arrives as a series of fresh presses, and anything that notices
synthetic input (games, remote-desktop clients, some password fields) sees Keyhac’s
key rather than yours. To leave a key alone, bind it to None, or do not bind it.
(Keyboard macros are the exception: playback re-enters the tables, so a recorded key
does what it does when you press it.)
Multi-stroke tables: assigning a named table arms it as a prefix — press
Ctrl-X, then a key bound in kt_ctrlx. While armed, a balloon shows the table’s
name. A key that is not bound in the armed table cancels it (and is swallowed, so a
typo does not leak a stray keystroke into your app).
The second stroke is matched with its modifiers, exactly like any other key. A user
who types Emacs-style holds Ctrl through both strokes, so the second key is
Ctrl-S, not S; bind both if both should work:
kt_cx = keymap.define_keytable(name="Ctrl-X")
kt["Ctrl-X"] = kt_cx
kt_cx["Ctrl-S"] = f"{MOD2}-S" # Ctrl held through: Ctrl-X Ctrl-S
kt_cx["S"] = f"{MOD2}-S" # Ctrl let go: Ctrl-X S
The prefix key itself no longer does what it did, in every application the table applies to — here Ctrl-X stops being Cut on Windows, and on macOS stops being whatever the application made of it (Cut is Cmd-X there; a text field takes Ctrl-X as an Emacs key, or ignores it). To keep it reachable, give it a second stroke of its own; pressing the prefix twice is the usual choice. Sending the prefix itself gives the key back as it was on each system, which is not the same thing on both — say so in the comment rather than calling it Cut:
kt_cx["Ctrl-X"] = "Ctrl-X" # Ctrl-X Ctrl-X: Ctrl-X as before (Cut on Windows)
keymap.replace_key("Insert", "LCtrl") # swap a key outright
keymap.define_modifier("Apps", "User0") # turn a key into your own modifier
replace_key runs before everything else; the rest of the config only ever sees
the replacement.define_modifier makes a key act as one of User0–User3 — modifiers that no
application sees. While defined, the key loses its original meaning entirely
(it is never emitted), so User0-J bindings cannot clash with anything an app
understands.define_modifier("LWin", …) is refused: a user modifier promises to be invisible
to everything, and a Windows key cannot be. Retiring one does not retire it
everywhere:
Everything else does go: Win+I, Win+T and their kind do not fire, and no application receives the key. The sample configuration reaches User0 the way Keyhac for Windows always did, retiring both Windows keys first:
keymap.replace_key("LWin", 235) # 235, 255: unassigned key codes
keymap.replace_key("RWin", 255)
keymap.define_modifier(235, "User0")
That is a deliberate trade — the Windows key is the only key every keyboard can
spare — and it does not change the two exceptions above. Do not begin an action
bound under that modifier by typing g.
One-shot modifiers (O- prefix) give a modifier key a second life: held with
another key it modifies as usual; tapped alone, it fires the one-shot binding.
kt["O-LCmd"] = "Eisu" # tap left Cmd alone -> IME off; held -> still Cmd
A one-shot can carry modifiers of its own — the grammar is
O-{Modifier-}...{Key} — and they are matched exactly, like in any other
binding. One key can therefore drive two directions:
kt["O-RCmd"] = next_terminal_window # tap right Cmd
kt["O-Shift-RCmd"] = prev_terminal_window # tap it with Shift held: other way
Those modifiers have to be held before the one-shot key goes down, and stay held until it comes back up — “tapped alone” means precisely that the key’s own press was the last input event before its release. Anything in between cancels the tap: another key pressed or released, a modifier included, and any mouse click or wheel turn. Half-finished shortcuts therefore do not trigger it.
Because the modifiers are part of the condition, a bare O-RCmd does not fire
while Shift is held — O-Shift-RCmd is what runs then, and nothing does if it
is unbound.
def wrap():
with keymap.get_input_context() as ctx:
ctx.send_key("Ctrl-C") # key expression, incl. modifiers
ctx.send_text("hello") # literal text, any characters
get_input_context() batches virtual input and reconciles modifiers for you: held
physical modifiers are released around the batch and restored after, so
ctx.send_key("Ctrl-C") works even while your binding’s own modifiers are still
physically down. It is safe from a ThreadedAction worker thread too.
For simple cases there are ready-made actions:
kt["Fn-Semicolon"] = InputText("me@example.com") # type a literal string
Mouse output: MouseMove(dx, dy), MouseButtonDown/Up/Click(button) ("left"
by default, or "right" / "middle"), MouseWheel(notches),
MouseHorizontalWheel(notches) (positive is away from you / to the right, 1.0 =
one notch) — plus the matching ctx.send_mouse_* methods. Buttons and wheels release held
modifiers first (so a User0-… binding does not click with a phantom modifier);
moves keep them. Relative moves are injected acceleration-proof on both OSes, and
rapid synthetic clicks register as double-clicks.
if keymap.get_ime_status(): # True on, False off, None can't tell
keymap.set_ime_status(False) # returns whether the state was reached
Both act on whatever holds the input focus, and neither takes a window. That is the one contract the two OSes can both honor: Windows reaches the state through a window handle and so could address a background window, while macOS only ever exposes “the current input source”. A window argument would mean two different APIs wearing one name.
get_ime_status() returns None — not False — when the state cannot be
determined: no IME is installed, or on Windows a TSF-only IME that does not answer
the IMM32 query. set_ime_status() reads the state back rather than assuming the
call took, so its False means the IME declined or there was none to ask.
Some caveats worth knowing:
set_ime_status(True) under en-US returns False
instead of switching the input language. Switching languages stays the user’s own
Win+Space. A portable config should therefore treat False as “the user is not
in an IME language right now”, not as a failure worth retrying.send_key() only queues its events for the application to pick up
later — so the restore lands first and the keys compose anyway ("git status"
arrives as "gいt"). Waiting it out is not the fix either: a key-triggered
action runs on the main thread inside the keyboard hook, where sleeping past the
hook timeout gets the hook unhooked. For literal text use ctx.send_text() or
InputText, which inject the characters themselves and are unaffected by the
IME. If keys must go out with the IME closed, close it and leave it closed — the
Kana / 半角全角 key is how the user puts it back.For simply toggling, the key names cost nothing and work on both OSes: Eisu is
IME off and Kana is IME on, reaching the macOS keys of those names and Windows’
VK_IME_OFF / VK_IME_ON.
kt["O-LCmd"] = "Eisu" # tap left Cmd alone -> IME off
kt["O-RCmd"] = "Kana" # tap right Cmd alone -> IME on
Windows additionally has the physical JIS keys Kanji (半角/全角), Henkan (変換)
and Muhenkan (無変換), which macOS has no equivalent of — guard those with
keymap.platform.
keymap.clipboard_history.max_items = 500
kt["Fn-V"] = ShowClipboardHistory()
ShowClipboardHistory() opens the chooser popup over the focused window: type to
filter, Up/Down to select, Enter pastes into the app you came from,
Shift-Enter only sets the clipboard, Escape cancels. Pressing the hotkey again
closes it.
Entries keep more than their text. Rich text (RTF/HTML), images and copied files are pasted back the way they were copied. Option-Enter (Alt-Enter on Windows) pastes an entry’s text alone, without its formatting; Option-Shift-Enter sets it without pasting. A copy that offers a picture of itself along with its text, such as spreadsheet cells, is listed by its text, and its preview shows both. An entry marked (text only) came from a copy the history could keep only the text of. Choosing the entry that is still on the clipboard pastes it untouched, with everything the copy offered.
Rich text and images last for the session (max_session_data_size, 64 MB by
default; past it the oldest fall back to their text). Text and file paths are saved
across restarts. Content a password manager marks as concealed is never recorded.
While such content, or something in a format the history cannot read, is on the
clipboard, a Current clipboard row comes first and pastes it untouched.
Shift-Delete in the list removes the selected entry from the history, and from
clipboard.json (fn-Shift-⌫ on a Mac keyboard). The clipboard itself keeps what
it holds. A source of your own can offer the same by overriding remove().
Filtering is multi-word AND substring, plus Migemo, so typing gijiroku finds an
entry containing 議事録 without switching to an input method.
The popup does not take keyboard focus, which is what keeps the application you came from active, keeps the console where it is, keeps you on the desktop you are on, and lets the paste go out with no delay. The keystrokes reach the popup through Keyhac’s own key hook instead. The one consequence to know about: an input method cannot compose in the filter field — composition follows OS keyboard focus, and this window does not take it. Type romaji and let Migemo find the Japanese.
Your key bindings work inside the popup. While it is open, key tables are
matched as if the popup were the focused window, and what a binding types goes to
the popup rather than to the app underneath. A table that applies everywhere
applies there too, so a global cursor remap moves the selection with no extra
setup; remaps, functions, multi-stroke prefixes and user modifiers all work. To
bind keys for the popup alone, match it by name — it reports itself as app
Keyhac, title Chooser (focus path /Keyhac/Chooser, which the console shows
while it is open):
kt = keymap.define_keytable(focus_path_pattern="*")
kt["Ctrl-J"] = "Down" # also moves the popup's selection
kt["Ctrl-K"] = "Up"
kt_chooser = keymap.define_keytable(app="Keyhac", title="Chooser")
kt_chooser["Ctrl-G"] = "Escape" # only in the popup
Keys no table binds keep their popup meaning (Up/Down, Enter, Escape, typing into
the filter). The app underneath keeps its own meaning for the rest: keymap.focus
and window actions still refer to it, and a key output that the popup cannot
take — Ctrl-S, say — is dropped rather than sent there.
kt["Fn-Shift-V"] = ShowClipboardSnippets([
("📧", "me@example.com"), # (icon, text)
("📮", "Mailing address", "400 Broad St, ..."), # (icon, label, text)
("🕒", "Date", DateTimeSnippet("%Y-%m-%d")), # (icon, label, callable)
])
kt["Fn-Ctrl-V"] = ShowClipboardTools([
("🔄", "Quote", ShowClipboardTools.quote),
("🔄", "Upper case", str.upper),
("🔄", "Pretty JSON", my_pretty_json), # str -> str
])
Tools transform the current clipboard text; the built-ins are quote, unindent,
to_half_width and to_full_width, and any str -> str callable works.
History behavior is configurable via keymap.clipboard_history: max_items
(default 1000), max_data_size (largest text captured, default 10 MB),
max_persist_data_size (largest entry written to disk, default 64 KB), and
persist = False to keep history in memory only. The API is scriptable too:
items(), get_current(), set_current(text).
Three choosers is three hotkeys, and a hotkey is the scarce thing — there are only so many you can hold. A source is a value you hand to one window instead, so several kinds of row share one key and one incremental search, each row labelled on the right with where it came from:
kt["Fn-P"] = ShowCandidates([
ClipboardHistorySource(),
SnippetsSource(my_snippets),
ClipboardToolsSource(my_tools),
])
Anything that returns a list can be a source — no class to subclass:
def open_windows():
return [Candidate(icon="🪟", display=w.title, payload=w)
for w in keymap.list_windows() if w.title]
kt["Fn-Shift-W"] = ShowCandidates(open_windows,
on_chosen=lambda c, mod: c.payload.activate())
Rows are ordered by how well they match, not by which source produced them: a match at the start of a row beats one starting a word, which beats one inside a word, and an earlier or shorter match wins a tie. With an empty query there is nothing to judge, so the sources’ own order stands — clipboard history newest first.
A source with real work to do can yield instead of returning a list. Its first rows appear immediately and the rest arrive while the window is already open, and closing it or switching page simply stops asking. Yield often, and do not block: a source runs on the main thread, in slices, and one that does not return holds the keyboard.
Give it a class once it wants a name in a shared window and its own idea of what
choosing does — CandidateSource with name, candidates() and on_chosen(). Enter runs
whatever the chosen row’s source says, so rows from different sources can mean
different things in the same window: paste this, activate that, press the other.
A single row can override even that with Candidate(action=...).
ShowClipboardHistory() and its two siblings are presets over exactly these
sources.
Group the sources into named pages and one key reaches all of them. Left and Right move between pages, and the query comes with you — type what you are looking for, then look for it somewhere else without retyping it. The current page is named at the right of the filter field.
kt["Fn-P"] = ShowCandidates([
ChooserPage("Run", [keys, actions]),
ChooserPage("Paste", [clipboard, snippets, tools]),
ChooserPage("Click", [menus, controls, windows]),
])
Name a page for what Enter does on it. The query you carry between pages is
then the noun and the page is the verb: type mail, and Left/Right asks run it,
paste it, or click it.
Aim for three, with the one 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. The pages stop at the
ends rather than wrapping, so left is left — and the ‹ or › beside the name
disappears when there is nothing that way.
If you want more, bind another key to another ShowCandidates. A key is the
scarce thing here, but it is yours to spend.
@ narrows to one sourceInside whichever page you are on, type @ and a source name — @Clip,
@Menu, @Key — to see only that source’s rows. Tab extends what you have
typed as far as it is sure of, and adds a space once one name is left, so the
rest of the query follows straight on.
The names are the ones already shown beside each row, so there is nothing to
memorise, and a name that is not on this page simply matches nothing. The rest
of the query still filters: @Menu save looks for save among menu commands.
This is why three pages is enough. A page is what you would do with it; @
is which of the things there you meant.
The built-in sources are ClipboardHistorySource, SnippetsSource,
ClipboardToolsSource, MenuItemsSource (every command in the front
application’s menus, with its shortcut), KeyBindingsSource (every binding in
effect right here, and Enter runs it — a binding you can run from a list does
not need a key of its own) and ActionsSource (every ThreadedAction under
~/.keyhac/extensions/, startable without ever binding it to anything) and
WindowControlsSource (everything clickable in the front window, by name).
The last two read the front application on every invocation, so give each a
ChooserPage of its own rather than putting it in a merged one.
BrowserTabsSource lists the tabs open in Chrome, Edge and Safari, across all
their windows, by title. Enter selects the tab and brings its window to the front.
Only tabs visible in the tab bar are listed: Chrome leaves out a tab it has no room
to show. It reads every browser window each time, so it too belongs on a page you
go to deliberately.
BrowserBookmarksSource lists the bookmarks of Chrome, Edge and Safari, and Enter
opens one in a new tab of the browser it came from. On macOS they come from each browser’s Bookmarks
menu, because macOS protects the browsers’ files. A browser’s bookmarks appear only
while it is running, and they can be found by title or folder, as the menu does not give
the URL. Chrome and Edge list the profile of their last active window. On Windows,
they come from the default browser’s files, for every profile, whether or not it is
running, and can also be found by URL. That browser must be Chrome or Edge: with any
other as the default, nothing is listed. Bookmarks are read each time and are not
stored.
ApplicationsSource lists the installed applications, and Enter launches one:
the .app bundles in the Applications folders on macOS, what the Start menu
lists on Windows.
MenuItemsSource is macOS only. There a 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 — which is what makes a flat list of every command
possible. A Windows menu belongs to a window, may not be there at all, and is
filled only when it opens, so the source finds no menu bar and yields nothing;
its top-level items are UI elements of the window instead, and
WindowControlsSource lists them with everything else clickable.
Build each source once and share it between pages. A source is read once
per window and remembered against the object, so a MenuItemsSource that
appears both in an everything-page and in a page of its own walks the menu bar
once — if it is the same instance. Two separately built sources are two
sources, which is what you want when they differ.
menus = MenuItemsSource()
kt["Fn-P"] = ShowCandidates([
ChooserPage("All", [clipboard, menus]),
ChooserPage("Menus", [menus]),
])
Pages are also how an expensive source stays affordable: one that has real work to do — walking the window’s controls, asking a server — costs that work every time it is in the page being opened, so putting it in a page of its own means it is paid for only when you ask for it.
Once the selection rests on a row, a preview window beside the chooser shows what one line cannot: the whole text with its size and format, an image, copied files, an action’s description. Clipboard entries, snippets, clipboard tools (the converted result, before you choose it), actions, key bindings (the docstring and what else follows a multi-stroke prefix) and menu items (the full path and the shortcut) have one. Window controls do not: the outline on the real control says which one a row is, and a window beside the chooser could cover it.
A source of your own offers one by overriding preview():
class Branches(CandidateSource):
name = "Branch"
preview_background = True # it runs git, not Keyhac: a worker may run it
def preview(self, candidate):
log = subprocess.run(["git", "log", "-5", "--oneline", candidate.payload],
capture_output=True, text=True).stdout
return CandidatePreview(title=candidate.payload, text=log)
CandidatePreview takes a title, an image (encoded bytes or a path),
text and fields — (label, value) pairs. Return None for rows whose label
already says it all. preview() is asked only after the selection rests, so it
may do real work; on the main thread that work holds the keyboard, so a slow one
sets preview_background = True, under the same rule as background: it may
touch only the world outside Keyhac.
By default the chooser opens under the caret, falling back to the focused control and then to the middle of the focused window. Each step falls through when the one before it cannot be read or cannot be believed — a good many applications answer the caret question with a rectangle that is not where the caret is, and a popup placed on one of those lands somewhere nobody was looking.
Pass anchor="window" for a chooser that acts on the window rather than on a
place in it — a window switcher has no business opening beside your caret:
kt["Fn-O"] = ShowCandidates([ChooserPage("Windows", [OpenWindows()])],
anchor="window")
Applications differ enormously here, so find out about one rather than
guessing. Bind ReportCaretAnchor() to a key and press it inside the
application in question:
kt["Fn-Ctrl-C"] = ReportCaretAnchor()
The console gets the caret Keyhac can read there — or why it cannot — at INFO,
with no debug logging to turn on first, and a balloon appears at the place it
found. make caret-probe does the same from a terminal, but a terminal is
what is in front while it runs, so the key is usually the one you want.
Custom choosers may also derive from ChooserAction: implement
list_items() -> [(icon, label, ...)] and on_chosen(item, modifier_flags); the
open/filter flow is inherited. Three class attributes tune it: matcher (default
substring + Migemo; WildcardMatcher() for * and ?), activates (default
False; set it True only if the filter field genuinely needs an input method,
which costs the focus of the application underneath) and anchor (above).
kt["O-RCmd"] = ActivateApplication(app="Terminal|ターミナル", # go to it, then
launch="Terminal.app") # window by window
kt["Fn-1"] = ActivateWindow(app="code|Visual Studio Code") # bring forward
kt["Fn-T"] = LaunchApplication("Terminal.app") # launch, every press
kt["Fn-Ctrl-Left"] = MoveWindow(direction="left", distance=20)
kt["Fn-Alt-Left"] = MoveWindow(direction="left", distance=9999,
window_edge=True, screen_edge=True)
kt["Fn-Ctrl-J"] = SnapWindow("left") # tile: left/right/top/bottom/full
kt["Fn-F"] = SnapWindow("full") # ratio=2/3 etc. picks the split
Three actions reach an application, and they differ in how much of “take me
there” they do. ActivateApplication does all of it: a press brings the
application’s front-most window forward, a press made while it is already in
front moves on to its next window (bind a second key with reverse=True to
walk back), and launch= starts it when it is not running. ActivateWindow is
the same minus those two — one press, the front-most window, never a launch.
LaunchApplication only hands the name to the OS, which on Windows means a new
window on every press.
On Windows, the name given to launch= or LaunchApplication can be the one the
Start menu shows, such as launch="Calculator", and this is how to reach a
Microsoft Store application. The whole name has to match, ignoring case. The
Start menu is asked first, so its entry wins over a same-named command on PATH;
to start the command instead, name it with its extension (launch="xefm.exe").
A path or URL goes straight to the OS, as does a name the Start menu does not
have. Start menu names follow the display language, so a config shared between
languages is safer with an executable name.
The rotation keeps no state: which window is current is read from the z-order
each time, and the order walked is where the windows sit on screen, so it
survives a config reload and windows opening, closing or being dragged
elsewhere. Match on the name the OS reports — macOS localizes it, so a
Japanese system calls Terminal ターミナル; the console’s focus fields show the
live value.
MoveWindow nudges by distance pixels (default 10), or with
window_edge=/screen_edge= travels until it hits other windows’ edges / the
screen edge (hopping to the next monitor when already there). Only screen_edge
is on by default. SnapWindow tiles within the screen’s work area — menu bar,
Dock and taskbar stay uncovered — taking half the screen unless ratio= says
otherwise. It places the window itself rather than handing it to the OS’s snap:
the window lands where Windows’ snap would put it, but no Snap Assist appears
and no snap group is formed.
For your own logic, Window objects are fully portable:
window = keymap.get_active_window() # or find_window(app=, title=,
x, y, w, h = window.get_frame() # class_name=), list_windows()
# the visible frame: Windows'
# invisible resize border is not
# part of it, on either accessor
window.set_frame(x + 100, y)
window.activate()
window.minimize(); window.maximize() # maximize: Window > Fill on macOS
window.enter_full_screen() # macOS only
window.restore() # the way back out of all three
window.is_minimized(); window.is_maximized(); window.is_full_screen()
window.title; window.app_name; window.pid; window.class_name # class_name: Windows
find_window matches exactly like define_keytable: wildcards, | alternation,
case-insensitive, .exe optional. Screen geometry lives on keymap:
screen_frames() (whole screens, primary first), screen_work_frames() (minus
menu bar / Dock / taskbar) and window_frames() (all normal on-screen windows) —
each frame is an (x, y, w, h) tuple in a shared coordinate space.
Thread contract: there is none to follow. Window objects, elements,
keymap.ui and the geometry queries can all be used from a
ThreadedAction.run(). They talk to the other application directly, so a
slow or hung application stalls that action and not the keyboard. The few
platform calls that cannot run off the main thread take themselves there:
the clipboard, screen_work_frames() and the IME calls.
What makes that possible is one rule: Keyhac’s own windows do not exist to
Keyhac’s APIs. Window lookups skip them, the element API never hands one
out, and focus.element is None while a Keyhac window is in front. (Key
tables still match there, on app= and the rest.) Screen readers are not
affected.
keymap.focus — and the argument of every custom_condition_func — is a snapshot
of the current keyboard focus: app_name, pid, window_title, class_name
(Windows only), path (the focus path string), element and native.
focus.element is the focused semantic element — an AX element on macOS, a UI
Automation element on Windows. Both have the same shape:
get_attribute_names(), get_attribute_value(name), get_action_names(),
perform_action(name), parent() — but each uses its own OS’s vocabulary:
| macOS (AX) | Windows (UI Automation) | |
|---|---|---|
| role | AXRole |
ControlType ("Edit", "Window", …) |
| label | AXTitle |
Name |
| text value | AXValue |
Value |
| selection | AXSelectedText |
SelectedText |
| press | perform_action("AXPress") |
perform_action("Invoke") |
Element-level code therefore branches on keymap.platform. The failure modes are
gentle: an unsupported attribute reads None, an unknown action logs and returns
False. focus.native is the platform power object — the same AX element on
macOS, an HWND wrapper on Windows.
Reading and writing another application’s UI — searching element trees, waiting
for a screen to change, filling fields — is a separate surface reached through
keymap.ui (or self.ui inside a ThreadedAction):
class Extract(ThreadedAction):
def run(self):
window = self.ui.window(app="Safari")
window.wait_for(role="AXTable", message="the results to load")
for row in window.find_all(role="AXRow"):
print([cell.all_text for cell in row.children])
It is deliberately its own namespace and method-style: a config binds keys, an
action drives somebody else’s UI, and only UINode, WaitTimeout and
FillFailed are importable. See Action API for the full
surface, and keyhac/skills/keyhac/ (references/actions.md) for how to write one.
A UINode is a snapshot — it records what an element was when it was read,
and the screen moves on without it noticing. reread() refreshes one
deliberately, and StaleElement tells you a node you are holding has outlived
what it pointed at. AI Integration covers turning the
endpoint on and what it can reach.
kt["Fn-OpenBracket"] = ToggleRecordingKeys() # record on/off
kt["Fn-CloseBracket"] = PlaybackRecordedKeys() # replay
StartRecordingKeys() / StopRecordingKeys() exist if you prefer separate keys.
Replayed keys run back through your keymap, so recorded bindings expand on
playback. The buffer is keymap.replay_buffer.
Anything slow — network, subprocess, sleeping, heavy computation — must not run
inline: your functions execute inside the keyboard hook’s deadline. Subclass
ThreadedAction instead:
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}")
kt["Fn-G"] = Fetch()
starting() and finished() run on the main thread and should stay light;
run() runs on a worker, and everything an action needs is allowed there (see
the thread contract above).
The pool is a single worker shared by every threaded action, so a run() that
sleeps or loops delays every other one until it returns. Keep long waits short, and
prefer keymap.call_on_main_thread(func) — thread-safe, and the supported way to
reach the main thread from anywhere — over holding the worker to wait for something.
Put a ThreadedAction subclass in a file under ~/.keyhac/extensions/ and it can
be started without a key at all — by name from the candidate window, and by an
AI assistant through the MCP endpoint. Subdirectories count, so
extensions/mine/extract.py is addressed as mine.extract.Extract; names
beginning with _ are treated as helpers and not offered.
Subclassing ThreadedAction is what puts it on those lists. A class that merely
defines __call__ binds to a key perfectly well and is deliberately not
enumerated: 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. If you want a
fast action on the list, subclass anyway and leave run() short — the worker
thread costs nothing when the work is small.
keymap.pop_balloon("hello", "Keyhac is running", 2.0) # name, text, timeout
keymap.close_balloon("hello")
A balloon is a small frameless tooltip, and it opens where you are typing: under
the caret, falling back to the focused control, then to the title bar of the focused
window, and only with none of those to the top-right corner of the main screen. That
is the same chain the chooser walks — everything in Where the window
opens applies here too, including the applications that
answer the caret question with a rectangle that is not where the caret is.
ReportCaretAnchor() is how you find out what one of those does.
Multi-stroke tables pop a balloon of their own automatically.
anchor= places it somewhere else:
keymap.pop_balloon("win", "acting on this window", 2.0, anchor="window")
keymap.pop_balloon("mode", "insert mode", 2.0, anchor="corner")
"window" goes straight to the focused window’s title bar, for a balloon about the
window rather than about a place in it. "corner" is the top-right of the main
screen, for a balloon that is not about a place at all — and the one placement that
asks the platform nothing.
Popping a balloon is main-thread work, as it always was: it draws a window, and
finding the caret is a UI Automation (Windows) or Accessibility (macOS) call on top
of that. Call it from a key binding, or from a ThreadedAction worker by way of
keymap.call_on_main_thread.
For something the user should see when they may be looking elsewhere, such as a
long action finishing, post a native notification from finished() instead:
keymap.notify("Deploy finished", "All 12 services are up") # title, text
It goes to Notification Center on macOS and appears as a toast on Windows. macOS asks for permission the first time. Where a notification cannot be posted, such as when permission was refused, the console says so. Focus and Do Not Disturb can hold a notification back.
A balloon and a notification are for different moments, and neither stands in for the other. A balloon is Keyhac’s own window, where the user is looking now: the answer to a key they just pressed, or a state they are watching. Once they look away it has done its job or missed it. A notification is the operating system’s, for a result that arrives while they may be elsewhere: it waits in the system’s list of notifications, and it follows their settings — the permission they gave, Focus, Do Not Disturb. So pick by where the user will be when the message arrives, not by which one works. A notification that is not posted is usually those settings at work; popping a balloon instead overrides a choice the user made and puts the message on a screen nobody may be watching. What a run did belongs in what it leaves behind — its output, its log — so the user learns it whether or not a message was seen.
on_click runs when the user clicks the notification. This argument is Preview and
may change in any release:
def reveal():
subprocess.run(["open", "-R", path]) # explorer /select,<path> on Windows
keymap.notify("Saved", path, on_click=reveal)
It takes no arguments and runs on the main thread, so it has to be quick. For
anything slow, pass a ThreadedAction instance, which can be called the same way
and does its work on a worker: on_click=ConvertReport(path). A click does nothing
after Keyhac has restarted. On Windows only the latest notification’s on_click runs.
In --no-ui mode these attributes are absent — guard with
getattr(keymap, "pop_balloon", None) if your config must run headless.
print() and getLogger(name) both land in the console window:
logger = getLogger("Config")
logger.info("loaded")
The console’s dropdown filters by level; -d/--debug on the command line enables
debug logging from startup. The console also shows the last key event and the live
focus path — the two things you need when writing new bindings.
To find out what a binding or an action costs, or why Keyhac is busy, choose
Advanced > Start Profiling in the tray / menu-bar menu, do the slow thing, and
choose Advanced > Stop Profiling. A capture nobody stops ends after ten minutes.
Keyhac then opens a new folder under ~/.keyhac/diagnostics/:
| File | Content |
|---|---|
summary.txt |
The part to read: your code, key handling, and each thread |
python-stacks.txt |
Every Python stack seen, in the folded format flame-graph tools read |
native-sample.txt |
macOS only: native stacks from the system’s sample tool |
summary.txt has these sections:
config.py or a module from extensions/ on the stack,
by function and by line, per thread.ThreadedAction.Times are wall-clock. A thread that is waiting still shows as time, in the call it waits in: the event loop’s own call on the main thread, a queue or a lock on a worker.
Stacks are sampled every few milliseconds, so a short handler can fall between samples. Key handling is measured on every key event and does not miss it.
The report names your bindings, functions and files. It holds no typed text: keys with no binding are counted together, not one by one.
Keyhac stays running for weeks, so memory that accumulates matters. To look into it,
choose Advanced > Write Memory Report. Keyhac opens a new folder under
~/.keyhac/diagnostics/:
| File | Content |
|---|---|
summary.txt |
The part to read |
types.txt |
Every Python type: objects, bytes, and growth since startup |
history.csv |
The process’s memory over time |
native-footprint.txt |
macOS only: the system’s breakdown of the process’s memory, from footprint |
allocations.txt |
Only while allocations are tracked (below) |
Keyhac records its memory every ten minutes from startup, so the history is already there when you first notice a problem. To read a report, ask in this order:
Types cannot show strings or bytes. To see those, and which line of code allocated what is still alive, tick Advanced > Track Python Allocations, and write a report a while later. It sees only what is allocated after you tick it, and Keyhac is slower and uses more memory until you untick it, so leave it off otherwise.
A report holds counts, sizes, and the names of types, threads and files. It holds no clipboard contents, console text or window titles.
| API | Notes |
|---|---|
keymap.platform |
"windows" / "mac" |
keymap.define_keytable(...) |
key tables + focus conditions |
keymap.replace_key(src, dst) / define_modifier(key, mod) |
pre-engine remap / user modifiers |
keymap.get_input_context() |
virtual input batch; thread-safe |
keymap.focus |
current Focus snapshot |
keymap.get_active_window() / list_windows() / find_window(...) |
portable Window objects (Keyhac’s own windows excluded) |
keymap.screen_frames() / screen_work_frames() / window_frames() |
screen/window geometry |
keymap.get_ime_status() / set_ime_status(on) |
IME on/off for the input focus |
keymap.clipboard_history |
settings + items() / get_current() / set_current() |
keymap.editor / edit_config() / reload_config() |
config lifecycle (tray menu uses these) |
keymap.replay_buffer |
macro buffer behind the record actions |
keymap.pop_balloon(name, text, timeout, anchor=…) / close_balloon(name) |
balloons (UI mode only); opens at the caret unless anchor says otherwise |
keymap.notify(title, text, on_click=None) |
native OS notification (UI mode only) |
InputText(s) |
type a literal string |
MoveWindow(...) / SnapWindow(...) / ActivateApplication(...) / ActivateWindow(...) / LaunchApplication(...) |
window & app actions |
MouseMove / MouseButtonDown/Up/Click / MouseWheel / MouseHorizontalWheel |
mouse output actions |
ShowClipboardHistory() / ShowClipboardSnippets(...) / ShowClipboardTools(...) / DateTimeSnippet(fmt) |
clipboard UI actions |
ChooserAction |
base class for custom chooser popups |
ThreadedAction |
background work |
Start/Stop/Toggle/PlaybackRecordedKeys() |
keyboard macros |
getLogger(name) |
console logging |
Exact signatures, defaults and per-argument notes for all of these are in the API reference.