Documentation
¶
Overview ¶
Package rline reads lines from a terminal, with editing, history, completion and syntax highlighting.
New returns a Prompt. A Prompt embeds a Session, which does the reading, and holds a MarkupWriter, which writes styled output:
p, err := rline.New(rline.WithPrompt("> ", "| "))
if err != nil {
return err
}
defer p.Close()
for {
line, err := p.ReadLine("")
switch {
case errors.Is(err, io.EOF):
return nil // the input ended
case errors.Is(err, rline.ErrInterrupted):
continue // the line was given up
case err != nil:
return err
}
fmt.Fprintf(p, "read: %s\n", line)
}
A Prompt is an io.Writer for plain text, which is what most of what a program prints is: a bracket in it is not a tag. Write through it rather than to os.Stdout, because the terminal it writes through is the one that knows where the prompt is. Markup such as "[red]text[/red]" goes through Prompt.Markup.
Every position and count this package takes is a byte offset, which is what indexes a Go string. The one exception is LineStyle.StyleRunes, which says so in its name.
Its origin ¶
rline is a port of isocline, a readline replacement written in C by Daan Leijen. isocline carries the MIT license, and this copyright notice covers every part of this package that derives from it:
Copyright (c) 2021, Daan Leijen
The port does not use cgo. Inside, it keeps the behavior of the C code even where that behavior is wrong, because recorded sessions from the C build are the test corpus, and each departure carries a comment where the code makes it. The interface above is deliberately not a translation of the C one: it is shaped for Go. [ReadLine] answering ErrInterrupted is the one place where a behavior rather than a name departs, because the C cannot tell an abandoned line from an empty one and a shell has to.
Index ¶
- Constants
- func Commands() []string
- type Binding
- type Candidate
- type Command
- type CommandFunc
- type Completer
- type CompleterFunc
- type Completion
- type Edit
- type Error
- type Highlighter
- type HighlighterFunc
- type HistoryControl
- type Line
- func (l *Line) AcceptAndRelease(fn func(rw io.ReadWriter) error) error
- func (l *Line) AcceptLine()
- func (l *Line) Bell()
- func (l *Line) Complete(name string, completer Completer)
- func (l *Line) Count() int
- func (l *Line) CountGiven() bool
- func (l *Line) Cursor() int
- func (l *Line) Insert(s string)
- func (l *Line) Key() key.Code
- func (l *Line) Kill(start, end int)
- func (l *Line) Mark() int
- func (l *Line) Print(text string)
- func (l *Line) Release(fn func(rw io.ReadWriter) error) error
- func (l *Line) Replace(text string, cursor int)
- func (l *Line) Run(name string)
- func (l *Line) SetMark(pos int)
- func (l *Line) Text() string
- type LineStyle
- type MarkupWriter
- type Option
- func WithAppName(appName string) Option
- func WithAutoPairs(autoPairs string) Option
- func WithAutoTab(autoTab bool) Option
- func WithBeep(beep bool) Option
- func WithBraceInsertion(autoPair bool) Option
- func WithBraceMatching(braceMatching bool) Option
- func WithColor(color bool) Option
- func WithCommand(name string, command Command) Option
- func WithCompleter(completer Completer) Option
- func WithCompletionMenu(completionMenu bool) Option
- func WithContinue(cont func(text string) bool) Option
- func WithHighlighter(highlighter Highlighter) Option
- func WithHintDelay(hintDelay time.Duration) Option
- func WithHints(hints bool) Option
- func WithHistory(enabled bool) Option
- func WithHistoryControl(historyControl HistoryControl) Option
- func WithHistoryDuplicates(historyDuplicates bool) Option
- func WithHistoryFile(name string) Option
- func WithHistoryFileLimit(historyFileLimit int) Option
- func WithHistoryFileMode(historyFileMode fs.FileMode) Option
- func WithHistoryFilter(historyFilter func(line, previous string) bool) Option
- func WithHistoryLimit(historyLimit int) Option
- func WithInlineHelp(inlineHelp bool) Option
- func WithInputrcFile(inputrcFile string) Option
- func WithInputrcLines(inputrcLines []string) Option
- func WithKeepInterrupted(bool) Optiondeprecated
- func WithLogger(logger slog.Handler) Option
- func WithManualHistory(manualHistory bool) Option
- func WithManualInterruptNewline(manualInterruptNewline bool) Option
- func WithMatchPairs(matchPairs string) Option
- func WithMultiline(multiline bool) Option
- func WithMultilineIndent(multilineIndent bool) Option
- func WithPrompt(marker, continuation string) Option
- func WithRowPrompt(rowPrompt func(before string) string) Option
- func WithStderr(stderr io.Writer) Option
- func WithStdin(stdin io.Reader) Option
- func WithStdout(stdout io.Writer) Option
- func WithTerminal(terminal Terminal) Option
- func WithUserInputrc(userInputrc bool) Option
- func WithViMode(viMode bool) Option
- func WithWrapMark(wrapMark bool) Option
- type Prompt
- type Session
- func (s *Session) AddCommand(name string, command Command) error
- func (s *Session) AddHistory(entry string)
- func (s *Session) Bind(keymap, seq, name string) error
- func (s *Session) Bindings(keymap string) ([]Binding, error)
- func (s *Session) ClearHistory()
- func (s *Session) Close() error
- func (s *Session) DefineStyle(name, spec string)
- func (s *Session) History() []string
- func (s *Session) HistoryErr() error
- func (s *Session) Interactive() bool
- func (s *Session) LoadHistory() error
- func (s *Session) Notices() []string
- func (s *Session) Palette() ansi.Palette
- func (s *Session) ParseAndBind(line string) error
- func (s *Session) Password(prompt string) (string, error)
- func (s *Session) PushInput(input []byte)
- func (s *Session) ReadInputrc(name string) error
- func (s *Session) ReadLine(prompt string) (string, error)
- func (s *Session) ReadLineWith(prompt, text string) (string, error)
- func (s *Session) Release(fn func(tty *os.File) error) error
- func (s *Session) RemoveLastHistory()
- func (s *Session) RunAtPrompt(fn func(w io.Writer) error)
- func (s *Session) SaveHistory() error
- func (s *Session) Set(opts ...Option) error
- func (s *Session) SetCompleter(completer Completer)
- func (s *Session) SetHighlighter(h Highlighter)
- func (s *Session) SetHistoryFile(name string)
- func (s *Session) SetPrompt(marker, continuation string)
- func (s *Session) SetVariable(name, value string) error
- func (s *Session) Size() (cols, rows int)
- func (s *Session) Stderr() io.Writer
- func (s *Session) Unbind(keymap, seq string) error
- func (s *Session) Variables() map[string]string
- func (s *Session) Write(p []byte) (int, error)
- func (s *Session) WriteString(text string) (int, error)
- type Terminal
Constants ¶
const ( // DefaultPromptMarker is written after the prompt text. DefaultPromptMarker = "> " // DefaultMatchPairs are the pairs whose partner is highlighted. DefaultMatchPairs = "()[]{}" // DefaultAutoPairs are the pairs that close themselves when typed. DefaultAutoPairs = `()[]{}""''` // DefaultHintDelay is how long to wait before showing a hint. DefaultHintDelay = 400 * time.Millisecond // DefaultMultilineEOL ends a line that carries on below. DefaultMultilineEOL = '\\' // DefaultAppName is the name of the program that $if tests in an inputrc // file, unless WithAppName sets another. DefaultAppName = "rline" // DefaultHistoryEntries is how many lines are remembered: 500, which is // what psql keeps. The C keeps 200 and cannot keep more (D67). DefaultHistoryEntries = 500 // NoHistoryLimit is the limit of WithHistoryLimit and // WithHistoryFileLimit that holds every entry, as a negative HISTSIZE // or HISTFILESIZE does in bash. NoHistoryLimit = math.MaxInt // DefaultHistoryFileMode is the permission a history file is created // with: readable and writable by its owner and by nobody else. // // A history file holds whatever was typed at the prompt, which for a // shell can include a connection string with a password in it. The C // takes the same view, calling chmod after fopen to force 0600, except // on Windows where it does not try. The port dropped that call and // created the file 0666, so the mode was whatever the umask left, // usually 0644 and readable by everyone on the machine. This is the // mode being chosen rather than inherited. // // The umask still applies, and it can only narrow this. An existing // file keeps the mode it has, because a mode is only used when a file // is created. Use WithHistoryFileMode to widen or narrow it. DefaultHistoryFileMode fs.FileMode = 0o600 )
Default settings.
const ( // LogWrite is the message of a record of what was written to the // terminal, at debug level. LogWrite = "write" // LogRead is the message of a record of a byte read from the keyboard, // at debug level. LogRead = "read" // LogLine is the message of a record of a line that ReadLine handed // back, at info level. LogLine = "line" // LogInterrupted is the message of a record of a line given up with // Ctrl-C, at info level. LogInterrupted = "interrupted" // LogEndOfInput is the message of a record of the end of the input, at // info level. LogEndOfInput = "end of input" // LogPassword is the message of a record that says Password read a // password, at info level. It holds nothing of the password. LogPassword = "password" // LogBytes is the attribute that holds the bytes of a LogWrite or a // LogRead record, as a string. LogBytes = "bytes" // LogText is the attribute that holds the line of a LogLine record. LogText = "text" )
The messages and the attributes of the records that WithLogger gives its handler (D54).
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Binding ¶
type Binding struct {
// Keys is the key sequence as readline prints it, which is how an inputrc
// file writes it, such as \C-a or \e[A.
Keys string
// Command is the command that the keys run. It is empty for a macro.
Command string
// Macro is the text of a macro, as readline prints it. It is empty for a
// command.
Macro string
}
A Binding is a key sequence of a keymap and what it runs, as bash's bind -p and bind -s print them (D76).
type Candidate ¶
type Candidate struct {
// Replacement is what goes into the line.
Replacement string
// Display is what the menu shows. An empty Display shows the
// Replacement itself.
Display string
// Help is a line shown below the menu.
Help string
// DeleteBefore and DeleteAfter are how many bytes on each side of the
// cursor this completion takes away.
DeleteBefore int
DeleteAfter int
// Suffix goes after the Replacement when it is the only completion, or
// when menu-complete or the menu of WithCompletionMenu puts it in, and
// the word reached the end of the line, as readline adds a space after
// a word (D46, D133). A hint is taken without it. An empty Suffix adds
// nothing. A directory has no Suffix, and gets the mark that Mode gives
// it.
Suffix string
// Mode is the mode of the file that Replacement names, as
// fs.FileInfo.Mode gives it after a symbolic link is followed, with
// fs.ModeSymlink also set when the name is a symbolic link. os.Stat
// never gives both, so the program sets fs.ModeSymlink itself for a
// link to a directory. The zero Mode says that the completion gets no
// mark (D127).
//
// A Mode with fs.ModeDir makes the completion a directory, and readline's
// commands put a slash after it as readline's mark-directories and
// mark-symlinked-directories say. Display then holds the name without
// the slash: a list adds the slash, and measures its columns without
// it. isocline's numbered menu of WithCompletionMenu shows the slash
// too, and puts it in as readline's menu-complete does.
Mode fs.FileMode
}
Candidate is one completion, said in full.
Every count here is in bytes, as every position in this package is, because that is what indexes a Go string. The one place characters are counted is LineStyle.StyleRunes, which says so in its name.
type Command ¶
type Command interface {
Run(l *Line)
}
A Command is a command of the program's own, which an inputrc file binds a key to by its name, as readline's rl_add_defun adds one (D58). WithCommand adds it.
This is an interface rather than a function type so that a command can grow a second method without breaking everyone who has one. Wrap a plain function in CommandFunc.
type CommandFunc ¶
type CommandFunc func(l *Line)
CommandFunc makes a Command out of an ordinary function.
type Completer ¶
type Completer interface {
Complete(c *Completion, prefix string)
}
Completer offers completions for the word at the cursor.
It is handed the prefix to complete and calls Add for each answer. Returning without adding anything means there is nothing to offer.
This is an interface rather than a function type so that a completer can grow a second method without breaking everyone who has one. Wrap a plain function in CompleterFunc.
type CompleterFunc ¶
type CompleterFunc func(c *Completion, prefix string)
CompleterFunc makes a Completer out of an ordinary function.
func (CompleterFunc) Complete ¶
func (f CompleterFunc) Complete(c *Completion, prefix string)
Complete satisfies Completer.
type Completion ¶
type Completion struct {
// contains filtered or unexported fields
}
Completion is what a completer is given: the whole line, where the cursor sits in it, and the way to offer an answer.
func (*Completion) Add ¶
func (c *Completion) Add(replacement string) bool
Add offers one completion, which replaces the prefix that was handed to the completer. When it is the only completion and the cursor is at the end of the line, a space follows it, as readline adds one (D56). It reports whether more are wanted: a completer that is walking a large directory should stop when it answers false.
func (*Completion) AddCandidate ¶
func (c *Completion) AddCandidate(cand Candidate) bool
AddCandidate offers one completion, said in full. It reports whether more are wanted, as Add does.
func (*Completion) Cursor ¶
func (c *Completion) Cursor() int
Cursor returns where the cursor sits in Text, as a byte offset.
func (*Completion) KeepOrder ¶
func (c *Completion) KeepOrder()
KeepOrder shows the completions in the order they were added, rather than sorted, as bash's complete -o nosort asks. It holds for this one request for completions (D75).
func (*Completion) Text ¶
func (c *Completion) Text() string
Text returns the whole line the completer was called on, not only the part before the cursor.
A completer is handed the prefix to complete, which is usually all it needs. This is for the times it is not — deciding whether the cursor sits inside a word, for one, which is what stops a completion being offered in the middle of a word that is already there.
type Edit ¶
Edit is how the line changed: the bytes from Start to OldEnd of Before became the bytes from Start to NewEnd of the line (D128).
It has what the edit of an incremental parser, such as tree-sitter, asks for. The rows and the columns of the three places are not in it, and Before is, so that a highlighter can count them in the text that it needs.
type Error ¶
type Error string
Error is an error.
The errors this package returns are constants of this type rather than package level variables, so that nothing can reassign one. A var holding an error is writable by any code that can see it, and an error value that changes underneath a caller comparing against it is a fault nobody looks for.
The text of each one is its own name with the Err prefix taken off: ErrClosed reads "closed". So the message a caller prints and the identifier they looked it up by are the same words, and neither can drift from the other. Context belongs in the wrapping at the place the error is returned, not in the sentinel.
const ( // ErrClosed is returned by a Session that has been closed. ErrClosed Error = "closed" // ErrInterrupted is returned when the user abandoned what was being read // with Ctrl-C, which asks for the reading to be given up rather than for // the input to end. The line stays on the screen with ^C in it, as bash // leaves it (D122). Ctrl-G is readline's abort, and gives nothing up // (D45). // // The C has no way to say this. It clears the line and hands back an // empty string, so a caller cannot tell an abandoned line from Enter on // an empty one. A shell has to: usql resets its statement buffer on an // interrupt and carries on, and would otherwise run whatever Ctrl-C left // behind. This is the one place where the port departs from the C over a // behaviour rather than a fault. ErrInterrupted Error = "interrupted" // ErrCommandExists is returned by New when WithCommand names a command // that readline or rline already has (D58). ErrCommandExists Error = "command exists" // ErrNotAFile is returned by Release when the Session writes to // something that is not a file, such as a buffer, so there is no file to // give to another program. ErrNotAFile Error = "not a file" // ErrUnknownCommand is returned by Bind when it is given a name that no // command has (D76). ErrUnknownCommand Error = "unknown command" // ErrUnknownKeymap is returned when a keymap is named that readline does // not have (D76). ErrUnknownKeymap Error = "unknown keymap" // ErrUnknownVariable is returned by SetVariable when it is given a name // that readline has no variable for (D76). ErrUnknownVariable Error = "unknown variable" // ErrInvalidSequence is returned when a key sequence holds a byte that // stands for no key (D76). ErrInvalidSequence Error = "invalid sequence" // ErrInvalidValue is returned by SetVariable and ParseAndBind when the // value or the line holds a line break, which no line of an inputrc file // can hold (D76, D77). ErrInvalidValue Error = "invalid value" // ErrNotSettable is returned by Set when it is given an option that // cannot change after New, such as WithStdout (D141). ErrNotSettable Error = "not settable" )
Error values.
type Highlighter ¶
type Highlighter interface {
Highlight(l *LineStyle)
}
Highlighter marks up a line. It is given the line and an environment to mark it through.
type HighlighterFunc ¶
type HighlighterFunc func(l *LineStyle)
HighlighterFunc makes a Highlighter out of an ordinary function.
func (HighlighterFunc) Highlight ¶
func (f HighlighterFunc) Highlight(l *LineStyle)
Highlight satisfies Highlighter.
type HistoryControl ¶
type HistoryControl uint8
HistoryControl says which lines the history leaves out, as HISTCONTROL does in bash (D99). WithHistoryControl sets it. The zero value leaves out no line.
const ( // HistoryIgnoreSpace leaves out a line that starts with a space, as // ignorespace does. A line that starts with a tab goes in, as in bash. HistoryIgnoreSpace HistoryControl = 1 << iota // HistoryIgnoreDups leaves out a line that is the same as the newest // entry, as ignoredups does. HistoryIgnoreDups // HistoryEraseDups takes each earlier copy of a line out of the history // before the line goes in, as erasedups does. HistoryEraseDups // HistoryIgnoreBoth is HistoryIgnoreSpace and HistoryIgnoreDups, as // ignoreboth is. HistoryIgnoreBoth = HistoryIgnoreSpace | HistoryIgnoreDups )
The values of HistoryControl, which combine with |. Each one has the meaning of the value of HISTCONTROL that it is named for.
type Line ¶
type Line struct {
// contains filtered or unexported fields
}
Line is the line being edited, as a Command sees it and changes it. Every position is a byte offset, as everywhere in this package. In one row, on a dumb terminal or with horizontal-scroll-mode, after Enter put in a newline because the line goes on, the line is the row after that newline, as bash gives bind -x only the line after PS2 (D143).
A change to the line, the mark or the kill ring happens at once, and undo takes back everything that the command changed as one step. Run and Complete wait until the command returns.
func (*Line) AcceptAndRelease ¶
func (l *Line) AcceptAndRelease(fn func(rw io.ReadWriter) error) error
AcceptAndRelease finishes the line as it stands, with the cursor moved below it and the line kept on the screen, and gives the terminal to fn, as bash's edit-and-execute-command does before it runs the editor. ReadLine then hands the line back, with what the command made of it, and draws no more of it: no prompt follows what fn wrote. It returns the error of fn (D85).
func (*Line) AcceptLine ¶
func (l *Line) AcceptLine()
AcceptLine finishes the line after the command returns, as accept-line does, so that ReadLine hands it back.
func (*Line) Bell ¶
func (l *Line) Bell()
Bell rings the bell, as a readline command does when it can do nothing.
func (*Line) Complete ¶
Complete runs a command that completes, such as complete, possible-completions or insert-completions, after this command returns, with completer in place of the Session's, as bash's complete-filename completes file names whatever the program's completer offers. The Session's completer is back in place afterwards (D80).
func (*Line) Count ¶
Count returns the numeric argument typed before the key, as readline passes it to a command. It is 1 when none was typed, and can be negative.
func (*Line) CountGiven ¶
CountGiven reports whether a numeric argument was typed before the key, as bash's READLINE_ARGUMENT is set only then (D82).
func (*Line) Kill ¶
Kill takes the text from start to end out of the line and puts it on the kill ring, as readline's kill commands do, so that yank brings it back. A kill by the command that ran just before joins it, as a second kill-word does. The cursor and the mark go to where the text was, and the two ends can come in either order (D83).
func (*Line) Print ¶
Print writes text below the line and keeps the line on the screen above it, and draws the prompt and the line again below the text, as bash's display-shell-version does (D85).
func (*Line) Release ¶
func (l *Line) Release(fn func(rw io.ReadWriter) error) error
Release gives the terminal to fn while the command runs, as bash does for bind -x: the line is taken off the screen, the terminal leaves raw mode, fn reads and writes the terminal through rw, and then the prompt and the line are drawn again below what fn wrote. It returns the error of fn, or the error of putting the terminal back into raw mode (D81).
func (*Line) Replace ¶
Replace makes the line text, with the cursor at cursor. Undo takes the change back as one step, with the rest of the command.
func (*Line) Run ¶
Run runs the readline or rline command called name after this command returns, as though its key were pressed then, with no numeric argument. Undo takes it back as a step of its own. A name that no command has rings the bell (D80).
type LineStyle ¶
type LineStyle struct {
// contains filtered or unexported fields
}
LineStyle is a line and the attributes drawn over it.
A highlighter is handed one of these, reads the line with Text, and calls Style or StyleRunes on the stretches it recognises. Anything it does not touch keeps the attributes of the terminal.
func (*LineStyle) Edit ¶
Edit returns how the line changed since the highlighter was last called in this Session: in the same line, or in the line before for the first call of a line. One call can follow many changes, such as a paste or keys typed ahead, and the Edit covers them all. A move of the cursor alone gives an Edit whose three places are the same. Edit reports false on the first call after WithHighlighter or SetHighlighter, when nothing was handed before (D128).
func (*LineStyle) Style ¶
Style marks count bytes from pos with a named style, such as "keyword" or a color name such as "red".
A negative count means a number of characters rather than bytes, which is what a caller counting characters wants. A negative pos is refused, which is what the C does.
func (*LineStyle) StyleMarkup ¶
StyleMarkup styles the stretch of line that s covers, taking the styles from markup that spells out the same text.
It is for a caller that would rather describe a whole line at once than a stretch at a time: pass the text and the same text with tags around it, and the tags decide the attributes.
Only the attributes are taken. The text the markup produces is thrown away, and when the two disagree in length the marks simply run out and the rest of the line keeps what it had. The C writes a debug line about that, which the port drops because nothing reads it.
func (*LineStyle) StyleRunes ¶
StyleRunes marks count characters from pos with a named style.
pos is still counted in bytes, because that is where the caller found the word; only the length is counted in characters. The name carries the unit because characters are the exception here: everywhere else in this package a count or an offset is in bytes, which is what indexes a Go string, and goes unnamed for the same reason strings.Index does not name it.
type MarkupWriter ¶
type MarkupWriter struct {
// contains filtered or unexported fields
}
MarkupWriter writes markup to a terminal, such as "[red]text[/red]".
A Session writes plain text, because most of what a program writes came from a user or a file and a bracket in it is not a tag. This is the other half: everything written here is read as markup.
A MarkupWriter with nowhere to write throws away what it is given rather than failing, which is what a program with no terminal gets. So a MarkupWriter is never nil and never has to be checked before it is used.
func (*MarkupWriter) Write ¶
func (w *MarkupWriter) Write(p []byte) (int, error)
Write satisfies io.Writer, reading what is written as markup.
Use fmt to do the formatting:
fmt.Fprintf(p.Markup(), "[rline-error]%s[/]\n", msg)
func (*MarkupWriter) WriteString ¶
func (w *MarkupWriter) WriteString(s string) (int, error)
WriteString writes markup without making a byte slice of it first.
type Option ¶
type Option struct {
// contains filtered or unexported fields
}
Option changes a setting of a Session. New takes every Option. Set takes the options that can change after New, and its documentation lists them (D141). The zero Option changes nothing.
func WithAppName ¶
WithAppName sets the name of the program that $if tests in an inputrc file, as readline's rl_readline_name does. It is DefaultAppName unless the program sets it.
func WithAutoPairs ¶
WithAutoPairs sets the pairs that close themselves when typed, which may include quotes as the default set does.
func WithAutoTab ¶
WithAutoTab keeps completing while there is only one answer. A completion that its Suffix ended is not completed again (D133).
func WithBraceInsertion ¶
WithBraceInsertion closes a brace automatically when one is typed.
func WithBraceMatching ¶
WithBraceMatching highlights the partner of the brace at the cursor.
func WithColor ¶
WithColor writes color when the terminal supports it. Turning it off writes none, whatever the terminal supports.
func WithCommand ¶
WithCommand adds a command of the program's own, called name, which an inputrc file binds a key to by that name, as readline's rl_add_defun adds one (D58). execute-named-command (M-x) runs it by name too. New returns ErrCommandExists when readline or rline already has a command called name.
func WithCompleter ¶
WithCompleter offers completions for the word at the cursor.
func WithCompletionMenu ¶
WithCompletionMenu binds Tab to rline-menu-complete, which completes as isocline does: Tab fills in what the completions share, and then opens a numbered menu of them below the line. The arrow keys, Tab and Shift-Tab move through the menu, a digit or Enter takes an entry, and Esc closes it. An entry taken at the end of the line gets its Suffix, as readline's menu-complete puts a space after a word (D133). Without it, Tab completes as GNU readline's does. The user's inputrc, read with WithUserInputrc, can bind Tab to something else (D51).
func WithContinue ¶
WithContinue decides whether Enter finishes the line or starts another row inside it.
The function is handed everything typed so far, across every row, not the row that was just typed, and answers true when it is not finished. That is how a prompt keeps reading until a statement is closed, and it keeps the whole statement in one buffer, which is handed back at once. readline's commands treat the rows as one line: Ctrl-A goes to the start of the statement, and Up puts an earlier statement in its place (D46). In one row, on a dumb terminal or with horizontal-scroll-mode, the keys stop at the newline instead, as bash's keys stop at the start of the line after PS2: no key goes back before it, and the completer and a Command see only the row after it (D143).
Enter and Ctrl-J both run readline's accept-line. When cont answers true, the line breaks at the cursor, wherever the cursor is.
Without this, Enter always finishes the line.
func WithHighlighter ¶
func WithHighlighter(highlighter Highlighter) Option
WithHighlighter marks up each line as it is typed.
func WithHintDelay ¶
WithHintDelay waits d before showing a hint. Zero shows it at once.
func WithHints ¶
WithHints shows the rest of the only completion that fits, in grey after the cursor.
func WithHistory ¶
WithHistory turns the history on or off, keeping whatever file and limit were set.
func WithHistoryControl ¶
func WithHistoryControl(historyControl HistoryControl) Option
WithHistoryControl leaves lines out of the history as HISTCONTROL does in bash (D99). The zero value leaves out none. It applies to the lines that ReadLine adds and to those of AddHistory, as bash applies HISTCONTROL to history -s.
With this option, at any value, ReadLine adds every line that is not empty, as bash does: a line of one character, and a line of only spaces, unless the control leaves it out. Without it, ReadLine adds only a line of two characters or more, as isocline does (D103).
HistoryEraseDups takes out each earlier copy of a line even with WithHistoryDuplicates. A program that wants bash's behavior gives WithHistoryDuplicates(true) too, so that a line that is already in the history stays there unless the control says otherwise.
func WithHistoryDuplicates ¶
WithHistoryDuplicates keeps every copy of a line in the history, as readline does. By default, a line that is already in the history moves to the end, and its earlier copy goes, so that Up does not show it twice (D72).
func WithHistoryFile ¶
WithHistoryFile keeps the history in the named file, so that it outlives the program. An empty name keeps it only while the program runs.
func WithHistoryFileLimit ¶
WithHistoryFileLimit writes at most the newest n entries to the history file, as HISTFILESIZE does in bash. A limit of zero or less writes an empty file. NoHistoryLimit, the default, writes every entry that the history holds (D99).
The file never holds more than the history, because rline writes the file from the history. A limit above the one of WithHistoryLimit changes nothing.
func WithHistoryFileMode ¶
WithHistoryFileMode sets the permission a history file is created with, rather than DefaultHistoryFileMode.
The umask still applies and can only narrow it, and an existing file keeps the mode it already has.
func WithHistoryFilter ¶
WithHistoryFilter asks historyFilter about each line before it goes into the history, after WithHistoryControl has kept it, as bash tests HISTIGNORE after HISTCONTROL (D99). previous is the newest entry, or "" when the history is empty, which is what the "&" of HISTIGNORE matches. The line goes in when historyFilter returns true. It applies where WithHistoryControl applies.
func WithHistoryLimit ¶
WithHistoryLimit holds at most n entries. A limit of zero or less turns the history off, so nothing is remembered between lines and the arrow keys have nothing to walk through. NoHistoryLimit holds every entry, as a negative HISTSIZE does in bash (D99).
func WithInlineHelp ¶
WithInlineHelp shows the short reminder below the line while searching the history.
func WithInputrcFile ¶
WithInputrcFile reads the named inputrc file in place of the user's. Notices lists each line of it, or of a file that it includes, that rline cannot parse, with the name of the file and the number of the line, and what in it rline does not support (D104, D108).
func WithInputrcLines ¶
WithInputrcLines applies the lines of an inputrc file after the inputrc file that WithUserInputrc or WithInputrcFile reads, as though they were one more file (D100). So they win over the user's file. They start in the keymap of the editing mode that the file left, as readline reads a file in the keymap in use. Notices lists a line that rline cannot parse, with its number in inputrcLines, counted from 1, in the form of a line of a file (D104), and what in the lines rline does not support. C-x C-r applies them again after the file.
func WithKeepInterrupted
deprecated
WithKeepInterrupted changes nothing. A line that Ctrl-C gives up always stays on the screen, as bash 5.3 leaves it: ^C goes where the cursor is, unless an inputrc file turns echo-control-characters off, and the next prompt starts below the line. ReadLine returns ErrInterrupted, and the history does not keep the line (D122).
Deprecated: rline keeps the line by default, and this option has no effect.
func WithLogger ¶
WithLogger records everything the session reads from the keyboard and writes to the terminal through logger, a log/slog handler, so that a session can be read back afterwards by someone who was not watching it (D54).
What is written to the terminal is a record at debug level with the message LogWrite, and each byte read from the keyboard is one with the message LogRead. Both hold the bytes in the attribute LogBytes. A line that ReadLine hands back is a record at info level with the message LogLine and the line in the attribute LogText. A line given up is LogInterrupted, and the end of the input is LogEndOfInput, both at info level.
What Password reads is never recorded. A record at info level with the message LogPassword says that a password was read, and holds nothing of it.
func WithManualHistory ¶
WithManualHistory leaves the history to the program, as readline does. ReadLine then adds no line itself, and the program adds what it keeps with AddHistory, as a shell does for HISTCONTROL and HISTIGNORE. By default, ReadLine adds each line of two characters or more (D72), and with WithHistoryControl each line that is not empty (D103).
ReadLine still writes the history file after each line, so a line that the program adds is in the file after the next line is read, or after SaveHistory.
func WithManualInterruptNewline ¶
WithManualInterruptNewline leaves the newline after a line that Ctrl-C gave up to the program. The program owns that newline: after ReadLine returns ErrInterrupted, the program must write it, or the next prompt goes on the same row. A shell can then write the output of its SIGINT trap before the newline, as bash does.
ReadLine writes what bash writes before the trap runs. That is ^C, unless an inputrc file turns echo-control-characters off. When the line goes on below the cursor, the cursor then goes to the left edge of the last row of the line. Then, when bracketed paste mode was on, ReadLine writes the sequence that turns the mode off, which ends with a carriage return, so the cursor is at the left edge of the row. On a terminal without bracketed paste, such as a dumb terminal, nothing more follows, and the cursor stays after ^C when the line ends on its row, as in bash.
Without this option, ReadLine writes the newline itself, as before (D121).
func WithMatchPairs ¶
WithMatchPairs sets the pairs whose partner is highlighted, written one after another such as "()[]{}".
func WithMultiline ¶
WithMultiline allows line breaks inside one line. Turning it off refuses them, so a line is always one row.
func WithMultilineIndent ¶
WithMultilineIndent lines the rows after the first up under the prompt.
func WithPrompt ¶
WithPrompt sets the marker written after the prompt text, and the one used on the lines after the first. An empty continuation marker repeats the first.
The marker is not the prompt. ReadLine is handed the prompt text for that one line, and the marker is what is drawn after it, so a prompt text of "sql" and a marker of "> " are shown as "sql> ".
func WithRowPrompt ¶
WithRowPrompt gives each row that starts after a newline its own prompt, in place of the continuation marker (D96). rowPrompt is handed all the text of the line before that row, the newline included, and returns the prompt of the row, such as psql's PROMPT2 with "%l" and "%R" filled in. A row that only wraps keeps the continuation marker.
rowPrompt is called again whenever the text changes, so an edit on an earlier row or a paste changes the prompts after it. It is called once for each row on each change, so it must be quick.
The rows after the first are all as wide as the widest of their prompts, and a narrower prompt is padded on the left, as the continuation marker is. So when a longer prompt appears, the rows above it move to the right.
func WithStderr ¶
WithStderr sends the program's errors to stderr rather than to os.Stderr.
The editor draws on the output, which WithStdout sets, and a program's own output goes there too, because the terminal the editor draws through is the one that knows where the prompt is. Errors are the one thing a program often wants somewhere else: a shell whose results are being written to a file still wants its errors on the screen.
Whatever the destination, errors written through Session.Stderr keep their order with respect to the output, because the terminal is flushed before each one. Writing to os.Stderr directly does not, and the two streams then interleave however the operating system happens to buffer them.
func WithStdin ¶
WithStdin reads keys from stdin rather than from os.Stdin.
As with WithStdout, the name does not promise the real standard input, and it does not promise a file descriptor either.
Editing needs a terminal, which is reached by file descriptor on Unix and by handle on Windows. So a reader that can say which descriptor it is — an *os.File, or anything else with an Fd method — is edited on, and anything else is read plainly with no editing, the same as a pipe.
A *bufio.Reader cannot be edited on, whatever it wraps, because wrapping hides the descriptor and takes bytes out of the terminal that the editor then never sees. Pass the *os.File itself.
A caller holding a bare descriptor can make one with os.NewFile.
func WithStdout ¶
WithStdout writes to stdout rather than to os.Stdout.
The name follows os/exec.Cmd, x/crypto/ssh.Session and chzyer/readline, where Stdout names the stream acting as standard output rather than the file descriptor: a bytes.Buffer or a pipe is a perfectly good one.
When stdout is a Windows console, the console reads escape sequences from New to Close, as it must for what rline writes. Close puts back the mode that the console had.
func WithTerminal ¶
WithTerminal reads keys from terminal and draws on it, in place of standard input and output, where there is no file descriptor to read keys from: xterm.js in a web page under GOOS=js, or a test (D79). The Session edits lines on it whatever $TERM says, takes no terminfo entry, and reads it as UTF-8. WithStdin and WithStdout are not used when it is set.
func WithUserInputrc ¶
WithUserInputrc reads the user's inputrc file, as GNU readline does. When $INPUTRC is set, it reads that file and no other, and reads nothing when the file is missing. Otherwise it reads ~/.inputrc, or else /etc/inputrc when that is missing. On Windows the file is ~/_inputrc, and there is no /etc/inputrc. The key bindings, macros and variables of the file change how the keys edit the line, and they override the program's own (D41). Notices lists each line of the file, or of a file that it includes, that rline cannot parse, and what in the file rline does not support (D108).
func WithViMode ¶
WithViMode edits as vi does, starting each line in insert mode, as "set editing-mode vi" does in an inputrc file. The user's inputrc, read with WithUserInputrc, can set the mode back (D41).
func WithWrapMark ¶
WithWrapMark draws a mark at the end of a row that filled the terminal, so that it reads differently from a row that the line breaks itself. It is on by default, as isocline draws it, with each row ending two columns before the edge. WithWrapMark(false) lays the rows out as readline does: a row fills the terminal to its edge, and a row that only wraps starts at the left edge with no continuation marker. With WithMultilineIndent(false) and empty markers, a long line then looks as it does in bash (D86, D91).
type Prompt ¶
type Prompt struct {
*Session
// contains filtered or unexported fields
}
Prompt is a Session and the markup writer that goes with it.
The reading methods are promoted, so a Prompt is used like a Session: ReadLine, Password and Close all work on it directly. Markup is reached through Markup, and a program that wants none simply never calls it.
A Prompt is an io.Writer as well, through the Session it holds, and writes plain text that way. That is deliberate: fmt.Fprintln(p, s) writes what a program has to say through the terminal that knows where the prompt is, without reading a bracket in it as a tag.
While a program reads lines with a Prompt, it must write all its output through the Prompt or its Session, and not straight to os.Stdout. rline counts the columns of the output that goes through it, so that the next prompt starts where that output stopped. Output written straight to os.Stdout is not counted, because neither rline nor GNU readline can see it, and the next draw of the prompt can write over it.
func New ¶
New returns a Session.
It returns a Session even when there is no terminal to edit on, such as when the input is a pipe. ReadLine then reads a plain line with no editing, which is what the C does and what a program reading a script expects.
func (*Prompt) Markup ¶
func (p *Prompt) Markup() *MarkupWriter
Markup returns the writer that reads what is written to it as markup.
It is never nil. When there is no terminal, or when colour is off, what is written to it is thrown away or written plainly, so a caller never has to ask whether markup is on before using it.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session reads lines from a terminal, with editing, history and completion.
A Session is not safe for use from more than one goroutine at a time.
func (*Session) AddCommand ¶
AddCommand adds a command of the program's own after New, as WithCommand adds one before it, so that Bind can bind a key to it. This is bash's bind -x: the command reads and changes the line through the Line it is given. Adding a command of the program's under a name it already used replaces it. It returns ErrCommandExists when readline or rline has a command called name (D76).
func (*Session) AddHistory ¶
AddHistory adds an entry to the history. WithHistoryControl and WithHistoryFilter can leave it out, as bash leaves out a line of history -s (D99).
Called from the function of RunAtPrompt while a line is read, it adds the entry before that line, as bash adds what history -s gives from a trap at its prompt. Up then finds the entry, and the line goes in after it.
func (*Session) Bind ¶
Bind binds the key sequence seq in keymap to the command called name, as a line of an inputrc file or bash's bind does (D76).
seq is written as an inputrc file writes it between double quotes, such as \C-a or \e[A. A name in double quotes is a macro, whose text runs as though it were typed, such as "\C-e;". keymap is one that an inputrc file names, such as emacs, emacs-meta, vi-insert or vi-command, and an empty keymap is the one of the editing mode. The binding takes effect at once.
It returns ErrUnknownCommand for a name that no command has, ErrUnknownKeymap for a keymap that readline does not have, and ErrInvalidSequence for a sequence or a macro with a byte that stands for no key.
func (*Session) Bindings ¶
Bindings returns every key sequence that keymap binds and what it runs, sorted as readline sorts them. keymap is written as Bind takes it. Under emacs-meta and emacs-ctlx, the sequences are those after Esc and after Ctrl-X (D76).
func (*Session) Close ¶
Close puts the terminal back as it was. A Session cannot be used afterwards.
func (*Session) DefineStyle ¶
DefineStyle gives a name to a set of attributes, so that markup can use it. The spec is written the way the inside of a tag is, such as "bold color=red".
func (*Session) History ¶
History returns the entries, newest first.
The slice is a fresh one each time and is the caller's to keep or change; changing it does not change the history.
A program that wants to show the history, search it its own way, or write it somewhere else needs to be able to read it, and adding, saving and clearing were the only ways to touch it.
func (*Session) HistoryErr ¶
HistoryErr returns what went wrong the last time the history file was read or written, or nil when that worked (D67).
New reads the file, and ReadLine writes it after every line, and neither can return an error for it: New still returns a Session that can read lines, and ReadLine still has a line to return. A program asks here, after New and after each line, and tells the user that the history is not being saved. LoadHistory and SaveHistory return the same error.
func (*Session) Interactive ¶
Interactive reports whether there is a terminal to edit on. When there is not, ReadLine reads a plain line.
func (*Session) LoadHistory ¶
LoadHistory reads the history back from its file, throwing away what is held.
New does this already. This is for a program that wants what another process has written since, or that has changed the file with SetHistoryFile.
It takes no file name, and SaveHistory takes none either: which file the history lives in is one setting, not two arguments that could disagree.
A file that is not there yet is not a failure — that is the ordinary state of a program on its first run — but a file that cannot be opened or read is, and the reason comes back wrapped. The C ignores all of it and reads nothing, silently.
func (*Session) Notices ¶
Notices returns what rline does not support in the inputrc file that the Session read: a variable of readline that it does not support, or a command it does not have. Each one says which.
Each line of the inputrc file, of a file that it includes, or of WithInputrcLines, that cannot be parsed is a notice too, in the order of the lines. It has the form and the words in which readline reports such a line, without the "readline: " in front: the file, "line" and the number, and what is wrong, such as "/home/me/.inputrc: line 3: editing-mode: could not set value to `nothing'" (D104, D108). A variable that readline does not have is such a line. A fault in the lines of WithInputrcLines names them in the place of the file. A file that cannot be read is one notice. An $include of a file that cannot be read gives none, as in readline (D109).
func (*Session) Palette ¶ added in v0.17.0
Palette returns the colors that rline writes to the terminal (D140). It is what rline found for the terminal in New: from COLORTERM, TERM and the variables of some terminals, or from the Terminal of WithTerminal, which gives 256 colors when it does not say.
It is ansi.PaletteMono when rline writes no color: with WithColor(false), with NO_COLOR set, on a dumb terminal, and when the output is not a terminal, such as a pipe or a file. A Session that does not edit, because its input is not a terminal, still writes color to a terminal, and so gives the palette that it found.
A program that writes colors of its own, outside the line, can format them for the palette with ansi.Format, so that it writes the colors that rline writes. The palette does not change after New, so Palette is safe to call from any goroutine.
func (*Session) ParseAndBind ¶
ParseAndBind reads one line of an inputrc file and applies it, as readline's rl_parse_and_bind does and as bash's bind does with a line such as `"\C-a": end-of-line` or "set bell-style none" (D77). A binding goes to the keymap of the editing mode, unless the line names one.
Nothing of the line applies when any of it is at fault. It returns ErrUnknownCommand, ErrUnknownVariable or ErrInvalidSequence as Bind and SetVariable do, ErrInvalidValue for a line with a line break, and the error of the parser for a line that is not one of an inputrc file, such as one that names a keymap readline does not have.
func (*Session) Password ¶
Password reads a line without showing it and without recording it.
Nothing is echoed, nothing is added to the history, and no completion, hinting or highlighting runs. Backspace deletes the last character and Ctrl-U clears what has been typed. Enter finishes.
It answers io.EOF when the user ends the input with Ctrl-D on an empty line, and ErrInterrupted when the user presses Ctrl-C, which a caller usually treats as "do not ask again" rather than as a failure.
When there is no terminal to read from, the line is read plainly from the input, which is what a program driven by a script needs. Nothing is hidden in that case, because there is no terminal to hide it from, and a caller that must not read a password from a pipe should check Interactive first.
func (*Session) PushInput ¶
PushInput gives the Session input that something else read from the terminal before the Session could, such as the keys that a user typed while a program waited for the terminal to answer a query (D70). The next read, by ReadLine or by Password, takes the bytes before anything from the terminal, as though they came from it, so that an escape sequence or a bracketed paste in them is read as it would be. A second call adds its bytes after those of the first. The bytes are copied.
When there is no terminal to edit on, ReadLine reads plain lines, and reads the bytes first there too. What PushInput gives does not reach the log of WithLogger, because the Session did not read it.
func (*Session) ReadInputrc ¶
ReadInputrc reads the inputrc file called name over the bindings and the variables in place, as bash's bind -f does. What the file holds that rline does not support goes into Notices. A file that cannot be read is the error. A line that cannot be parsed is in the error too, and the rest of the file still counts, as readline reads on past it (D76).
func (*Session) ReadLine ¶
ReadLine reads one line.
The prompt is drawn in front of the line, followed by the marker of WithPrompt. In the prompt and the markers, what is between the bytes 1 and 2 is written but takes no width, as readline counts what bash marks with \[ and \] in PS1, and the two bytes are not written. When the prompt has newlines, the lines before the last one are written once, and only the last line shares a row with the input. See D71 in docs/PLAN.md.
The line holds the bytes that were typed. When the locale is not UTF-8, as in Latin-1 or C, each byte is one character, and the line can hold bytes that are not UTF-8 (D111). In the C and POSIX locales, and in no locale at all, a byte above 0x7f that is typed is a key with Meta, as in readline, unless an inputrc file turns convert-meta off (D112).
It returns io.EOF when the user ended the input, which is Ctrl-D on an empty line, and which is what the C answers with a null pointer. Where readline leaves the cursor then, so does rline: below the line when bracketed paste mode was on, and on the line when it was off, so that a shell can write "exit" after the prompt (D74, D78).
It returns ErrInterrupted when the user abandoned the line, which is Ctrl-C or Ctrl-G. This is a deliberate departure: the C clears the line and hands back an empty string, so a caller cannot tell an abandoned line from Enter on an empty one, and a shell has to. See D13 in docs/PLAN.md.
func (*Session) ReadLineWith ¶
ReadLineWith reads one line, as ReadLine does, and starts the line with text, with the cursor at its end, as bash's read -e -i does. The text goes in as one change, so an undo takes it back out. When there is no terminal to edit on, the text is not used, as bash leaves it unused (D73).
func (*Session) Release ¶
Release gives the terminal to fn, and takes it back when fn returns. It is for a program that runs another program on the terminal between two reads, such as a pager, an editor or a shell.
Release writes out what the Session still holds, and then calls fn with the file that the Session writes to: os.Stdout, or the file given to WithStdout. fn hands that file to the other program as its output. The terminal is in its own mode between reads, so the other program gets it as the shell would give it. On a Windows console, fn also gets the output in the mode that it had before the Session turned on escape sequences. A file that is not a terminal is handed over all the same, and the program that called Release decides what to do with it. What the other program writes does not reach the log of WithLogger.
While fn runs, the keys that raise a signal belong to the other program. The terminal sends Ctrl-C to every process in the foreground, the program that called Release among them, and Release keeps the signal from ending that program. A handler that the program set up for the signal still gets it. Ctrl-Z still stops both programs, so that the shell can take the terminal back.
After fn returns, the Session reads the size of the terminal again, because the other program can have changed the screen.
Release returns what fn returns. It returns ErrNotAFile without calling fn when the Session writes to something that is not a file, and ErrClosed when the Session is closed. Do not call it while a line is being read, such as from a Completer.
func (*Session) RemoveLastHistory ¶
func (s *Session) RemoveLastHistory()
RemoveLastHistory forgets the most recent entry.
ReadLine adds every line it returns, unless WithManualHistory is on, so this is how a caller says that one should not have been kept: a command that leaves the program, or a line that turned out to hold a secret. The C offers the same thing as ic_history_remove_last, and the port had it inside and never exposed it, which the example noticed by remembering every \q anyone ever typed.
It removes whatever is newest, so call it before reading another line.
It changes the list rather than the file. ReadLine writes the file after every line it returns, so by the time a caller decides a line was not worth keeping, the file already holds it. Call SaveHistory afterwards to write the shorter list, which is what the example does before it leaves.
func (*Session) RunAtPrompt ¶
RunAtPrompt runs fn at the prompt, as bash runs a trap while readline waits for a key (D87, D93). It is safe to call from any goroutine, as from a signal handler.
While ReadLine waits for a key, it wakes, takes the line off the screen, and calls fn on its own goroutine, with w writing where the line was. It then draws the last line of the prompt and the line again below what fn wrote, with the text and the cursor as they were. When no line is being read, fn runs when ReadLine next starts, before the prompt is drawn. A terminal that cannot be woken, which is none of those rline knows, runs fn after the next key.
When fn returns an error, the line is given up and ReadLine returns that error, with the terminal put back, as a trap that calls exit ends bash's line. What else RunAtPrompt asked for waits for the next line (D94).
func (*Session) SaveHistory ¶
SaveHistory writes the history to the file it was given, if it was given one.
func (*Session) Set ¶ added in v0.17.0
Set changes settings of the Session after New, with the options that New takes (D141). Each option has the effect that it has in New. Set takes these options:
- WithHistoryFile, WithHistoryLimit, WithHistory, WithHistoryFileLimit, WithHistoryControl, WithHistoryFilter, WithHistoryDuplicates, WithManualHistory and WithHistoryFileMode, which change the history.
- WithPrompt, which does what SetPrompt does.
- WithCompleter, which does what SetCompleter does.
- WithHighlighter, which does what SetHighlighter does.
A lower history limit drops the oldest entries that do not fit, as New drops them from a file that holds more, and as bash drops them when HISTSIZE goes down. A higher limit does not bring them back. When the limit was zero, the history reads its file with the new limit, as New reads it. WithHistoryFile with the name of the file in place changes nothing. With another name, the history drops what it holds and reads the new file, as New reads it. SetHistoryFile changes the file and reads nothing. HistoryErr says whether a read worked.
The file limit, the control, the filter and the file mode apply from the next line that goes in, or from the next save. ReadLine saves after each line, and SaveHistory saves at once. bash cuts the file at once when HISTFILESIZE changes, and docs/PORT.md lists this departure. The control and the filter do not take out an entry that is in the history already.
Every other option cannot change after New. Set then changes nothing, and returns ErrNotSettable, wrapped with the name of each such option. Set returns ErrClosed after Close.
Set is not safe to call while ReadLine runs on another goroutine, as no method of a Session but RunAtPrompt and Palette is. Call it between two reads, or from the function of RunAtPrompt, which runs on the goroutine of ReadLine. There, a change to the history applies to the line that is read.
func (*Session) SetCompleter ¶
SetCompleter changes the function that offers completions.
A program whose completions depend on something that changes while it runs sets a new completer rather than building a new reader: usql replaces its completer when the connection changes, so that the words offered come from the database that is actually open. A nil completer offers nothing.
func (*Session) SetHighlighter ¶
func (s *Session) SetHighlighter(h Highlighter)
SetHighlighter changes the function that marks up the line. The first call of the new highlighter gets no Edit from LineStyle.Edit (D128).
A nil highlighter draws the line plainly.
func (*Session) SetHistoryFile ¶
SetHistoryFile changes the file the history is kept in. It does not read the new file; call LoadHistory for that.
func (*Session) SetPrompt ¶
SetPrompt changes the marker written after the prompt text, and the one used for the lines after the first.
A program that reads a statement over several calls changes the marker between them, so that the first line is asked for differently from the ones that carry on. An empty continuation repeats the first.
func (*Session) SetVariable ¶
SetVariable sets a variable of readline, as the line "set name value" of an inputrc file sets it, so that on and off, and numbers, are read as readline reads them. editing-mode switches between emacs and vi, as bash's set -o vi does. A variable takes effect from the next ReadLine.
It returns ErrUnknownVariable for a name that readline has no variable for, and ErrInvalidValue for a value with a line break (D76).
func (*Session) Size ¶
Size returns the width and the height of the terminal that the Session writes to, in characters. It reads them again on each call, so it gives the size after the window was last changed.
Size returns zero for both when the output is not a terminal, such as when it goes to a pipe, a file or a buffer.
func (*Session) Stderr ¶
Stderr returns where the program's errors go.
This is the one stream a program usually wants apart from its output: a shell writing its results to a file still wants its errors on the screen. WithStderr says where, and standard error is the default.
What is written here keeps its order with respect to what is written through the Session, because the terminal is flushed first. Writing to os.Stderr directly does not, and the two then interleave however the operating system happens to buffer them.
Every public write through a Session flushes already, so today that order would hold without the flush. What the flush protects is text the terminal is still holding, which is the state the editor is in while it draws, so the guarantee holds by construction rather than by coincidence.
There is no matching Stdout, because the Session is the output: hand it straight to anything that wants an io.Writer.
func (*Session) Unbind ¶
Unbind takes away what the key sequence seq in keymap runs, as bash's bind -r does, so that the keys ring the bell as an unbound key does. seq and keymap are written as Bind takes them (D76).
func (*Session) Variables ¶
Variables returns every variable of readline with its value now, as bash's bind -v prints them: on or off, a number, or the text (D76).
func (*Session) Write ¶
Write writes plain text to the terminal, with no markup in it.
This is what to use for anything that came from the user or from a file, because Print would read a bracket in it as a tag: "a[b]c" printed as markup comes out as "ac". A Session is therefore an io.Writer, so fmt.Fprintf works on it.
A program with its own output to write should write it here rather than to os.Stdout, because the terminal this goes through is the one that knows where the prompt is. An adapter that has to offer an io.Writer can return the Session itself.
On a terminal, the control bytes that a terminal has no use for are dropped, and so is every color sequence when color is off. When the output is a pipe or a file, the bytes go out unchanged (D57).
type Terminal ¶
A Terminal is a terminal that the program gives to WithTerminal, where there is no file descriptor to read keys from: xterm.js in a web page, or a test (D79).
Read gives the bytes that the user types, as a terminal in raw mode sends them: escape sequences and bracketed paste included. It returns io.EOF when the input ends. Write takes what rline draws, with the same escape sequences that rline writes to a real terminal. Size gives the width and the height in characters.
A Terminal can have three more methods, which rline uses when they are there:
- Resized() <-chan struct{} sends when the size changes, as SIGWINCH does on a real terminal. Without it, rline asks Size after each key.
- SetRaw(on bool) error is called when rline starts and stops reading keys, where a real terminal goes into raw mode and out of it.
- Palette() ansi.Palette gives the colors that the terminal can show. Without it, rline writes 256 colors.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
bash
command
Command bash is a prompt that reads lines as bash does and runs none of them.
|
Command bash is a prompt that reads lines as bash does and runs none of them. |
|
isocline
command
Command isocline is the sample program of isocline, isocline/test/example.c, written with rline.
|
Command isocline is the sample program of isocline, isocline/test/example.c, written with rline. |
|
sql
command
Command sql is a small SQL prompt built on rline.
|
Command sql is a small SQL prompt built on rline. |
|
Package ansi holds colors as a terminal understands them, and reduces one to what the terminal at hand can actually show.
|
Package ansi holds colors as a terminal understands them, and reduces one to what the terminal at hand can actually show. |
|
config
module
|
|
|
internal
|
|
|
capture
Package capture records terminal sessions from a program that runs under a pseudo-terminal.
|
Package capture records terminal sessions from a program that runs under a pseudo-terminal. |
|
editor
Package editor holds a line being edited, the operations that change it, and the undo stack behind them.
|
Package editor holds a line being edited, the operations that change it, and the undo stack behind them. |
|
readline
Package readline edits one line with the commands of GNU readline: the cursor and the mark, the kill ring, the undo list, the numeric argument and the history (D44, D45, D46).
|
Package readline edits one line with the commands of GNU readline: the cursor and the mark, the kill ring, the undo list, the numeric argument and the history (D44, D45, D46). |
|
text
Package text holds the buffer a line is edited in, and everything that measures or walks over it.
|
Package text holds the buffer a line is edited in, and everything that measures or walks over it. |
|
Package key holds the key codes that rline reads from a terminal.
|
Package key holds the key codes that rline reads from a terminal. |
|
Command uitest opens a real terminal emulator, types into it as a person would, and records what was sent and what was drawn.
|
Command uitest opens a real terminal emulator, types into it as a person would, and records what was sent and what was drawn. |