terminal

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2024 License: Apache-2.0 Imports: 16 Imported by: 4

README

Go Reference

terminal

Fortio's terminal is a readline style library. It handles prompts, edit (like Ctrl-A for beginning of line etc...), navigating through history using arrow keys, loading and saving history from file, etc... It works on everywhere go does (including macOS, Windows (using Terminal app), Linux).

See example/main.go for a rather complete example/demo.

See the godoc above for details.

The grol command line repl and others use this.

The implementations currently is a wrapper fully encapsulating (our fork of) x/term, i.e. fortio.org/term and new features like the interrupts handling (filters Ctrl-C ahead of term' reads)

FPS

There is also a new ansipixels package for drawing on the terminal and the tagged release also include fps that uses that package to test your terminal frames per second capabilities. See the source ansipixels/fps/fps.go

You can get the binary from releases

Or just run

CGO_ENABLED=0 go install fortio.org/terminal/ansipixels/fps@latest  # to install or just
CGO_ENABLED=0 go run fortio.org/terminal/ansipixels/fps@latest  # to run without install

or even

docker run -ti fortio/fps # but that's obviously slower

or

brew install fortio/tap/fps

Use the -image flag to pass a different image to load as background. Or use -i and fps is now just a terminal image viewer.

Pass an optional maxfps as argument.

E.g fps -image my.jpg 60 will run at 60 fps with my.jpg as background.

After hitting any key to start the measurement, you can also resize the window at any time and fps will render with the new size. Use q to stop.

fps screenshot

Additional flags/usage:

fps v0.14.0 usage:
	fps [flags] [maxfps] or fps -i imagefiles...
or 1 of the special arguments
	fps {help|envhelp|version|buildinfo}
flags:
  -color
    	If your terminal supports color, this will load image in (216) colors instead of monochrome (default true)
  -gray
    	Convert the image to grayscale
  -i	Arguments are now images files to show, no FPS test (hit any key to continue)
  -image string
    	Image file to display in monochrome in the background instead of the default one
  -nobox
    	Don't draw the box around the image, make the image full screen instead of 1 pixel less on all sides
  -truecolor
    	If your terminal supports truecolor, this will load image in truecolor (24bits) instead of monochrome

Documentation

Overview

Library to interact with ansi/v100 style terminals.

Index

Constants

View Source
const CtrlC = 3 // Control-C is ascii 3 (C is 3rd letter of the alphabet)
View Source
const DefaultHistoryCapacity = term.DefaultHistoryEntries

DefaultHistoryCapacity is the default number of entries in the history (99).

View Source
const IsUnix = true

Variables

View Source
var (
	ErrUserInterrupt = NewErrInterrupted("terminal interrupted by user")
	ErrStopped       = NewErrInterrupted("interrupt reader stopped") // not really an error more of a marker.
)

Functions

func SleepWithContext added in v0.8.0

func SleepWithContext(ctx context.Context, duration time.Duration) error

func TimeoutReader added in v0.8.1

func TimeoutReader(fd int, tv *unix.Timeval, buf []byte) (int, error)

func TimeoutToTimeval added in v0.8.1

func TimeoutToTimeval(timeout time.Duration) *unix.Timeval

Types

type AutoCompleteCallback

type AutoCompleteCallback func(t *Terminal, line string, pos int, key rune) (newLine string, newPos int, ok bool)

AutoCompleteCallback is called with "this" terminal as first argument so AutoCompleteCallback can use t.Out etc. (compared to the original x/term callback).

type InterruptReader added in v0.8.0

type InterruptReader struct {
	// contains filtered or unexported fields
}

func NewInterruptReader added in v0.8.0

func NewInterruptReader(reader *os.File, bufSize int) *InterruptReader

NewInterruptReader creates a new interrupt reader. it needs to be Start()ed to start reading from the underlying reader and intercept Ctrl-C and listen for interrupt signals.

func (*InterruptReader) Read added in v0.8.0

func (ir *InterruptReader) Read(p []byte) (int, error)

Implement io.Reader interface.

func (*InterruptReader) Start added in v0.8.0

Start or restart (after a cancel/interrupt) the interrupt reader.

func (*InterruptReader) Stop added in v0.9.0

func (ir *InterruptReader) Stop()

type InterruptedError added in v0.8.1

type InterruptedError struct {
	DetailedReason string
	OriginalError  error
}

func NewErrInterrupted added in v0.8.1

func NewErrInterrupted(reason string) InterruptedError

func NewErrInterruptedWithErr added in v0.8.1

func NewErrInterruptedWithErr(reason string, err error) InterruptedError

func (InterruptedError) Error added in v0.8.1

func (e InterruptedError) Error() string

func (InterruptedError) Unwrap added in v0.8.1

func (e InterruptedError) Unwrap() error

type Terminal

type Terminal struct {
	// Use this for any output to the screen/console so the required \r are added in raw mode
	// the prompt and command edit is refresh as needed when input comes in.
	Out io.Writer
	// Cancellable context after Open(). Use it to cancel the terminal reading or check for done.
	Context context.Context //nolint:containedctx // To avoid Open() returning 4 values.
	Cancel  context.CancelFunc
	// contains filtered or unexported fields
}

func Open

func Open(ctx context.Context) (t *Terminal, err error)

Open opens stdin as a terminal, do `defer terminal.Close()` to restore the terminal to its original state upon exit. fortio.org/log (and thus stdlib "log") will be redirected to the terminal in a manner that preserves the prompt. New cancellable context is returned, use it to cancel the terminal reading or check for done for control-c or signal.

func (*Terminal) AddToHistory added in v0.4.0

func (t *Terminal) AddToHistory(commands ...string)

AddToHistory add commands to the history.

func (*Terminal) AutoHistory added in v0.5.0

func (t *Terminal) AutoHistory() bool

AutoHistory returns the current auto history setting.

func (*Terminal) Close

func (t *Terminal) Close() error

Close restores the terminal to its original state. Must be called at exit to avoid leaving the terminal in raw mode. Safe to call multiple times. Will save the history to the history file if one was set using [SetHistoryFile] and the capacity is > 0.

func (*Terminal) History added in v0.4.0

func (t *Terminal) History() []string

History returns the current history state.

func (*Terminal) IsTerminal

func (t *Terminal) IsTerminal() bool

func (*Terminal) NewHistory added in v0.4.0

func (t *Terminal) NewHistory(capacity int)

NewHistory creates/resets the history to a new one with the given capacity. Using 0 as capacity will disable history reading and writing but not change the underlying history state from it's DefaultHistoryCapacity.

func (*Terminal) ReadLine

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

ReadLine reads a line from the terminal using the setup prompt and history and edit capabilities. Returns the line and an error if any. io.EOF is returned when the user presses Control-D. ErrInterrupted is returned when the user presses Control-C or a signal is received.

func (*Terminal) ReplaceLatest added in v0.5.0

func (t *Terminal) ReplaceLatest(command string) string

ReplaceLatest replaces the current history with the given commands, returns the previous value.

func (*Terminal) ResetInterrupts added in v0.8.0

func (t *Terminal) ResetInterrupts(ctx context.Context) (context.Context, context.CancelFunc)

If you want to reset and restart after an interrupt, call this.

func (*Terminal) Resume added in v0.9.0

func (*Terminal) SetAutoCompleteCallback

func (t *Terminal) SetAutoCompleteCallback(f AutoCompleteCallback)

SetAutoCompleteCallback sets the callback called for each key press. Can be used to implement auto completion. See example/main.go for an example.

func (*Terminal) SetAutoHistory added in v0.5.0

func (t *Terminal) SetAutoHistory(enabled bool)

SetAutoHistory enables/disables auto history (default is enabled).

func (*Terminal) SetHistoryFile

func (t *Terminal) SetHistoryFile(f string) error

Sets up a file to load and save history from/to. File is being read when this is called. If no error is returned, the file will also be automatically updated on Close().

func (*Terminal) SetPrompt

func (t *Terminal) SetPrompt(s string)

Sets or change the prompt.

func (*Terminal) Suspend added in v0.9.0

func (t *Terminal) Suspend()

Temporarily suspend/resume of the terminal back to normal (for example to run a sub process). use defer t.Resume() after calling Suspend() to put the terminal back in raw mode.

Directories

Path Synopsis
ansipixel provides terminal drawing and key reading abilities.
ansipixel provides terminal drawing and key reading abilities.
fps
* A more interesting/real example is https://github.com/grol-io/grol * but this demonstrates most of the features of the terminal package.
* A more interesting/real example is https://github.com/grol-io/grol * but this demonstrates most of the features of the terminal package.

Jump to

Keyboard shortcuts

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