prompt

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: MIT Imports: 14 Imported by: 1

README

prompt

Go Reference Go Report Card MultiPlatformUnitTest

日本語 | Русский | 中文 | 한국어 | Español | Français

logo

prompt is a simple terminal prompt library for Go that provides powerful interactive command-line interfaces. This library is designed as a replacement for the unmaintained go-prompt library, addressing critical issues while adding enhanced functionality and better cross-platform support.

sample

✨ Features

  • 🖥️ Cross-Platform Support - Works seamlessly on Linux, macOS, and Windows
  • 🔍 Auto-Completion - Tab completion with fuzzy matching and customizable suggestions
  • 📚 Command History - Navigation with arrow keys, persistent history, and reverse search (Ctrl+R)
  • ⌨️ Key Bindings - Comprehensive shortcuts including Emacs-style navigation
  • 🌈 Color Themes - Built-in color schemes and customizable theming
  • 📝 Multi-line Input - Support for multi-line input with proper cursor navigation
  • 🔧 Simple API - Clean, modern API design with functional options pattern

📦 Installation

go get github.com/nao1215/prompt

🔧 Requirements

  • Go Version: 1.24 or later
  • Operating Systems:
    • Linux
    • macOS
    • Windows

🚀 Quick Start

Basic Usage
package main

import (
    "errors"
    "fmt"
    "log"
    "github.com/nao1215/prompt"
)

func main() {
    p, err := prompt.New("$ ")
    if err != nil {
        log.Fatal(err)
    }
    defer p.Close()

    for {
        input, err := p.Run()
        if err != nil {
            if errors.Is(err, prompt.ErrEOF) {
                fmt.Println("Goodbye!")
                break
            }
            log.Printf("Error: %v\n", err)
            continue
        }

        if input == "exit" {
            break
        }
        fmt.Printf("You entered: %s\n", input)
    }
}
With Auto-completion
package main

import (
    "errors"
    "log"
    "github.com/nao1215/prompt"
)

func completer(d prompt.Document) []prompt.Suggestion {
    return []prompt.Suggestion{
        {Text: "help", Description: "Show help message"},
        {Text: "users", Description: "List all users"},
        {Text: "groups", Description: "List all groups"},
        {Text: "exit", Description: "Exit the program"},
    }
}

