Skip to main content

SequenceKeymap

Struct SequenceKeymap 

Source
#[non_exhaustive]
pub struct SequenceKeymap<A> { /* private fields */ }
Expand description

A table mapping sequences of normalized KeyInputs to a caller-defined action A.

This is the sequence-level analogue of keymap_core::Keymap: state-free, with the action type A brought by the caller. It is prefix-free by construction — see SequenceKeymap::bind and the crate-level docs — so lookup never needs a timeout to disambiguate.

Implementations§

Source§

impl<A> SequenceKeymap<A>

Source

pub fn new() -> Self

Creates an empty sequence map.

Examples found in repository?
examples/leader_sequence.rs (line 39)
37fn untimed() {
38    println!("== untimed ==");
39    let mut map = SequenceKeymap::new();
40    map.bind([ctrl('x'), ctrl('s')], Action::Save).unwrap();
41    map.bind([ctrl('x'), ctrl('c')], Action::Quit).unwrap();
42    map.bind([plain('g'), plain('g')], Action::GotoTop).unwrap();
43
44    // A stream a terminal might deliver: a completed save, an abandoned prefix
45    // (`ctrl+x` then an unrelated key), then `g g`.
46    let stream = [
47        ctrl('x'),
48        ctrl('s'),
49        ctrl('x'),
50        plain('z'),
51        plain('g'),
52        plain('g'),
53    ];
54
55    let mut pending: Vec<KeyInput> = Vec::new();
56    for key in stream {
57        pending.push(key);
58        match map.lookup(&pending) {
59            Match::Exact(action) => {
60                println!("{} -> fire {action:?}", render(&pending));
61                pending.clear();
62            }
63            Match::Prefix => {
64                println!("{} -> prefix, waiting", render(&pending));
65            }
66            Match::NoMatch => {
67                println!("{} -> no binding, passing through", render(&pending));
68                pending.clear();
69            }
70        }
71    }
72}
73
74/// `jj`-style time window, driven through [`PendingSequence`]. The window —
75/// "abandon a pending prefix if the next key is too slow" — is the *caller's*
76/// policy, not the table's: `keymap-seq` has no clock, so the caller measures
77/// inter-key time and decides when a prefix is stale. The helper owns the buffer
78/// bookkeeping; the caller owns only the timing decision and the one `flush` call
79/// it triggers.
80///
81/// Note what this demo does *not* do: real vim `jj` also binds `j` on its own (a
82/// literal cursor move), so a lone `j` must fire while a quick `j j` escapes. That
83/// needs both `j` *and* `[j, j]` bound — which the prefix-free invariant forbids
84/// (`bind` would reject it with `PrefixShadow`). Resolving "is this `j` a literal
85/// or the first half of `jj`?" is therefore caller timing policy layered on top
86/// of `lookup`, not a trie outcome. Here `j` alone is unbound, so the timeout is
87/// the *only* caller policy needed.
88///
89/// Unlike the raw-loop version this once was, the idle flush is *exercised*, not
90/// just described: a too-slow key abandons the held prefix (mid-stream), and the
91/// stream ends mid-prefix so the trailing `flush` drains the dangling `j` as a
92/// literal — the case a real caller's idle timer fires on when no further key
93/// arrives.
94fn timed() {
95    const WINDOW: Duration = Duration::from_millis(500);
96
97    println!("== timed (jj) ==");
98    let mut map = SequenceKeymap::new();
99    map.bind([plain('j'), plain('j')], Action::NormalMode)
100        .unwrap();
101
102    // `(key, timestamp-since-start)`: a deterministic stand-in for an event
103    // loop's clock (no real `Instant`/`sleep`, so the demo can't be flaky). We
104    // compare the *inter-key* gap to the window — the gap since the last key the
105    // pending prefix accepted, which is what "pressed twice quickly" means.
106    let stream = [
107        (plain('j'), Duration::from_millis(0)),
108        (plain('j'), Duration::from_millis(120)), // quick: completes `jj`
109        (plain('j'), Duration::from_millis(900)),
110        (plain('j'), Duration::from_millis(1700)), // 800ms gap: too slow
111    ];
112
113    let mut pending = PendingSequence::new();
114    let mut last: Option<Duration> = None;
115    for (key, now) in stream {
116        // Timeout check lives here, in the caller, before the new key is judged:
117        // a too-slow key means the held prefix was abandoned, so flush it (pass
118        // its keys through as literals) and let this key start fresh.
119        if let Some(prev) = last {
120            if now.saturating_sub(prev) > WINDOW && !pending.is_empty() {
121                let dropped = pending.flush();
122                println!(
123                    "{} @ {now:?} -> idle ({:?} gap > {WINDOW:?}), flushed as literals",
124                    render(&dropped),
125                    now.saturating_sub(prev),
126                );
127            }
128        }
129
130        // `last` tracks the time of the key that last extended a live prefix, so
131        // it is set solely by this resolution: only `Pending` leaves a prefix
132        // waiting on the clock.
133        last = match pending.feed(&map, key) {
134            Step::Fired(action) => {
135                println!("{key} @ {now:?} -> fire {action:?}");
136                None
137            }
138            Step::Pending => {
139                println!("{key} @ {now:?} -> prefix, waiting (window {WINDOW:?})");
140                Some(now)
141            }
142            Step::PassThrough(keys) => {
143                println!("{} @ {now:?} -> no binding, passing through", render(&keys));
144                None
145            }
146        };
147    }
148
149    // The stream ended mid-prefix. A real caller's idle timer would fire after the
150    // window with no further key; here we flush that dangling `j` as a literal —
151    // the step the old version of this example could only describe in a comment.
152    let dangling = pending.flush();
153    if !dangling.is_empty() {
154        println!(
155            "{} -> still pending at end; idle timer flushes it as a literal",
156            render(&dangling)
157        );
158    }
159}
Source

