feat(hotkeys): read an skhdrc

komorebi for Mac's users bind komorebic in an skhdrc, so that is the first file
the crate reads. `skhd::parse` reads the whole syntax into the model: bindings
with every modifier skhd has, literal keys and macOS keycodes, mode declarations
(with `@` and an entry command), mode switches and bindings in one or more
modes, per-application lists with `~` and `*`, `.blacklist`, and skhd.zig's
`.define` command templates and application groups, which are expanded where
they are used. A mode may be used before it is declared, so bindings are put in
their modes at the end of the file.

Reading never fails. Text that is not valid skhd is an error with its span and
is skipped, up to the end of the line or of the list it opened, and reading goes
on. What is valid but not realized the way skhd does it has a warning that says
so: side-specific modifiers are the modifier, a capturing mode lets unbound keys
through, `->` does not pass the key on, and `fn`, `.load`, `.alias`, key
forwarding and key sequences are left out. Comments, continued lines and the
line numbers of diagnostics are shared with the readers that follow.

The tests cover the modifiers, macOS keycodes and the shifted symbol rule,
comments and continued lines, modes, lists, defines, spans and recovery after an
error, and the corpus test now checks that every skhdrc fixture reads into the
keymap of its case. The keymaps of the other cases are written down too, for the
readers to be written against.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:20:57 -07:00
1 parent 0520068b48
commit ecf91f077f
8 files changed
+1806 -7

No files matched your search

