command

package
v0.1.17 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 9 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,
	)
)

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")
)
View Source
var (
	// ErrCommandLineParse is the sentinel error for command-line parse failures
	ErrCommandLineParse = errors.New("command line parse error")
)

Functions

func DocumentModes

func DocumentModes() []string

DocumentModes returns modes backed by editable document views

func PaneModes

func PaneModes() []string

PaneModes returns modes for commands that apply to every pane kind

func SplitCommandLine

func SplitCommandLine(input string) (string, string, bool)

SplitCommandLine separates the command name from its argument text

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) Empty

func (a *Args) Empty() bool

Empty reports whether there are no positional arguments

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) 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 Command

type Command struct {
	Name      string
	Run       Run
	DocString string
	Modes     []string
	Keys      map[string][]KeyBinding
	Aliases   []string
	Signature Signature
}

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
}

Completion replaces prompt input from Start to the end of the line

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

Continuation is called with subsequent keys while an action is in progress. Returns nil to signal completion, or another Continuation to consume more keys

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 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 names the key when Char is 0
	Special Special
}

KeyCode represents a single keyboard key

func (KeyCode) String

func (k KeyCode) String() string

type KeyEvent

type KeyEvent struct {
	Code KeyCode
	Mods KeyModifiers
}

KeyEvent is a key code combined with modifier state

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

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
}

KeyHint is a (key-string, label) pair used by the pending-key info popup

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

func (KeyModifiers) HasOnly

func (k KeyModifiers) HasOnly(mod KeyModifiers) bool

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) Bind

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

Bind adds extra key sequences to an already-registered command

func (*Keymaps) Bindings

func (k *Keymaps) Bindings(mode, name string) []KeyBinding

Bindings returns key sequences bound to a command in a mode

func (*Keymaps) Commands

func (k *Keymaps) Commands() []Command

Commands returns all registered commands in registration order

func (*Keymaps) CommandsIn

func (k *Keymaps) CommandsIn(mode string) []Command

CommandsIn returns registered commands available in the named mode

func (*Keymaps) LabelNode

func (k *Keymaps) LabelNode(mode string, 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 string, seq []KeyEvent,
) (action KeyAction, found, prefix bool)

Lookup traverses the key trie. Returns (action, true, false) on a complete match, (nil, false, true) on a valid prefix, (nil, false, false) otherwise

func (*Keymaps) LookupCommand

func (k *Keymaps) LookupCommand(
	mode string, seq []KeyEvent,
) (name string, found, prefix bool)

LookupCommand traverses the key trie and returns the registered command name

func (*Keymaps) PendingHints

func (k *Keymaps) PendingHints(
	mode string, seq []KeyEvent,
) (string, []KeyHint)

PendingHints returns the title and (key, label) pairs for the node reached by seq in mode, used to populate the pending-key info popup

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, bool)

ResolveCommand looks up a command by typeable alias

func (*Keymaps) ResolveCommandIn

func (k *Keymaps) ResolveCommandIn(mode, name string) (Command, bool)

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

type Module

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

Module groups a set of commands, runtime options, and an optional config section. Options are registered into the editor option registry when the module is installed

type Option

type Option struct {
	Key      string
	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 for options that are not boolean-toggleable

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

func (*ParseError) Is

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

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 // 0 = no maximum
}

Positionals constrains the accepted positional argument count

type PrefixLabel

type PrefixLabel struct {
	Modes []string
	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

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

func (*Registry) BoolOptionKeys

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

BoolOptionKeys returns registered option keys that support toggle

func (*Registry) LookupOption

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

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

func (*Registry) OptionCompleter

func (r *Registry) OptionCompleter() CompletionFunc

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) 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 its kebab-cased name as the first alias

func (*Registry) RegisterModule

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

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

type Section

type Section struct {
	Config any // *ConcreteConfig, pre-filled with defaults
	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

func DefaultSignature

func DefaultSignature() Signature

DefaultSignature returns a signature that accepts any number of positionals

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

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

func (*SyntaxError) Is

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

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)

func (*Tokenizer) Pos

func (t *Tokenizer) Pos() int

func (*Tokenizer) Rest

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

Jump to

Keyboard shortcuts

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