command

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package command defines the command registry types for the editor

Index

Constants

View Source
const (
	CompletionStateFlag         = CompletionStateKind(argsCompletionFlag)
	CompletionStateFlagArgument = CompletionStateKind(
		argsCompletionFlagArgument,
	)
)
View Source
const (
	// AllModes is every editing and pane mode
	AllModes = view.ModeNormal |
		view.ModeSelect |
		view.ModeInsert |
		view.ModeTerminal |
		view.ModeImage |
		view.ModeBinary

	// DocNormalModes is the non-insert document modes
	DocNormalModes = view.ModeNormal |
		view.ModeSelect

	// DocModes is every mode backed by an editable document view
	DocModes = view.ModeNormal |
		view.ModeSelect |
		view.ModeInsert

	// PaneModes is every mode for commands that apply to every pane kind
	PaneModes = view.ModeNormal |
		view.ModeSelect |
		view.ModeTerminal |
		view.ModeImage |
		view.ModeBinary

	// CmdKeyModes is every pane mode except terminal, where keystrokes
	// belong to the shell
	CmdKeyModes = view.ModeNormal |
		view.ModeSelect |
		view.ModeImage |
		view.ModeBinary
)

Variables

View Source
var (
	ErrDuplicateCommand = errors.New("duplicate command registration")
	ErrNoModes          = errors.New("command has no modes")
	ErrUnknownMode      = errors.New("keys references mode not in modes")

	ErrBindingExists = i18n.NewError(i18n.ErrorBindingExists)
)
View Source
var (
	// ErrCommandLineParse is the sentinel error for command-line parse failures
	ErrCommandLineParse = errors.New("command line parse error")
)
View Source
var (
	// ErrInvalidKey reports malformed keycap notation
	ErrInvalidKey = i18n.NewError(i18n.ErrorInvalidKey)
)

Functions

This section is empty.

Types

type Action

type Action func(*view.Editor)

Action is a function that performs an operation on an editor

type Args

type Args struct {
	// contains filtered or unexported fields
}

Args is command-line input interpreted by a command signature

func NewArgs

func NewArgs(sig Signature, validate bool) *Args

NewArgs returns an empty argument accumulator for a signature

func ParseArgs

func ParseArgs(
	input string, sig Signature, validate bool, expand TokenExpander,
) (*Args, error)

ParseArgs parses command input using the supplied signature; expand may be nil, in which case raw token content is used as-is

func (*Args) CompletionState

func (a *Args) CompletionState() CompletionState

CompletionState returns what kind of argument the last token was

func (*Args) Finish

func (a *Args) Finish() error

Finish validates final argument state

func (*Args) First

func (a *Args) First() (string, bool)

First returns the first positional argument

func (*Args) Flag

func (a *Args) Flag(name string) (string, bool)

Flag returns a flag argument value

func (*Args) Get

func (a *Args) Get(i int) (string, bool)

Get returns the positional argument at index

func (*Args) HasFlag

func (a *Args) HasFlag(name string) bool

HasFlag reports whether a boolean flag was supplied

func (*Args) IsEmpty added in v0.3.2

func (a *Args) IsEmpty() bool

IsEmpty reports whether there are no positional arguments

func (*Args) Join

func (a *Args) Join(sep string) string

Join joins positional arguments with a separator

func (*Args) Len

func (a *Args) Len() int

Len returns the positional argument count

func (*Args) Positionals

func (a *Args) Positionals() []string

Positionals returns a copy of the positional arguments

func (*Args) Push

func (a *Args) Push(arg string) error

Push adds one already-expanded argument to the accumulator

type BindActionArgs added in v0.1.31

type BindActionArgs struct {
	Modes  []view.Mode
	Action KeyResultAction
	When   func(*view.Editor) bool
	Label  string
	Seqs   [][]KeyEvent
}

BindActionArgs bundles the inputs for BindResultAction

type Command

type Command struct {
	Name      string
	Run       Run
	DocString string
	Modes     view.Mode
	Keys      map[view.Mode]KeyBinding
	Aliases   []string
	Signature Signature
	Counted   bool
	Hints     HintProvider
}

Command describes one registered command: its runner, key bindings, mode applicability, typeable aliases, and argument signature

