package module
v1.2.2 Latest Latest

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

Go to latest
Published: Jan 14, 2022 License: MIT Imports: 16 Imported by: 1,942



Liner is a command line editor with history. It was inspired by linenoise; everything Unix-like is a VT100 (or is trying very hard to be). If your terminal is not pretending to be a VT100, change it. Liner also support Windows.

Liner is intended for use by cross-platform applications. Therefore, the decision was made to write it in pure Go, avoiding cgo, for ease of cross compilation. Furthermore, features only supported on some platforms have been intentionally omitted. For example, Ctrl-Z is "suspend" on Unix, but "EOF" on Windows. In the interest of making an application behave the same way on every supported platform, Ctrl-Z is ignored by Liner.

Liner is released under the X11 license (which is similar to the new BSD license).

Line Editing

The following line editing commands are supported on platforms and terminals that Liner supports:

Keystroke Action
Ctrl-A, Home Move cursor to beginning of line
Ctrl-E, End Move cursor to end of line
Ctrl-B, Left Move cursor one character left
Ctrl-F, Right Move cursor one character right
Ctrl-Left, Alt-B Move cursor to previous word
Ctrl-Right, Alt-F Move cursor to next word
Ctrl-D, Del (if line is not empty) Delete character under cursor
Ctrl-D (if line is empty) End of File - usually quits application
Ctrl-C Reset input (create new empty prompt)
Ctrl-L Clear screen (line is unmodified)
Ctrl-T Transpose previous character with current character
Ctrl-H, BackSpace Delete character before cursor
Ctrl-W, Alt-BackSpace Delete word leading up to cursor
Alt-D Delete word following cursor
Ctrl-K Delete from cursor to end of line
Ctrl-U Delete from start of line to cursor
Ctrl-P, Up Previous match from history
Ctrl-N, Down Next match from history
Ctrl-R Reverse Search history (Ctrl-S forward, Ctrl-G cancel)
Ctrl-Y Paste from Yank buffer (Alt-Y to paste next yank instead)
Tab Next completion
Shift-Tab (after Tab) Previous completion

Note that "Previous" and "Next match from history" will retain the part of the line that the user has already typed, similar to zsh's "up-line-or-beginning-search" (which is the default on some systems) or bash's "history-search-backward" (which is my preferred behaviour, but does not appear to be the default Up keybinding on any system).

Getting started

package main

