lineedit

package
v0.54.9 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT, BSD-3-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package lineedit is a copy of the VT100 line editor (Terminal) from golang.org/x/term v0.29.0 (terminal.go), made display-width aware.

x/term counts every rune as one terminal column, so East Asian wide runes (CJK, fullwidth forms, most emoji: two columns) break backspace, cursor movement and line wrapping. Local modifications, all width related:

  • visualLength sums display columns (runeWidth, width.go) instead of runes;
  • cursor positions are computed by laying out the line cell by cell (posToXY/cellIndex); a wide rune that would start in the last column is moved to the next row, the skipped cell being written as a space;
  • writeLine, setLine, eraseNPreviousChars and Ctrl-K blank cells by columns, not by rune count;
  • Backspace, Ctrl-D and Left/Right step over zero-width runes (combining marks) together with their base rune;
  • readPasswordLine (unused here) is dropped; stRingBuffer moved to history.go.

Additions for asking a question during a pending read (take.go): TakeLine, SetPendingLine, ReadLineNoHistory and AbortLine; a Ctrl-C/Ctrl-D that ends a read is consumed instead of staying in the input remainder.

Addition for a lone Esc the caller already decided on (esc.go): SetEscAlone and EscCallback.

Addition for taking a line back into the editor: WithdrawCallback, called when Up is pressed on an empty input line, so a caller can fill the line in (chat taking a message still waiting in the running turn back for editing).

Addition for the status line chat shows above the input line while a turn runs (status.go): SetStatus. The status line's row belongs to the block the editor keeps on screen - the prompt and the line being edited - so every repaint (Write) clears it with them and draws it again from the top of the block.

Addition for Ctrl-C on a non-empty line (SetCtrlCClearsLine): it drops the line and goes on reading instead of ending the read, so a stray key press does not throw a half-typed message away; chat turns it on for the person's own input line (the prompt, and the read a running turn keeps) and leaves it off where Ctrl-C means "cancel" (the answer of an approval question).

Change to bracketed pastes (paste.go): a newline inside a paste is inserted into the line instead of ending the read, so a pasted multi-line text lands on the input line as one piece; SetNewlineAsText lets a caller declare the same for a terminal that does not bracket pastes. Upstream's ErrPasteIndicator (a line that consists only of pasted data) is gone with it: no paste ends a read.

This file holds the terminal itself and the read loop; key parsing is in keys.go, the cursor and repainting helpers are in render.go.

For ASCII input the output is byte-for-byte identical to x/term.

Index

Constants

View Source
const DefaultWidth = 80

DefaultWidth is the terminal width the editor lays lines out with until it is told the real one (SetSize).

Variables

View Source
var ErrInterrupt error = interruptError{}

ErrInterrupt is returned by ReadLine for Ctrl-C. It matches io.EOF too, so callers that only know "input ended" keep treating it that way, while chat can tell it apart from Ctrl-D to ask for a second Ctrl-C.

Functions

func PadLine

func PadLine(text string, width int) string

PadLine returns text followed by as many spaces as it takes to fill width columns, so the background of a highlighted line reaches the end of the terminal row; text that already reaches width comes back unchanged. It is what chat uses for the messages it prints on a background (Renderer.External), measured with the same rules as the line editor (escapes zero, wide runes two).

Types

type EscapeCodes

type EscapeCodes struct {
	// Foreground colors
	Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte

	// Reset all attributes
	Reset []byte
}

EscapeCodes contains escape sequences that can be written to the terminal in order to achieve different styles of text.

type InputStyle

type InputStyle struct {
	// Prefix opens the style (background, plus the foreground that stays
	// readable on it) and Suffix closes it; an empty Prefix turns the repaint
	// off.
	Prefix, Suffix string
	// FillWidth is the number of columns the background is filled to. The
	// terminal's own layout width wins when it is larger: rows are cut at that
	// width, so filling further would spill into the next row.
	FillWidth int
}

InputStyle is the style a submitted line is repainted with; a zero InputStyle (the default) leaves the line exactly as it was typed.

type Terminal

type Terminal struct {
	// AutoCompleteCallback, if non-null, is called for each keypress with
	// the full input line and the current position of the cursor (in
	// bytes, as an index into |line|). If it returns ok=false, the key
	// press is processed normally. Otherwise it returns a replacement line
	// and the new cursor position.
	AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)

	// Escape contains a pointer to the escape codes for this terminal.
	// It's always a valid pointer, although the escape codes themselves
	// may be empty if the terminal doesn't support them.
	Escape *EscapeCodes

	// EscCallback, when non-nil, is called for a lone Esc press the caller declared
	// with SetEscAlone. It is called from inside ReadLine with the terminal lock
	// released (like AutoCompleteCallback), so it must not use the terminal; a
	// declared Esc without a callback is dropped like any other key the editor has no
	// use for.
	EscCallback func()
	// WithdrawCallback, when non-nil, is called from inside ReadLine when Up is
	// pressed on an empty input line. ok=true means the caller filled a line in -
	// text it took back from somewhere, which the editor then shows with the cursor
	// at its end - so the key is consumed; ok=false keeps Up's usual meaning
	// (history). It is called with the terminal lock released (like EscCallback and
	// AutoCompleteCallback), so it may write to the terminal; an empty line always
	// keeps Up's usual meaning.
	WithdrawCallback func() (string, bool)
	// PasteImageCallback, when non-nil, runs on Alt+V (design 0.3): the chat
	// appends the clipboard's picture to its pending queue and prints the
	// "[已附图 …]" note above the input line. Called with the terminal lock
	// released (like WithdrawCallback), so it may write to the terminal.
	PasteImageCallback func()
	// contains filtered or unexported fields
}

Terminal contains the state for running a VT100 terminal that is capable of reading lines of input.

func NewTerminal

func NewTerminal(c io.ReadWriter, prompt string) *Terminal

NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is a local terminal, that terminal must first have been put into raw mode. prompt is a string that is written at the start of each input line (i.e. "> ").

func (*Terminal) AbortLine

func (t *Terminal) AbortLine()

AbortLine ends the screen state of a read that returned io.EOF (Ctrl-C, or Ctrl-D on an empty line): the cursor moves past the typed text to a new row and the text is dropped, so the next ReadLine starts on a clean line. A status line above the input line (chat.steering) goes with it: the read it belonged to is over.

func (*Terminal) PrependLine

func (t *Terminal) PrependLine(text string)

PrependLine puts text in front of the line being edited (or of the pending line when no ReadLine runs) and shows it at once; the existing line follows on a line of its own, so nothing typed is lost. The cursor goes to the end. It is how chat writes a message that could not be inserted into a running turn back into the input line, for the person to review and submit; nothing is submitted here.

func (*Terminal) ReadLine

func (t *Terminal) ReadLine() (line string, err error)

ReadLine returns a line of input from the terminal.

func (*Terminal) ReadLineNoHistory

func (t *Terminal) ReadLineNoHistory() (line string, err error)

ReadLineNoHistory is ReadLine without adding the line to the history.

func (*Terminal) ReadPassword

func (t *Terminal) ReadPassword(prompt string) (line string, err error)

ReadPassword temporarily changes the prompt and reads a password, without echo, from the terminal.

func (*Terminal) RestoreEcho

func (t *Terminal) RestoreEcho()

RestoreEcho gives the read in progress its echo back and records it. The turn's steer read echoes like the prompt read (chat.steering keeps the person's input line on screen for the whole turn), so nothing turns echoing off while a turn runs; the method is the counterpart of a read that changes hands - an approval question asking on the turn's own read gives it back with RestoreEcho - and a caller that wants a silent read reads a password (ReadPassword) instead. It draws nothing by itself: the caller sets and redraws the prompt (UpdatePrompt) or lets the next read do it.

func (*Terminal) SetBracketedPasteMode

func (t *Terminal) SetBracketedPasteMode(on bool)

SetBracketedPasteMode requests that the terminal bracket paste operations with markers. Not all terminals support this; where it is supported a paste reaches the editor as one chunk with its own start and end markers, which is what tells its newlines from a typed Enter (paste.go).

func (*Terminal) SetCtrlCClearsLine

func (t *Terminal) SetCtrlCClearsLine(on bool)

