Skip to content

keymap 实验性 ​

实验性

本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。

go
import "github.com/tangoui/tango/ui/editor/keymap"

本页由 site/tools/apigen 从源码注释生成(按 darwin 构建标签选文件),请勿手改。

Package keymap parses keybinding text and resolves key events to commands, with VS Code's rule semantics.

Key text is MinCode's format (vue-app/src/domain/keybindings/keys.ts), which is VS Code's with a few aliases: chords "mod+shift+p" joined by "+", case-insensitive; "mod" (also "cmdorctrl") is ⌘ on macOS and Ctrl elsewhere; "cmd"/"command"/"meta"/"win"/"super" is ⌘ / the Windows key; "ctrl"/"control", "shift", "alt"/"option"/"opt". Key names are VS Code's: a-z, 0-9, f1-f12, up down left right, enter (return), escape (esc), tab, space, backspace, delete (del), insert, home, end, pageup, pagedown, / \ . , ; ' ` [ ] - =, numpad0-numpad9, numpad_add, numpad_subtract, numpad_multiply, numpad_divide, numpad_decimal, capslock, contextmenu. A sequence is one chord or two separated by blanks ("mod+k mod+c"; MaxChords), or a double tap of one modifier ("shift shift").

Not supported (ParseKey reports an error): f13-f24 (input.Key has no such keys), numpad_separator, VS Code's scan-code form ("[KeyA]") and the oem_* / abnt_c1 / abnt_c2 names, the media and browser keys (audiovolumemute, mediaplaypause, browserback...), pausebreak, printscreen, numlock, scrolllock, and a "+" key (use "=" with shift or numpad_add).

Keys match by physical position: input.KeyEvent.Code, which the Runner fills from Key when the platform reports none. Where the platform reports the physical key (Windows), ⌥/Alt+letter and non-US layouts match by position. Keypad keys match both their own name and the main key they duplicate (Numpad7 matches "numpad7" and "7", NumpadEnter matches "enter"), as MinCode's normalizeKeyCode folds them.

Platform limitation (macOS and Linux, as of this milestone): a key that produces text while the text input client is on arrives as TextInput only, with no KeyEvent (macOS passes it through interpretKeyEvents, GTK through its input-method filter), and macOS never fills Code, so the Runner's Code is the layout-dependent Key. Consequently ⌥-letter bindings never fire on macOS, plain-character chord second keys ("mod+k c") arrive as text (the editor resolves them from the text, see EventForText), and physical-key matching on macOS holds only for keys that do not depend on the layout. Fixing it needs the platform layer to fill Code from the hardware keyCode and to offer key events to the keymap before interpretKeyEvents / the IM filter.

Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").

常量 ​

go
const (
	DoubleTapMaxPress = 300 * time.Millisecond
	DoubleTapMaxGap   = 400 * time.Millisecond
)

Double-tap timing (MinCode's DOUBLE_TAP_MAX_PRESS_MS and DOUBLE_TAP_MAX_GAP_MS), applied when the Keymap has a clock (SetClock).

go
const MaxChords = 2

MaxChords is the longest chord sequence (VS Code's two).

go
const MaxKeyTextLength = 64

MaxKeyTextLength is the longest key text ParseKey accepts.

函数 ​

func EventForText ​

go
func EventForText(text string) (input.KeyEvent, bool)

EventForText returns the key press that types text on a US layout: one ASCII letter, digit, space or punctuation character (an upper-case letter or a shifted symbol with Shift); ok is false for anything else. It stands in for the KeyEvent that macOS and Linux do not send for keys that produce text (see the package doc), for example to resolve the second chord of "mod+k c" from the committed "c". Modifiers other than Shift are unknown and not set.

The mapping is a guess from the character alone, so it is wrong when the character was not typed the US way:

  • CapsLock: with CapsLock on, "c" arrives as "C" and is reported as Shift+C, so "mod+k c" does not complete (and "mod+k shift+c" does).
  • Non-US layouts and ⌥ on macOS: a character the layout produces with ⌥ (or AltGr) that happens to be ASCII, such as "@" from ⌥L on a German layout, is reported as the US key for it (Shift+2), without Alt; a chord on that US key fires, one on the physical key does not.

func Label ​

go
func Label(text string, p Platform) string

Label formats key text directly; text that does not parse is returned as is (MinCode's formatKeyText).

类型 ​

Chord ​

go
type Chord struct {
	Mods input.Modifiers
	Key  input.Key
}

Chord is one key press: modifiers and a physical key.

func ChordOf ​

go
func ChordOf(ev input.KeyEvent) (Chord, bool)

ChordOf returns the chord of a key event with keypad keys folded onto the main keys (Key.Base), as MinCode's keyChordFromEvent; ok is false for modifier keys pressed alone and unknown keys.

func (Chord) Label ​

go
func (c Chord) Label(p Platform) string

Label returns the chord as shown to the user: "⇧⌘P" on macOS (Apple's modifier order ⌃⌥⇧⌘), "Ctrl+Shift+P" elsewhere (VS Code's order Ctrl, Shift, Alt, Win/Super).

func (Chord) String ​

go
func (c Chord) String() string

String returns the canonical, platform-independent text of the chord, modifiers in the order ctrl, shift, alt, meta ("ctrl+shift+p", "alt+meta+up").

Keymap ​

go
type Keymap struct {
	// contains filtered or unexported fields
}

Keymap resolves key events to commands. It holds the chord state (the first chord of a two-chord binding) and the double-tap state, so give each focus scope its own Keymap (Clone shares the compiled rules). It is not safe for concurrent use.

func New ​

go
func New(p Platform, rules ...[]Rule) *Keymap

New compiles rule sets for platform p: later sets take priority over earlier ones (defaults first, then user rules), as do later rules within a set. Rules that do not parse are skipped and reported by Errors.

func (*Keymap) ClearPending ​

go
func (k *Keymap) ClearPending()

ClearPending cancels a pending chord and a double tap in progress (focus lost, window deactivated). Chords have no timeout otherwise.

func (*Keymap) Clone ​

go
func (k *Keymap) Clone() *Keymap

Clone returns a Keymap with the same rules and fresh chord and double-tap state.

func (*Keymap) Errors ​

go
func (k *Keymap) Errors() []error

Errors returns the rules New skipped, one error each.

func (*Keymap) Keys ​

go
func (k *Keymap) Keys(command string, ctx when.Context) []Sequence

Keys returns the sequences bound to command whose when holds in ctx (a nil ctx ignores when), highest priority first: for menus and the command palette.

func (*Keymap) Pending ​

go
func (k *Keymap) Pending() bool

Pending reports whether the first chord of a multi-chord binding was pressed and the next key completes or cancels it.

func (*Keymap) Platform ​

go
func (k *Keymap) Platform() Platform

Platform returns the Keymap's platform.

func (*Keymap) ResetTap ​

go
func (k *Keymap) ResetTap()

ResetTap voids a double tap in progress. Call it when committed text arrives without key events (macOS and Linux deliver text-producing keys as text only), so Shift held for a capital letter is not a Shift tap.

func (*Keymap) Resolve ​

go
func (k *Keymap) Resolve(ev input.KeyEvent, ctx when.Context) (cmd string, args any, pending bool)

Resolve feeds one key event (presses, repeats and releases; releases matter only to double taps) and returns the command it triggers with the rule's args. pending is true when ev was the first chord of a two-chord binding: the caller swallows the key and the next press completes the binding (or cancels it: a press that matches no continuation returns no command and clears the state, VS Code's behaviour). Modifier keys pressed alone keep a pending chord.

Among the rules whose sequence starts with the chords pressed so far, the last one (highest priority) whose when holds in ctx wins; if it is longer than the chords pressed, the result is pending.

func (*Keymap) ResolveEnabled ​

go
func (k *Keymap) ResolveEnabled(ev input.KeyEvent, ctx when.Context, enabled func(command string) bool) (cmd string, args any, pending bool)

ResolveEnabled is Resolve where a rule also needs enabled(command) to hold (nil: always), as if the command's precondition were part of the rule's when (Monaco registers editor commands' keybindings with when = precondition && kbExpr): the key of an unavailable command is not consumed and does not shadow lower-priority rules.

func (*Keymap) SetClock ​

go
func (k *Keymap) SetClock(now func() time.Time)

SetClock gives the Keymap a clock for the double-tap timing: each press must be shorter than DoubleTapMaxPress and the gap between the taps shorter than DoubleTapMaxGap. Without a clock any two clean taps count.

Platform ​

go
type Platform int

Platform selects the meaning of "mod", platform-specific default rules and key labels.

go
const (
	Mac Platform = iota
	Windows
	Linux
)

func Current ​

go
func Current() Platform

Current returns the Platform of runtime.GOOS (iOS counts as Mac, every other non-Windows system as Linux).

func PlatformFrom ​

go
func PlatformFrom(name string) Platform

PlatformFrom maps a platform name (runtime.GOOS, navigator.platform, "macOS", "Win32"...) to a Platform, as MinCode's keyboardPlatformFrom: anything mentioning mac, darwin, iphone, ipad or ipod is Mac, then anything mentioning win is Windows, the rest Linux.

func (Platform) String ​

go
func (p Platform) String() string

Rule ​

go
type Rule struct {
	Key     string
	Command string
	When    string
	Args    any
}

Rule binds key text to a command, VS Code's keybindings.json entry.

A Command starting with "-" is a removal rule (Monaco 0.56's KeybindingResolver.handleRemovals): it removes rules for that command from the default rule set — the first set passed to New, normally DefaultRules — never rules of later sets, wherever the removal appears. When Key is set, only defaults whose sequence starts with Key's chords are removed ("ctrl+k" removes "ctrl+k ctrl+c"); when When is set, only defaults whose when entails it (when.Implies(default, removal): "a" removes a default with "a && b", not one with "a || b" or none). As in Monaco's whenIsEntirelyIncluded, a when of "true" counts as absent on either side: a removal with When "true" removes defaults with any when or none, and a default whose when is "true" is removed only by a removal without a when (or with "true").

Entailment is decided structurally (see when.Implies): parentheses, nesting and term order are ignored, but an expression is not otherwise normalized. A when that is not in that flat form, for example "!(a || b)" where the default says "!a && !b", is a different term, so such a removal can miss its default; write removal whens in the form the default uses. A rule with an empty Command does nothing.

func DefaultRules ​

go
func DefaultRules(p Platform) []Rule

DefaultRules returns the default rules for platform p (see the table above), lowest priority first.

The table lists a command's primary key first, then its secondary keys (Monaco's kbOpts primary / secondary). Monaco registers the secondary keys with a lower weight, so its primary key is the command's highest-priority binding: the one menus show (lookupPrimaryKeybinding) and Keymap.Keys returns first. DefaultRules therefore emits each run of rows of one command in reverse order. The rows of a command have different keys, so this changes no key's resolution.

Sequence ​

go
type Sequence struct {
	Chords []Chord
	Double input.Modifiers
}

Sequence is parsed key text: one or two chords, or (Double non-zero) a double tap of one modifier.

func MustParseKey ​

go
func MustParseKey(text string, p Platform) Sequence

MustParseKey is ParseKey that panics on error (tables and tests).

func ParseKey ​

go
func ParseKey(text string, p Platform) (Sequence, error)

ParseKey parses key text for platform p.

func (Sequence) Equal ​

go
func (s Sequence) Equal(o Sequence) bool

Equal reports whether s and o are the same sequence.

func (Sequence) Label ​

go
func (s Sequence) Label(p Platform) string

Label returns the sequence as shown to the user, MinCode's formatKeySequence: "⇧⌘P", "⌘K ⌘S", "⇧⇧" on macOS; "Ctrl+Shift+P", "Ctrl+K Ctrl+S", "Shift Shift" elsewhere.

func (Sequence) String ​

go
func (s Sequence) String() string

String returns the canonical, platform-independent text ("ctrl+shift+p", "meta+k meta+s", "shift shift"), MinCode's sequenceId.

以 MIT 许可发布