Skip to content
xoPublic

About

Pure Go readline library with Emacs and vi modes, history, completion, syntax highlighting and inputrc support

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

213 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


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.

Editing a SQL statement with rline: Tab completing a word, the completion menu, syntax highlighting as each word is typed, and a statement continued over several rows

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.


About

Pure Go readline library with Emacs and vi modes, history, completion, syntax highlighting and inputrc support

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages