terminal

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 32 Imported by: 1 module, 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 terminal is a terminal for NSGo apps: a View that runs the user's shell, or any program, in a pseudo-terminal, with Ghostty's terminal emulator, libghostty-vt, loaded at run time with no cgo.

It runs programs on macOS, Linux and Windows, and remote sessions (Options.Conn) there, on iOS, Android and in the browser; elsewhere New returns an error. It does what terminals do: colors (16, 256 and 24-bit) and styles, wide characters and grapheme clusters, a scrollback that reflows, the alternate screen, the keyboard as programs ask (legacy sequences, modifyOtherKeys or the Kitty keyboard protocol), bracketed paste, the title (OSC 0 and 2) and the working directory (OSC 7).

Index

Constants

This section is empty.

Variables

View Source
var DefaultKeyBar = []string{"escape", "tab", "ctrl", "alt", "left", "up", "down", "right", "|", "~", "/", "-"}

DefaultKeyBar is the keys the key bar shows when View.KeyBarKeys is nil: those a software keyboard lacks, Control and Alt applying to the next key.

Functions

func GhosttyThemes

func GhosttyThemes() []string

GhosttyThemes returns the names GhosttyTheme takes, sorted: those of the user's theme files and of the themes Ghostty ships.

func LibraryPath

func LibraryPath() (string, error)

LibraryPath returns the embedded module identity in a browser, or the libghostty-vt the native terminal loads, the first of: the file $NSGO_GHOSTTY_VT names; the one beside the executable, or in its iOS or Catalyst GhosttyVT.framework or macOS Frameworks; the build the package embeds for the platform, written once into the user's cache (<cache>/nsgo/libghostty-vt/<sha256>/).

func Load

func Load() error

Load loads libghostty-vt, once, from LibraryPath. New calls it; call it earlier to report a missing library before showing a terminal.

Types

type Action

type Action uint8

Action is a terminal action, named after Ghostty's. Actions belonging to an app's windows or tabs stay in the app's own keymap.

const (
	CopyToClipboard Action = iota
	PasteFromClipboard
	SelectAll
	ClearScreen
	IncreaseFontSize
	DecreaseFontSize
	ResetFontSize
	SetFontSize
	// Ignore consumes the binding without sending input to the program.
	Ignore
)

type CursorStyle

type CursorStyle int

CursorStyle is the shape of the cursor.

const (
	CursorBlock CursorStyle = iota
	CursorBar
	CursorUnderline
)

type Keybind

type Keybind struct {
	Key    string
	Action Action
	Amount core.Points
}

Keybind binds Key, as core.Scope.OnKey names it, to Action. Amount is the point size for SetFontSize and the step for Increase/DecreaseFontSize, one point when zero. Bindings run only while the terminal input is focused and no input method is composing.

type Mirror

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

