input

package
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: GPL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package input provides input handling for the gsh REPL.

Package input provides input handling for the gsh REPL.

Package input provides a unified line input component for the gsh REPL. It merges functionality from pkg/gline and pkg/shellinput into a single cohesive Bubble Tea component that handles text input, cursor management, key bindings, tab completion, and LLM prediction integration.

Package input provides input handling for the gsh REPL.

Package input provides input handling for the gsh REPL.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateCursorPosition

func CalculateCursorPosition(prompt string, text string, cursorPos int) int

CalculateCursorPosition calculates the visual cursor position in the rendered line. This accounts for the prompt width and any multi-width characters.

func GetPredictionSuffix

func GetPredictionSuffix(text, prediction string) string

GetPredictionSuffix returns the portion of the prediction that extends beyond the current input text. Returns empty string if no valid prediction.

func GetWordBoundary

func GetWordBoundary(text string, cursorPos int) (start, end int)

GetWordBoundary finds the start and end positions of the word at the given cursor position in the input text. A word is defined as a sequence of non-whitespace characters.

func Paste

func Paste() tea.Msg

Paste returns a command that reads from the clipboard.

Types

type Action

type Action int

Action represents a keyboard action that can be triggered by key bindings.

const (
	// ActionNone represents no action (used when a key doesn't match any binding).
	ActionNone Action = iota

	// Navigation actions
	ActionCharacterForward  // Move cursor one character forward (Ctrl+F, Right)
	ActionCharacterBackward // Move cursor one character backward (Ctrl+B, Left)
	ActionWordForward       // Move cursor one word forward (Alt+F, Alt+Right)
	ActionWordBackward      // Move cursor one word backward (Alt+B, Alt+Left)
	ActionLineStart         // Move cursor to start of line (Ctrl+A, Home)
	ActionLineEnd           // Move cursor to end of line (Ctrl+E, End)

	// Deletion actions
	ActionDeleteCharacterBackward // Delete character before cursor (Backspace, Ctrl+H)
	ActionDeleteCharacterForward  // Delete character at cursor (Delete, Ctrl+D)
	ActionDeleteWordBackward      // Delete word before cursor (Ctrl+W, Alt+Backspace)
	ActionDeleteWordForward       // Delete word after cursor (Alt+D, Alt+Delete)
	ActionDeleteBeforeCursor      // Delete all text before cursor (Ctrl+U)
	ActionDeleteAfterCursor       // Delete all text after cursor (Ctrl+K)

	// Vertical navigation (context-dependent: history or completion)
	ActionCursorUp   // Move up (Up, Ctrl+P) - history previous or completion previous
	ActionCursorDown // Move down (Down, Ctrl+N) - history next or completion next

	// Completion actions
	ActionComplete         // Trigger tab completion (Tab)
	ActionCompleteBackward // Cycle backwards through completions (Shift+Tab)

	// Special actions
	ActionSubmit      // Submit the current input (Enter)
	ActionCancel      // Cancel current operation (Escape)
	ActionInterrupt   // Send interrupt signal (Ctrl+C)
	ActionEOF         // End of file / exit (Ctrl+D when input is empty)
	ActionClearScreen // Clear the screen (Ctrl+L)
	ActionPaste       // Paste from clipboard (Ctrl+V)

	// Prediction actions
	ActionAcceptPrediction // Accept the current prediction (Right arrow at end of line)

	// History search actions
	ActionHistorySearchBackward // Start/continue reverse history search (Ctrl+R)
)

func (Action) String

func (a Action) String() string

String returns the string representation of an Action.

type Buffer

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

Buffer manages text content and cursor position for line input. It provides rune-based text storage with efficient insert/delete operations and word boundary detection for navigation.

func NewBuffer

func NewBuffer() *Buffer

NewBuffer creates a new empty buffer.

func NewBufferWithText

func NewBufferWithText(text string) *Buffer

NewBufferWithText creates a buffer with initial text.

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear removes all text from the buffer and resets the cursor.

func (*Buffer) CursorEnd

func (b *Buffer) CursorEnd()

CursorEnd moves the cursor to the end of the buffer.

func (*Buffer) CursorStart

func (b *Buffer) CursorStart()

CursorStart moves the cursor to the start of the buffer.

