readline

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: MIT, MIT Imports: 19 Imported by: 0

README

Readline Shortcut

Meta+B means press Esc and n separately.
Users can change that in terminal simulator(i.e. iTerm2) to Alt+B
Notice: Meta+B is equals with Alt+B in windows.

  • Shortcut in normal mode
Shortcut Comment
Ctrl+A Beginning of line
Ctrl+B / Backward one character
Meta+B Backward one word
Ctrl+C Send io.EOF
Ctrl+D Delete one character
Meta+D Delete one word
Ctrl+E End of line
Ctrl+F / Forward one character
Meta+F Forward one word
Ctrl+G Cancel
Ctrl+H Delete previous character
Ctrl+I / Tab Command line completion
Ctrl+J Line feed
Ctrl+K Cut text to the end of line
Ctrl+L Clear screen
Ctrl+M Same as Enter key
Ctrl+N / Next line (in history)
Ctrl+P / Prev line (in history)
Ctrl+R Search backwards in history
Ctrl+S Search forwards in history
Ctrl+T Transpose characters
Meta+T Transpose words (TODO)
Ctrl+U Cut text to the beginning of line
Ctrl+W Cut previous word
Backspace Delete previous character
Meta+Backspace Cut previous word
Enter Line feed
  • Shortcut in Search Mode (Ctrl+S or Ctrl+r to enter this mode)
Shortcut Comment
Ctrl+S Search forwards in history
Ctrl+R Search backwards in history
Ctrl+C / Ctrl+G Exit Search Mode and revert the history
Backspace Delete previous character
Other Exit Search Mode
  • Shortcut in Complete Select Mode (double Tab to enter this mode)
Shortcut Comment
Ctrl+F Move Forward
Ctrl+B Move Backward
Ctrl+N Move to next line
Ctrl+P Move to previous line
Ctrl+A Move to the first candicate in current line
Ctrl+E Move to the last candicate in current line
Tab / Enter Use the word on cursor to complete
Ctrl+C / Ctrl+G Exit Complete Select Mode
Other Exit Complete Select Mode

Documentation

Index

Constants

View Source
const (
	CharLineStart = 1
	CharBackward  = 2
	CharInterrupt = 3
	CharEOT       = 4
	CharLineEnd   = 5
	CharForward   = 6
	CharBell      = 7
	CharCtrlH     = 8
	CharTab       = 9
	CharCtrlJ     = 10
	CharKill      = 11
	CharCtrlL     = 12
	CharEnter     = 13
	CharNext      = 14
	CharPrev      = 16
	CharBckSearch = 18
	CharFwdSearch = 19
	CharTranspose = 20
	CharCtrlU     = 21
	CharCtrlW     = 23
	CharCtrlY     = 25
	CharCtrlZ     = 26
	CharEsc       = 27
	CharCtrl_     = 31
	CharO         = 79
	CharEscapeEx  = 91
	CharBackspace = 127
)
View Source
const (
	MetaBackward rune = -iota - 1
	MetaForward
	MetaDelete
	MetaBackspace
	MetaTranspose
	MetaShiftTab
	MetaDeleteKey
)

Variables

View Source
var (
	ErrInterrupt = errors.New("Interrupt")
)

NewEx is an alias for NewFromConfig, for compatibility.

Functions

This section is empty.

Types

type AutoCompleter

type AutoCompleter interface {
	// Do will pass the whole line and current offset to it
	// Completer need to pass all the candidates, and how long they shared the same characters in line
	// Example:
	//   [go, git, git-shell, grep]
	//   Do("g", 1) => ["o", "it", "it-shell", "rep"], 1
	//   Do("gi", 2) => ["t", "t-shell"], 2
	//   Do("git", 3) => ["", "-shell"], 3
	Do(line []rune, pos int) (newLine [][]rune, length int)
}

type Config

type Config struct {
	// Prompt is the input prompt (ANSI escape sequences are supported on all platforms)
	Prompt string

	// HistoryFile is the path to the file where persistent history will be stored
	// (empty string disables).
	HistoryFile string

	// HistoryLimit is the maximum number of history entries to store. If it is 0
	// or unset, the default value is 500; set to -1 to disable.
	HistoryLimit int

	// DisableAutoSaveHistory disables automatically saving input lines to history; if true, lines will only be added to history if SaveToHistory is called explicitly.
	DisableAutoSaveHistory bool

	// HistorySearchFold enables case-insensitive history searching.
	HistorySearchFold bool

	// AutoComplete defines the tab-completion behavior. See the documentation for the AutoCompleter interface for details.
	AutoComplete AutoCompleter

	// Listener is an optional callback to intercept keypresses.
	Listener Listener

	// Painter is an optional callback to rewrite the buffer for display.
	Painter Painter

	// FuncFilterInputRune is an optional callback to translate keyboard inputs;
	// it takes in the input rune and returns (translation, ok). If ok is false,
	// the rune is skipped.
	FuncFilterInputRune func(rune) (rune, bool)

	// VimMode enables Vim-style insert mode by default.
	VimMode bool

	// InterruptPrompt is the string to display when the user sends an interrupt signal (e.g. Ctrl+C). If set to "\n", no prompt will be displayed.
	InterruptPrompt string

	// EOFPrompt is the string to display when the user sends an EOF signal (e.g. Ctrl+D). If set to "\n", no prompt will be displayed.
	EOFPrompt string

	// EnableMask enables password masking mode, where input characters are not displayed on screen. MaskRune specifies the character to display for each input character (default '*').
	EnableMask bool

	// MaskRune is the character to display for each input character when EnableMask is true (default '*').
	MaskRune rune

	// Undo controls whether to maintain an undo buffer (if enabled, Ctrl+_ will undo the previous action).
	Undo bool

	// Stdin is the input source for the shell instance (default os.Stdin).
	Stdin io.Reader

	// Stdout is the output destination for the shell instance (default os.Stdout).
	Stdout io.Writer

	// Stderr is the error output destination for the shell instance (default os.Stderr).
	Stderr io.Writer

	// FuncIsTerminal is a function that returns true if the current environment is a terminal, false otherwise. If not provided, it defaults to checking if both stdin and stdout are terminals.
	FuncIsTerminal func() bool

	// FuncGetSize is a function that returns the width and height of the terminal. If not provided, it defaults to a platform-specific implementation.
	FuncMakeRaw func() error

	// FuncExitRaw is a function that restores the terminal to its previous state after FuncMakeRaw has been called. If not provided, it defaults to a platform-specific implementation.
	FuncExitRaw func() error

	// FuncMakeRaw is a function that puts the terminal into raw mode, which allows for more direct control over input and output. If not provided, it defaults to a platform-specific implementation.
	FuncGetSize func() (width int, height int)

	// FuncOnWidthChanged is a function that registers a callback to be called when the terminal width changes. If not provided, it defaults to a platform-specific implementation that listens for terminal resize events.
	FuncOnWidthChanged func(func())
	// contains filtered or unexported fields
}

Config defines the configuration for a shell instance.

type Instance

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

Instance represents a shell instance, which maintains state for the terminal and line editing operations.

func New

func New(prompt string) (*Instance, error)

New creates a shell instance with default configuration.

func NewFromConfig

func NewFromConfig(cfg *Config) (*Instance, error)

NewFromConfig creates a shell instance from the specified configuration.

func (*Instance) CaptureExitSignal

func (i *Instance) CaptureExitSignal()

CaptureExitSignal registers handlers for common exit signals that will close the readline instance.

func (*Instance) ClearScreen

func (i *Instance) ClearScreen()

ClearScreen clears the screen.

func (*Instance) Close

func (i *Instance) Close() error

Close closes the readline instance, cleaning up state changes to the terminal. It interrupts any concurrent Readline() operation, so it can be asynchronously or from a signal handler. It is concurrency-safe and idempotent, so it can be called multiple times.

func (*Instance) DisableHistory

func (i *Instance) DisableHistory()

DisableHistory disables the saving of input lines in history.

func (*Instance) EnableHistory

func (i *Instance) EnableHistory()

EnableHistory enables the saving of input lines in history.

func (*Instance) GeneratePasswordConfig

func (i *Instance) GeneratePasswordConfig() *Config

GeneratePasswordConfig generates a suitable Config for reading passwords; this config can be modified and then used with ReadLineWithConfig, or SetConfig.

func (*Instance) GetConfig

func (i *Instance) GetConfig() *Config

GetConfig returns a copy of the current config.

func (*Instance) IsVimMode

func (i *Instance) IsVimMode() bool

IsVimMode returns true if Vim-style insert mode is enabled, false otherwise.

func (*Instance) ReadLine

func (i *Instance) ReadLine() (string, error)

ReadLine reads a line from the configured input source, allowing inline editing. The returned error is either nil, io.EOF, or readline.ErrInterrupt.