pub fn is_empty(&self) -> bool

Returns true if no sequences are bound.

Source

pub fn bind( &mut self, sequence: impl IntoIterator<Item = KeyInput>, action: A, ) -> Result<Option<A>, SeqBindError>

Binds a key sequence to action.

Re-binding the exact same sequence overwrites and returns the previous action, mirroring keymap_core::Keymap::bind.

§Errors
  • SeqBindError::Empty if sequence yields no keys.
  • SeqBindError::PrefixShadow if the new sequence would be a proper prefix of an existing binding, or an existing binding would be a proper prefix of it. Either case is unresolvable without a timeout (see the crate docs), so it is rejected rather than silently shadowed; the map is left unchanged.
Examples found in repository?
examples/leader_sequence.rs (line 40)
37fn untimed() {
38    println!("== untimed ==");
39    let mut map = SequenceKeymap::new();
40    map.bind([ctrl('x'), ctrl('s')], Action::Save).unwrap();
41    map.bind([ctrl('x'), ctrl('c')], Action::Quit).unwrap();
42    map.bind([plain('g'), plain('g')], Action::GotoTop).unwrap();
43
44    // A stream a terminal might deliver: a completed save, an abandoned prefix
45    // (`ctrl+x` then an unrelated key), then `g g`.
46    let stream = [
47        ctrl('x'),
48        ctrl('s'),
49        ctrl('x'),
50        plain('z'),
51        plain('g'),
52        plain('g'),
53    ];
54
55    let mut pending: Vec<KeyInput> = Vec::new();
56    for key in stream {
57        pending.push(key);
58        match map.lookup(&pending) {
59            Match::Exact(action) => {
60                println!("{} -> fire {action:?}", render(&pending));
61                pending.clear();
62            }
63            Match::Prefix => {
64                println!("{} -> prefix, waiting", render(&pending));
65            }
66            Match::NoMatch => {
67                println!("{} -> no binding, passing through", render(&pending));
68                pending.clear();
69            }
70        }
71    }
72}
73
74/// `jj`-style time window, driven through [`PendingSequence`]. The window —
75/// "abandon a pending prefix if the next key is too slow" — is the *caller's*
76/// policy, not the table's: `keymap-seq` has no clock, so the caller measures
77/// inter-key time and decides when a prefix is stale. The helper owns the buffer
78/// bookkeeping; the caller owns only the timing decision and the one `flush` call
79/// it triggers.
80///
81/// Note what this demo does *not* do: real vim `jj` also binds `j` on its own (a
82/// literal cursor move), so a lone `j` must fire while a quick `j j` escapes. That
83/// needs both `j` *and* `[j, j]` bound — which the prefix-free invariant forbids
84/// (`bind` would reject it with `PrefixShadow`). Resolving "is this `j` a literal
85/// or the first half of `jj`?" is therefore caller timing policy layered on top
86/// of `lookup`, not a trie outcome. Here `j` alone is unbound, so the timeout is
87/// the *only* caller policy needed.
88///
89/// Unlike the raw-loop version this once was, the idle flush is *exercised*, not
90/// just described: a too-slow key abandons the held prefix (mid-stream), and the
91/// stream ends mid-prefix so the trailing `flush` drains the dangling `j` as a
92/// literal — the case a real caller's idle timer fires on when no further key
93/// arrives.
94fn timed() {
95    const WINDOW: Duration = Duration::from_millis(500);
96
97    println!("== timed (jj) ==");
98    let mut map = SequenceKeymap::new();
99    map.bind([plain('j'), plain('j')], Action::NormalMode)
100        .unwrap();
101
102    // `(key, timestamp-since-start)`: a deterministic stand-in for an event
103    // loop's clock (no real `Instant`/`sleep`, so the demo can't be flaky). We
104    // compare the *inter-key* gap to the window — the gap since the last key the
105    // pending prefix accepted, which is what "pressed twice quickly" means.
106    let stream = [
107        (plain('j'), Duration::from_millis(0)),
108        (plain('j'), Duration::from_millis(120)), // quick: completes `jj`
109        (plain('j'), Duration::from_millis(900)),
110        (plain('j'), Duration::from_millis(1700)), // 800ms gap: too slow
111    ];
112
113    let mut pending = PendingSequence::new();
114    let mut last: Option<Duration> = None;
115    for (key, now) in stream {
116        // Timeout check lives here, in the caller, before the new key is judged:
117        // a too-slow key means the held prefix was abandoned, so flush it (pass
118        // its keys through as literals) and let this key start fresh.
119        if let Some(prev) = last {
120            if now.saturating_sub(prev) > WINDOW && !pending.is_empty() {
121                let dropped = pending.flush();
122                println!(
123                    "{} @ {now:?} -> idle ({:?} gap > {WINDOW:?}), flushed as literals",
124                    render(&dropped),
125                    now.saturating_sub(prev),
126                );
127            }
128        }
129
130        // `last` tracks the time of the key that last extended a live prefix, so
131        // it is set solely by this resolution: only `Pending` leaves a prefix
132        // waiting on the clock.
133        last = match pending.feed(&map, key) {
134            Step::Fired(action) => {
135                println!("{key} @ {now:?} -> fire {action:?}");
136                None
137            }
138            Step::Pending => {
139                println!("{key} @ {now:?} -> prefix, waiting (window {WINDOW:?})");
140                Some(now)
141            }
142            Step::PassThrough(keys) => {
143                println!("{} @ {now:?} -> no binding, passing through", render(&keys));
144                None
145            }
146        };
147    }
148
149    // The stream ended mid-prefix. A real caller's idle timer would fire after the
150    // window with no further key; here we flush that dangling `j` as a literal —
151    // the step the old version of this example could only describe in a comment.
152    let dangling = pending.flush();
153    if !dangling.is_empty() {
154        println!(
155            "{} -> still pending at end; idle timer flushes it as a literal",
156            render(&dangling)
157        );
158    }
159}
Source