func (*Buffer) DeleteAfterCursor

func (b *Buffer) DeleteAfterCursor()

DeleteAfterCursor deletes all text after the cursor.

func (*Buffer) DeleteBeforeCursor

func (b *Buffer) DeleteBeforeCursor()

DeleteBeforeCursor deletes all text before the cursor.

func (*Buffer) DeleteCharBackward

func (b *Buffer) DeleteCharBackward() bool

DeleteCharBackward deletes the character before the cursor. Returns true if a character was deleted.

func (*Buffer) DeleteCharForward

func (b *Buffer) DeleteCharForward() bool

DeleteCharForward deletes the character at the cursor. Returns true if a character was deleted.

func (*Buffer) DeleteWordBackward

func (b *Buffer) DeleteWordBackward()

DeleteWordBackward deletes the word to the left of the cursor.

func (*Buffer) DeleteWordForward

func (b *Buffer) DeleteWordForward()

DeleteWordForward deletes the word to the right of the cursor.

func (*Buffer) Insert

func (b *Buffer) Insert(text string)

Insert inserts text at the current cursor position. The cursor is moved to the end of the inserted text.

func (*Buffer) InsertRunes

func (b *Buffer) InsertRunes(runes []rune)

InsertRunes inserts runes at the current cursor position. The cursor is moved to the end of the inserted runes.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the length of the text in runes.

func (*Buffer) Pos

func (b *Buffer) Pos() int

Pos returns the current cursor position.

func (*Buffer) RuneAt

func (b *Buffer) RuneAt(pos int) rune

RuneAt returns the rune at the given position. Returns 0 if position is out of bounds.

func (*Buffer) RuneAtCursor

func (b *Buffer) RuneAtCursor() rune

RuneAtCursor returns the rune at the cursor position. Returns 0 if cursor is at the end or buffer is empty.

func (*Buffer) Runes

func (b *Buffer) Runes() []rune

Runes returns the current text content as a slice of runes.

func (*Buffer) SetPos

func (b *Buffer) SetPos(pos int)

SetPos sets the cursor position. If pos is out of bounds, it will be clamped to valid range [0, len(runes)].

func (*Buffer) SetRunes

func (b *Buffer) SetRunes(runes []rune)

SetRunes replaces the entire buffer content with new runes. The cursor is moved to the end of the new content.

func (*Buffer) SetText

func (b *Buffer) SetText(text string)

SetText replaces the entire buffer content with new text. The cursor is moved to the end of the new text.

func (*Buffer) Text

func (b *Buffer) Text() string

Text returns the current text content as a string.

func (*Buffer) TextAfterCursor

func (b *Buffer) TextAfterCursor() string

TextAfterCursor returns the text after the cursor.

func (*Buffer) TextBeforeCursor

func (b *Buffer) TextBeforeCursor() string

TextBeforeCursor returns the text before the cursor.

func (*Buffer) WordBackward

func (b *Buffer) WordBackward()

WordBackward moves the cursor one word to the left. A word is a sequence of non-whitespace characters.

func (*Buffer) WordForward

func (b *Buffer) WordForward()

WordForward moves the cursor one word to the right. A word is a sequence of non-whitespace characters.

type CompletionProvider

type CompletionProvider interface {
	// GetCompletions returns a list of completion suggestions for the current input
	// line and cursor position. Returns an empty slice if no completions are available.
	GetCompletions(line string, pos int) []string

	// GetHelpInfo returns help information for the current input.
	// This can be used to show documentation or hints for commands.
	// Returns empty string if no help is available.
	GetHelpInfo(line string, pos int) string
}

CompletionProvider is the interface that provides completion suggestions. Implementations should return completion candidates based on the current input line and cursor position.

type CompletionResult

type CompletionResult struct {
	// NewText is the resulting text after applying the completion
	NewText string
	// NewCursorPos is the new cursor position after applying the completion
	NewCursorPos int
}

CompletionResult represents the result of applying a completion suggestion.

func ApplySuggestion

func ApplySuggestion(text string, suggestion string, startPos, endPos int) CompletionResult

ApplySuggestion applies a completion suggestion to the given text. It replaces the text between startPos and endPos with the suggestion. Returns the new text and the new cursor position.

type CompletionState

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