func (*Instance) ReadLineWithConfig

func (i *Instance) ReadLineWithConfig(cfg *Config) (string, error)

ReadLineWithConfig reads a line from the configured input source using the provided Config, allowing inline editing. The returned error is either nil, io.EOF, or shell.ErrInterrupt.

func (*Instance) ReadLineWithDefault

func (i *Instance) ReadLineWithDefault(defaultValue string) (string, error)

ReadLineWithDefault is a convenience method that combines SetDefault and ReadLine, allowing you to read a line with a prefilled default value. The returned error is either nil, io.EOF, or readline.ErrInterrupt.

func (*Instance) ReadPassword

func (i *Instance) ReadPassword(prompt string) ([]byte, error)

ReadPassword reads a line from the configured input source using a suitable Config for password input (with masking enabled), allowing inline editing. The returned error is either nil, io.EOF, or readline.ErrInterrupt.

func (*Instance) ReadSlice

func (i *Instance) ReadSlice() ([]byte, error)

ReadSlice is a lower-level method that reads the input buffer as a slice of bytes, without any processing.

func (*Instance) Readline

func (i *Instance) Readline() (string, error)

Readline is an alias for ReadLine, for compatibility.

func (*Instance) Refresh

func (i *Instance) Refresh()

Refresh redraws the input buffer on screen.

func (*Instance) ResetHistory

func (i *Instance) ResetHistory()

func (*Instance) SaveToHistory

func (i *Instance) SaveToHistory(content string) error

SaveToHistory adds a string to the instance's stored history. This is particularly relevant when DisableAutoSaveHistory is configured.

func (*Instance) SetConfig

func (i *Instance) SetConfig(cfg *Config) error

SetConfig modifies the current instance's config.

func (*Instance) SetDefault

func (i *Instance) SetDefault(defaultValue string)

SetDefault prefills a default value for the next call to Readline() or related methods. The value will appear after the prompt for the user to edit, with the cursor at the end of the line.

func (*Instance) SetPrompt

func (i *Instance) SetPrompt(s string)

func (*Instance) SetVimMode

func (i *Instance) SetVimMode(on bool)

SetVimMode enables or disables Vim-style insert mode. When enabled, the instance starts in insert mode, and the user can press Esc to switch to normal mode, where they can use Vim-style keybindings for navigation and editing. Pressing i or a in normal mode switches back to insert mode. This method is concurrency-safe and can be called at any time.

func (*Instance) Stderr

func (i *Instance) Stderr() io.Writer

Stderr returns the error output destination for the shell instance, which can be used to write error output that will be displayed on screen without interfering with the input prompt and buffer.

func (*Instance) Stdout

func (i *Instance) Stdout() io.Writer

Stdout returns the output destination for the shell instance, which can be used to write output that will be displayed on screen without interfering with the input prompt and buffer.

func (*Instance) Write

func (i *Instance) Write(b []byte) (int, error)

Write writes output to the screen, redrawing the prompt and buffer as needed.

type Listener

type Listener func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)

Listener is a callback type to listen for keypresses while the line is being edited. It is invoked initially with (nil, 0, 0), and then subsequently for any keypress until (but not including) the newline/enter keypress that completes the input.

type Painter

type Painter func(line []rune, pos int) []rune

Painter is a callback type to allow modifying the buffer before it is rendered on screen, for example, to implement real-time syntax highlighting.

type PrefixCompleter

type PrefixCompleter struct {
	// Name is the name of a command, subcommand, or argument eligible for completion.
	Name string
	// Callback is optional; if defined, it takes the current line and returns
	// a list of possible completions associated with the current node (i.e.
	// in place of Name).
	Callback func(string) []string
	// Children is a list of possible completions that can follow the current node.
	Children []*PrefixCompleter
	// contains filtered or unexported fields
}

PrefixCompleter implements AutoCompleter via a recursive tree.

func NewPrefixCompleter

func NewPrefixCompleter(pc ...*PrefixCompleter) *PrefixCompleter

func PcItem

func PcItem(name string, pc ...*PrefixCompleter) *PrefixCompleter

func PcItemDynamic

func PcItemDynamic(callback func(string) []string, pc ...*PrefixCompleter) *PrefixCompleter

func (*PrefixCompleter) Do

func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int)

func (*PrefixCompleter) SetChildren

func (p *PrefixCompleter) SetChildren(children []*PrefixCompleter)

func (*PrefixCompleter) Tree

func (p *PrefixCompleter) Tree(prefix string) string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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