func main() {
    p, err := prompt.New("myapp> ",
        prompt.WithCompleter(completer),
        prompt.WithColorScheme(prompt.ThemeNightOwl),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer p.Close()

    for {
        input, err := p.Run()
        if err != nil {
            if errors.Is(err, prompt.ErrEOF) {
                break
            }
            continue
        }

        if input == "exit" {
            break
        }
        // Handle commands...
    }
}
With History and Advanced Features
package main

import (
    "context"
    "fmt"
    "log"
    "time"
    "github.com/nao1215/prompt"
)

func main() {
    // Create prompt with history and timeout
    p, err := prompt.New(">>> ",
        prompt.WithMemoryHistory(100),
        prompt.WithColorScheme(prompt.ThemeDracula),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer p.Close()

    // Use context for timeout support
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    input, err := p.RunWithContext(ctx)
    if err == context.DeadlineExceeded {
        fmt.Println("Timeout reached")
        return
    }

    fmt.Printf("Input: %s\n", input)
}
SQL-like Interactive Shell
package main

import (
    "errors"
    "fmt"
    "log"
    "strings"
    "github.com/nao1215/prompt"
)

func sqlCompleter(d prompt.Document) []prompt.Suggestion {
    keywords := []string{
        "SELECT", "FROM", "WHERE", "INSERT", "UPDATE",
        "DELETE", "CREATE TABLE", "DROP TABLE",
    }

    suggestions := []prompt.Suggestion{}
    input := strings.ToUpper(d.GetWordBeforeCursor())

    for _, keyword := range keywords {
        if strings.HasPrefix(keyword, input) {
            suggestions = append(suggestions, prompt.Suggestion{
                Text: keyword,
                Description: "SQL keyword",
            })
        }
    }
    return suggestions
}

func main() {
    p, err := prompt.New("sql> ",
        prompt.WithCompleter(sqlCompleter),
        prompt.WithMemoryHistory(50),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer p.Close()

    for {
        query, err := p.Run()
        if err != nil {
            if errors.Is(err, prompt.ErrEOF) {
                break
            }
            continue
        }

        if query == "exit" || query == "quit" {
            break
        }

        if strings.TrimSpace(query) != "" {
            fmt.Printf("Executing: %s\n", query)
            // Execute SQL query here...
        }
    }
}

🔧 Advanced Usage

Using Fuzzy Completion
// Create a fuzzy completer for commands
commands := []string{
    "git status", "git commit", "git push", "git pull",
    "docker run", "docker build", "docker ps",
    "kubectl get", "kubectl apply", "kubectl delete",
}

fuzzyCompleter := prompt.NewFuzzyCompleter(commands)

p, err := prompt.New("$ ",
    prompt.WithCompleter(fuzzyCompleter),
)
Custom Key Bindings
keyMap := prompt.NewDefaultKeyMap()
// Add Ctrl+L to clear the line
keyMap.Bind('\x0C', prompt.ActionDeleteLine)

p, err := prompt.New("$ ",
    prompt.WithKeyMap(keyMap),
)
Persistent History
historyConfig := &prompt.HistoryConfig{
    Enabled:     true,
    MaxEntries:  1000,
    File:        "/home/user/.myapp_history",
    MaxFileSize: 1024 * 1024, // 1MB
    MaxBackups:  3,
}

p, err := prompt.New("$ ",
    prompt.WithHistory(historyConfig),
)

⌨️ Key Bindings

The library supports comprehensive key bindings out of the box:

Key Action
Enter Submit input
Ctrl+C Cancel and return ErrInterrupted
Ctrl+D EOF when buffer is empty
↑/↓ Navigate history (or lines in multi-line mode)
←/→ 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
Backspace Delete character backwards
Delete Delete character forwards
Ctrl+←/→ Move by word boundaries

🎨 Color Themes

Built-in color themes:

// Available themes
prompt.ThemeDefault
prompt.ThemeDracula
prompt.ThemeNightOwl
prompt.ThemeMonokai
prompt.ThemeSolarizedDark
prompt.ThemeSolarizedLight

// Usage
p, err := prompt.New("$ ",
    prompt.WithColorScheme(prompt.ThemeDracula),
)

📋 Examples

See the example directory for complete working examples:

⚠️ Important Notes

Thread Safety

⚠️ IMPORTANT: This library is NOT thread-safe:

  • Do NOT share prompt instances across goroutines
  • Do NOT call methods concurrently on the same prompt instance
  • Do NOT call Close() while Run() is active in another goroutine
  • Use separate prompt instances for concurrent operations if needed
Error Handling

The library provides specific error types:

  • prompt.ErrEOF: User pressed Ctrl+D with empty buffer
  • prompt.ErrInterrupted: User pressed Ctrl+C
  • context.DeadlineExceeded: Timeout reached (when using context)
  • context.Canceled: Context was cancelled

🤝 Contributing

Contributions are welcome! Please see the Contributing Guide for more details.

Development Requirements
  • Go 1.24 or later
  • golangci-lint for code quality
  • Cross-platform testing on Linux, macOS, and Windows

💖 Support

If you find this project useful, please consider:

  • ⭐ Giving it a star on GitHub - it helps others discover the project
  • 💝 Becoming a sponsor - your support keeps the project alive and motivates continued development

Your support, whether through stars, sponsorships, or contributions, is what drives this project forward. Thank you!

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

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

Constants

This section is empty.

Variables

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

View Source
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

func NewHistorySearcher(history []string) func(string) []string

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)

func Reset

func Reset() string

Reset returns the ANSI reset sequence.

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.

func (Color) ToANSI

func (c Color) ToANSI() string

ToANSI converts a Color to an ANSI escape sequence.

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

func (d *Document) CurrentLine() string

CurrentLine returns the current line

func (*Document) GetWordBeforeCursor

func (d *Document) GetWordBeforeCursor() string

GetWordBeforeCursor returns the word before the cursor

func (*Document) TextAfterCursor

func (d *Document) TextAfterCursor() string

TextAfterCursor returns the text after the cursor

func (*Document) TextBeforeCursor

func (d *Document) TextBeforeCursor() string

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

func (km *KeyMap) Bind(key rune, action KeyAction)

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

func (km *KeyMap) BindSequence(seq string, action KeyAction)

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

func (km *KeyMap) GetAction(key rune) KeyAction

GetAction returns the action for a key, or ActionNone if not bound

func (*KeyMap) GetSequenceAction

func (km *KeyMap) GetSequenceAction(seq string) KeyAction

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

func WithFileHistory(file string, maxEntries int) Option

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 WithKeyMap

func WithKeyMap(keyMap *KeyMap) Option

WithKeyMap sets the key bindings

func WithMemoryHistory

func WithMemoryHistory(maxEntries int) Option

WithMemoryHistory is a convenience function for memory-only history setup.

Example:

prompt.New("$ ", prompt.WithMemoryHistory(100))

func WithMultiline

func WithMultiline(multiline bool) Option

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

func New(prefix string, options ...Option) (*Prompt, error)

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

func (p *Prompt) AddHistory(command string)

AddHistory adds a command to the history

func (*Prompt) ClearHistory

func (p *Prompt) ClearHistory()

ClearHistory clears the command history

func (*Prompt) Close

func (p *Prompt) Close() error

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

func (p *Prompt) GetHistory() []string

GetHistory returns the current command history

func (*Prompt) Run

func (p *Prompt) Run() (string, error)

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

func (p *Prompt) RunWithContext(ctx context.Context) (string, error)

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

func (p *Prompt) SetHistory(history []string)

SetHistory replaces the entire history

func (*Prompt) SetPrefix

func (p *Prompt) SetPrefix(prefix string)

SetPrefix changes the prompt prefix

func (*Prompt) SetTheme

func (p *Prompt) SetTheme(theme *ColorScheme)

SetTheme changes the color theme of the prompt

type Suggest

type Suggest = Suggestion

Suggest is an alias for Suggestion for compatibility

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.

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.

Jump to

Keyboard shortcuts

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