rline

package module
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 32 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README


Unit Tests Go Reference Releases Discord Discussion

rline is a readline package for Go. A readline package reads a line of text from a terminal, and gives the person typing it editing, history, completion and colored output.

This package is written in pure Go. It does not use cgo, and it does not link against any C library.

rline is a port of isocline, a readline replacement written in C by Daan Leijen, under the MIT license.

The recording is generated rather than taken by hand. contrib/make-demo-gif.sh opens a real terminal on a private compositor, types the session with a virtual keyboard and records it, so it can be made again after the code changes and shows what rline does now rather than what it did when somebody last remembered to take a screenshot. See uitest/README.md for the harness.

Status

Complete and working on Linux, macOS and Windows, including cmd.exe, Windows PowerShell and pwsh. Every module of isocline is either ported or deliberately replaced.

What works:

  • Editing a line, and moving by character, word and line.
  • The eleven kinds of delete, with undo and redo.
  • Input over more than one line.
  • Syntax highlighting, matching braces, and hints.
  • Markup for colored output.
  • A history file.
  • Editing on a dumb terminal, such as TERM=dumb, in one row that scrolls sideways, as readline edits there.
  • readline's horizontal-scroll-mode, which draws the line in one row that scrolls sideways on any terminal.
  • Reading a plain line when there is no terminal to edit on, and when TERM is emacs or the program runs inside Emacs, as bash does.

Password reads a line without showing it, without recording it, and without completion or highlighting.

Completion is finished too, and it works as readline's does. Tab fills in the longest start that every completion shares. A second Tab lists the completions below the line, in columns that run down and then across, and the list stops at each full screen with --More--. readline's completion-display-width, print-completions-horizontally and page-completions change the list, as in readline. WithCompletionMenu(true) gives isocline's numbered menu in place of the list: Tab fills in what the completions share and opens the menu, the arrow keys and Tab move through it, and a digit or Enter takes an entry.

Inside, the port keeps the C's behavior even where that behavior is wrong, because recorded output from the C build is the test corpus. The interface is deliberately not a translation of the C one: it is shaped for Go. One behavior departs rather than one name. ReadLine answers ErrInterrupted, because the C cannot tell a line the user gave up from an empty one, and a shell has to.

Quickstart

p, err := rline.New(
    rline.WithPrompt("> ", "| "),
    rline.WithHistoryFile(".history"),
    rline.WithHistoryLimit(200),
)
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: Ctrl-D on an empty line
    case errors.Is(err, rline.ErrInterrupted):
        continue              // the line was given up: Ctrl-C
    case err != nil:
        return err
    }
    fmt.Fprintf(p, "read: %s\n", line)
}

New returns a *Prompt: a Session that reads lines, with the markup Writer that goes with it. The reading methods are promoted, so p.ReadLine, p.Password and p.Close are the Session's.

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. Markup goes through p.Markup(), which is never nil:

fmt.Fprintf(p, "read: %s\n", line)                     // plain
fmt.Fprintf(p.Markup(), "[rline-error]%s[/]\n", err) // styled

While a program reads lines with rline, it must write all its output through the Prompt or its Session. Do not write straight to os.Stdout. rline counts the columns of the output that goes through it, so that it knows where the next prompt starts. rline cannot see output that goes straight to os.Stdout, and GNU readline cannot see it either. The next draw of the prompt can then write over that output.

A Prompt is an io.Writer, so give it to anything that wants one. Output that does not end its row, such as fmt.Fprint(p, "foo"), stays on the screen, and the next prompt starts after it, as in psql.

The prompt that ReadLine is given, and the markers of WithPrompt, are plain text. A bracket in them is not a tag, and an escape sequence in them goes to the terminal as it is.

The history keeps 500 lines by default, as psql does. ReadLine writes the history file after every line, and cannot return an error for it, because it has a line to return. Call p.HistoryErr() after New and after a line to learn whether the last read or write of the file failed.

A program can keep the history as bash keeps it. WithHistoryControl leaves lines out as HISTCONTROL does, and WithHistoryFilter asks a function about each line, as bash tests a line against HISTIGNORE. WithHistoryFileLimit writes only the newest entries to the file, as HISTFILESIZE does. rline.NoHistoryLimit holds every entry, as a negative HISTSIZE does:

p, err := rline.New(
    rline.WithHistoryFile(".history"),
    rline.WithHistoryLimit(rline.NoHistoryLimit),
    rline.WithHistoryFileLimit(10000),
    rline.WithHistoryDuplicates(true),
    rline.WithHistoryControl(rline.HistoryIgnoreBoth),
)

ReadLine answers io.EOF when the input ends and ErrInterrupted when the user gave the line up with Ctrl-C. Those are different answers on purpose: the C cannot tell them apart, and a shell has to.

Ctrl-C leaves the line on the screen, as bash does. ^C goes where the cursor is, and the next prompt starts below the line. WithKeepInterrupted changes nothing now, and is deprecated.

ReadLine writes a newline after a line that Ctrl-C gave up. WithManualInterruptNewline(true) leaves that newline to the program, so that a shell can write the output of its SIGINT trap first, as bash does. With this option, the program must write the newline itself after ErrInterrupted.

Keys

The keys are GNU readline's, and the commands behave as readline 8.3's commands do. rline has all 143 of readline's commands, including those that no key is bound to, so an inputrc file can bind any of them. rline's tests replay recordings of readline 8.3 to check this. The emacs keys are the default. WithViMode(true) gives readline's vi insert and command modes.

WithUserInputrc(true) reads the user's inputrc file as readline finds it: the file that $INPUTRC names, and no other when it is set, or else ~/.inputrc, or else /etc/inputrc. On Windows the file is ~/_inputrc. Its bindings, macros and variables apply, and set editing-mode vi turns vi mode on. WithAppName sets the name that $if tests. Notices lists what in the file rline does not support. It also lists each line of the file of WithInputrcFile that rline cannot parse, as readline reports such a line: FILE: line N: and what is wrong. C-x C-r reads the file again, when the program asked for one. WithInputrcLines applies more lines of an inputrc file after the file, so that the lines of the program win over those of the user.

set show-mode-in-prompt on puts the editing mode in front of the prompt, as readline does. The mode is @ in emacs mode, and (ins) and (cmd) in vi's insert and command modes. emacs-mode-string, vi-ins-mode-string and vi-cmd-mode-string change them. Text between \1 and \2 goes to the terminal and takes no column. For example, these lines give a bar cursor in insert mode and a block cursor in command mode:

set show-mode-in-prompt on
set vi-ins-mode-string "\1\e[6 q\2"
set vi-cmd-mode-string "\1\e[2 q\2"

set bell-style visible flashes the screen in place of the bell. rline writes the flash sequence from the terminfo entry of the terminal. A terminal with no flash, such as vt100 or a Windows console, rings the bell. set bell-style none turns the bell off.

A paste goes into the line as text, in bracketed paste mode, as it does in readline: a paste of several lines is one entry, and Enter hands it back. set enable-bracketed-paste off turns the mode off, and then each line of a paste is an entry of its own.

rline shows a paste as the active region until the next key, as readline does: in the standout of the terminal, from its terminfo entry. The match of a history search shows the same way. set enable-active-region off turns this off, and active-region-start-color and active-region-end-color set other colors.

p, err := rline.New(rline.WithUserInputrc(true), rline.WithAppName("usql"))
for _, n := range p.Notices() {
	fmt.Fprintln(p.Stderr(), "inputrc:", n)
}

A program can add commands of its own, which an inputrc file binds by name, as readline's rl_add_defun adds them. A command gets the line, the cursor, the numeric argument and the key, and changes the line through a Line:

upcase := rline.CommandFunc(func(l *rline.Line) {
	l.Replace(strings.ToUpper(l.Text()), l.Cursor())
})
p, err := rline.New(rline.WithUserInputrc(true), rline.WithCommand("upcase-line", upcase))

With that, "\C-xu": upcase-line in the inputrc file binds Ctrl-X u to it, and M-x runs it by name. New returns ErrCommandExists for a name that readline or rline already has.

A command can do more through its Line. Kill puts text on the kill ring, Mark, SetMark and CountGiven give what bash gives bind -x, Run and Complete run another command after it, and Release gives it the terminal while the line is off the screen. Print writes below the line and keeps it, and AcceptAndRelease finishes the line and gives the command the terminal, with no prompt after it.

RunAtPrompt runs work while ReadLine waits for a key, as bash runs a trap or writes a job notice at the prompt. It is safe to call from any goroutine.

A program can also change the bindings and the variables while it runs, as bash's bind builtin does. AddCommand adds a command after New, Bind and Unbind change what a key runs, SetVariable sets a variable such as editing-mode, ParseAndBind applies one line of an inputrc file, and ReadInputrc reads another file. Bindings, Variables and Commands list what is there:

_ = p.AddCommand("upcase-line", upcase)
_ = p.Bind("emacs", `\C-xu`, "upcase-line")
_ = p.Bind("emacs", `\C-xd`, `"\C-e;"`)
_ = p.SetVariable("editing-mode", "vi")
_ = p.ParseAndBind(`"\C-xe": end-of-line`)

Tab completes as readline does: the first Tab fills in what the completions share, and the second lists them below the line. Ctrl-R is readline's incremental search.

config.yaml

The module github.com/xo/rline/config, in config/, reads the history and editor stanzas of a config.yaml. usql and hail both read these stanzas, with the same keys and the same meanings, from this one package. It has a go.mod of its own, because it needs the styles of transit, and rline itself does not. It turns the stanzas into options of rline, and gives back each bad value as a warning for the program to print:

c := config.Default()
// Fill c from config.yaml, with ox or goccy/go-yaml.
r := config.Options(c, config.Program{
    Dir:         dir,
    HistoryFile: defaultHistoryFile,
    Lookup:      styles.Get,
    Captures:    query.CaptureNames(),
    Highlighter: newHighlighter,
})
for _, w := range r.Warnings {
    fmt.Fprintln(os.Stderr, w)
}
p, err := rline.New(append(opts, r.Options...)...)
if err == nil && r.Styles != nil {
    r.Styles.Define(p)
}

"The config module" in docs/LAYOUT.md says how it is released.

The example

_examples/sql/ is a small SQL prompt. It shows input over more than one line, highlighting that changes as the line is typed, and a completer.

A statement ends at a semicolon. Until then Enter starts another row inside the same line rather than handing it back, which is what WithContinue does. The rows are one buffer, and the whole statement comes back at once. The keys are GNU readline's, so Up brings back an earlier statement in place of this one.

The example turns on WithCompletionMenu, so Tab opens isocline's numbered menu when several words fit. -vi edits with vi's keys, and Tab opens the menu in vi's insert mode too.

\pass reads a password and then echoes it back, so that what was collected can be checked against what was typed. A real program does not echo it.

The history is kept in rline_example_history, in the directory the example was run from rather than the home directory, so that running it leaves nothing where the person running it is not looking. The up arrow brings back what was typed in an earlier run.

Run it from the root of the repository with:

go run ./_examples/sql

The folder starts with an underscore, so go build ./... and go test ./... leave the examples out, and a command has to name the folder.

Pass -log FILE to record the session. Every line says which direction it went: < for what was written to the terminal, > for a key that was read, and = for a finished line. The bytes are escaped, so the log can be read by eye.

_examples/transit/ highlights and completes code with transit, the pure Go port of tree-sitter. After each key it parses the text again from the old tree and marks it with the grammar's highlight query, and Tab offers what the parser can accept at the cursor. It is a module of its own, so rline gets no new dependency, and its go.mod requires published versions of rline and transit. Run it from its folder, with one of bash, c, go, javascript, json, python, ruby and rust:

cd _examples/transit && go run . -lang python

_examples/bash/ reads lines as bash does and runs none of them. It highlights bash as it is typed, prints each line back exactly as it was typed, and keeps every line in rline_example_bash_history. A line that ends with a backslash, or that leaves a quote open, carries on to the next row, as it does in bash. Its keys are bash's: readline's emacs keys, vi keys with -vi or with set editing-mode vi, and the user's inputrc, with its $if Bash sections. -inputrc FILE reads another file. exit or Ctrl-D leaves. Run it from the root of the repository:

go run ./_examples/bash
go run ./_examples/bash -vi

How the port was checked

Reading C and writing Go that looks like it is not enough to know the two agree. So each module was checked against the C rather than against a reading of it.

A probe program links the C code, calls it with a fixed corpus of inputs, and writes down what it returns. The Go port then answers the same corpus and the two are compared. There are fifteen such corpora, holding about 130000 recorded calls, and tools/ holds the probe that produced each one.

The whole editor is checked the same way. internal/capture starts a program under a pseudo-terminal, sends it keystrokes, and records every byte it wrote.

This found faults that reading does not find. It also found the limit of the method. A corpus checks that a function answers correctly, and nothing in a corpus checks that the functions are wired together. So the parts that only a running program exercises are tested by running one.

A third kind of test sits between the two. It feeds a string of keystrokes to the editor and asserts on the line and the cursor that come out. That covers the key dispatch, meaning which key reaches which operation. It is also where the behaviors other line editors test live: how a line ends, input that is not UTF-8, characters wider than one column, and a completion list too long to show.

A test that nobody attacked is not known to work. So before a corpus is trusted, the code it covers is broken on purpose. One break per thing the corpus is meant to pin, and each break has to fail it. tools/mutate.sh does that. It reports "did not compile" as its own answer rather than folding it into "caught".

Linux, macOS and Windows each have their own session running the same checks. A person also drove the Windows editor by hand from a real console. Everything else on that platform is a test or an injected record. The Platforms section below says what that run covered.

docs/PORT.md records the port order, every place the port departs from the C, and why.

Platforms

Linux, macOS and Windows are supported and tested. Each has its own session running the same checks, and the full suite, the linter and go vet for all three targets pass on each. The race detector runs clean on Linux and macOS.

On Windows the editor works in cmd.exe, Windows PowerShell 5.1 and pwsh, under the classic console host. Everything passes there except the recorded sessions, which do not exist yet. Recording one needs a pseudo console, which Windows creates with CreatePseudoConsole, and that part is not written. Instead, a person drove the editor by hand from a real console: typing, syntax highlighting, backspace, statements over three and four rows, the completion menu, the arrow keys within and between rows, the password read, and leaving. Those runs found no fault.

In a web page, where GOOS=js has no terminal, a program gives rline one with WithTerminal: a reader of the keys, a writer for the screen, and the size, such as xterm.js gives them. Go and TinyGo both build it for js and wasm.

On Windows, rline is tested on Windows 11 and nothing older (D62). It asks the console to read escape sequences rather than driving the console through its API, so a console that cannot read them is not supported: Windows 10 before version 1511, or a console with "Use legacy console" ticked. Go itself needs Windows 10 or later.

FreeBSD 15.1, NetBSD 11.0 and OmniOS r151058 pass the whole suite, built from source on the machine with the Go each one ships. None of them can record sessions, so that one test fails there as it does on Windows.

OpenBSD, Dragonfly and Solaris compile and are not tested. They take the same terminal code as their measured relatives, with their own ioctl numbers. Compiling is not the same as being supported, so treat the editor there as unproven.

Any other system builds and reads plain lines with no editing. That is a mode rather than a failure: the prompt still works, and the keys are not read one at a time.

Documents

About

rline supports usql, a universal command-line interface for SQL databases.


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

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

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

func Commands

func Commands() []string

Commands returns the name of every command that a key can be bound to, readline's and rline's, sorted, as bash's bind -l lists them. A command of the program's own is not among them (D76).

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.

func (CommandFunc) Run

func (f CommandFunc) Run(l *Line)

Run satisfies Command.

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

type Edit struct {
	Start, OldEnd, NewEnd int
	Before                string
}

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.

func (Error) Error

func (err Error) Error() string

Error satisfies the error interface.

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

func (l *Line) Complete(name string, completer Completer)

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

func (l *Line) Count() int

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

func (l *Line) CountGiven() bool

CountGiven reports whether a numeric argument was typed before the key, as bash's READLINE_ARGUMENT is set only then (D82).

func (*Line) Cursor

func (l *Line) Cursor() int

Cursor returns where the cursor is in Text.

func (*Line) Insert

func (l *Line) Insert(s string)

Insert puts s in at the cursor and leaves the cursor after it.

func (*Line) Key

func (l *Line) Key() key.Code

Key returns the key that ran the command.

func (*Line) Kill

func (l *Line) Kill(start, end int)

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

func (l *Line) Mark() int

Mark returns the mark, as bash's READLINE_MARK gives it (D82).

func (*Line) Print

func (l *Line) Print(text string)

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

func (l *Line) Replace(text string, cursor int)

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

func (l *Line) Run(name string)

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

func (*Line) SetMark

func (l *Line) SetMark(pos int)

SetMark puts the mark at pos, within the line (D82).

func (*Line) Text

func (l *Line) Text() string

Text returns the line.

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

func (l *LineStyle) Edit() (Edit, bool)

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

func (l *LineStyle) Style(pos, count int, style string)

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

func (l *LineStyle) StyleMarkup(s, markup string)

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

func (l *LineStyle) StyleRunes(pos, count int, style string)

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.

func (*LineStyle) Text

func (l *LineStyle) Text() string

Text returns the line being marked up.

A highlighter reads the line from here rather than being handed it separately, so that there is one copy of it and no way for the two to disagree.

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

func WithAppName(appName string) Option

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

func WithAutoPairs(autoPairs string) Option

WithAutoPairs sets the pairs that close themselves when typed, which may include quotes as the default set does.

func WithAutoTab

func WithAutoTab(autoTab bool) Option

WithAutoTab keeps completing while there is only one answer. A completion that its Suffix ended is not completed again (D133).

func WithBeep

func WithBeep(beep bool) Option

WithBeep beeps where the editor would. Turning it off stays quiet.

func WithBraceInsertion

func WithBraceInsertion(autoPair bool) Option

WithBraceInsertion closes a brace automatically when one is typed.

func WithBraceMatching

func WithBraceMatching(braceMatching bool) Option

WithBraceMatching highlights the partner of the brace at the cursor.

func WithColor

func WithColor(color bool) Option

WithColor writes color when the terminal supports it. Turning it off writes none, whatever the terminal supports.

func WithCommand

func WithCommand(name string, command Command) Option

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

func WithCompleter(completer Completer) Option

WithCompleter offers completions for the word at the cursor.

func WithCompletionMenu

func WithCompletionMenu(completionMenu bool) Option

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

func WithContinue(cont func(text string) bool) Option

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

func WithHintDelay(hintDelay time.Duration) Option

WithHintDelay waits d before showing a hint. Zero shows it at once.

func WithHints

func WithHints(hints bool) Option

WithHints shows the rest of the only completion that fits, in grey after the cursor.

func WithHistory

func WithHistory(enabled bool) Option

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

func WithHistoryDuplicates(historyDuplicates bool) Option

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

func WithHistoryFile(name string) Option

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

func WithHistoryFileLimit(historyFileLimit int) Option

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

func WithHistoryFileMode(historyFileMode fs.FileMode) Option

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

func WithHistoryFilter(historyFilter func(line, previous string) bool) Option

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

func WithHistoryLimit(historyLimit int) Option

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

func WithInlineHelp(inlineHelp bool) Option

WithInlineHelp shows the short reminder below the line while searching the history.

func WithInputrcFile

func WithInputrcFile(inputrcFile string) Option

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

func WithInputrcLines(inputrcLines []string) Option

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

func WithKeepInterrupted(bool) Option

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

func WithLogger(logger slog.Handler) Option

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

func WithManualHistory(manualHistory bool) Option

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

func WithManualInterruptNewline(manualInterruptNewline bool) Option

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

func WithMatchPairs(matchPairs string) Option

WithMatchPairs sets the pairs whose partner is highlighted, written one after another such as "()[]{}".

func WithMultiline

func WithMultiline(multiline bool) Option

WithMultiline allows line breaks inside one line. Turning it off refuses them, so a line is always one row.

func WithMultilineIndent

func WithMultilineIndent(multilineIndent bool) Option

WithMultilineIndent lines the rows after the first up under the prompt.

func WithPrompt

func WithPrompt(marker, continuation string) Option

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

func WithRowPrompt(rowPrompt func(before string) string) Option

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

func WithStderr(stderr io.Writer) Option

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

func WithStdin(stdin io.Reader) Option

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

func WithStdout(stdout io.Writer) Option

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

func WithTerminal(terminal Terminal) Option

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

func WithUserInputrc(userInputrc bool) Option

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

func WithViMode(viMode bool) Option

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

func WithWrapMark(wrapMark bool) Option

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

func New(opts ...Option) (*Prompt, error)

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

func (s *Session) AddCommand(name string, command Command) error

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

func (s *Session) AddHistory(entry string)

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

func (s *Session) Bind(keymap, seq, name string) error

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

func (s *Session) Bindings(keymap string) ([]Binding, error)

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

func (s *Session) ClearHistory()

ClearHistory empties the history.

func (*Session) Close

func (s *Session) Close() error

Close puts the terminal back as it was. A Session cannot be used afterwards.

func (*Session) DefineStyle

func (s *Session) DefineStyle(name, spec string)

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

func (s *Session) History() []string

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

func (s *Session) HistoryErr() error

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

func (s *Session) Interactive() bool

Interactive reports whether there is a terminal to edit on. When there is not, ReadLine reads a plain line.

func (*Session) LoadHistory

func (s *Session) LoadHistory() error

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

func (s *Session) Notices() []string

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

func (s *Session) Palette() ansi.Palette

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

func (s *Session) ParseAndBind(line string) error

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

func (s *Session) Password(prompt string) (string, error)

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

func (s *Session) PushInput(input []byte)

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

func (s *Session) ReadInputrc(name string) error

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

func (s *Session) ReadLine(prompt string) (string, error)

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

func (s *Session) ReadLineWith(prompt, text string) (string, error)

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

func (s *Session) Release(fn func(tty *os.File) error) error

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

func (s *Session) RunAtPrompt(fn func(w io.Writer) error)

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

func (s *Session) SaveHistory() error

SaveHistory writes the history to the file it was given, if it was given one.

func (*Session) Set added in v0.17.0

func (s *Session) Set(opts ...Option) error

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

func (s *Session) SetCompleter(completer Completer)

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

func (s *Session) SetHistoryFile(name string)

SetHistoryFile changes the file the history is kept in. It does not read the new file; call LoadHistory for that.

func (*Session) SetPrompt

func (s *Session) SetPrompt(marker, continuation string)

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

func (s *Session) SetVariable(name, value string) error

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

func (s *Session) Size() (cols, rows int)

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

func (s *Session) Stderr() io.Writer

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

func (s *Session) Unbind(keymap, seq string) error

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

func (s *Session) Variables() map[string]string

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

func (s *Session) Write(p []byte) (int, error)

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

func (*Session) WriteString

func (s *Session) WriteString(text string) (int, error)

WriteString writes plain text without making a byte slice of it first, which is what io.StringWriter asks for and what the markup writer beside this one already does.

type Terminal

type Terminal interface {
	io.Reader
	io.Writer
	Size() (cols, rows int)
}

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.

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.

Jump to

Keyboard shortcuts

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