type Completer

type Completer struct {
	Positionals []CompletionFunc
	Raw         CompletionFunc
}

Completer describes positional and raw argument completion

func PositionalCompleter

func PositionalCompleter(c ...CompletionFunc) Completer

PositionalCompleter completes positionals by argument index

func (Completer) Complete

func (c Completer) Complete(
	e *view.Editor, sig Signature, input string,
) []Completion

Complete returns argument completions for a command signature

type Completion

type Completion struct {
	Start   int
	Text    string
	Display string
	Detail  string
	Indices []int
}

Completion replaces prompt input from Start to the end of the line. Detail describes the entry beside it, and is never matched against

type CompletionFunc

type CompletionFunc func(*view.Editor, *Args, string) []Completion

CompletionFunc returns completions for command-line input, given the arguments already parsed for the current command

func StaticCompleter

func StaticCompleter[T ~string](items ...T) CompletionFunc

StaticCompleter completes from a fixed string set

type CompletionState

type CompletionState struct {
	Kind CompletionStateKind
	Flag *Flag
}

CompletionState describes what kind of argument is being typed

type CompletionStateKind

type CompletionStateKind int

CompletionStateKind identifies the kind of the last parsed argument

type Continuation

type Continuation func(*view.Editor, KeyEvent) (Continuation, Transition)

Continuation is called with subsequent keys while an action is in progress. Its result tells the key-entry UI how the interaction moved. ContinuationStay with nil retains the current callback

func PopOnBackspace added in v0.3.0

func PopOnBackspace(handle Continuation) Continuation

PopOnBackspace makes unmodified Backspace pop a continuation

func ReadChar added in v0.3.0

func ReadChar(handle func(*view.Editor, rune) Continuation) Continuation

ReadChar handles an unmodified character, or pops on Backspace

type ExpansionKind

type ExpansionKind int

ExpansionKind identifies a percent-token expansion kind

const (
	ExpansionVariable ExpansionKind = iota
	ExpansionUnicode
	ExpansionShell
	ExpansionRegister
)

type Flag

type Flag struct {
	Name        string
	Alias       rune
	Doc         string
	Completions []string
}

Flag describes a command flag and optional shorthand

type HintProvider added in v0.3.0

type HintProvider func(*view.Editor) []KeyHint

HintProvider answers the keys a command accepts next when they are not bindings in the trie, such as the registers currently holding a value

type KeyAction

type KeyAction func(*view.Editor) Continuation

KeyAction handles a key sequence and may return a continuation

type KeyBinding

type KeyBinding [][]KeyEvent

KeyBinding describes default key sequences for a command

type KeyCode

type KeyCode struct {
	// Char holds the rune for printable characters; 0 for special keys
	Char    rune
	Special Special
}

KeyCode represents a single keyboard key

func (KeyCode) String

func (k KeyCode) String() string

String returns the binding name of a key code

type KeyEvent

type KeyEvent struct {
	Code KeyCode
	Mods KeyModifiers
}

KeyEvent is a key code combined with modifier state

func ParseKeySequence added in v0.1.28

func ParseKeySequence(input string) ([]KeyEvent, error)

ParseKeySequence parses a space-separated sequence of keycap names

func (KeyEvent) IsTypable

func (k KeyEvent) IsTypable() bool

IsTypable reports whether k is a printable character that should be accepted as literal text input: Char is set and neither Ctrl nor Alt is held; ModShift alone is fine; it is already reflected in the Char value

func (KeyEvent) String

func (k KeyEvent) String() string

String returns the binding notation for a key press

func (KeyEvent) WithMods

func (k KeyEvent) WithMods(m KeyModifiers) KeyEvent

WithMods returns a copy of k with the given modifiers added

type KeyHint

type KeyHint struct {
	Key    string
	Label  string
	Prefix bool
}

KeyHint is a (key-string, label) pair used by the pending-key info popup. Prefix marks a key that opens another menu rather than running a command

type KeyMatch added in v0.2.0

type KeyMatch struct {
	Action KeyResultAction
	When   func(*view.Editor) bool
	Name   string
	Prefix bool
}

KeyMatch is a binding matched by traversing the key trie