+3 -3
View File
@@ -91,9 +91,9 @@ without a checkout of the toolchain.
- [`komorebi-client`](komorebi-client): a library that sends messages to the
daemon, reads its answers, subscribes to its notifications, and re-exports
the types they are made of.
- [`komorebi-hotkeys`](komorebi-hotkeys): the key bindings of skhd, whkd and
sxhkd files in one model, with the keys as KDE stores them. It does not depend
on the daemon. Its tests read the files in
- [`komorebi-hotkeys`](komorebi-hotkeys): reads the key binding file of skhd
into a model that also has room for whkd's and sxhkd's, with the keys as KDE
stores them. It does not depend on the daemon. Its tests read the files in
[`komorebi-hotkeys/tests/fixtures`](komorebi-hotkeys/tests/fixtures), where
each case is written in every format that can express it.
- [`komorebic`](komorebic): the command line. A subcommand that asks something
+12 -3
View File
@@ -1584,6 +1584,7 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
- **Diagnostic**: something about a file its user should know: its span (byte offsets and line),
its severity (error, warning, note) and how faithfully the construct is realized (exactly,
approximated, not at all).
- **Parsed**: a file, read: the keymap and the diagnostics.
### The parts
@@ -1592,6 +1593,11 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
`Combo`, which applies the shifted symbol rule: KWin matches the character a key press
produced, so Alt+Shift+1 is registered as Alt+!.
- [`ir`](../../komorebi-hotkeys/src/ir.rs): the model.
- [`skhd`](../../komorebi-hotkeys/src/skhd.rs): reads an skhdrc. A mode may be used before it
is declared, so each binding waits for the end of the file to be put in its modes. skhd.zig's
`.define` templates and application groups are expanded where they are used.
- [`text`](../../komorebi-hotkeys/src/text.rs): what the readers share: line numbers, comments,
continued lines and the diagnostics' wording.
- [`tests/fixtures`](../../komorebi-hotkeys/tests/fixtures): the corpus, `<case>.skhdrc`,
`<case>.whkdrc` and `<case>.sxhkdrc`, each case in every format that can express it.
@@ -1602,7 +1608,9 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
| A combo is in the form KWin matches (the shifted symbol rule is applied) | type system: `Combo`'s fields are private, and `Combo::new` applies the rule | `compile_fail,E0451` on `Combo`; `shift_on_a_symbol_key_is_the_symbol_it_types` | none |
| A key has the same code whichever vocabulary names it | test | `the_three_vocabularies_name_the_same_keys` | none |
| Positional key names (macOS keycodes, `oem_*`) are read as on a US layout | convention only | none | none |
| The files of a corpus case mean the same keymap | convention only | `the_files_of_a_case_say_what_it_is_about_in_the_same_words` checks only that they start with the same comment | none |
| Reading a file returns a keymap, whatever the text | type system: a reader returns `Parsed`, not a `Result` | none | none |
| Text that is left out has a diagnostic that points at it | test | `what_cannot_be_read_is_reported_and_left_out`, `reading_goes_on_after_an_error`, `diagnostics_point_at_the_text_they_are_about` | none |
| A fixture reads, without errors, into the keymap of its case | test, for the skhdrc files; convention only for the others | `every_file_reads_without_errors_into_the_keymap_of_its_case` | none |
## Where to look in the code
@@ -1778,8 +1786,9 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
[`nix/tests/vm/suites/kwin-contract`](../../nix/tests/vm/suites/kwin-contract/test.py), the
behavior of KWin's per-output virtual desktops komorebi relies on, with two outputs and no
komorebi.
- [`komorebi-hotkeys/src/lib.rs`](../../komorebi-hotkeys/src/lib.rs): the key binding model, and
[`komorebi-hotkeys/src/qt.rs`](../../komorebi-hotkeys/src/qt.rs) the keys.
- [`komorebi-hotkeys/src/lib.rs`](../../komorebi-hotkeys/src/lib.rs): the key binding model,
[`komorebi-hotkeys/src/qt.rs`](../../komorebi-hotkeys/src/qt.rs) the keys, and one module per
format, [`skhd.rs`](../../komorebi-hotkeys/src/skhd.rs).
- [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module;
[`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in
real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py),
+12
View File
@@ -708,3 +708,15 @@ derives for the enum is an object with a `Placement` or an `Index` key, which th
`JsonSchema` impl of [`PlacementTarget`](../../komorebi/src/core/mod.rs) calls "not what
`Serialize` and `Deserialize` read and write". The schema `schema.json` has says a name, a number,
or text that is a number, which is also what the module's typed `config` takes.
## Why are the key binding files read by parsers written for komorebi?
All three formats, skhd's, whkd's and sxhkd's, are read by parsers written by hand in
`komorebi-hotkeys`. For whkd there is a Rust parser, `whkd-parser`, under the same license
as komorebi, but it requires a `.shell pwsh|powershell|cmd` line, panics in `Shell::from` on
any other shell, and its per-application bindings match Windows process names. For skhd and
sxhkd the reason is not recorded; this entry needs one.
What is not plain syntax is expanded while the file is read: skhd's `.define` templates and
application groups are replaced where they are used, so the model has only expanded bindings
in it.
+46
View File
@@ -40,11 +40,38 @@
//!
//! Key names are read as on a US keyboard layout; [the `qt` module](qt#a-us-layout-only) says
//! what that means for other layouts.
//!
//! # Reading a file
//!
//! Each format has a module with a `parse` function, which reads the text of a file into a
//! [`Parsed`]: the [`Keymap`] and the [diagnostics](Diagnostic) about the file. Reading never
//! fails. What is not valid syntax is skipped with an error, and what is valid but cannot be
//! realized on KDE, or only differently, is reported with a warning that says so. Each module
//! lists what it reads and what it does not.
//!
//! - [`skhd`]: an skhdrc, with modes, per-application bindings, `.blacklist` and skhd.zig's
//! `.define`.
//!
//! ```rust
//! use komorebi_hotkeys::{ParseOptions, Severity, skhd};
//!
//! let parsed = skhd::parse(
//! "alt - h : komorebic focus left\nlalt - l : komorebic focus right\n",
//! &ParseOptions::default(),
//! );
//! let bindings = &parsed.keymap.modes[0].bindings;
//! assert_eq!(bindings[1].chord[0].to_string(), "Alt+L");
//! // KDE has no left Alt, so the binding is on either Alt, and the reader says so
//! assert_eq!(parsed.diagnostics[0].severity, Severity::Warning);
//! assert_eq!(parsed.diagnostics[0].span.line, 2);
//! ```
#![deny(missing_docs)]
mod ir;
pub mod qt;
pub mod skhd;
mod text;
pub use ir::App;
pub use ir::Binding;
@@ -64,6 +91,25 @@ pub use ir::Span;
pub use ir::Support;
pub use ir::Then;
/// Options for reading a file.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ParseOptions {
/// The keyboard layout to read positional key names with: skhd's macOS keycodes and whkd's
/// `oem_*` keys, and the [shifted symbol rule](qt#the-shifted-symbol-rule).
///
/// The default for this is [`Layout::Us`](qt::Layout::Us), the only layout.
pub layout: qt::Layout,
}
/// A file, read: its keymap, and what the reader has to say about it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Parsed {
/// The bindings that could be read.
pub keymap: Keymap,
/// The diagnostics, in the order of the text they are about.
pub diagnostics: Vec<Diagnostic>,
}
/// The file formats this crate reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Format {
+10
View File
@@ -51,6 +51,16 @@ use std::fmt;
use std::ops::BitOr;
use std::ops::BitOrAssign;
/// A keyboard layout: which key is at each position, and which symbol Shift gives each key.
///
/// The US layout is the only one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Layout {
/// The US layout.
#[default]
Us,
}
/// A set of modifiers, as the flags Qt or's into a key code.
///
/// The four modifiers are the ones KDE knows. Side-specific modifiers (left Alt, right Alt) do
File diff suppressed because it is too large. Load diff
+190
View File
@@ -0,0 +1,190 @@
//! What the readers share: line numbers, diagnostics, comments and continued lines.
use crate::Diagnostic;
use crate::Severity;
use crate::Span;
use crate::Support;
/// The byte offset at which each line of a text starts.
pub(crate) struct Lines {
starts: Vec<usize>,
}
impl Lines {
pub(crate) fn new(text: &str) -> Lines {
let mut starts = vec![0];
starts.extend(text.match_indices('\n').map(|(i, _)| i + 1));
Lines { starts }
}
/// The span from `start` to `end`, with the line of `start`.
pub(crate) fn span(&self, start: usize, end: usize) -> Span {
let line = self.starts.partition_point(|&s| s <= start);
Span { start, end, line }
}
}
pub(crate) fn error(span: Span, msg: impl Into<String>) -> Diagnostic {
Diagnostic {
span,
severity: Severity::Error,
support: Support::Unsupported,
msg: msg.into(),
}
}
pub(crate) fn approximated(span: Span, msg: impl Into<String>) -> Diagnostic {
Diagnostic {
span,
severity: Severity::Warning,
support: Support::Approximated,
msg: msg.into(),
}
}
pub(crate) fn unsupported(span: Span, msg: impl Into<String>) -> Diagnostic {
Diagnostic {
span,
severity: Severity::Warning,
support: Support::Unsupported,
msg: msg.into(),
}
}
pub(crate) fn note(span: Span, support: Support, msg: impl Into<String>) -> Diagnostic {
Diagnostic {
span,
severity: Severity::Note,
support,
msg: msg.into(),
}
}
/// The diagnostic for a side-specific modifier, which KDE does not have.
pub(crate) fn one_sided(span: Span, written: &str, kde: &str) -> Diagnostic {
approximated(
span,
format!("`{written}` is {kde}: KDE does not tell the left and right {kde} apart"),
)
}
/// Drops a trailing ` # comment` from a command, unless the `#` is quoted or part of a word.
pub(crate) fn strip_comment(command: &str) -> &str {
let mut quote: Option<char> = None;
let mut previous = ' ';
for (index, c) in command.char_indices() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(None, '"' | '\'') => quote = Some(c),
(None, '#') if previous.is_whitespace() => return &command[..index],
_ => {}
}
previous = c;
}
command
}
/// Joins the lines of `text` that end in `\` with the next, with one space between the two.
pub(crate) fn join_continued(text: &str) -> String {
let mut joined = String::new();
let mut lines = text.split('\n').peekable();
while let Some(line) = lines.next() {
let line = line.strip_suffix('\r').unwrap_or(line);
match line.strip_suffix('\\') {
Some(continued) if lines.peek().is_some() => {
joined.push_str(continued.trim_end());
joined.push(' ');
if let Some(next) = lines.peek_mut() {
*next = next.trim_start();
}
}
_ => {
joined.push_str(line);
if lines.peek().is_some() {
joined.push('\n');
}
}
}
}
joined
}
/// The text of a binding as it was written, on one line: continued lines are joined, and the
/// lines of a block are trimmed and joined with a space.
pub(crate) fn one_line(text: &str) -> String {
let mut out = String::new();
let mut lines = text.split('\n').peekable();
while let Some(line) = lines.next() {
let line = line.strip_suffix('\r').unwrap_or(line);
match line.strip_suffix('\\') {
Some(continued) if lines.peek().is_some() => {
out.push_str(continued);
out.push(' ');
}
_ => {
out.push_str(line.trim_end());
if lines.peek().is_some() {
out.push(' ');
if let Some(next) = lines.peek_mut() {
*next = next.trim_start();
}
}
}
}
}
out.trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_trailing_comment_is_not_part_of_the_command() {
assert_eq!(
strip_comment("komorebic unstack # 0x29 is ;").trim(),
"komorebic unstack"
);
assert_eq!(
strip_comment("echo '# not a comment'"),
"echo '# not a comment'"
);
assert_eq!(strip_comment("echo a#b"), "echo a#b");
}
#[test]
fn lines_are_counted_from_one() {
let lines = Lines::new("a\nbc\n\nd");
assert_eq!(lines.span(0, 1).line, 1);
assert_eq!(lines.span(2, 3).line, 2);
assert_eq!(lines.span(5, 5).line, 3);
assert_eq!(lines.span(6, 7).line, 4);
}
#[test]
fn a_continued_line_is_joined_with_one_space() {
assert_eq!(
join_continued("komorebic focus \\\n left"),
"komorebic focus left"
);
assert_eq!(join_continued("a\\\nb\\\n c\nd"), "a b c\nd");
// a backslash on the last line continues nothing
assert_eq!(join_continued("a \\"), "a \\");
}
#[test]
fn a_binding_is_written_on_one_line() {
assert_eq!(
one_line("alt - x : komorebic \\\n flip-layout"),
"alt - x : komorebic flip-layout"
);
assert_eq!(
one_line("alt - n [\n \"a\" : x\n * ~\n]"),
"alt - n [ \"a\" : x * ~ ]"
);
assert_eq!(
one_line("alt - h : komorebic focus left"),
"alt - h : komorebic focus left"
);
}
}
+233 -1
View File
@@ -2,8 +2,20 @@
//!
//! Each case is a file per format in `tests/fixtures`, `<case>.skhdrc`, `<case>.whkdrc` and
//! `<case>.sxhkdrc`, for the formats that can express the case. The files of a case mean the same
//! keymap, and start with the same comment, which says what the case is about.
//! keymap, and start with the same comment, which says what the case is about. [`EXPECTED`] is
//! that keymap, written out by [`render`].
use komorebi_hotkeys::App;
use komorebi_hotkeys::Body;
use komorebi_hotkeys::DEFAULT_MODE;
use komorebi_hotkeys::Edge;
use komorebi_hotkeys::Keymap;
use komorebi_hotkeys::ParseOptions;
use komorebi_hotkeys::Parsed;
use komorebi_hotkeys::Run;
use komorebi_hotkeys::Severity;
use komorebi_hotkeys::Then;
use komorebi_hotkeys::skhd;
use std::path::PathBuf;
/// Every case, and the formats it is written in.
@@ -23,6 +35,169 @@ const CASES: &[(&str, &[&str])] = &[
("release", &["sxhkdrc"]),
];
/// The keymap of each case, as [`render`] writes it.
const EXPECTED: &[(&str, &str)] = &[
(
"plain",
"Alt+H: komorebic focus left
Alt+J: komorebic focus down
Alt+K: komorebic focus up
Alt+L: komorebic focus right
Alt+Q: komorebic close",
),
(
"modifiers",
"Meta+Return: konsole
Ctrl+Alt+Left: komorebic stack left
Alt+Shift+H: komorebic move left
Ctrl+Shift+Right: komorebic resize-edge right increase
Alt+!: komorebic move-to-workspace 0
Ctrl+Alt+(: komorebic move-to-workspace 8
Meta+Ctrl+Alt+Shift+A: komorebic retile
Ctrl+Alt+Shift+M: komorebic toggle-monocle",
),
(
"keycodes",
"Alt+[: komorebic cycle-stack previous
Alt+]: komorebic cycle-stack next
Alt+;: komorebic unstack
Alt+=: komorebic resize-axis horizontal increase
Alt+-: komorebic resize-axis horizontal decrease
Alt+{: komorebic cycle-focus previous",
),
(
"comments",
"Alt+H: komorebic focus left
Alt+X: komorebic flip-layout horizontal",
),
(
"braces",
"Alt+H: komorebic focus left
Alt+J: komorebic focus down
Alt+K: komorebic focus up
Alt+L: komorebic focus right
Alt+1: komorebic focus-workspace 0
Alt+2: komorebic focus-workspace 1
Alt+3: komorebic focus-workspace 2
Alt+!: komorebic move-to-workspace 0
Alt+@: komorebic move-to-workspace 1
Alt+#: komorebic move-to-workspace 2",
),
(
"scopes",
"Alt+N: firefox: komorebic focus-workspace 1 | kitty: ignore | *: komorebic focus-workspace 0
Alt+H: komorebic focus left",
),
(
"define",
"Alt+B: firefox: komorebic toggle-monocle | chromium: komorebic toggle-monocle | *: ignore
Alt+H: komorebic focus left
Alt+L: komorebic focus right",
),
(
"blacklist",
"blacklist: steam, dota2
Alt+H: komorebic focus left",
),
(
"modes",
"Alt+R: mode resize
Alt+Q: komorebic close
mode resize, captures, on enter: notify-send resize
[resize] H: komorebic resize-edge left increase
[resize] L: komorebic resize-edge right increase
[resize] Esc: mode default
[resize] Alt+Q: komorebic close",
),
(
"pause",
"pause Alt+Shift+P: komorebic toggle-pause
Alt+H: komorebic focus left",
),
(
"chords",
"Alt+W, H: komorebic move left
Alt+W, L: komorebic move right
Alt+R: mode Alt+R
mode Alt+R
[Alt+R] H: komorebic resize-edge left increase
[Alt+R] L: komorebic resize-edge right increase
[Alt+R] Esc: mode default",
),
("release", "release Alt+Space: komorebic toggle-float"),
];
/// Writes a keymap out, one line per binding, mode, blacklist and pause binding. Where each binding
/// was written, and the defines, are left out.
fn render(keymap: &Keymap) -> String {
let run = |run: &Run| match run {
Run::Command(command) => command.clone(),
Run::Mode(mode) => format!("mode {mode}"),
};
let mut lines = Vec::new();
if !keymap.blacklist.is_empty() {
lines.push(format!("blacklist: {}", keymap.blacklist.join(", ")));
}
if let Some(pause) = &keymap.pause {
lines.push(format!(
"pause {}: {}",
pause.combo,
pause.hook.as_deref().unwrap_or("nothing")
));
}
for mode in &keymap.modes {
let prefix = if mode.name == DEFAULT_MODE {
String::new()
} else {
let mut header = format!("mode {}", mode.name);
if mode.capture {
header.push_str(", captures");
}
if let Some(command) = &mode.on_enter {
header.push_str(&format!(", on enter: {command}"));
}
lines.push(header);
format!("[{}] ", mode.name)
};
for binding in &mode.bindings {
let chord: Vec<String> = binding.chord.iter().map(ToString::to_string).collect();
let edge = match binding.edge {
Edge::Press => "",
Edge::Release => "release ",
};
let body = match &binding.body {
Body::Run(action) => run(action),
Body::Scoped(scopes) => scopes
.iter()
.map(|scope| {
let app = match &scope.app {
App::Named(name) => name.as_str(),
App::Other => "*",
};
let then = match &scope.then {
Then::Run(action) => run(action),
Then::Ignore => "ignore".to_string(),
};
format!("{app}: {then}")
})
.collect::<Vec<_>>()
.join(" | "),
};
lines.push(format!("{prefix}{edge}{}: {body}", chord.join(", ")));
}
}
lines.join("\n")
}
/// Reads a fixture in the format its extension names.
fn parse(extension: &str, text: &str) -> Option<Parsed> {
let options = ParseOptions::default();
match extension {
"skhdrc" => Some(skhd::parse(text, &options)),
_ => None,
}
}
fn fixtures() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}
@@ -63,3 +238,60 @@ fn the_files_of_a_case_say_what_it_is_about_in_the_same_words() {
);
}
}
#[test]
fn every_file_reads_without_errors_into_the_keymap_of_its_case() {
for (case, extensions) in CASES {
for extension in *extensions {
let Some(parsed) = parse(extension, &read(case, extension)) else {
continue;
};
let errors: Vec<String> = parsed
.diagnostics
.iter()
.filter(|d| d.severity == Severity::Error)
.map(ToString::to_string)
.collect();
assert!(errors.is_empty(), "{case}.{extension}: {errors:#?}");
if let Some((_, expected)) = EXPECTED.iter().find(|(c, _)| c == case) {
assert_eq!(render(&parsed.keymap), *expected, "{case}.{extension}");
}
}
}
}
#[test]
fn every_case_but_the_sample_has_an_expected_keymap() {
for (case, _) in CASES {
let expected = EXPECTED.iter().any(|(c, _)| c == case);
assert_eq!(expected, *case != "sample", "{case}");
}
}
#[test]
fn the_sample_reads_completely() {
for extension in ["skhdrc"] {
let parsed = parse(extension, &read("sample", extension)).unwrap();
assert!(parsed.diagnostics.is_empty(), "{:#?}", parsed.diagnostics);
let bindings = &parsed.keymap.modes[0].bindings;
assert_eq!(bindings.len(), 50);
let rendered = render(&parsed.keymap);
for line in [
"Alt+L: komorebic focus right",
"Alt+{: komorebic cycle-focus previous",
"Alt+[: komorebic cycle-stack previous",
"Alt+(: komorebic move-to-workspace 8",
"Alt+=: komorebic resize-axis horizontal increase",
] {
assert!(rendered.lines().any(|l| l == line), "{extension}: {line}");
}
// no two bindings share a key
let mut keys: Vec<_> = bindings.iter().map(|b| b.chord.clone()).collect();
keys.sort();
keys.dedup();
assert_eq!(keys.len(), bindings.len());
}
}