pub fn lookup(&self, keys: &[KeyInput]) -> Match<'_, A>

Resolves the keys pressed so far against the table.

keys is the caller’s pending buffer. The result is one of:

  • Match::Exactkeys is a complete binding; the caller should fire it and clear the buffer.
  • Match::Prefixkeys is a proper prefix of one or more bindings; the caller should keep buffering (and, for timed bindings, run its timer).
  • Match::NoMatchkeys is not on any binding path; the caller should clear the buffer and handle the keys itself (e.g. pass through).
Examples found in repository?
examples/leader_sequence.rs (line 58)
37fn untimed() {
38    println!("== untimed ==");
39    let mut map = SequenceKeymap::new();
40    map.bind([ctrl('x'), ctrl('s')], Action::Save).unwrap();
41    map.bind([ctrl('x'), ctrl('c')], Action::Quit).unwrap();
42    map.bind([plain('g'), plain('g')], Action::GotoTop).unwrap();
43
44    // A stream a terminal might deliver: a completed save, an abandoned prefix
45    // (`ctrl+x` then an unrelated key), then `g g`.
46    let stream = [
47        ctrl('x'),
48        ctrl('s'),
49        ctrl('x'),
50        plain('z'),
51        plain('g'),
52        plain('g'),
53    ];
54
55    let mut pending: Vec<KeyInput> = Vec::new();
56    for key in stream {
57        pending.push(key);
58        match map.lookup(&pending) {
59            Match::Exact(action) => {
60                println!("{} -> fire {action:?}", render(&pending));
61                pending.clear();
62            }
63            Match::Prefix => {
64                println!("{} -> prefix, waiting", render(&pending));
65            }
66            Match::NoMatch => {
67                println!("{} -> no binding, passing through", render(&pending));
68                pending.clear();
69            }
70        }
71    }
72}
Source