SetCtrlCClearsLine makes Ctrl-C on a non-empty line drop that line and go on reading instead of ending the read with ErrInterrupt; an empty line always ends it. It is off by default: a reader that wants Ctrl-C as "cancel what I am asking" (chat's approval question, ask.go) leaves it off, while the reader of the person's own input line turns it on (chat's prompt and its read during a turn), so a stray key press does not throw a half-typed message away.

func (*Terminal) SetEscAlone

func (t *Terminal) SetEscAlone()

func (*Terminal) SetHistory

func (t *Terminal) SetHistory(entries []string)

SetHistory replaces the editor history with entries ordered oldest to newest.

func (*Terminal) SetInputStyle

func (t *Terminal) SetInputStyle(style InputStyle)

SetInputStyle sets the style of a submitted line (a zero InputStyle turns the repaint off). Safe from any goroutine and at any time: it only takes effect when a line is submitted.

func (*Terminal) SetNewlineAsText

func (t *Terminal) SetNewlineAsText()

SetNewlineAsText declares that the newline key the editor is about to read is text of a paste, not a submit: it is inserted into the line like any other pasted rune. The declaration covers one key only; a caller that sees something other than a newline follow it does not declare it (esc.go's SetEscAlone works the same way). Like SetEscAlone it is called from the byte pump, that is while a ReadLine is blocked in Read and holds no terminal lock.

func (*Terminal) SetPasteImageCallback

func (t *Terminal) SetPasteImageCallback(cb func())

SetEscAlone declares that the 0x1b byte the editor is about to read is an Esc key press on its own: the next read that ends on an Esc byte with nothing after it reports the key instead of waiting for the rest of a sequence. A caller that sees a follow-up byte never declares it, so a real sequence is unaffected. SetPasteImageCallback binds chat's Alt+V clipboard paste: the callback runs from inside ReadLine on an Alt+V press (see PasteImageCallback).

func (*Terminal) SetPendingLine

func (t *Terminal) SetPendingLine(line string)

SetPendingLine prefills the next ReadLine with line (cursor at its end), as if it had been typed. An empty line clears a pending one.

func (*Terminal) SetPrompt

func (t *Terminal) SetPrompt(prompt string)

SetPrompt sets the prompt to be used when reading subsequent lines.

func (*Terminal) SetSize

func (t *Terminal) SetSize(width, height int) error

func (*Terminal) SetStatus

func (t *Terminal) SetStatus(text string)

SetStatus replaces the status line shown above the input line; an empty text drops it. The text must be one display line: control runes are turned into spaces and the text is cut to the width of the terminal, so it can never wrap into the row of the prompt and break the layout the block is tracked with.

While nothing of the block is on screen the text is remembered and drawn together with the prompt of the read that follows (readLine); otherwise the row changes where it is, without touching the prompt, the line being edited or the cursor in it. Safe from any goroutine.

func (*Terminal) SetWin32InputMode

func (t *Terminal) SetWin32InputMode(on bool)

SetWin32InputMode switches the terminal's win32-input-mode (DECSET 9001) on or off and makes the line editor read its records while it is on. It is written where bracketed paste is written - around a read that holds raw mode - so the terminal goes back to plain key bytes whenever chat leaves the line editor (a turn, a local command, the end of chat); a terminal that does not know the sequence ignores it, and the byte parser still reads its keys.

func (*Terminal) TakeInterruptedLine

func (t *Terminal) TakeInterruptedLine() string

TakeInterruptedLine takes the line a just-finished read left in the editor out of it and clears it from the screen, and returns its content. It is how chat reports what the person had typed when Ctrl-C ended a read that keeps the line (a running local command's read, whose Ctrl-C means "end the command"): the content rides on the read's abort event, so putting it back into the input line does not depend on the editor buffer surviving to the next read. A read that clears the line itself has nothing here to take; a read that is not over yet (a later ReadLine already runs) waits for it. When nothing is on the line the editor is left as it is.

func (*Terminal) TakeLine

func (t *Terminal) TakeLine() (line string, reading bool)

TakeLine removes the line being edited and repaints the prompt without it. reading reports whether a ReadLine is in progress; if so, the rest of that read (whatever is typed from now on) is not added to history. When no read is running, the line set by SetPendingLine (not yet shown) is taken instead.

func (*Terminal) UpdatePrompt

func (t *Terminal) UpdatePrompt(prompt string) error

UpdatePrompt replaces the prompt and, when a prompt is on screen (a ReadLine is in progress), repaints it together with the line being edited. SetPrompt alone only takes effect on the next redraw. (Local addition.)

func (*Terminal) Write

func (t *Terminal) Write(buf []byte) (n int, err error)

Directories

Path Synopsis
Package pump is the byte pump a line editor (lineedit.Terminal) reads through, plus the terminal helpers around it (platform input wait, input flush, output flags, window size watching).
Package pump is the byte pump a line editor (lineedit.Terminal) reads through, plus the terminal helpers around it (platform input wait, input flush, output flags, window size watching).

Jump to

Keyboard shortcuts

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