live

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 14 Imported by: 3 modules, 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.

Documentation

Overview

Package live draws terminal output that changes in place, and keeps the terminal usable when the program drawing it stops unexpectedly.

Live redraws a block of lines in place: each Live.Draw replaces the previous block instead of adding to the scrollback. Blocks sets a command's step-by-step detail lines apart from the results it reports.

Cursor hides and shows a terminal's cursor, and InstallSignalRestore makes sure a hidden cursor is shown again when the process is interrupted, terminated or suspended. A cursor is a property of the terminal, not of any one writer, and signal handlers are process-wide, so this part of the package keeps process-wide state: a registry of hidden cursors and at most one installed signal handler. Everything else is per instance.

None of the types here decide whether drawing is appropriate. Check term.CanAnimate before drawing in place: escape sequences that move the cursor ruin a log file or a pipe.

Index

Examples

Constants

View Source
const (
	// HideCursorSequence hides the terminal cursor (DECTCEM reset).
	HideCursorSequence = "\x1b[?25l"
	// ShowCursorSequence shows the terminal cursor (DECTCEM set).
	ShowCursorSequence = "\x1b[?25h"
)

Variables

This section is empty.

Functions

func HideCursor

func HideCursor(w io.Writer) (restore func())

HideCursor hides the cursor of the terminal w writes to and returns the function that shows it again. The function is idempotent, so it can be deferred and also called earlier.

func InstallSignalRestore

func InstallSignalRestore() (uninstall func())

InstallSignalRestore keeps a hidden cursor from staying hidden when the process never reaches its deferred cleanup. It returns the function that uninstalls the handler again; that function is safe to call more than once.

On Unix, terminating signals (SIGINT, SIGTERM, SIGHUP, SIGQUIT) show every hidden Cursor and are then re-raised with their default disposition, so the exit status and SIGQUIT's goroutine dump are unchanged. SIGTSTP (Ctrl-Z) shows the cursors while the process is stopped and hides them again once SIGCONT continues it. SIGTTIN and SIGTTOU are left alone: they mean the terminal is denied to the process, and writing to it would only raise another one. Elsewhere, os.Interrupt and SIGTERM show the cursors and end the process with exit status 1.

SIGKILL and SIGSTOP cannot be caught; a process ended or stopped by them leaves the cursor hidden.

Signal dispositions are process-wide, so at most one handler is installed. While one is active, further calls do nothing and return a function that does nothing.

Installing the handler also means the signals it handles no longer end the process before the handler has run; a program that handles SIGINT itself should call RestoreAll from its own handler instead.

func RestoreAll

func RestoreAll()

RestoreAll shows every cursor this process hid and has not shown again. It waits no longer than a moment for a frame in progress, so it is safe to call on any exit path.

Types

type Blocks

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

Blocks sets a command's progress lines apart from the results it reports. Detail lines are written as a block of their own, with a blank line before and after it, and painted in the theme's Status style on a terminal that takes color. A detail line that should stand out, a warning by default, is left unpainted. Plain lines are everything else; the first plain line after a block closes it.

Both writers expect whole lines per write, the way fmt.Fprintln writes them. A Blocks is safe for concurrent use.

Example
package main

import (
	"fmt"
	"os"

	"github.com/mittwald/cli-kit/live"
)

func main() {
	blocks := live.NewBlocks(os.Stdout)
	fmt.Fprintln(blocks.Plain(), "Building release 1.4.2")
	fmt.Fprintln(blocks.Detail(), "compiling 12 packages")
	fmt.Fprintln(blocks.Detail(), "linking binary")
	fmt.Fprintln(blocks.Plain(), "Built release 1.4.2")
}
Output:
Building release 1.4.2

compiling 12 packages
linking binary

Built release 1.4.2

func NewBlocks

func NewBlocks(w io.Writer, options ...BlocksOption) *Blocks

NewBlocks returns a Blocks writing to w. Detail lines are painted when term.Colored(w) reports true.

func (*Blocks) Close

func (b *Blocks) Close()

Close ends an open block. Call it before output that Blocks does not see, such as a line written to the other stream of the same terminal. Closing a closed block writes nothing.

func (*Blocks) Detail

func (b *Blocks) Detail() io.Writer

Detail returns the writer for progress lines. The writer also has Close and Spaced methods that act on b, for callers that hold only the writer.

func (*Blocks) Plain

func (b *Blocks) Plain() io.Writer

Plain returns the writer for everything else written to the same place.

func (*Blocks) Spaced

func (b *Blocks) Spaced()

Spaced tells Blocks that a blank line was written past it, for example after an answered prompt, and that output continues below that line. The blank line ends an open block, and a block opening next does not add a second one.

type BlocksOption

type BlocksOption func(*Blocks)

BlocksOption configures a Blocks.

func WithDetailStyle