pub fn bindings(&self) -> impl Iterator<Item = (Vec<KeyInput>, &A)>

Enumerates every bound sequence as a (path, action) pair — the sequence-level dual of keymap_core::Keymap::iter.

Each yielded Vec<KeyInput> is a complete bound sequence (a leaf path); by the prefix-free invariant it is never a partial prefix. Unlike Keymap::iter, which can borrow its stored key, a trie path is reconstructed during traversal, so each item owns its Vec and borrows only the action.

Order is unspecified (the trie’s children live in a HashMap); collect and sort caller-side for stable output. This is the data source for listing, search, and serialization on top of keymap-seq.

Source

pub fn continuations( &self, prefix: &[KeyInput], ) -> impl Iterator<Item = (KeyInput, Continuation<'_, A>)>

Enumerates the keys that may immediately follow prefix, for rendering a which-key-style menu of what can be pressed next.

Each item is a KeyInput that extends prefix by one, paired with what pressing it does: complete a binding (Continuation::Action, carrying the action) or open a deeper prefix (Continuation::Prefix).

The iterator is empty when prefix does not name an internal node — whether it is off the tree, already completes a binding (a leaf has no children), or the map is empty. continuations deliberately does not re-encode that distinction; call lookup to tell those apart.

Order is unspecified (the children live in a HashMap); collect and sort caller-side for a stable menu.

use keymap_core::{Key, KeyInput, Modifiers};
use keymap_seq::{Continuation, SequenceKeymap};

#[derive(Debug, PartialEq)]
enum Action { Save, Quit }

let k = |c| KeyInput::new(Key::Char(c), Modifiers::NONE);
let mut map = SequenceKeymap::new();
map.bind([k('a'), k('b')], Action::Save).unwrap();
map.bind([k('c')], Action::Quit).unwrap();

// From the root: `a` opens a deeper prefix, `c` completes a binding.
let mut next: Vec<_> = map.continuations(&[]).collect();
next.sort_by_key(|(key, _)| key.to_string());
assert_eq!(
    next,
    vec![
        (k('a'), Continuation::Prefix),
        (k('c'), Continuation::Action(&Action::Quit)),
    ],
);

// A completed binding has no continuations.
assert_eq!(map.continuations(&[k('c')]).count(), 0);

Trait Implementations§

Source§

impl<A: Clone> Clone for SequenceKeymap<A>

Source§

fn clone(&self) -> SequenceKeymap<A>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<A: Debug> Debug for SequenceKeymap<A>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<A> Default for SequenceKeymap<A>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<A> Freeze for SequenceKeymap<A>
where A: Freeze,

§

impl<A> RefUnwindSafe for SequenceKeymap<A>
where A: RefUnwindSafe,

§

impl<A> Send for SequenceKeymap<A>
where A: Send,

§

impl<A> Sync for SequenceKeymap<A>
where A: Sync,

§

impl<A> Unpin for SequenceKeymap<A>
where A: Unpin,

§

impl<A> UnsafeUnpin for SequenceKeymap<A>
where A: UnsafeUnpin,

§

impl<A> UnwindSafe for SequenceKeymap<A>
where A: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.