CompletionState tracks the state of tab completion and implements InfoPanelContent. It manages the list of suggestions, current selection, and the text boundaries where the completion should be applied.

func NewCompletionState

func NewCompletionState() *CompletionState

NewCompletionState creates a new CompletionState in its initial (inactive) state.

func (*CompletionState) Activate

func (cs *CompletionState) Activate(suggestions []string, prefix string, startPos, endPos int)

Activate starts a new completion session with the given suggestions. It sets up the completion boundaries based on the provided positions.

func (*CompletionState) Cancel

func (cs *CompletionState) Cancel() string

Cancel cancels the current completion and returns the original text. After calling this, the completion state is reset.

func (*CompletionState) CurrentSuggestion

func (cs *CompletionState) CurrentSuggestion() string

CurrentSuggestion returns the currently selected suggestion. Returns empty string if no suggestion is selected or completion is inactive.

func (*CompletionState) EndPos

func (cs *CompletionState) EndPos() int

EndPos returns the end position of the completion in the input.

func (*CompletionState) HandleAction

func (cs *CompletionState) HandleAction(action Action) (InfoPanelContent, bool)

HandleAction implements InfoPanelContent. It processes completion-related actions like cycling through suggestions.

func (*CompletionState) HasMultipleCompletions

func (cs *CompletionState) HasMultipleCompletions() bool

HasMultipleCompletions returns true if there are multiple completion options.

func (*CompletionState) IsActive

func (cs *CompletionState) IsActive() bool

IsActive returns true if completion mode is currently active.

func (*CompletionState) IsInteractive

func (cs *CompletionState) IsInteractive() bool

IsInteractive implements InfoPanelContent. Returns true because completion supports cycling through suggestions with Tab/Shift+Tab.

func (*CompletionState) IsVisible

func (cs *CompletionState) IsVisible() bool

IsVisible implements InfoPanelContent. Returns true if there are multiple suggestions to display.

func (*CompletionState) NextSuggestion

func (cs *CompletionState) NextSuggestion() string

NextSuggestion advances to the next suggestion and returns it. Wraps around to the first suggestion after the last one. Returns empty string if completion is inactive or there are no suggestions.

func (*CompletionState) OriginalText

func (cs *CompletionState) OriginalText() string

OriginalText returns the original input text before completion started.

func (*CompletionState) Prefix

func (cs *CompletionState) Prefix() string

Prefix returns the text prefix being completed.

func (*CompletionState) PrevSuggestion

func (cs *CompletionState) PrevSuggestion() string

PrevSuggestion moves to the previous suggestion and returns it. Wraps around to the last suggestion before the first one. Returns empty string if completion is inactive or there are no suggestions.

func (*CompletionState) Render

func (cs *CompletionState) Render(width int) string

Render implements InfoPanelContent. It returns a string representation of the completion suggestions for display in the info panel.

func (*CompletionState) Reset

func (cs *CompletionState) Reset()

Reset clears all completion state and returns to inactive mode.

func (*CompletionState) Selected

func (cs *CompletionState) Selected() int

Selected returns the index of the currently selected suggestion. Returns -1 if no suggestion is selected.

func (*CompletionState) SetOriginalText

func (cs *CompletionState) SetOriginalText(text string)

SetOriginalText stores the original input text for potential cancellation.

func (*CompletionState) StartPos

func (cs *CompletionState) StartPos() int

StartPos returns the start position of the completion in the input.

func (*CompletionState) Suggestions

func (cs *CompletionState) Suggestions() []string

Suggestions returns the current list of completion suggestions.

func (*CompletionState) UpdateBoundaries

func (cs *CompletionState) UpdateBoundaries(prefix string, startPos, endPos int)

UpdateBoundaries updates the start and end positions for the completion. This is used when cycling through completions to update the boundaries based on the current input state.

type Config

type Config struct {
	// Prompt is the prompt string to display.
	Prompt string

	// AliasExistsFunc returns true if the given name is currently defined as a shell alias
	// or shell function. If set, the input syntax highlighter will treat aliases and
	// functions (e.g., from .gshenv or .gsh_profile) as valid commands.
	AliasExistsFunc func(name string) bool

	// GetEnvFunc returns the value of an environment variable from the shell.
	// If set, the syntax highlighter will use the shell's PATH (which may have been
	// modified in .gshenv or .gsh_profile) for command lookups, and the shell's
	// environment for variable highlighting.
	GetEnvFunc func(name string) string

	// GetWorkingDirFunc returns the current working directory from the shell.
	// If set, the syntax highlighter will resolve relative paths against this
	// directory instead of the process working directory.
	GetWorkingDirFunc func() string

	// HistoryValues is the list of previous commands for history navigation.
	// Index 0 is the most recent.
	HistoryValues []string

	// HistorySearchFunc is a function for searching history (used by Ctrl+R).
	// If nil, history search will use the HistoryValues list.
	HistorySearchFunc HistorySearchFunc

	// CompletionProvider provides tab completion suggestions.
	CompletionProvider CompletionProvider

	// PredictionState manages command predictions.
	PredictionState *PredictionState

	// KeyMap provides key bindings. If nil, DefaultKeyMap is used.
	KeyMap *KeyMap

	// RenderConfig provides styling. If nil, DefaultRenderConfig is used.
	RenderConfig *RenderConfig

	// MinHeight is the minimum number of lines to render.
	MinHeight int

	// Width is the initial terminal width.
	Width int

	// Logger for debug output. If nil, a no-op logger is used.
	Logger *zap.Logger
}

Config holds configuration for creating a new Model.

type HelpContent

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

HelpContent displays contextual help or documentation text. It implements InfoPanelContent for passive, non-interactive display.

func NewHelpContent

func NewHelpContent(text string) *HelpContent

NewHelpContent creates a new HelpContent with the given text.

func (*HelpContent) Clear

func (h *HelpContent) Clear()

Clear removes the help text content.

func (*HelpContent) HandleAction

func (h *HelpContent) HandleAction(action Action) (InfoPanelContent, bool)

HandleAction implements InfoPanelContent. Help content doesn't handle any actions, so it always returns false.

func (*HelpContent) IsInteractive

func (h *HelpContent) IsInteractive() bool

IsInteractive implements InfoPanelContent. Returns false because help content is read-only and doesn't respond to navigation.

func (*HelpContent) IsVisible

func (h *HelpContent) IsVisible() bool

IsVisible implements InfoPanelContent. Returns true if there is help text.

func (*HelpContent) Render

func (h *HelpContent) Render(width int) string

Render implements InfoPanelContent. Returns the help text.

func (*HelpContent) SetText

func (h *HelpContent) SetText(text string)

SetText updates the help text content.

func (*HelpContent) Text

func (h *HelpContent) Text() string

Text returns the help text content.

type Highlighter

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

Highlighter provides syntax highlighting for shell input.

func NewHighlighter

func NewHighlighter(
	aliasExists func(name string) bool,
	getEnv func(name string) string,
	getWorkingDir func() string,
) *Highlighter

NewHighlighter creates a new syntax highlighter.

If aliasExists is non-nil, any name for which it returns true is treated as an existing command (useful for shell aliases loaded at runtime).

If getEnv is non-nil, it is used to get environment variables from the shell, allowing the highlighter to use the shell's PATH and variable values.

If getWorkingDir is non-nil, it is used to resolve relative command paths so highlighting matches the shell's current working directory.

func (*Highlighter) Highlight

func (h *Highlighter) Highlight(input string) string

Highlight returns the input text with syntax highlighting applied.

type HistoryPredictionAdapter

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

HistoryPredictionAdapter adapts a history.HistoryManager to the HistoryProvider interface.

func NewHistoryPredictionAdapter

func NewHistoryPredictionAdapter(manager *history.HistoryManager) *HistoryPredictionAdapter

NewHistoryPredictionAdapter creates a new adapter for the history manager.

func (*HistoryPredictionAdapter) GetRecentEntriesByPrefix

func (a *HistoryPredictionAdapter) GetRecentEntriesByPrefix(prefix string, limit int) ([]history.HistoryEntry, error)

GetRecentEntriesByPrefix implements HistoryProvider.

type HistoryProvider

type HistoryProvider interface {
	// GetRecentEntriesByPrefix returns history entries matching the given prefix.
	GetRecentEntriesByPrefix(prefix string, limit int) ([]history.HistoryEntry, error)
}

HistoryProvider defines the interface for history-based predictions.

type HistorySearchFunc

type HistorySearchFunc func(query string) []string

HistorySearchFunc is a function type for searching history. It takes a query string and returns matching commands.

type HistorySearchState

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

HistorySearchState manages the state for reverse history search (Ctrl+R).

func NewHistorySearchState

func NewHistorySearchState() *HistorySearchState

NewHistorySearchState creates a new history search state.

func (*HistorySearchState) Accept

func (s *HistorySearchState) Accept() string

Accept exits history search, keeping the current match selected. Returns the selected command (or original input if no match).

func (*HistorySearchState) AddChar

func (s *HistorySearchState) AddChar(r rune)

AddChar adds a character to the search query.

func (*HistorySearchState) Cancel

func (s *HistorySearchState) Cancel() (originalInput string, originalCursorPos int)

Cancel exits history search and returns the original input to restore.

func (*HistorySearchState) CurrentMatch

func (s *HistorySearchState) CurrentMatch() string

CurrentMatch returns the currently selected match, or empty string if no matches.

func (*HistorySearchState) DeleteChar

func (s *HistorySearchState) DeleteChar() bool

DeleteChar removes the last character from the search query. Returns true if a character was deleted.

func (*HistorySearchState) IsActive

func (s *HistorySearchState) IsActive() bool

IsActive returns true if history search mode is active.

func (*HistorySearchState) MatchCount

func (s *HistorySearchState) MatchCount() int

MatchCount returns the total number of matches.

func (*HistorySearchState) MatchIndex

func (s *HistorySearchState) MatchIndex() int

MatchIndex returns the current match index.

func (*HistorySearchState) NextMatch

func (s *HistorySearchState) NextMatch() bool

NextMatch moves to the next (older) match. Returns true if the index changed.

func (*HistorySearchState) OriginalInput

func (s *HistorySearchState) OriginalInput() string

OriginalInput returns the input text from before the search started.

func (*HistorySearchState) PrevMatch

func (s *HistorySearchState) PrevMatch() bool

PrevMatch moves to the previous (newer) match. Returns true if the index changed.

func (*HistorySearchState) Query

func (s *HistorySearchState) Query() string

Query returns the current search query.

func (*HistorySearchState) Reset

func (s *HistorySearchState) Reset()

Reset clears the history search state.

func (*HistorySearchState) SetMatches

func (s *HistorySearchState) SetMatches(matches []string)

SetMatches updates the list of matching history entries.

func (*HistorySearchState) SetQuery

func (s *HistorySearchState) SetQuery(query string)

SetQuery updates the search query.

func (*HistorySearchState) Start

func (s *HistorySearchState) Start(currentInput string, cursorPos int)

Start begins a history search session, saving the current input state.

type InfoPanelContent

type InfoPanelContent interface {
	// Render returns the styled string to display in the info panel.
	// The width parameter indicates the available width for rendering.
	Render(width int) string

	// IsInteractive returns true if this content responds to navigation actions.
	// Interactive content can handle actions like cycling through options.
	IsInteractive() bool

	// HandleAction processes a keyboard action and returns the updated content
	// and whether the action was handled. If handled is true, the action should
	// not be processed further by the parent component.
	HandleAction(action Action) (content InfoPanelContent, handled bool)

	// IsVisible returns true if this content should be displayed.
	IsVisible() bool
}

InfoPanelContent is the interface for content that can be displayed in the info panel overlay. Different content types (completions, help text, errors, etc.) implement this interface to provide their rendering and interaction logic.

type KeyBinding

type KeyBinding struct {
	// Keys is the list of key sequences that trigger this binding.
	// Each string should be a valid tea.KeyMsg string representation.
	Keys []string
	// Action is the action to perform when this binding is triggered.
	Action Action
}

KeyBinding represents a single key binding that maps a key to an action.

type KeyMap

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

KeyMap holds all key bindings for the input component. It provides a configurable mapping from key presses to actions. Lookup is O(1) using an internal hash map.

func DefaultKeyMap

func DefaultKeyMap() *KeyMap

DefaultKeyMap returns a KeyMap with default Emacs-style key bindings.

func NewKeyMap

func NewKeyMap(bindings []KeyBinding) *KeyMap

NewKeyMap creates a new KeyMap with the given bindings.

func (*KeyMap) AddKeys

func (km *KeyMap) AddKeys(action Action, keys ...string)

AddKeys adds additional keys to an existing action binding. If the action doesn't exist, a new binding is created.

func (*KeyMap) Bindings

func (km *KeyMap) Bindings() []KeyBinding

Bindings returns a copy of all bindings in the keymap.

func (*KeyMap) Clone

func (km *KeyMap) Clone() *KeyMap

Clone creates a deep copy of the KeyMap.

func (*KeyMap) GetBinding

func (km *KeyMap) GetBinding(action Action) *KeyBinding

GetBinding returns the binding for the given action, or nil if not found.

func (*KeyMap) Lookup

func (km *KeyMap) Lookup(msg tea.KeyMsg) Action

Lookup finds the action for the given key message. Returns ActionNone if no binding matches. This is an O(1) operation using the internal lookup map.

func (*KeyMap) RemoveBinding

func (km *KeyMap) RemoveBinding(action Action)

RemoveBinding removes all bindings for the given action.

func (*KeyMap) RemoveKeys

func (km *KeyMap) RemoveKeys(action Action, keys ...string)

RemoveKeys removes specific keys from an action binding.

func (*KeyMap) SetBinding

func (km *KeyMap) SetBinding(binding KeyBinding)

SetBinding adds or updates a key binding. If a binding for the same action already exists, it will be replaced.

type LLMPredictionProvider

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

LLMPredictionProvider implements PredictionProvider using an LLM model.

func NewLLMPredictionProvider

func NewLLMPredictionProvider(
	model *interpreter.ModelValue,
	provider interpreter.ModelProvider,
	logger *zap.Logger,
) *LLMPredictionProvider

NewLLMPredictionProvider creates a new LLM prediction provider.

func (*LLMPredictionProvider) Predict

func (p *LLMPredictionProvider) Predict(ctx context.Context, input string) (string, error)

Predict implements PredictionProvider.

func (*LLMPredictionProvider) UpdateContext

func (p *LLMPredictionProvider) UpdateContext(contextText string)

UpdateContext updates the context text used for predictions.

type Model

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

Model is the Bubble Tea model for the unified input component. It coordinates the buffer, keymap, completion, prediction, and rendering.

func New

func New(cfg Config) Model

New creates a new input Model with the given configuration.

func (*Model) Blur

func (m *Model) Blur()

Blur removes focus from the model.

func (Model) Buffer

func (m Model) Buffer() *Buffer

Buffer returns the underlying buffer (for testing).

func (Model) Completion

func (m Model) Completion() *CompletionState

Completion returns the completion state (for testing).

func (Model) CurrentPrediction

func (m Model) CurrentPrediction() string

CurrentPrediction returns the current prediction text.

func (*Model) Focus

func (m *Model) Focus()

Focus sets the focus state on the model.

func (Model) Focused

func (m Model) Focused() bool

Focused returns whether the model is focused.

func (Model) HistorySearch

func (m Model) HistorySearch() *HistorySearchState

HistorySearch returns the history search state (for testing/rendering).

func (Model) Init

func (m Model) Init() tea.Cmd

Init implements tea.Model. It triggers an initial prediction request.

func (Model) Prompt

func (m Model) Prompt() string

Prompt returns the current prompt string.

func (*Model) Reset

func (m *Model) Reset()

Reset clears the input state for a new input session.

func (Model) Result

func (m Model) Result() Result

Result returns the current result. Check Type != ResultNone to see if complete.

func (*Model) SetHistorySearchFunc

func (m *Model) SetHistorySearchFunc(fn HistorySearchFunc)

SetHistorySearchFunc sets the function used for history search.

func (*Model) SetHistoryValues

func (m *Model) SetHistoryValues(values []string)

SetHistoryValues updates the history values for navigation.

func (*Model) SetPrompt

func (m *Model) SetPrompt(prompt string)

SetPrompt updates the prompt string.

func (*Model) SetValue

func (m *Model) SetValue(text string)

SetValue sets the input text and moves cursor to end.

func (Model) Update

func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update implements tea.Model. It handles all input events.

func (Model) Value

func (m Model) Value() string

Value returns the current input text.

func (Model) View

func (m Model) View() string

View implements tea.Model. It renders the input component.