func WithDetailStyle(style theme.Style) BlocksOption

WithDetailStyle paints detail lines in style instead of the active theme's Status style.

func WithHighlight

func WithHighlight(highlight func(text string) bool) BlocksOption

WithHighlight decides which detail lines are left unpainted so they stand out from the rest of the block. The default leaves lines containing "WARNING" or "ERROR" unpainted.

type Cursor

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

Cursor tracks whether a program hid the cursor of the terminal it writes to, so that every way out of the program can show it again: a deferred call, a recovered panic, or a signal handler installed by InstallSignalRestore.

A Cursor also serializes output to its terminal. Code that draws frames holds Cursor.Lock while it writes, so a show sequence written from a signal handler never lands in the middle of a frame.

A hidden Cursor is recorded in a process-wide registry until it is shown again; that registry is what the signal handler and RestoreAll use. Hide, Show and the lock are safe for concurrent use.

Example
package main

import (
	"fmt"
	"os"

	"github.com/mittwald/cli-kit/live"
)

func main() {
	// Show the cursor again if the program is interrupted while it is hidden.
	defer live.InstallSignalRestore()()

	cursor := live.NewCursor(os.Stderr)
	cursor.Hide()
	defer cursor.Show()

	go func() {
		defer cursor.RestoreOnPanic()
		cursor.Lock()
		defer cursor.Unlock()
		fmt.Fprint(os.Stderr, "\rworking…")
	}()
}

func NewCursor

func NewCursor(w io.Writer) *Cursor

NewCursor returns a Cursor for the terminal w writes to. It does not write anything.

func (*Cursor) Hidden

func (c *Cursor) Hidden() bool

Hidden reports whether c currently keeps the cursor hidden.

func (*Cursor) Hide

func (c *Cursor) Hide()

Hide hides the cursor and records it, so a signal handler can show it again. Hiding a hidden cursor writes nothing.

func (*Cursor) Lock

func (c *Cursor) Lock()

Lock serializes a write to the terminal with the cursor's own writes. Hold it while writing a frame; do not call Hide or Show while holding it.

func (*Cursor) RestoreOnPanic

func (c *Cursor) RestoreOnPanic()

RestoreOnPanic shows the cursor and re-panics. A panic in a goroutine runs only that goroutine's deferred calls before the process dies, so every goroutine that draws while the cursor is hidden should start with

defer cursor.RestoreOnPanic()

It has to be called directly by a deferred statement.

func (*Cursor) Show

func (c *Cursor) Show()

Show makes the cursor visible again if Cursor.Hide hid it. It is idempotent, so it can be deferred, called at an output boundary, and called again from a signal handler without writing a stray sequence.

func (*Cursor) Unlock

func (c *Cursor) Unlock()

Unlock releases the lock taken by Cursor.Lock.

type Live

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

Live is a block of lines that a terminal shows as it is now: each Live.Draw replaces the lines the previous draw showed instead of adding to the scrollback.

Nothing else may write to the terminal between two draws, because the block is found again by counting rows up from the cursor. For the same reason a block has to fit on the screen: the cursor cannot move above the top of the screen, so rows that scrolled off cannot be redrawn.

A Live is not safe for concurrent use.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/mittwald/cli-kit/live"
)

func main() {
	var screen bytes.Buffer
	block := live.New(&screen)
	_ = block.Draw([]string{"downloading: 10%"})
	_ = block.Draw([]string{"downloading: 60%"})
	fmt.Printf("%q\n", screen.String())
}
Output:
"\x1b[Jdownloading: 10%\n\r\x1b[1A\x1b[Jdownloading: 60%\n"

func New

func New(w io.Writer) *Live

New returns a Live that draws to w, which has to be a terminal.

func (*Live) Clear

func (l *Live) Clear() error

Clear erases the block the last draw showed and leaves the cursor where the block started, so the next output takes its place. A block that did not fit on the screen cannot be taken back and is left as it is.

func (*Live) Draw

func (l *Live) Draw(lines []string) error

Draw replaces what the previous draw showed with lines, and leaves the cursor at the start of the row below them, so output written after the last draw follows it like any other output. Drawing the lines already on screen writes nothing.

Lines that do not fit lose their first lines until they do, and a single remaining line that still wraps past the bottom of the screen is cut short. A block cut down this way can still be redrawn in place; a block running off the screen would pile up in the scrollback. Callers that know which lines matter least should keep within Live.Fits themselves. On a terminal one row high nothing fits, and each draw goes below the previous one.

func (*Live) Fits

func (l *Live) Fits(lines []string) bool

Fits reports whether lines can be drawn and later redrawn in place. Lines get one row less than the terminal has: the cursor ends up on the row below them.

func (*Live) Width

func (l *Live) Width() int

Width returns the width of the terminal in cells, or 0 when it is not known.

Jump to

Keyboard shortcuts

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