Mirror frames what a terminal shows for another terminal to show, as a server that keeps a session's terminal sends its clients: Frame returns the VT sequences that bring a terminal showing the frames before to what this one shows now. The other terminal, as one whose Conn reads the frames, then shows this one's screen and scrollback cell for cell, with its cursor and the modes that change what it sends (the cursor keys', the keyboard protocols', the mouse's, bracketed paste), and never lays out a program's output itself: it cannot come to show something else, as a terminal fed the program's output from a snapshot can.

Frames draw rows where they are, and rows that scroll off pass through the other terminal's screen in order, so that its scrollback is this one's: rows this one's limit lets go of stay there, under its own limit. Soft wraps stay soft. The first frame, and a frame after the screen took another size, start the other terminal over. A frame does not come while a program holds a synchronized update (mode 2026), for up to a second, as the view's frames do not: Frame then reports that one is due.

Programs' writes to the clipboard (OSC 52) go on to the other terminal of each Mirror.

Frames read the terminal as its view does, which takes the terminal's record of what changed since it last read it: a terminal a view shows too would not repaint all that changed. A Mirror is for a terminal no view shows, as a server's; many Mirrors of one terminal are fine.

func (*Mirror) Close

func (m *Mirror) Close()

Close frees the mirror.

func (*Mirror) Frame

func (m *Mirror) Frame() (frame []byte, due bool)

Frame returns what brings the other terminal to what this one shows, nil when it shows it already; due reports that a frame is due later, as one a synchronized update holds back.

func (*Mirror) Reset

func (m *Mirror) Reset()

Reset has the next frame start the other terminal over, as when another terminal shows the frames from now.

type MouseScrollMultiplier

type MouseScrollMultiplier struct {
	Precision, Discrete float64
}

MouseScrollMultiplier scales a program's scrolling: Precision for touchpads, Discrete for mouse wheels. Zero uses Ghostty's defaults, 1 and 3; positive values are clamped to [0.01, 10000].

type Options

type Options struct {
	// Command is the program and its arguments: the user's login shell
	// when empty ($SHELL, else /bin/zsh on macOS and /bin/sh elsewhere,
	// and PowerShell on Windows).
	Command []string
	// Dir is the program's working directory: the home directory when
	// empty.
	Dir string
	// Env adds to the app's environment, which has TERM=xterm-256color,
	// COLORTERM=truecolor, and LANG=en_US.UTF-8 when no locale is set.
	Env []string
	// Conn connects the terminal to what reads and writes, as an SSH
	// session, instead of a program. A Conn with a method Resize(cols,
	// rows int) error is told the screen's size.
	Conn io.ReadWriteCloser
	// ResizeByConn leaves the size of the screen to whoever reads Conn: a
	// view asks Conn's ResizePixels(cols, rows, cellWidth, cellHeight int)
	// error, or else its Resize, for the size it fits, and the screen keeps
	// its size until Resize sets it, as a terminal showing a server's
	// (see Mirror) does for the frames that come.
	ResizeByConn bool
	// Scrollback is about how many bytes of output to keep above the
	// screen: 10 MB when zero, none when negative.
	Scrollback int
	// ImageLimit bounds Kitty graphics storage in bytes: 64 MiB when zero, disabled when negative.
	ImageLimit int64
	// Cursor is the cursor programs reset to: a block when zero.
	Cursor CursorStyle
	// CursorBlink sets the default blinking state. Programs
	// can override it with DECSCUSR or DEC mode 12.
	CursorBlink bool
	// OnTitle, OnExit and OnBell run on a goroutine of the terminal when
	// the program sets the title, ends or rings the bell.
	OnTitle func(title string)
	OnExit  func(code int)
	OnBell  func()
	// OnSearch runs on the engine as the status of the search changes.
	OnSearch func(s SearchStatus)
}

Options configure a terminal.

type Padding

type Padding struct{ X, Y core.Points }

Padding is the room around a terminal's grid, in points (View.Padding).

type PaddingColor

type PaddingColor uint8

PaddingColor is how View colors the space outside its grid.

const (
	// PaddingBackground uses the terminal's background, including OSC 11.
	PaddingBackground PaddingColor = iota
	// PaddingExtend extends the nearest cell's background. On the primary
	// screen, top/bottom extension is suppressed for prompt rows, Powerline
	// rows or rows with any default-background cell.
	PaddingExtend
	// PaddingExtendAlways extends every edge without those heuristics.
	PaddingExtendAlways
)

type Ref

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

Ref reaches a View's selection and clipboard, for the app's menus: a base.ContextMenu around the view opens at the pointer on desktops and, after a long press, as a sheet on touch screens, where the press first selects the word under the finger.

func (*Ref) ClearSelection

func (r *Ref) ClearSelection()

ClearSelection lets go of the selection.

func (*Ref) Copy

func (r *Ref) Copy()

Copy puts the selection on the clipboard.

func (*Ref) Focus

func (r *Ref) Focus()

Focus gives the view the keyboard focus, which shows a software keyboard.

func (*Ref) FontSize

func (r *Ref) FontSize() core.Points

FontSize reports the view's current point size, tracked for controls that display it. It returns zero while the view is unmounted.

func (*Ref) Paste

func (r *Ref) Paste()

Paste pastes what the clipboard holds, bracketed as the program asks.

func (*Ref) Perform

func (r *Ref) Perform(action Action, amount core.Points) bool

Perform runs an action on the mounted view, returning false for an unknown action or an unavailable session operation.

func (*Ref) SelectAll

func (r *Ref) SelectAll()

SelectAll selects the scrollback and the screen.

func (*Ref) Selected

func (r *Ref) Selected() bool

Selected reports whether text is selected; it is a signal, so a menu item's Disabled follows it.

func (*Ref) SetFontSize

func (r *Ref) SetFontSize(size core.Points)

SetFontSize sets the view's point size, clamped to Ghostty's range of 1–255 points. It does not restart the terminal or replace its input.

type RightClickAction

type RightClickAction uint8

RightClickAction is what the view does on a secondary click. A program that captures the mouse takes it before these UI actions.

const (
	RightClickContextMenu RightClickAction = iota
	RightClickPaste
	RightClickCopy
	RightClickCopyOrPaste
	RightClickIgnore
)

type SearchStatus

type SearchStatus struct {
	// Text is what the search looks for: "" when none goes.
	Text string
	// Total counts the matches found so far, on the screen that shows: a
	// full-screen program's, or the main screen's with its scrollback.
	// Selected is the selected match's place among them, 1 the newest, as
	// a find bar's "1 of 3"; 0 when none is.
	Total, Selected int
	// Searching tells that the search has more of the scrollback to go
	// through: Total may grow.
	Searching bool
}

SearchStatus is how a search of the terminal goes (Terminal.Search, Options.OnSearch).

type Terminal

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

Terminal is a terminal emulator and the program it runs. Its methods are safe from any goroutine.

func New

func New(opts Options) (*Terminal, error)

New makes a terminal running opts.Command, or connected to opts.Conn. The program starts once a view shows the terminal, at the size of the view, or half a second later at 80×24 when none does.

func (*Terminal) ClearScreen

func (t *Terminal) ClearScreen() bool

ClearScreen clears the scrollback and the screen above the cursor's line, which moves to the top, so the prompt the shell shows stays. A full-screen program's screen, which this would break, is left alone; it reports whether it cleared.

func (*Terminal) ClearScrollback

func (t *Terminal) ClearScrollback()

ClearScrollback clears the scrollback, leaving the screen as it is.

func (*Terminal) Close

func (t *Terminal) Close() error

Close closes the terminal and frees the emulator. On Unix it hangs up the program and the jobs it started, the process groups of the terminal's session, then escalates to SIGTERM and SIGKILL if needed; on Windows it closes the console. A Conn is closed instead.

func (*Terminal) Dir

func (t *Terminal) Dir() string

Dir returns the working directory the shell reported (OSC 7), as a path when it is a file URL.

func (*Terminal) Done

func (t *Terminal) Done() <-chan struct{}

Done is closed once the program exited (or Conn ended).

func (*Terminal) EndSearch

func (t *Terminal) EndSearch()

EndSearch ends the search, and its highlights.

func (*Terminal) ExitCode

func (t *Terminal) ExitCode() int

ExitCode returns the exit code of the program once it exited: -1 for a program that could not start.

func (*Terminal) Feed

func (t *Terminal) Feed(data []byte)

Feed shows data as if the program wrote it: text and escape sequences.

func (*Terminal) History

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

History returns what the terminal shows as rows of VT sequences, for a terminal that takes the session over, as after the program that wrote them ended: the scrollback and the screen down to the cursor's row, or to the last row with something on it when that is above, without the cursor and the modes. Fed to a terminal of the same width, it leaves the cursor below what it shows, for the next program to start under it, not over it. A full-screen program's screen has no history: History returns nothing while the alternate screen shows.

func (*Terminal) NewMirror

func (t *Terminal) NewMirror() (*Mirror, error)

NewMirror returns a Mirror of the terminal, whose first frame starts the other terminal over. Close frees it.

func (*Terminal) Paste

func (t *Terminal) Paste(text string)

Paste pastes text, bracketed when the program asks (mode 2004), so that pasted lines do not run as commands.

func (*Terminal) Resize

func (t *Terminal) Resize(cols, rows int)

Resize sets the size of the screen in cells, for a terminal no view shows.

func (*Terminal) ResizePixels

func (t *Terminal) ResizePixels(cols, rows, cellWidth, cellHeight int)

ResizePixels is Resize with the size of a cell in pixels, for a terminal no view shows that stands for one that does, as a server's for the window showing its session: programs asking the size in pixels get it. A zero cell size keeps the one before.

func (*Terminal) Search

func (t *Terminal) Search(text string)

Search searches the screen and the scrollback for text, as Ghostty's find does, and highlights the matches (Theme.Search) as they are found, following the output that comes; the newest match is selected and shown, scrolling to it. Matching is exact but for the case of ASCII letters, which it ignores. Searching for the text searched already keeps the selected match; "" ends the search, as EndSearch. A view drives the search, which goes on in the frames that show the terminal.

func (*Terminal) SearchNext

func (t *Terminal) SearchNext()

SearchNext selects the next match of the search toward older output, up the screen and into the scrollback, wrapping around past the oldest, and unless it shows scrolls it to the middle of the view, clear of a find bar over an edge; SearchPrevious goes the other way.

func (*Terminal) SearchPrevious

func (t *Terminal) SearchPrevious()

func (*Terminal) SearchStatus

func (t *Terminal) SearchStatus() SearchStatus

SearchStatus returns how the search goes.

func (*Terminal) Send

func (t *Terminal) Send(data []byte)

Send sends data to the program as if typed.

func (*Terminal) SetCursor

func (t *Terminal) SetCursor(s CursorStyle)

SetCursor changes the cursor programs reset to, as Options.Cursor, and shows it now.

func (*Terminal) Size

func (t *Terminal) Size() (cols, rows int)

Size returns the size of the screen in cells.

func (*Terminal) Text

func (t *Terminal) Text() string

Text returns the text of the screen and its scrollback, with the lines a program soft-wrapped joined.

func (*Terminal) Title

func (t *Terminal) Title() string

Title returns the title the program set (OSC 0, OSC 2).

type Theme

type Theme struct {
	Foreground, Background core.Color
	// Cursor colors the cursor: the foreground when unset. CursorText
	// colors the text under a block cursor: the background when unset.
	Cursor, CursorText core.Color
	// Selection highlights the selected text: the foreground, a third
	// opaque, when unset. SelectionText colors the selected text: its own
	// colors when unset.
	Selection, SelectionText core.Color
	// Search, SearchText, SearchSelected and SearchSelectedText are the backgrounds and foregrounds of search matches and the current match. Unset colors use gold backgrounds and black text.
	Search, SearchText, SearchSelected, SearchSelectedText core.Color
	// Palette holds the 16 colors of programs: black, red, green, yellow,
	// blue, magenta, cyan and white, then their bright kinds.
	Palette [16]core.Color
}

Theme is the colors of a terminal, which programs may change (OSC 4, 10, 11, 12) until the terminal resets. GhosttyTheme returns Ghostty's themes. A zero color is unset.

func DarkTheme

func DarkTheme() *Theme

DarkTheme returns Visual Studio Code's dark terminal colors.

func GhosttyTheme

func GhosttyTheme(name string) (*Theme, error)

GhosttyTheme returns a theme of Ghostty's by its name, as Ghostty's theme option takes it ("Catppuccin Mocha", "Dracula", "Rose Pine Dawn"…): a theme file of the user's in Ghostty's themes directory ($XDG_CONFIG_HOME/ghostty/themes, ~/.config/ghostty/themes by default), else one of the themes Ghostty ships, which the plugin carries, of any case; or the theme file a path names. Each call returns a new Theme.

func LightTheme

func LightTheme() *Theme

LightTheme returns Visual Studio Code's light terminal colors.

func ParseGhosttyTheme

func ParseGhosttyTheme(data []byte) (*Theme, error)

ParseGhosttyTheme reads a theme in Ghostty's format, Ghostty's configuration's lines that set colors:

palette = 0=#45475a
…
palette = 15=#a6adc8
background = #1e1e2e
foreground = #cdd6f4
cursor-color = #f5e0dc
cursor-text = #1e1e2e
selection-background = #f5e0dc
selection-foreground = #1e1e2e

Colors are in hex (#rgb, #rrggbb, rrggbb…). Other lines of Ghostty's configuration are ignored, as are the palette's colors past the 16th, and the colors set to cell-foreground or cell-background, which the terminal then picks itself (see Theme). The colors a theme leaves out are those of DarkTheme, or LightTheme when its background is light.

type View

type View struct {
	Terminal *Terminal
	// AllowClipboardRead and AllowClipboardWrite permit program-initiated reads and writes (OSC 52 / Kitty), denied by default. Apps own consent UI. An explicit user paste independently offers only its text/PNG snapshot.
	AllowClipboardRead, AllowClipboardWrite bool
	// Font is the terminal's font: the platform's fixed-pitch font at 13
	// points when its family and size are unset. Bold and italic text
	// take its variants.
	Font core.Font
	// Theme colors the terminal in light appearances, and DarkTheme in
	// dark ones; LightTheme and DarkTheme when nil.
	Theme, DarkTheme *Theme
	// Padding is the room around the grid: 6 points across and 4 down
	// when zero, none when negative.
	Padding Padding
	// PaddingColor chooses the background outside the grid.
	PaddingColor PaddingColor
	// MinimumContrast is the minimum text-to-cell contrast ratio, 1 to
	// 21. Zero preserves colors. Graphics, emoji and images are unchanged.
	MinimumContrast float64
	// AutoFocus gives the view the keyboard focus as it mounts.
	AutoFocus bool
	// Transparent leaves the terminal's default background undrawn, so
	// what is behind the view shows through.
	Transparent bool
	// HideIndicator hides the scroll bar; the scrollback still scrolls.
	HideIndicator bool
	// Keybinds override the terminal's defaults while its input is focused. They use core's key names and Ghostty's actions; later entries win.
	Keybinds []Keybind
	// RightClickAction is ContextMenu by default. RightClickIgnore leaves secondary clicks to an enclosing app menu.
	RightClickAction RightClickAction
	// MenuClass and MenuStyle style the default context menu's surface; MenuItemClass and MenuItemStyle style its four items.
	MenuClass     string
	MenuStyle     core.Style
	MenuItemClass string
	MenuItemStyle core.Style
	// MouseReporting allows programs to capture the mouse when they request it; nil means true. Turning it off leaves selection and scrolling to the view. Shift also bypasses mouse capture for selection.
	MouseReporting func() bool
	// MouseScrollMultiplier scales wheel reports and alternate-screen arrow keys, separately for touchpads and discrete wheels. It does not change the platform's ordinary scrollback scrolling.
	MouseScrollMultiplier MouseScrollMultiplier
	// Class is Tailwind CSS classes, as core.View's, under Style.
	Class string
	Style core.Style
	Label string
	// TestID names the view, and with a suffix its parts for tests: the
	// screen "-screen", the key bar's keys "-key-" and the key's name.
	TestID  string
	OnFocus func()
	OnBlur  func()
	// OnSizeChange receives the size of the screen in cells as the view
	// sets it.
	OnSizeChange func(cols, rows int)
	// Ref, when set, is bound to the view as it mounts.
	Ref *Ref

	// KeyBarKeys are the keys of the bar over a touch screen's keyboard,
	// as core names them ("escape", "ctrl", "left") or characters ("|"):
	// DefaultKeyBar when nil. NoKeyBar shows none.
	KeyBarKeys []string
	NoKeyBar   bool
	// KeyBarClass and KeyBarStyle style the bar, a horizontal Scroll;
	// KeyClass and KeyStyle each key, with KeyOnClass and KeyOnStyle over
	// them while Control or Alt is latched for the next key. A part's
	// StyleFunc merges over its Style and follows the signals it reads.
	KeyBarClass     string
	KeyBarStyle     core.Style
	KeyBarStyleFunc func() core.Style
	KeyClass        string
	KeyStyle        core.Style
	KeyStyleFunc    func() core.Style
	KeyOnClass      string
	KeyOnStyle      core.Style
	KeyOnStyleFunc  func() core.Style
}

View shows a terminal and takes its keyboard. Its size sets the terminal's, in cells of its font; a press gives it the keyboard focus. A terminal shows in one view at a time.

The screen is a canvas. A vertical Scroll over it is the hit layer: the wheel, the touchpad, a finger and the scroll bar move through the scrollback, and a press and a drag select (two presses a word, three a line, Shift extends), a long press of a finger a word. An invisible text input at the cursor, the sink, takes typed text and input methods; the keys that type no text are bound while it has the focus. Copy is Command+C on Apple platforms and Control+Shift+C elsewhere; paste Command+V, or Control+Shift+V; Ref gives them to the app's menus.

Links, programs' hyperlinks (OSC 8) and URLs printed as text, underline faintly under the mouse, fully with a hand with Command held, or Control off Apple platforms, when a click opens URLs with Scope.OpenURL and existing local paths with Scope.OpenFile. Relative paths use the shell's OSC 7 directory, or Options.Dir before a local shell reports one.

On touch screens a bar of the keys software keyboards lack shows over the keyboard while the view has the focus, and the grid keeps to what the keyboard leaves of the view.

func (View) Render

func (p View) Render(cx *core.Scope) core.Node

Render implements core.Node.

Directories

Path Synopsis
internal
library
Package library finds libghostty-vt for the terminal: the file $NSGO_GHOSTTY_VT names, the one the nsgo tool put into the app, or on desktops the build for the platform the package embeds, written once into the user's cache.
Package library finds libghostty-vt for the terminal: the file $NSGO_GHOSTTY_VT names, the one the nsgo tool put into the app, or on desktops the build for the platform the package embeds, written once into the user's cache.
pty
Package pty runs processes in pseudo-terminals, in pure Go: /dev/ptmx on macOS and Linux, ConPTY on Windows.
Package pty runs processes in pseudo-terminals, in pure Go: /dev/ptmx on macOS and Linux, ConPTY on Windows.
vt
Package vt binds libghostty-vt, Ghostty's terminal emulator, through purego on native targets and an embedded WebAssembly module in a browser: no cgo.
Package vt binds libghostty-vt, Ghostty's terminal emulator, through purego on native targets and an embedded WebAssembly module in a browser: no cgo.
Package locales says the terminal's own messages in the language the app shows.
Package locales says the terminal's own messages in the language the app shows.

Jump to

Keyboard shortcuts

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