func (KeyMatch) Enabled added in v0.2.0

func (k KeyMatch) Enabled(e *view.Editor) bool

Enabled reports whether a matched binding's :when predicate allows it

type KeyModifiers

type KeyModifiers uint8

KeyModifiers is a bitmask of modifier keys

const (
	ModNone  KeyModifiers = 0
	ModShift KeyModifiers = 1 << iota
	ModCtrl
	ModAlt
)

func (KeyModifiers) Has

func (k KeyModifiers) Has(mod KeyModifiers) bool

Has reports whether every modifier in mod is set

type KeyResultAction added in v0.1.28

type KeyResultAction func(*view.Editor) Result

KeyResultAction handles a key sequence and returns its command result

type Keymaps

type Keymaps struct {
	// contains filtered or unexported fields
}

Keymaps is the combined command registry and key-event dispatch trie

func NewKeymaps

func NewKeymaps() *Keymaps

NewKeymaps creates an empty Keymaps

func (*Keymaps) AcceptsCount added in v0.3.0

func (k *Keymaps) AcceptsCount(mode view.Mode, seq []KeyEvent) bool

AcceptsCount reports whether seq reaches a node with a counted command

func (*Keymaps) Bind

func (k *Keymaps) Bind(mode view.Mode, name string, seqs ...[]KeyEvent)

Bind adds extra key sequences to an already-registered command

func (*Keymaps) BindResultAction added in v0.1.28

func (k *Keymaps) BindResultAction(args BindActionArgs) error

BindResultAction adds key sequences for a result-returning action

func (*Keymaps) Bindings

func (k *Keymaps) Bindings(mode view.Mode, name string) KeyBinding

Bindings returns key sequences bound to a command in a mode

func (*Keymaps) CommandsIn

func (k *Keymaps) CommandsIn(mode view.Mode) []*Command

CommandsIn returns registered commands available in the named mode

func (*Keymaps) LabelNode

func (k *Keymaps) LabelNode(mode view.Mode, prefix KeyBinding, name string)

LabelNode names the node reached by each alternative in prefix, so a shared menu (e.g. the Space and Ctrl-\ leaders) is labelled everywhere it is reached

func (*Keymaps) Lookup

func (k *Keymaps) Lookup(mode view.Mode, seq []KeyEvent) (KeyMatch, bool)

Lookup traverses the key trie. The bool reports a complete match

func (*Keymaps) PendingHints

func (k *Keymaps) PendingHints(
	e *view.Editor, mode view.Mode, seq []KeyEvent, counting bool,
) (string, []KeyHint)

PendingHints returns the title and (key, label) pairs offered after seq in mode, from the node's children or its hint provider. A binding rejected by :when, or unusable with the count typed, is omitted

func (*Keymaps) Register

func (k *Keymaps) Register(name string, cmd Command) error

Register adds a command entry and wires its key bindings. Returns ErrDuplicateCommand if name is already registered - each command must be fully declared once, in the module that owns it

func (*Keymaps) ResolveCommand

func (k *Keymaps) ResolveCommand(name string) *Command

ResolveCommand looks up a command by typeable alias

func (*Keymaps) ResolveCommandIn

func (k *Keymaps) ResolveCommandIn(mode view.Mode, name string) *Command

ResolveCommandIn looks up a command by alias and filters it by mode

type Line added in v0.2.0

type Line struct {
	Name string
	Rest string
}

Line is an input line split into the command name and the argument text that follows it

func SplitCommandLine

func SplitCommandLine(input string) (Line, bool)

SplitCommandLine separates the command name from its argument text. The bool reports whether the name is still being typed

type Module

type Module struct {
	Commands     []Command
	Translations i18n.Translations
	Options      []Option
	Section      *Section
	Labels       []PrefixLabel
}

Module groups commands, translations, runtime options, and an optional config section for installation together

type Option

type Option struct {
	Key       string
	DocString string
	Private   bool
	Get       OptionGetter
	Set       OptionSetter
	KeyGet    OptionKeyGetter
	KeySet    OptionKeySetter
	Toggle    OptionGetter
	Complete  CompletionFunc
}

Option describes a runtime editor option owned by a module. Toggle is nil when it is not boolean-toggleable, and Private keeps editor-managed state out of :set and its completions

