Skip to content

nao1215/prompt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

17 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

prompt

Go Reference Go Report Card MultiPlatformUnitTest Coverage

ζ—₯本θͺž | Русский | δΈ­ζ–‡ | ν•œκ΅­μ–΄ | 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 c-bata/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.

About

prompt - interactive terminal prompts library in Go

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published