import (


var (
	history_fn = filepath.Join(os.TempDir(), ".liner_example_history")
	names      = []string{"john", "james", "mary", "nancy"}

func main() {
	line := liner.NewLiner()
	defer line.Close()


	line.SetCompleter(func(line string) (c []string) {
		for _, n := range names {
			if strings.HasPrefix(n, strings.ToLower(line)) {
				c = append(c, n)

	if f, err := os.Open(history_fn); err == nil {

	if name, err := line.Prompt("What is your name? "); err == nil {
		log.Print("Got: ", name)
	} else if err == liner.ErrPromptAborted {
	} else {
		log.Print("Error reading line: ", err)

	if f, err := os.Create(history_fn); err != nil {
		log.Print("Error writing history file: ", err)
	} else {

For documentation, see



Package liner implements a simple command line editor, inspired by linenoise ( This package supports WIN32 in addition to the xterm codes supported by everything else.




View Source
const HistoryLimit = 1000

HistoryLimit is the maximum number of entries saved in the scrollback history.

View Source
const KillRingMax = 60

KillRingMax is the max number of elements to save on the killring.


View Source
var ErrInternal = errors.New("liner: internal error")

ErrInternal is returned when liner experiences an error that it cannot handle. For example, if the number of colums becomes zero during an active call to Prompt

View Source
var ErrInvalidPrompt = errors.New("invalid prompt")

ErrInvalidPrompt is returned from Prompt or PasswordPrompt if the prompt contains any unprintable runes (including substrings that could be colour codes on some platforms).

View Source
var ErrNotTerminalOutput = errors.New("standard output is not a terminal")

ErrNotTerminalOutput is returned from Prompt or PasswordPrompt if the platform is normally supported, but stdout has been redirected

View Source
var ErrPromptAborted = errors.New("prompt aborted")

ErrPromptAborted is returned from Prompt or PasswordPrompt when the user presses Ctrl-C if SetCtrlCAborts(true) has been called on the State


func TerminalSupported added in v1.1.0

func TerminalSupported() bool

TerminalSupported returns true if the current terminal supports line editing features, and false if liner will use the 'dumb' fallback for input. Note that TerminalSupported does not check all factors that may cause liner to not fully support the terminal (such as stdin redirection)


type Completer

type Completer func(line string) []string

Completer takes the currently edited line content at the left of the cursor and returns a list of completion candidates. If the line is "Hello, wo!!!" and the cursor is before the first '!', "Hello, wo" is passed to the completer which may return {"Hello, world", "Hello, Word"} to have "Hello, world!!!".

type ModeApplier added in v1.1.0

type ModeApplier interface {
	ApplyMode() error

ModeApplier is the interface that wraps a representation of the terminal mode. ApplyMode sets the terminal to this mode.

func TerminalMode added in v1.1.0

func TerminalMode() (ModeApplier, error)

TerminalMode returns the current terminal input mode as an InputModeSetter.

This function is provided for convenience, and should not be necessary for most users of liner.

type ShouldRestart added in v1.1.0

type ShouldRestart func(err error) bool

ShouldRestart is passed the error generated by readNext and returns true if the the read should be restarted or false if the error should be returned.

type State

type State struct {
	// contains filtered or unexported fields

State represents an open terminal

func NewLiner

func NewLiner() *State

NewLiner initializes a new *State, and sets the terminal into raw mode. To restore the terminal to its previous state, call State.Close().

func (*State) AppendHistory

func (s *State) AppendHistory(item string)

AppendHistory appends an entry to the scrollback history. AppendHistory should be called iff Prompt returns a valid command.

func (*State) ClearHistory added in v1.1.0

func (s *State) ClearHistory()

ClearHistory clears the scrollback history.

func (*State) Close

func (s *State) Close() error

Close returns the terminal to its previous mode

func (*State) PasswordPrompt added in v1.1.0

func (s *State) PasswordPrompt(prompt string) (string, error)

PasswordPrompt displays p, and then waits for user input. The input typed by the user is not displayed in the terminal.

func (*State) Prompt

func (s *State) Prompt(prompt string) (string, error)

Prompt displays p and returns a line of user input, not including a trailing newline character. An io.EOF error is returned if the user signals end-of-file by pressing Ctrl-D. Prompt allows line editing if the terminal supports it.

func (*State) PromptWithSuggestion added in v1.1.0

func (s *State) PromptWithSuggestion(prompt string, text string, pos int) (string, error)

PromptWithSuggestion displays prompt and an editable text with cursor at given position. The cursor will be set to the end of the line if given position is negative or greater than length of text (in runes). Returns a line of user input, not including a trailing newline character. An io.EOF error is returned if the user signals end-of-file by pressing Ctrl-D.

func (*State) ReadHistory

func (s *State) ReadHistory(r io.Reader) (num int, err error)

ReadHistory reads scrollback history from r. Returns the number of lines read, and any read error (except io.EOF).

func (*State) SetBeep added in v1.2.0

func (s *State) SetBeep(beep bool)

SetBeep sets whether liner should beep the terminal at various times (output ASCII BEL, 0x07). Default is true (will beep).

func (*State) SetCompleter

func (s *State) SetCompleter(f Completer)

SetCompleter sets the completion function that Liner will call to fetch completion candidates when the user presses tab.

func (*State) SetCtrlCAborts added in v1.1.0

func (s *State) SetCtrlCAborts(aborts bool)

SetCtrlCAborts sets whether Prompt on a supported terminal will return an ErrPromptAborted when Ctrl-C is pressed. The default is false (will not return when Ctrl-C is pressed). Unsupported terminals typically raise SIGINT (and Prompt does not return) regardless of the value passed to SetCtrlCAborts.

func (*State) SetMultiLineMode added in v1.1.0

func (s *State) SetMultiLineMode(mlmode bool)

SetMultiLineMode sets whether line is auto-wrapped. The default is false (single line).

func (*State) SetShouldRestart added in v1.1.0

func (s *State) SetShouldRestart(f ShouldRestart)

SetShouldRestart sets the restart function that Liner will call to determine whether to retry the call to, or return the error returned by, readNext.

func (*State) SetTabCompletionStyle added in v1.1.0

func (s *State) SetTabCompletionStyle(tabStyle TabStyle)

SetTabCompletionStyle sets the behvavior when the Tab key is pressed for auto-completion. TabCircular is the default behavior and cycles through the list of candidates at the prompt. TabPrints will print the available completion candidates to the screen similar to BASH and GNU Readline

func (*State) SetWordCompleter added in v1.1.0

func (s *State) SetWordCompleter(f WordCompleter)

SetWordCompleter sets the completion function that Liner will call to fetch completion candidates when the user presses tab.

func (*State) WriteHistory

func (s *State) WriteHistory(w io.Writer) (num int, err error)

WriteHistory writes scrollback history to w. Returns the number of lines successfully written, and any write error.

Unlike the rest of liner's API, WriteHistory is safe to call from another goroutine while Prompt is in progress. This exception is to facilitate the saving of the history buffer during an unexpected exit (for example, due to Ctrl-C being invoked)


This example demonstrates a way to retrieve the current history buffer without using a file.

var s State

buf := new(bytes.Buffer)
_, err := s.WriteHistory(buf)
if err == nil {
	history := strings.Split(strings.TrimSpace(buf.String()), "\n")
	for i, line := range history {
		fmt.Println("History entry", i, ":", line)

History entry 0 : foo
History entry 1 : bar

type TabStyle added in v1.1.0

type TabStyle int

TabStyle is used to select how tab completions are displayed.

const (
	TabCircular TabStyle = iota

Two tab styles are currently available:

TabCircular cycles through each completion item and displays it directly on the prompt

TabPrints prints the list of completion items to the screen after a second tab key is pressed. This behaves similar to GNU readline and BASH (which uses readline)

type WordCompleter added in v1.1.0

type WordCompleter func(line string, pos int) (head string, completions []string, tail string)

WordCompleter takes the currently edited line with the cursor position and returns the completion candidates for the partial word to be completed. If the line is "Hello, wo!!!" and the cursor is before the first '!', ("Hello, wo!!!", 9) is passed to the completer which may returns ("Hello, ", {"world", "Word"}, "!!!") to have "Hello, world!!!".

Jump to

Keyboard shortcuts

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