func (Option) WithDoc added in v0.3.0

func (o Option) WithDoc(doc string) Option

WithDoc returns a copy of the option described by doc, for options built by a helper rather than declared as a literal

type OptionGetter

type OptionGetter func(*view.Editor) (string, error)

OptionGetter reads an option's current value from the editor

type OptionKeyGetter

type OptionKeyGetter func(*view.Editor) (map[string]string, error)

OptionKeyGetter reads concrete values owned by an option key prefix

type OptionKeySetter

type OptionKeySetter func(*view.Editor, string, string) error

OptionKeySetter applies a concrete option key owned by a key prefix

type OptionSetter

type OptionSetter func(*view.Editor, string) error

OptionSetter applies a new option value to the editor

type ParseError

type ParseError struct {
	Kind   ParseErrorKind
	Token  Token
	Flag   string
	Text   string
	Min    int
	Max    int // 0 = no maximum
	Actual int
}

ParseError reports a command-line parser validation failure

func (*ParseError) Error

func (p *ParseError) Error() string

Error describes which argument failed to parse

func (*ParseError) Is

func (p *ParseError) Is(target error) bool

Is matches the shared command-line parse sentinel

type ParseErrorKind

type ParseErrorKind int

ParseErrorKind identifies a parser validation failure

const (
	ParseErrorWrongPositionalCount ParseErrorKind = iota
	ParseErrorUnterminatedToken
	ParseErrorDuplicatedFlag
	ParseErrorUnknownFlag
	ParseErrorFlagMissingArgument
	ParseErrorMissingExpansionDelimiter
	ParseErrorUnknownExpansion
)

type Positionals

type Positionals struct {
	Min int
	Max int // negative = no maximum
	Map func(string) (string, error)
}

Positionals constrains the accepted positional argument count

type PrefixLabel

type PrefixLabel struct {
	Modes view.Mode
	Seq   KeyBinding
	Label string
}

PrefixLabel names an intermediate key-sequence node for the pending-key hint popup, letting a module label the prefixes it owns

type Quote

type Quote int

Quote identifies a literal quote delimiter

const (
	QuoteSingle Quote = iota
	QuoteBacktick
)

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry owns installed commands, runtime options, and config sections

func NewRegistry

func NewRegistry(km *Keymaps) *Registry

NewRegistry returns an empty command registry bound to keymaps

func (*Registry) ApplyOptionValues

func (r *Registry) ApplyOptionValues(
	e *view.Editor, values map[string]string,
) error

ApplyOptionValues applies a set of runtime option strings through the same handlers used by :set

func (*Registry) ApplyTOML

func (r *Registry) ApplyTOML(e *view.Editor, raw map[string]any) error

ApplyTOML resets all sections to defaults, decodes the merged TOML map into each section, then calls each section's Apply to push typed values into editor Options. Pass an empty map when no config file is present

func (*Registry) BoolOptionCompleter

func (r *Registry) BoolOptionCompleter() CompletionFunc

BoolOptionCompleter completes only the boolean option keys

func (*Registry) BoolOptionKeys

func (r *Registry) BoolOptionKeys() []string

BoolOptionKeys returns settable option keys that support toggle

func (*Registry) ChangedOptionValues added in v0.2.3

func (r *Registry) ChangedOptionValues(
	e *view.Editor,
) (map[string]string, error)

ChangedOptionValues returns the option values that differ from the editor's base options. With no base recorded, every option counts as changed

func (*Registry) LookupOption

func (r *Registry) LookupOption(key string) *Option

LookupOption returns the registered Option for the given key, if any

func (*Registry) OptionCompleter

func (r *Registry) OptionCompleter() CompletionFunc

OptionCompleter completes every option a user may set

func (*Registry) OptionKeys

func (r *Registry) OptionKeys() []string

OptionKeys returns all registered option keys in sorted order

func (*Registry) OptionValueCompleter

func (r *Registry) OptionValueCompleter() CompletionFunc

OptionValueCompleter completes an option's value, dispatching to the completer registered against the option named by the already-parsed first positional argument (e.g. the key in "set <key> <value>")