type PredictionProvider

type PredictionProvider interface {
	// Predict returns a prediction for the given input.
	// The context can be used for cancellation.
	Predict(ctx context.Context, input string) (prediction string, err error)
}

PredictionProvider defines the interface for making predictions. This abstraction allows for different prediction backends (history, LLM, etc.)

type PredictionResult

type PredictionResult struct {
	// Prediction is the predicted command text.
	Prediction string

	// StateID is the state ID when this prediction was requested.
	// Used to discard stale predictions.
	StateID int64

	// Source indicates where the prediction came from.
	Source PredictionSource

	// Error contains any error that occurred during prediction.
	Error error
}

PredictionResult contains the result of a prediction request.

type PredictionSource

type PredictionSource int

PredictionSource indicates the source of a prediction.

const (
	// PredictionSourceNone indicates no prediction was made.
	PredictionSourceNone PredictionSource = iota
	// PredictionSourceHistory indicates the prediction came from command history.
	PredictionSourceHistory
	// PredictionSourceLLM indicates the prediction came from an LLM.
	PredictionSourceLLM
)

func (PredictionSource) String

func (ps PredictionSource) String() string

String returns the string representation of the prediction source.

type PredictionState

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

PredictionState manages the prediction lifecycle including debouncing, state coordination, and async prediction handling.

func NewPredictionState

func NewPredictionState(config PredictionStateConfig) *PredictionState

NewPredictionState creates a new PredictionState with the given configuration.

func (*PredictionState) Clear

func (ps *PredictionState) Clear()

Clear clears the current prediction.

func (*PredictionState) HasPrediction

func (ps *PredictionState) HasPrediction() bool

HasPrediction returns true if there is a current prediction.

func (*PredictionState) IsDirty

func (ps *PredictionState) IsDirty() bool

IsDirty returns whether the input has been modified.

func (*PredictionState) OnInputChanged

func (ps *PredictionState) OnInputChanged(input string) <-chan PredictionResult

OnInputChanged should be called when the input text changes. It returns a channel that will receive the prediction result, or nil if no prediction should be made (e.g., prediction already matches input). The caller should handle the result asynchronously.

History-based predictions are checked synchronously for instant feedback, while LLM predictions are debounced to avoid API spam.

func (*PredictionState) Prediction

func (ps *PredictionState) Prediction() string

Prediction returns the current prediction text.

func (*PredictionState) PredictionSuggestion

func (ps *PredictionState) PredictionSuggestion(input string) string

PredictionSuggestion returns the prediction as a suggestion string. If the prediction starts with the input, only returns the suffix.

func (*PredictionState) Reset

func (ps *PredictionState) Reset()

Reset clears all state including dirty flag.

func (*PredictionState) SetPrediction

func (ps *PredictionState) SetPrediction(stateID int64, prediction string) bool

SetPrediction sets the prediction if the state ID matches. Returns true if the prediction was set.

func (*PredictionState) StateID

func (ps *PredictionState) StateID() int64

StateID returns the current state ID.

type PredictionStateConfig

type PredictionStateConfig struct {
	// DebounceDelay is the delay before making a prediction request.
	// Defaults to 200ms if not set.
	DebounceDelay time.Duration

	// HistoryProvider provides history-based predictions.
	HistoryProvider HistoryProvider

	// LLMProvider provides LLM-based predictions.
	LLMProvider PredictionProvider

	// Logger for debug output.
	Logger *zap.Logger

	// HistoryPrefixLimit is the number of history entries to check.
	// Defaults to 10 if not set.
	HistoryPrefixLimit int
}

PredictionStateConfig holds configuration for creating a PredictionState.

type RenderConfig

type RenderConfig struct {
	// PromptStyle is the style applied to the prompt string.
	PromptStyle lipgloss.Style

	// TextStyle is the style applied to the input text.
	TextStyle lipgloss.Style

	// CursorStyle is the style applied to the cursor character.
	CursorStyle lipgloss.Style

	// PredictionStyle is the style for ghost text predictions.
	PredictionStyle lipgloss.Style

	// InfoPanelStyle is the style for the info panel border/container.
	InfoPanelStyle lipgloss.Style

	// CompletionPanelStyle is the style for the completion panel border/container.
	CompletionPanelStyle lipgloss.Style

	// SelectedStyle is the style for selected items in lists.
	SelectedStyle lipgloss.Style
}

