Documentation
¶
Overview ¶
Package prompt provides a modern, robust terminal prompt library for Go.
This library is designed as a replacement for the unmaintained go-prompt library, addressing critical issues like divide-by-zero panics, memory leaks, and limited cross-platform support while providing enhanced functionality.
Key Features:
- Interactive terminal prompts with rich editing capabilities
- Multi-line input support with proper cursor navigation
- Fuzzy auto-completion with intelligent ranking
- Command history with reverse search (Ctrl+R)
- Configurable key bindings and shortcuts
- Cross-platform compatibility (Windows, macOS, Linux)
- Context support for timeouts and cancellation
- Comprehensive error handling and resource management
Quick Start:
The simplest way to create a prompt:
package main
import (
"fmt"
"log"
"github.com/nao1215/prompt"
)
func main() {
p, err := prompt.New("Enter command: ")
if err != nil {
log.Fatal(err)
}
defer p.Close()
result, err := p.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("You entered: %s\n", result)
}
Advanced Usage with Completion:
completer := prompt.NewFuzzyCompleter([]string{
"git status", "git commit", "docker run", "kubectl get",
})
p, err := prompt.New("$ ",
prompt.WithCompleter(completer),
prompt.WithMemoryHistory(100),
)
if err != nil {
log.Fatal(err)
}
defer p.Close()
result, err := p.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Command: %s\n", result)
Key Bindings:
The library supports comprehensive key bindings out of the box:
- Enter: Submit input (Shift+Enter for multi-line in appropriate contexts)
- Ctrl+C: Cancel and return ErrInterrupted
- Ctrl+D: EOF when buffer is empty
- Arrow keys: Navigate history (up/down) and move cursor (left/right)
- Ctrl+A / Home: Move to beginning of line
- Ctrl+E / End: Move to end of line
- Ctrl+K: Delete from cursor to end of line
- Ctrl+U: Delete entire line
- Ctrl+W: Delete word backwards
- Ctrl+R: Reverse history search (like bash)
- Tab: Auto-completion
- Backspace: Delete character backwards
- Delete: Delete character forwards
- Ctrl+Left/Right: Move by word boundaries
Custom Key Bindings:
You can customize key bindings by creating a custom KeyMap:
keyMap := prompt.NewDefaultKeyMap()
// Add Ctrl+L to clear the line
keyMap.Bind('\x0C', prompt.ActionDeleteLine)
// Add F1 key for help (escape sequence)
keyMap.BindSequence("OP", prompt.ActionComplete)
config := prompt.Config{
Prefix: "$ ",
KeyMap: keyMap,
}
Context Support:
Use RunWithContext for timeout or cancellation support:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result, err := p.RunWithContext(ctx)
if err == context.DeadlineExceeded {
fmt.Println("Timeout reached")
return
}
Error Handling:
The library provides specific error types for different scenarios:
- prompt.ErrInterrupted: User pressed Ctrl+C
- io.EOF: User pressed Ctrl+D with empty buffer
- context.DeadlineExceeded: Timeout reached (when using context)
- context.Canceled: Context was cancelled
Multi-line Input:
The prompt automatically detects and handles multi-line input. When the buffer contains newline characters, arrow keys navigate between lines instead of history, and Home/End keys move to line boundaries instead of buffer boundaries.
Thread Safety:
Prompt instances are not thread-safe. Each prompt should be used from a single goroutine. However, you can safely cancel a prompt from another goroutine using context cancellation.
Resource Management:
Always call Close() when done with a prompt to prevent resource leaks:
p, err := prompt.New(config)
if err != nil {
return err
}
defer p.Close() // Essential for cleanup
The Close method is safe to call multiple times and should be called even if Run or RunWithContext returns an error.
Package prompt provides a library for building powerful interactive terminal prompts. This is a modern replacement for go-prompt with better cross-platform support, simpler API, and built-in color scheme support.
Index ¶
- Variables
- func GetDefaultHistoryFile() string
- func NewFileCompleter() func(Document) []Suggestion
- func NewFuzzyCompleter(candidates []string) func(Document) []Suggestion
- func NewHistorySearcher(history []string) func(string) []string
- func Reset() string
- type Color
- type ColorScheme
- type Config
- type Document
- type HistoryConfig
- type HistoryManager
- func (hm *HistoryManager) AddEntry(entry string)
- func (hm *HistoryManager) ClearHistory()
- func (hm *HistoryManager) GetHistory() []string
- func (hm *HistoryManager) IsEnabled() bool
- func (hm *HistoryManager) LoadHistory() error
- func (hm *HistoryManager) SaveHistory() error
- func (hm *HistoryManager) SetHistory(history []string)
- type KeyAction
- type KeyBinding
- type KeyMap
- type Option
- func WithColorScheme(colorScheme *ColorScheme) Option
- func WithCompleter(completer func(Document) []Suggestion) Option
- func WithFileHistory(file string, maxEntries int) Option
- func WithHistory(historyConfig *HistoryConfig) Option
- func WithKeyMap(keyMap *KeyMap) Option
- func WithMemoryHistory(maxEntries int) Option
- func WithMultiline(multiline bool) Option
- func WithTheme(theme *ColorScheme) Option
- type Prompt
- func (p *Prompt) AddHistory(command string)
- func (p *Prompt) ClearHistory()
- func (p *Prompt) Close() error
- func (p *Prompt) GetHistory() []string
- func (p *Prompt) Run() (string, error)
- func (p *Prompt) RunWithContext(ctx context.Context) (string, error)
- func (p *Prompt) SetCompleter(completer func(Document) []Suggestion)
- func (p *Prompt) SetHistory(history []string)
- func (p *Prompt) SetPrefix(prefix string)
- func (p *Prompt) SetTheme(theme *ColorScheme)
- type Suggest
- type Suggestion
- type SuggestionColors
Constants ¶
This section is empty.
Variables ¶
var ( // ErrEOF is returned when the user presses Ctrl+D or EOF is encountered ErrEOF = errors.New("EOF") // ErrInterrupted is returned when the user presses Ctrl+C ErrInterrupted = errors.New("interrupted") )
Common errors
var ThemeAccessible = &ColorScheme{ Name: "Accessible", Prefix: Color{R: 0, G: 114, B: 178, Bold: true}, Input: Color{R: 255, G: 255, B: 255, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 255, G: 255, B: 255, Bold: false}, Description: Color{R: 204, G: 204, B: 204, Bold: false}, Match: Color{R: 240, G: 228, B: 66, Bold: true}, Background: nil, }, Selected: Color{R: 230, G: 159, B: 0, Bold: true}, Background: nil, Cursor: Color{R: 255, G: 255, B: 255, Bold: false}, }
ThemeAccessible is a colorblind-safe theme with high contrast
var ThemeDark = &ColorScheme{ Name: "Dark", Prefix: Color{R: 102, G: 217, B: 239, Bold: true}, Input: Color{R: 248, G: 248, B: 242, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 189, G: 147, B: 249, Bold: false}, Description: Color{R: 98, G: 114, B: 164, Bold: false}, Match: Color{R: 255, G: 184, B: 108, Bold: true}, Background: nil, }, Selected: Color{R: 80, G: 250, B: 123, Bold: true}, Background: &Color{R: 40, G: 42, B: 54}, Cursor: Color{R: 248, G: 248, B: 242, Bold: false}, }
ThemeDark is a dark theme with light blue prefix and off-white text
var ThemeDefault = &ColorScheme{ Name: "default", Prefix: Color{R: 0, G: 255, B: 0, Bold: true}, Input: Color{R: 255, G: 255, B: 255, Bold: true}, Suggestion: SuggestionColors{ Text: Color{R: 200, G: 200, B: 200, Bold: false}, Description: Color{R: 128, G: 128, B: 128, Bold: false}, Match: Color{R: 255, G: 255, B: 0, Bold: true}, Background: nil, }, Selected: Color{R: 0, G: 255, B: 255, Bold: true}, Background: nil, Cursor: Color{R: 255, G: 255, B: 255, Bold: true}, }
ThemeDefault is the default color scheme with green prefix and white text
var ThemeDracula = &ColorScheme{ Name: "Dracula", Prefix: Color{R: 255, G: 121, B: 198, Bold: true}, Input: Color{R: 248, G: 248, B: 242, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 139, G: 233, B: 253, Bold: false}, Description: Color{R: 98, G: 114, B: 164, Bold: false}, Match: Color{R: 241, G: 250, B: 140, Bold: true}, Background: nil, }, Selected: Color{R: 80, G: 250, B: 123, Bold: true}, Background: &Color{R: 40, G: 42, B: 54}, Cursor: Color{R: 248, G: 248, B: 242, Bold: false}, }
ThemeDracula is the Dracula color scheme
var ThemeLight = &ColorScheme{ Name: "Light", Prefix: Color{R: 0, G: 119, B: 187, Bold: true}, Input: Color{R: 36, G: 41, B: 46, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 88, G: 96, B: 105, Bold: false}, Description: Color{R: 149, G: 157, B: 165, Bold: false}, Match: Color{R: 215, G: 58, B: 73, Bold: true}, Background: nil, }, Selected: Color{R: 40, G: 167, B: 69, Bold: true}, Background: &Color{R: 255, G: 255, B: 255}, Cursor: Color{R: 36, G: 41, B: 46, Bold: false}, }
ThemeLight is a light theme with blue prefix and dark gray text
var ThemeMonokai = &ColorScheme{ Name: "Monokai", Prefix: Color{R: 249, G: 38, B: 114, Bold: true}, Input: Color{R: 248, G: 248, B: 242, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 166, G: 226, B: 46, Bold: false}, Description: Color{R: 117, G: 113, B: 94, Bold: false}, Match: Color{R: 253, G: 151, B: 31, Bold: true}, Background: nil, }, Selected: Color{R: 102, G: 217, B: 239, Bold: true}, Background: &Color{R: 39, G: 40, B: 34}, Cursor: Color{R: 248, G: 248, B: 242, Bold: false}, }
ThemeMonokai is the Monokai color scheme
var ThemeNightOwl = &ColorScheme{ Name: "Night Owl", Prefix: Color{R: 130, G: 170, B: 255, Bold: true}, Input: Color{R: 214, G: 222, B: 235, Bold: true}, Suggestion: SuggestionColors{ Text: Color{R: 197, G: 228, B: 120, Bold: false}, Description: Color{R: 127, G: 219, B: 202, Bold: false}, Match: Color{R: 199, G: 146, B: 234, Bold: true}, Background: nil, }, Selected: Color{R: 34, G: 218, B: 110, Bold: true}, Background: &Color{R: 1, G: 22, B: 39}, Cursor: Color{R: 214, G: 222, B: 235, Bold: true}, }
ThemeNightOwl is the Night Owl color scheme
var ThemeSolarizedDark = &ColorScheme{ Name: "Solarized Dark", Prefix: Color{R: 133, G: 153, B: 0, Bold: true}, Input: Color{R: 147, G: 161, B: 161, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 131, G: 148, B: 150, Bold: false}, Description: Color{R: 88, G: 110, B: 117, Bold: false}, Match: Color{R: 181, G: 137, B: 0, Bold: true}, Background: nil, }, Selected: Color{R: 38, G: 139, B: 210, Bold: true}, Background: &Color{R: 0, G: 43, B: 54}, Cursor: Color{R: 253, G: 246, B: 227, Bold: false}, }
ThemeSolarizedDark is the Solarized Dark color scheme
var ThemeVSCode = &ColorScheme{ Name: "VS Code", Prefix: Color{R: 0, G: 122, B: 204, Bold: true}, Input: Color{R: 255, G: 255, B: 255, Bold: false}, Suggestion: SuggestionColors{ Text: Color{R: 156, G: 220, B: 254, Bold: false}, Description: Color{R: 106, G: 153, B: 85, Bold: false}, Match: Color{R: 255, G: 206, B: 84, Bold: true}, Background: nil, }, Selected: Color{R: 0, G: 122, B: 204, Bold: true}, Background: &Color{R: 30, G: 30, B: 30}, Cursor: Color{R: 255, G: 255, B: 255, Bold: true}, }
ThemeVSCode is the VS Code dark theme colors
Functions ¶
func GetDefaultHistoryFile ¶
func GetDefaultHistoryFile() string
GetDefaultHistoryFile returns the default history file path following XDG Base Directory Specification. Returns ~/.config/prompt/history or $XDG_CONFIG_HOME/prompt/history if XDG_CONFIG_HOME is set.
func NewFileCompleter ¶
func NewFileCompleter() func(Document) []Suggestion
NewFileCompleter creates a completer that provides file and directory suggestions
func NewFuzzyCompleter ¶
func NewFuzzyCompleter(candidates []string) func(Document) []Suggestion
NewFuzzyCompleter creates a new fuzzy completer with the given candidates.
The fuzzy completer provides intelligent auto-completion by matching user input against a list of candidates using fuzzy string matching. It supports partial matches, substring matches, and character-by-character fuzzy matching with scoring.
This is a convenience function that returns a completer function that can be used directly in Config.Completer. The returned function implements fuzzy matching and scoring automatically.
Example:
candidates := []string{
"git status", "git commit", "git push", "git pull",
"docker run", "docker build", "docker ps",
"kubectl get", "kubectl apply", "kubectl delete",
}
config := prompt.Config{
Prefix: "$ ",
Completer: prompt.NewFuzzyCompleter(candidates),
}
p, _ := prompt.New(config)
defer p.Close()
result, _ := p.Run()
func NewHistorySearcher ¶
NewHistorySearcher creates a new history searcher for command history.
The history searcher provides fuzzy search capabilities through command history, similar to reverse-i-search in bash (Ctrl+R). This is primarily used internally by the prompt for history search functionality.
This function returns a search function that can be used to find commands in the provided history that match a given query using fuzzy matching.
Example:
history := []string{
"git status",
"git commit -m 'fix bug'",
"docker run -it ubuntu",
"kubectl get pods",
}
search := prompt.NewHistorySearcher(history)
matches := search("git")
// Returns: ["git commit -m 'fix bug'", "git status"] (sorted by relevance)
Types ¶
type Color ¶
type Color struct {
R uint8 `json:"r"`
G uint8 `json:"g"`
B uint8 `json:"b"`
Bold bool `json:"bold"`
}
Color represents an RGB color with optional formatting.
type ColorScheme ¶
type ColorScheme struct {
Name string `json:"name"`
Prefix Color `json:"prefix"`
Input Color `json:"input"`
Suggestion SuggestionColors `json:"suggestion"`
Selected Color `json:"selected"`
Background *Color `json:"background"` // nil for transparent
Cursor Color `json:"cursor"`
}
ColorScheme defines the color configuration for the prompt.
type Config ¶
type Config struct {
Prefix string // Prompt prefix (e.g., "$ ")
Completer func(Document) []Suggestion // Completion function (accepts Document for context)
HistoryConfig *HistoryConfig // History configuration (nil for default)
ColorScheme *ColorScheme // Color scheme (nil for default)
KeyMap *KeyMap // Key bindings (nil for default)
Theme *ColorScheme // Alias for ColorScheme for compatibility
Multiline bool // Enable multiline input mode
}
Config holds the configuration for a prompt.
type Document ¶
type Document struct {
Text string // The entire input text
CursorPosition int // Current cursor position in the text
}
Document represents the current input state for completers
func (*Document) CurrentLine ¶
CurrentLine returns the current line
func (*Document) GetWordBeforeCursor ¶
GetWordBeforeCursor returns the word before the cursor
func (*Document) TextAfterCursor ¶
TextAfterCursor returns the text after the cursor
func (*Document) TextBeforeCursor ¶
TextBeforeCursor returns the text before the cursor
type HistoryConfig ¶
type HistoryConfig struct {
Enabled bool // Enable/disable history functionality
MaxEntries int // Maximum number of entries to keep in memory (default: 1000)
File string // File path for history persistence (empty = memory only)
MaxFileSize int64 // Maximum file size in bytes before rotation (default: 1MB)
MaxBackups int // Maximum number of backup files to keep (default: 3)
}
HistoryConfig holds all history-related configuration.
This struct consolidates all history settings for memory limits and file persistence options. History data is loaded from files or accumulated during runtime usage.
File path supports multiple formats: - Empty string: Memory-only history (no persistence) - Absolute path: "/home/user/.app_history" - Home directory: "~/.app_history" - Relative path: "./app_history" (converted to absolute) - XDG compliant: Use GetDefaultHistoryFile() for "~/.config/prompt/history"
The implementation follows XDG Base Directory Specification when possible.
func DefaultHistoryConfig ¶
func DefaultHistoryConfig() *HistoryConfig
DefaultHistoryConfig returns a default history configuration following XDG Base Directory Specification
type HistoryManager ¶
type HistoryManager struct {
// contains filtered or unexported fields
}
HistoryManager manages command history persistence and rotation
func NewHistoryManager ¶
func NewHistoryManager(config *HistoryConfig) *HistoryManager
NewHistoryManager creates a new history manager with the given configuration
func (*HistoryManager) AddEntry ¶
func (hm *HistoryManager) AddEntry(entry string)
AddEntry adds a new entry to the history
func (*HistoryManager) ClearHistory ¶
func (hm *HistoryManager) ClearHistory()
ClearHistory clears the current history
func (*HistoryManager) GetHistory ¶
func (hm *HistoryManager) GetHistory() []string
GetHistory returns a copy of the current history
func (*HistoryManager) IsEnabled ¶
func (hm *HistoryManager) IsEnabled() bool
IsEnabled returns whether history functionality is enabled
func (*HistoryManager) LoadHistory ¶
func (hm *HistoryManager) LoadHistory() error
LoadHistory loads history from the configured file
func (*HistoryManager) SaveHistory ¶
func (hm *HistoryManager) SaveHistory() error
SaveHistory saves the current history to the configured file
func (*HistoryManager) SetHistory ¶
func (hm *HistoryManager) SetHistory(history []string)
SetHistory replaces the current history
type KeyAction ¶
type KeyAction int
KeyAction represents the action to perform when a key is pressed
const ( ActionNone KeyAction = iota ActionSubmit ActionCancel ActionMoveLeft ActionMoveRight ActionMoveUp ActionMoveDown ActionMoveHome ActionMoveEnd ActionMoveWordLeft ActionMoveWordRight ActionDeleteChar ActionDeleteLine ActionDeleteToEnd ActionDeleteWordBack ActionComplete ActionHistoryUp ActionHistoryDown ActionHistorySearch ActionNewLine )
Key action constants define the actions that can be performed when keys are pressed
type KeyBinding ¶
type KeyBinding struct {
Key rune // Key character (for simple keys)
Seq string // Escape sequence (for special keys like arrows)
Action KeyAction
}
KeyBinding represents a keyboard shortcut mapping
type KeyMap ¶
type KeyMap struct {
// contains filtered or unexported fields
}
KeyMap holds the key binding configuration
func NewDefaultKeyMap ¶
func NewDefaultKeyMap() *KeyMap
NewDefaultKeyMap creates the default key bindings for the prompt.
The default key map includes common terminal shortcuts and navigation keys. You can create a custom key map by modifying the returned KeyMap or by creating a new one and using the Bind and BindSequence methods.
Default key bindings:
- Enter/Return: Submit input
- Ctrl+C: Cancel (interrupt)
- Ctrl+A: Move to beginning of line
- Ctrl+E: Move to end of line
- Ctrl+K: Delete from cursor to end of line
- Ctrl+U: Delete entire line
- Ctrl+W: Delete word backwards
- Ctrl+R: Reverse history search
- Tab: Auto-completion
- Backspace: Delete character backwards
- Arrow keys: Navigate history and move cursor
- Home/End: Move to line beginning/end
- Delete: Delete character forwards
- Ctrl+Left/Right: Move by word
Example:
keyMap := prompt.NewDefaultKeyMap()
// Add custom binding for Ctrl+L to clear screen
keyMap.Bind('\x0C', prompt.ActionNewLine)
config := prompt.Config{
Prefix: "$ ",
KeyMap: keyMap,
}
func (*KeyMap) Bind ¶
Bind adds or updates a key binding for a single character.
Use this method to bind actions to control characters, printable characters, or special keys that can be represented as a single rune.
Example:
keyMap := prompt.NewDefaultKeyMap()
// Bind Ctrl+L (\x0C) to clear the current line
keyMap.Bind('\x0C', prompt.ActionDeleteLine)
// Bind F1 key (if represented as a single rune)
keyMap.Bind('\x91', prompt.ActionComplete)
func (*KeyMap) BindSequence ¶
BindSequence adds or updates an escape sequence binding.
Use this method to bind actions to escape sequences like function keys, arrow keys, or other multi-character key combinations that start with ESC. The sequence should not include the initial ESC character.
Example:
keyMap := prompt.NewDefaultKeyMap()
// Bind F1 key (ESC + OP)
keyMap.BindSequence("OP", prompt.ActionComplete)
// Bind Shift+Tab (ESC + [Z)
keyMap.BindSequence("[Z", prompt.ActionHistoryUp)
// Bind Page Up (ESC + [5~)
keyMap.BindSequence("[5~", prompt.ActionHistoryUp)
func (*KeyMap) GetSequenceAction ¶
GetSequenceAction returns the action for an escape sequence, or ActionNone if not bound
type Option ¶
type Option func(*Config)
Option represents a configuration option for prompt
func WithColorScheme ¶
func WithColorScheme(colorScheme *ColorScheme) Option
WithColorScheme sets the color scheme
func WithCompleter ¶
func WithCompleter(completer func(Document) []Suggestion) Option
WithCompleter sets the completion function
func WithFileHistory ¶
WithFileHistory is a convenience function for history with file persistence.
Example:
prompt.New("$ ", prompt.WithFileHistory("~/.myapp_history", 100))
func WithHistory ¶
func WithHistory(historyConfig *HistoryConfig) Option
WithHistory configures history settings with the provided configuration. This is the recommended way to configure all history-related options.
Example:
prompt.New("$ ", prompt.WithHistory(&prompt.HistoryConfig{
Enabled: true,
MaxEntries: 100,
File: "~/.myapp_history",
}))
func WithMemoryHistory ¶
WithMemoryHistory is a convenience function for memory-only history setup.
Example:
prompt.New("$ ", prompt.WithMemoryHistory(100))
func WithMultiline ¶
WithMultiline enables or disables multiline input mode
func WithTheme ¶
func WithTheme(theme *ColorScheme) Option
WithTheme sets the color scheme (alias for compatibility)
type Prompt ¶
type Prompt struct {
// contains filtered or unexported fields
}
Prompt represents an interactive terminal prompt.
func New ¶
New creates a new prompt with the specified prefix and optional configuration.
This is the recommended way to create a new prompt as it provides a clean API with sensible defaults and allows for flexible configuration through options.
Example:
// Basic prompt with just a prefix
p, err := prompt.New("$ ")
if err != nil {
log.Fatal(err)
}
defer p.Close()
// Prompt with completion and history
p, err := prompt.New("$ ",
prompt.WithCompleter(func(d prompt.Document) []prompt.Suggestion {
if strings.HasPrefix(d.Text, "git") {
return []prompt.Suggestion{
{Text: "git status", Description: "Show working tree status"},
{Text: "git commit", Description: "Record changes to repository"},
}
}
return nil
}),
prompt.WithMemoryHistory(100),
)
if err != nil {
log.Fatal(err)
}
defer p.Close()
result, err := p.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("You entered: %s\n", result)
func (*Prompt) AddHistory ¶
AddHistory adds a command to the history
func (*Prompt) ClearHistory ¶
func (p *Prompt) ClearHistory()
ClearHistory clears the command history
func (*Prompt) Close ¶
Close closes the prompt and cleans up resources.
This method should be called when the prompt is no longer needed to prevent resource leaks. It's safe to call Close multiple times. It's recommended to use defer for automatic cleanup.
Example:
p, err := prompt.New(config)
if err != nil {
log.Fatal(err)
}
defer p.Close() // Ensure cleanup
// Use the prompt...
result, err := p.Run()
func (*Prompt) GetHistory ¶
GetHistory returns the current command history
func (*Prompt) Run ¶
Run starts the interactive prompt and returns the user input.
This is a convenience method that calls RunWithContext with a background context. The prompt will accept user input until Enter is pressed or an error occurs.
Example:
p, _ := prompt.New(prompt.Config{Prefix: "Enter command: "})
defer p.Close()
input, err := p.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("User entered: %s\n", input)
func (*Prompt) RunWithContext ¶
RunWithContext starts the interactive prompt with context support.
The prompt can be cancelled via the provided context, allowing for timeouts or cancellation from other goroutines. The function supports all configured key bindings, multi-line input, completion, and history navigation.
Supported key bindings include:
- Enter: Submit input (or add newline in multi-line mode)
- Ctrl+C: Cancel and return ErrInterrupted
- Ctrl+D: EOF when buffer is empty
- Arrow keys: Navigate history or move cursor
- Ctrl+A/Home: Move to beginning of line
- Ctrl+E/End: Move to end of line
- Ctrl+K: Delete from cursor to end of line
- Ctrl+U: Delete entire line
- Ctrl+W: Delete word backwards
- Ctrl+R: Reverse history search
- Tab: Auto-completion
Example with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
p, _ := prompt.New(prompt.Config{Prefix: "Command: "})
defer p.Close()
input, err := p.RunWithContext(ctx)
if err == context.DeadlineExceeded {
fmt.Println("Timeout reached")
return
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("Input: %s\n", input)
func (*Prompt) SetCompleter ¶
func (p *Prompt) SetCompleter(completer func(Document) []Suggestion)
SetCompleter changes the completion function
func (*Prompt) SetHistory ¶
SetHistory replaces the entire history
func (*Prompt) SetTheme ¶
func (p *Prompt) SetTheme(theme *ColorScheme)
SetTheme changes the color theme of the prompt
type Suggestion ¶
type Suggestion struct {
Text string // The text to complete
Description string // Description of the suggestion
}
Suggestion represents a completion suggestion.
type SuggestionColors ¶
type SuggestionColors struct {
Text Color `json:"text"`
Description Color `json:"description"`
Match Color `json:"match"` // Highlight color for matching parts
Background *Color `json:"background"` // nil for transparent
}
SuggestionColors defines colors for completion suggestions.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
autocomplete
command
Package main demonstrates autocomplete functionality using only public APIs.
|
Package main demonstrates autocomplete functionality using only public APIs. |
|
basic
command
Package main demonstrates basic usage of the prompt library.
|
Package main demonstrates basic usage of the prompt library. |
|
history
command
Package main demonstrates history management features of the prompt library.
|
Package main demonstrates history management features of the prompt library. |
|
multiline
command
Package main demonstrates multiline input capabilities of the prompt library.
|
Package main demonstrates multiline input capabilities of the prompt library. |
|
shell
command
Package main provides a shell-like file explorer example using the prompt library.
|
Package main provides a shell-like file explorer example using the prompt library. |