func (*Registry) OptionValueCompleterFor added in v0.2.3

func (r *Registry) OptionValueCompleterFor(key string) CompletionFunc

OptionValueCompleterFor completes values for a fixed option key

func (*Registry) OptionValues

func (r *Registry) OptionValues(e *view.Editor) (map[string]string, error)

OptionValues returns the current string value for every registered runtime option

func (*Registry) RegisterCommand

func (r *Registry) RegisterCommand(name string, c Command) error

RegisterCommand registers a command with kebab-cased name as the first alias

func (*Registry) RegisterModule

func (r *Registry) RegisterModule(m Module) error

RegisterModule adds a module's commands, options, and bindings

type Result

type Result struct {
	Signal       Signal
	Message      string
	Error        error
	Continuation Continuation
}

Result is returned by a Run function

type Run

type Run func(*view.Editor, *Args) Result

Run executes a registered command, optionally with parsed arguments. A nil Run declares the name, docs, and bindings of a command whose behavior a UI component implements by intercepting the resolved name

type Section

type Section struct {
	Config any
	Reset  func()
	Apply  func(*view.Editor)
}

Section declares a module's live config pointer and Apply hook

type Signal

type Signal int

Signal is a post-execution application-level effect

const (
	SignalQuit Signal
	SignalClearScreen
)

type Signature

type Signature struct {
	Positionals Positionals
	RawAfter    int // 0 = disabled; n = switch to raw after n positionals
	Flags       []Flag
	Completer   Completer
}

Signature describes positional, raw, and flag parsing for a command

type Special

type Special uint8

Special enumerates the non-printable keys; SpecialNone means the key is a printable KeyCode.Char instead

const (
	SpecialNone Special = iota
	SpecialUnknown
	Enter
	Backspace
	Delete
	Escape
	Tab
	Up
	Down
	Left
	Right
	Home
	End
	PageUp
	PageDown
)

func (Special) String

func (s Special) String() string

String returns the binding name of a special key

type SyntaxError

type SyntaxError struct {
	Kind  SyntaxErrorKind
	Token Token
	Text  string
}

SyntaxError is a tokenizer-level parse error

func (*SyntaxError) Error

func (s *SyntaxError) Error() string

Error describes where the command line failed to tokenize

func (*SyntaxError) Is

func (s *SyntaxError) Is(target error) bool

Is matches the shared command-line parse sentinel

type SyntaxErrorKind

type SyntaxErrorKind int

SyntaxErrorKind identifies a tokenizer-level parse failure

const (
	SyntaxErrorUnterminatedToken SyntaxErrorKind = iota
	SyntaxErrorMissingExpansionDelimiter
	SyntaxErrorUnknownExpansion
)

type Token

type Token struct {
	Kind         TokenKind
	Expansion    ExpansionKind
	Quote        Quote
	ContentStart int
	Content      string
	Terminated   bool
}

Token is a token from command-line input

type TokenExpander

type TokenExpander func(Token) (string, error)

TokenExpander maps a raw token to its expanded string value; a nil expander uses the token content verbatim

type TokenKind

type TokenKind int

TokenKind identifies how a token should be interpreted

const (
	TokenUnquoted TokenKind = iota
	TokenQuoted
	TokenExpand
	TokenExpansion
	TokenExpansionKind
)

type Tokenizer

type Tokenizer struct {
	// contains filtered or unexported fields
}

Tokenizer tokenizes command-line input

func NewTokenizer

func NewTokenizer(input string, validate bool) *Tokenizer

NewTokenizer returns a tokenizer for command-line input

func (*Tokenizer) Next

func (t *Tokenizer) Next() (Token, bool, error)

Next consumes the next token, reporting false at end of input

func (*Tokenizer) Pos

func (t *Tokenizer) Pos() int

Pos is the offset the tokenizer has consumed to

func (*Tokenizer) Rest

func (t *Tokenizer) Rest() (Token, bool)

Rest consumes everything left as one unterminated expansion token, for commands taking a raw trailing argument

type Transition added in v0.3.0

type Transition uint8

Transition describes how an interaction handled a key

const (
	ContinuationDone Transition = iota
	ContinuationStay
	ContinuationPush
	ContinuationPop
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL