readline

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2023 License: MIT Imports: 20 Imported by: 21

README

readline

This is a pure Go implementation of functionality comparable to GNU Readline, i.e. line editing and command history for simple TUI programs.

It is a fork of chzyer/readline.

Documentation

Overview

Readline is a pure go implementation for GNU-Readline kind library.

example:

rl, err := readline.New("> ")
if err != nil {
	panic(err)
}
defer rl.Close()

for {
	line, err := rl.Readline()
	if err != nil { // io.EOF
		break
	}
	println(line)
}

Index

Constants

View Source
const (
	T_DATA = MsgType(iota)
	T_WIDTH
	T_WIDTH_REPORT
	T_ISTTY_REPORT
	T_RAW
	T_ERAW // exit raw
	T_EOF
)
View Source
const (
	S_STATE_FOUND = iota
	S_STATE_FAILING
)
View Source
const (
	S_DIR_BCK = iota
	S_DIR_FWD
)
View Source
const (
	CharLineStart = 1
	CharBackward  = 2
	CharInterrupt = 3
	CharDelete    = 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
	CharO         = 79
	CharEscapeEx  = 91
	CharBackspace = 127
)
View Source
const (
	MetaBackward rune = -iota - 1
	MetaForward
	MetaDelete
	MetaBackspace
	MetaTranspose
	MetaShiftTab
)
View Source
const (
	VIM_NORMAL = iota
	VIM_INSERT
	VIM_VISUAL
)

Variables

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

NewEx is an alias for NewFromConfig, for compatibility.

Functions

func DialRemote

func DialRemote(n, addr string) error

func Do

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

func ListenRemote

func ListenRemote(n, addr string, cfg *Config, h func(*Instance), onListen ...func(net.Listener) error) error

func Print

func Print(p PrefixCompleterInterface, prefix string, level int, buf *bytes.Buffer)

func RetSegment

func RetSegment(segments [][]rune, cands [][]rune, idx int) ([][]rune, int)

func SplitSegment

func SplitSegment(line []rune, pos int) ([][]rune, int)

Types

type AutoCompleter

type AutoCompleter interface {
	// Readline 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)
}

func SegmentFunc

func SegmentFunc(f func([][]rune, int) [][]rune) AutoCompleter

type Config

type Config struct {
	// prompt supports ANSI escape sequence, so we can color some characters even in windows
	Prompt string

	// readline will persist historys to file where HistoryFile specified
	HistoryFile string
	// specify the max length of historys, it's 500 by default, set it to -1 to disable history
	HistoryLimit           int
	DisableAutoSaveHistory bool
	// enable case-insensitive history searching
	HistorySearchFold bool

	// AutoCompleter will called once user press TAB
	AutoComplete AutoCompleter

	// Any key press will pass to Listener
	// NOTE: Listener will be triggered by (nil, 0, 0) immediately
	Listener Listener

	Painter Painter

	// If VimMode is true, readline will in vim.insert mode by default
	VimMode bool

	InterruptPrompt string
	EOFPrompt       string

	FuncGetWidth func() int
	// Function that returns width, height of the terminal or -1,-1 if unknown
	FuncGetSize func() (width int, height int)

	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer

	EnableMask bool
	MaskRune   rune

	// erase the editing line after user submited it
	// it use in IM usually.
	UniqueEditLine bool

	// filter input runes (may be used to disable CtrlZ or for translating some keys to different actions)
	// -> output = new (translated) rune and true/false if continue with processing this one
	FuncFilterInputRune func(rune) (rune, bool)

	// force use interactive even stdout is not a tty
	FuncIsTerminal      func() bool
	FuncMakeRaw         func() error
	FuncExitRaw         func() error
	FuncOnWidthChanged  func(func())
	ForceUseInteractive bool
	// contains filtered or unexported fields
}

func (Config) Clone

func (c Config) Clone() *Config

func (*Config) Init

func (c *Config) Init() error

func (*Config) SetListener

func (c *Config) SetListener(f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool))

type DumpListener

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

func (*DumpListener) OnChange

func (d *DumpListener) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)

type DynamicCompleteFunc

type DynamicCompleteFunc func(string) []string

Caller type for dynamic completion

type DynamicPrefixCompleterInterface

type DynamicPrefixCompleterInterface interface {
	PrefixCompleterInterface
	IsDynamic() bool
	GetDynamicNames(line []rune) [][]rune
}

type Instance

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

func HandleConn

func HandleConn(cfg Config, conn net.Conn) (*Instance, error)

func New

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

New creates a readline instance with default configuration.

func NewFromConfig

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

NewFromConfig creates a readline 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) Clean

func (i *Instance) Clean()

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

func (i *Instance) GenPasswordConfig() *Config

func (*Instance) HistoryDisable

func (i *Instance) HistoryDisable()

HistoryDisable the save of the commands into the history

func (*Instance) HistoryEnable

func (i *Instance) HistoryEnable()

HistoryEnable the save of the commands into the history (default on)

func (*Instance) IsVimMode

func (i *Instance) IsVimMode() bool

func (*Instance) ReadPassword

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

func (*Instance) ReadPasswordWithConfig

func (i *Instance) ReadPasswordWithConfig(cfg *Config) ([]byte, error)

we can generate a config by `i.GenPasswordConfig()`

func (*Instance) ReadSlice

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

same as readline

func (*Instance) Readline

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

err is one of (nil, io.EOF, readline.ErrInterrupt)

func (*Instance) ReadlineWithDefault

func (i *Instance) ReadlineWithDefault(what string) (string, error)

func (*Instance) Refresh

func (i *Instance) Refresh()

func (*Instance) ResetHistory

func (i *Instance) ResetHistory()

func (*Instance) SaveHistory

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

func (*Instance) SetConfig

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

func (*Instance) SetHistoryPath

func (i *Instance) SetHistoryPath(p string)

change history persistence in runtime

func (*Instance) SetMaskRune

func (i *Instance) SetMaskRune(r rune)

func (*Instance) SetPrompt

func (i *Instance) SetPrompt(s string)

func (*Instance) SetVimMode

func (i *Instance) SetVimMode(on bool)

switch VimMode in runtime

func (*Instance) Stderr

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

readline will refresh automatic when write through Stdout()

func (*Instance) Stdout

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

readline will refresh automatic when write through Stdout()

func (*Instance) Write

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

func (*Instance) WriteStdin

func (i *Instance) WriteStdin(val []byte) (int, error)

WriteStdin prefills the next Stdin fetch. On the next call to Readline(), this data will be written before the user input, and the user will be able to edit it. For example:

i := readline.New()
i.WriteStdin([]byte("test"))
_, _= i.Readline()

yields

> test[cursor]

type Listener

type Listener interface {
	OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)
}

func FuncListener

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

type Message

type Message struct {
	Type MsgType
	Data []byte
}

func NewMessage

func NewMessage(t MsgType, data []byte) *Message

func ReadMessage

func ReadMessage(r io.Reader) (*Message, error)

func (*Message) WriteTo

func (m *Message) WriteTo(w io.Writer) (int64, error)

type MsgType

type MsgType int16

type Operation

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

func NewOperation

func NewOperation(t *Terminal, cfg *Config) *Operation

func (*Operation) Clean

func (o *Operation) Clean()

func (*Operation) Close

func (o *Operation) Close()

func (*Operation) GenPasswordConfig

func (o *Operation) GenPasswordConfig() *Config

func (*Operation) GetConfig

func (o *Operation) GetConfig() *Config

func (*Operation) IsNormalMode

func (o *Operation) IsNormalMode() bool

func (*Operation) Password

func (o *Operation) Password(prompt string) ([]byte, error)

func (*Operation) PasswordWithConfig

func (o *Operation) PasswordWithConfig(cfg *Config) ([]byte, error)

func (*Operation) Refresh

func (o *Operation) Refresh()

func (*Operation) ResetHistory

func (o *Operation) ResetHistory()

func (*Operation) Runes

func (o *Operation) Runes() ([]rune, error)

func (*Operation) SaveHistory

func (o *Operation) SaveHistory(content string) error

if err is not nil, it just mean it fail to write to file other things goes fine.

func (*Operation) SetBuffer

func (o *Operation) SetBuffer(what string)

func (*Operation) SetConfig

func (op *Operation) SetConfig(cfg *Config) (*Config, error)

func (*Operation) SetHistoryPath

func (o *Operation) SetHistoryPath(path string)

func (*Operation) SetMaskRune

func (o *Operation) SetMaskRune(r rune)

func (*Operation) SetPrompt

func (o *Operation) SetPrompt(s string)

func (*Operation) SetTitle

func (o *Operation) SetTitle(t string)

func (*Operation) Slice

func (o *Operation) Slice() ([]byte, error)

func (*Operation) Stderr

func (o *Operation) Stderr() io.Writer

func (*Operation) Stdout

func (o *Operation) Stdout() io.Writer

func (*Operation) String

func (o *Operation) String() (string, error)

type Painter

type Painter interface {
	Paint(line []rune, pos int) []rune
}

type PrefixCompleter

type PrefixCompleter struct {
	Name     []rune
	Dynamic  bool
	Callback DynamicCompleteFunc
	Children []PrefixCompleterInterface
}

func NewPrefixCompleter

func NewPrefixCompleter(pc ...PrefixCompleterInterface) *PrefixCompleter

func PcItem

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

func (*PrefixCompleter) Do

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

func (*PrefixCompleter) GetChildren

func (p *PrefixCompleter) GetChildren() []PrefixCompleterInterface

func (*PrefixCompleter) GetDynamicNames

func (p *PrefixCompleter) GetDynamicNames(line []rune) [][]rune

func (*PrefixCompleter) GetName

func (p *PrefixCompleter) GetName() []rune

func (*PrefixCompleter) IsDynamic

func (p *PrefixCompleter) IsDynamic() bool

func (*PrefixCompleter) Print

func (p *PrefixCompleter) Print(prefix string, level int, buf *bytes.Buffer)

func (*PrefixCompleter) SetChildren

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

func (*PrefixCompleter) Tree

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

type PrefixCompleterInterface

type PrefixCompleterInterface interface {
	Print(prefix string, level int, buf *bytes.Buffer)
	Do(line []rune, pos int) (newLine [][]rune, length int)
	GetName() []rune
	GetChildren() []PrefixCompleterInterface
	SetChildren(children []PrefixCompleterInterface)
}

type RemoteCli

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

func NewRemoteCli

func NewRemoteCli(conn net.Conn) (*RemoteCli, error)

func (*RemoteCli) Close

func (r *RemoteCli) Close()

func (*RemoteCli) MarkIsTerminal

func (r *RemoteCli) MarkIsTerminal(is bool)

func (*RemoteCli) Serve

func (r *RemoteCli) Serve() error

func (*RemoteCli) ServeBy

func (r *RemoteCli) ServeBy(source io.Reader) error

func (*RemoteCli) Write

func (r *RemoteCli) Write(b []byte) (int, error)

type RemoteSvr

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

func NewRemoteSvr

func NewRemoteSvr(conn net.Conn) (*RemoteSvr, error)

func (*RemoteSvr) Close

func (r *RemoteSvr) Close() error

func (*RemoteSvr) EnterRawMode

func (r *RemoteSvr) EnterRawMode() error

func (*RemoteSvr) ExitRawMode

func (r *RemoteSvr) ExitRawMode() error

func (*RemoteSvr) GetWidth

func (r *RemoteSvr) GetWidth() int

func (*RemoteSvr) GotIsTerminal

func (r *RemoteSvr) GotIsTerminal(data []byte)

func (*RemoteSvr) GotReportWidth

func (r *RemoteSvr) GotReportWidth(data []byte)

func (*RemoteSvr) HandleConfig

func (r *RemoteSvr) HandleConfig(cfg *Config)

func (*RemoteSvr) IsTerminal

func (r *RemoteSvr) IsTerminal() bool

func (*RemoteSvr) Read

func (r *RemoteSvr) Read(b []byte) (int, error)

func (*RemoteSvr) Write

func (r *RemoteSvr) Write(b []byte) (int, error)

type RuneBuffer

type RuneBuffer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewRuneBuffer

func NewRuneBuffer(w *Terminal, prompt string, cfg *Config) *RuneBuffer

func (*RuneBuffer) BackEscapeWord

func (r *RuneBuffer) BackEscapeWord()

func (*RuneBuffer) Backspace

func (r *RuneBuffer) Backspace()

func (*RuneBuffer) Backup

func (r *RuneBuffer) Backup()

func (*RuneBuffer) Clean

func (r *RuneBuffer) Clean()

func (*RuneBuffer) CurrentWidth

func (r *RuneBuffer) CurrentWidth(x int) int

func (*RuneBuffer) CursorLineCount

func (r *RuneBuffer) CursorLineCount() int

func (*RuneBuffer) Delete

func (r *RuneBuffer) Delete() (success bool)

func (*RuneBuffer) DeleteWord

func (r *RuneBuffer) DeleteWord()

func (*RuneBuffer) Erase

func (r *RuneBuffer) Erase()

func (*RuneBuffer) IdxLine

func (r *RuneBuffer) IdxLine(width int) int

func (*RuneBuffer) IsCursorInEnd

func (r *RuneBuffer) IsCursorInEnd() bool

func (*RuneBuffer) Kill

func (r *RuneBuffer) Kill()

func (*RuneBuffer) KillFront

func (r *RuneBuffer) KillFront()

func (*RuneBuffer) Len

func (r *RuneBuffer) Len() int

func (*RuneBuffer) LineCount

func (r *RuneBuffer) LineCount() int

LineCount returns number of lines the buffer takes as it appears in the terminal.

func (*RuneBuffer) MoveBackward

func (r *RuneBuffer) MoveBackward()

func (*RuneBuffer) MoveForward

func (r *RuneBuffer) MoveForward()

func (*RuneBuffer) MoveTo

func (r *RuneBuffer) MoveTo(ch rune, prevChar, reverse bool) (success bool)

func (*RuneBuffer) MoveToEndWord

func (r *RuneBuffer) MoveToEndWord()

func (*RuneBuffer) MoveToLineEnd

func (r *RuneBuffer) MoveToLineEnd()

func (*RuneBuffer) MoveToLineStart

func (r *RuneBuffer) MoveToLineStart()

func (*RuneBuffer) MoveToNextWord

func (r *RuneBuffer) MoveToNextWord()

func (*RuneBuffer) MoveToPrevWord

func (r *RuneBuffer) MoveToPrevWord() (success bool)

func (*RuneBuffer) Pos

func (r *RuneBuffer) Pos() int

func (*RuneBuffer) Print

func (r *RuneBuffer) Print()

Print writes out the prompt and buffer contents at the current cursor position

func (*RuneBuffer) PromptLen

func (r *RuneBuffer) PromptLen() int

func (*RuneBuffer) Refresh

func (r *RuneBuffer) Refresh(f func())

func (*RuneBuffer) Replace

func (r *RuneBuffer) Replace(ch rune)

func (*RuneBuffer) Reset

func (r *RuneBuffer) Reset() []rune

func (*RuneBuffer) Restore

func (r *RuneBuffer) Restore()

func (*RuneBuffer) RuneSlice

func (r *RuneBuffer) RuneSlice(i int) []rune

func (*RuneBuffer) Runes

func (r *RuneBuffer) Runes() []rune

func (*RuneBuffer) Set

func (r *RuneBuffer) Set(buf []rune)

func (*RuneBuffer) SetConfig

func (r *RuneBuffer) SetConfig(cfg *Config)

func (*RuneBuffer) SetMask

func (r *RuneBuffer) SetMask(m rune)

func (*RuneBuffer) SetOffset

func (r *RuneBuffer) SetOffset(position cursorPosition)

func (*RuneBuffer) SetPrompt

func (r *RuneBuffer) SetPrompt(prompt string)

func (*RuneBuffer) SetStyle

func (r *RuneBuffer) SetStyle(start, end int, style string)

func (*RuneBuffer) SetWithIdx

func (r *RuneBuffer) SetWithIdx(idx int, buf []rune)

func (*RuneBuffer) Transpose

func (r *RuneBuffer) Transpose()

func (*RuneBuffer) WriteRune

func (r *RuneBuffer) WriteRune(s rune)

func (*RuneBuffer) WriteRunes

func (r *RuneBuffer) WriteRunes(s []rune)

func (*RuneBuffer) WriteString

func (r *RuneBuffer) WriteString(s string)

func (*RuneBuffer) Yank

func (r *RuneBuffer) Yank()

type SegmentComplete

type SegmentComplete struct {
	SegmentCompleter
}

func SegmentAutoComplete

func SegmentAutoComplete(completer SegmentCompleter) *SegmentComplete

func (*SegmentComplete) Do

func (c *SegmentComplete) Do(line []rune, pos int) (newLine [][]rune, offset int)

type SegmentCompleter

type SegmentCompleter interface {
	// a
	// |- a1
	// |--- a11
	// |- a2
	// b
	// input:
	//   DoTree([], 0) [a, b]
	//   DoTree([a], 1) [a]
	//   DoTree([a, ], 0) [a1, a2]
	//   DoTree([a, a], 1) [a1, a2]
	//   DoTree([a, a1], 2) [a1]
	//   DoTree([a, a1, ], 0) [a11]
	//   DoTree([a, a1, a], 1) [a11]
	DoSegment([][]rune, int) [][]rune
}

type TabCompleter

type TabCompleter struct{}

func (*TabCompleter) Do

func (t *TabCompleter) Do([]rune, int) ([][]rune, int)

type Terminal

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

func NewTerminal

func NewTerminal(cfg *Config) (*Terminal, error)

func (*Terminal) Bell

func (t *Terminal) Bell()

func (*Terminal) Close

func (t *Terminal) Close() error

func (*Terminal) EnterRawMode

func (t *Terminal) EnterRawMode() (err error)

func (*Terminal) ExitRawMode

func (t *Terminal) ExitRawMode() (err error)

func (*Terminal) GetCursorPosition

func (t *Terminal) GetCursorPosition(deadline chan struct{}) (cursorPosition, error)

getOffset sends a DSR query to get the current offset, then blocks until the query returns.

func (*Terminal) GetRune

func (t *Terminal) GetRune(deadline chan struct{}) (rune, error)

func (*Terminal) GetWidthHeight

func (t *Terminal) GetWidthHeight() (width, height int)

GetWidthHeight returns the cached width, height values from the terminal

func (*Terminal) OnSizeChange

func (t *Terminal) OnSizeChange()

OnSizeChange gets the current terminal size and caches it

func (*Terminal) SetConfig

func (t *Terminal) SetConfig(c *Config) error

func (*Terminal) SleepToResume

func (t *Terminal) SleepToResume()

SleepToResume will sleep myself, and return only if I'm resumed.

func (*Terminal) Write

func (t *Terminal) Write(b []byte) (int, error)

Directories

Path Synopsis
example
readline-demo command
readline-pass-strength command
This is a small example using readline to read a password and check it's strength while typing using the zxcvbn library.
This is a small example using readline to read a password and check it's strength while typing using the zxcvbn library.
internal
term
Package term provides support functions for dealing with terminals, as commonly found on UNIX systems.
Package term provides support functions for dealing with terminals, as commonly found on UNIX systems.

Jump to

Keyboard shortcuts

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