RenderConfig holds styling configuration for rendering input components.

func DefaultRenderConfig

func DefaultRenderConfig() RenderConfig

DefaultRenderConfig returns a RenderConfig with sensible default styles.

type Renderer

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

Renderer handles rendering of input components.

func NewRenderer

func NewRenderer(config RenderConfig, h *Highlighter) *Renderer

NewRenderer creates a new Renderer with the given configuration.

func (*Renderer) Config

func (r *Renderer) Config() RenderConfig

Config returns the current render configuration.

func (*Renderer) RenderCompletionBox

func (r *Renderer) RenderCompletionBox(cs *CompletionState, maxVisible int) string

RenderCompletionBox renders the completion suggestions in a box format. maxVisible controls how many items are visible at once (scrolling window).

func (*Renderer) RenderFullView

func (r *Renderer) RenderFullView(
	prompt string,
	buffer *Buffer,
	prediction string,
	focused bool,
	completion *CompletionState,
	infoContent InfoPanelContent,
	minHeight int,
) string

RenderFullView renders the complete input view including: - Input line with prompt, text, cursor, and prediction - Completion box (if active) - Info/help panel (if available)

func (*Renderer) RenderHelpBox

func (r *Renderer) RenderHelpBox(text string) string

RenderHelpBox renders help text in an info panel.

func (*Renderer) RenderHistorySearchPrompt

func (r *Renderer) RenderHistorySearchPrompt(state *HistorySearchState, showCursor bool) string

RenderHistorySearchPrompt renders the prompt for history search mode. It shows "(history search)`query': " similar to bash's Ctrl+R style. The cursor is rendered at the end of the query.

func (*Renderer) RenderInfoPanel

func (r *Renderer) RenderInfoPanel(content InfoPanelContent) string

RenderInfoPanel renders an info panel with the given content.

func (*Renderer) RenderInputLine

func (r *Renderer) RenderInputLine(prompt string, buffer *Buffer, prediction string, focused bool) string

RenderInputLine renders the input line with prompt, text, cursor, and prediction. It returns the rendered string for the input line, with automatic line wrapping when the content exceeds the terminal width.

func (*Renderer) SetConfig

func (r *Renderer) SetConfig(config RenderConfig)

SetConfig updates the render configuration.

func (*Renderer) SetWidth

func (r *Renderer) SetWidth(width int)

SetWidth sets the terminal width for rendering.

func (*Renderer) Width

func (r *Renderer) Width() int

Width returns the current terminal width.

type Result

type Result struct {
	// Type indicates what action caused the input to complete.
	Type ResultType
	// Value is the input text (empty for interrupt/EOF).
	Value string
}

Result contains the outcome of an input session.

type ResultType

type ResultType int

ResultType indicates the type of result from the input component.

const (
	// ResultNone indicates no result yet (still editing).
	ResultNone ResultType = iota
	// ResultSubmit indicates the user submitted the input (Enter).
	ResultSubmit
	// ResultInterrupt indicates the user interrupted (Ctrl+C).
	ResultInterrupt
	// ResultEOF indicates end of input (Ctrl+D on empty line).
	ResultEOF
)

type StyledSpan

type StyledSpan struct {
	Text  string
	Style lipgloss.Style
}

StyledSpan represents a portion of text with a specific style.

type TokenType

type TokenType int

TokenType represents the type of a syntax token for highlighting.

const (
	TokenDefault     TokenType = iota // Default text, no special highlighting
	TokenCommand                      // Command/executable name
	TokenCommandOK                    // Command that exists (green)
	TokenCommandErr                   // Command that doesn't exist (red)
	TokenString                       // Quoted strings
	TokenVariableOK                   // Variables with non-empty value (green)
	TokenVariableErr                  // Variables that are empty/unset (red)
	TokenOperator                     // Operators (|, &&, ||, ;, >, <)
	TokenFlag                         // Flags (-f, --help)
	TokenComment                      // Comments (# ...)
	TokenAgentPrefix                  // Agent mode prefix (#)
	TokenAgentCmd                     // Agent commands (/clear, /agents)
)

Jump to

Keyboard shortcuts

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