shell

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 27 Imported by: ? 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 shell is the embedded subshell of a two-panel program, as behind C-o in Midnight Commander: the user's $SHELL on a pseudo-terminal, drawn by a terminal emulator either full screen or as the one shell line under the panels.

A Terminal owns the pty, the emulator, the shell process, the goroutine that waits for it and the watch of the commands the shell runs. The program creates it with New, starts the first shell with Init, passes it resizes, keys, pastes and the emulator's messages with Update, and draws View. Close ends it when the program quits: the emulator's read loop ends, the shell gets a hangup, the watch stops and the command that waits for the shell returns no message.

Each start has a generation, and the messages of the shell's lifecycle carry it: a shell that ended, the end of a restart delay and a report on its commands. The program passes them to Lifecycle whatever covers the screen, and Lifecycle drops a message about an earlier shell. It returns an Event: an Exit when a shell ended, a Done when a command ended. The program words them; the terminal has no texts of its own.

When the shell exits, the terminal starts a new one. A shell that exits at once starts again after a delay that doubles, and after five such exits in a row the terminal stops starting shells until StartNow. While no shell runs, the shell line shows Config.Status.

The terminal follows the shell line: Line is the text typed since the last command while every key was one the terminal can follow, and HasInput tells whether the line holds text, so the program can leave the keys to the shell's line editor. Running is the command the shell runs, from the pty's foreground process group, and Done carries its exit status when the shell sends OSC 133 marks: fish 4 does, and package hook makes bash, zsh, sh and fish 3 do when Config.HookRoot is set.

RunOnTerminal hands the terminal to another program, such as an editor, on a pty of its own, as script(1) does, and OutputLines reads what the program printed after its last full screen. InterruptGate keeps a SIGINT meant for a child that owns the terminal from quitting the program.

The shell needs a Unix system; elsewhere no command shows as running.

Index

Examples

Constants

View Source
const InlineLines = 1

InlineLines is the height of the shell area shown under the panels. Like the Midnight Commander command line it is a single line: the line with the shell cursor.

Variables

This section is empty.

Functions

func EmulatorCursor

func EmulatorCursor(term *bubbleterm.Model) *tea.Cursor

EmulatorCursor reads the cursor of a bubbleterm model, nil when hidden.

func ForwardQuitSignals

func ForwardQuitSignals(sigs <-chan os.Signal, gate *InterruptGate, quit func())

ForwardQuitSignals calls quit on the first signal from sigs that is not a SIGINT meant for a child holding gate. It returns after quit, or when sigs is closed; a program runs it in its own goroutine.

func OutputLines

func OutputLines(transcript string) []string

OutputLines returns the lines a program printed to a terminal after the last full-screen program left the alternate screen, without escape sequences or blank lines: what is left on the screen once the screen of an editor is gone. Output with no alternate screen counts whole. Use it on the record of RunOnTerminal to show what a command printed after its editor closed.

Example

This example reads the last words of a command that opened an editor, from what RunOnTerminal recorded: the editor's screen is gone.

package main

import (
	"fmt"

	"github.com/stokaro/kc/tui/shell"
)

func main() {
	transcript := "\x1b[?1049h\x1b[H\x1b[2Jname: demo\r\n~\r\n:wq\r\x1b[?1049l" +
		"\x1b[33mWarning:\x1b[0m waiting\r\x1b[Kdemo saved\r\n\r\n"
	for _, line := range shell.OutputLines(transcript) {
		fmt.Println(line)
	}
}
Output:
demo saved

func PasteInput

func PasteInput(content string) string

PasteInput prepares pasted text for a terminal. Multi-line text is wrapped in bracketed paste markers so a shell does not run each line as it arrives; shells with line editing (zsh, bash 5.1+, fish) enable bracketed paste. Single-line text is sent as is, which is safe either way.

func RunOnTerminal

func RunOnTerminal(cmd *exec.Cmd, stdin io.Reader, stdout, record io.Writer) error

RunOnTerminal runs cmd on a pseudo-terminal it owns, as script(1) does, and copies everything cmd prints to stdout and to record. cmd and the programs it starts, such as an editor, see a terminal of the size of stdout; keys typed on stdin reach them as they arrive. The terminal is in raw mode for the run, so the pty's own line discipline handles C-c and sends SIGINT to cmd, not to the calling program. A Bubble Tea program calls it from the Run method of a tea.ExecCommand, where the terminal is released; it returns cmd's error once cmd ended and the rest of its output arrived.

func WriteNow

func WriteNow(cmd tea.Cmd) tea.Cmd

WriteNow runs a bubbleterm input command at once. bubbleterm returns writes to its terminal as tea.Cmds, and Bubble Tea runs commands concurrently, so fast typing could reach the shell out of order ("echo" became "ehco"). The write is a short pty write; an error message is still delivered.

Types

type Config

type Config struct {
	// Env returns the environment of the next shell. The terminal calls
	// it on the update loop at each start, so a new shell gets what the
	// program wants at that time. nil, or an empty result, starts the
	// shell with os.Environ(). TERM is xterm-256color either way: the
	// emulator understands what it describes.
	Env func() []string
	// HookRoot is the directory for the startup files of the status hook
	// (package hook), which makes bash, zsh, sh and fish 3 report the
	// exit status of each command. "" starts shells without the hook.
	HookRoot string
	// Status returns what the shell line shows while no shell runs. exit
	// is nil while a shell starts; otherwise it says how the last shell
	// ended and when the next one starts. nil shows nothing.
	Status func(exit *Exit) string
}

Config is what a program gives its Terminal.

type Done

type Done struct {
	// Command is the command line, "" when the terminal does not know it.
	Command string
	// Status is the exit status when HaveStatus is true: the shell
	// reported it with an OSC 133 D mark (package hook).
	Status     int
	HaveStatus bool
	// LastLine is the last line the command printed that is not blank,
	// without escape sequences.
	LastLine string
}

Done is a command of the shell that ended.

type Event

type Event struct {
	// Exit is set when a shell ended.
	Exit *Exit
	// Done is set when a command of the shell ended that was not
	// reported before.
	Done *Done
}

Event is what Lifecycle reports for the program to tell the user.

type Exit

type Exit struct {
	// Command is the shell, as the terminal started it.
	Command string
	// Err says why the shell or its terminal did not start.
	Err error
	// Status is how a failed shell ended, as "exit status 127"; "" when
	// it exited with status 0.
	Status string
	// Quick is true for a shell that did not start or ran less than two
	// seconds.
	Quick bool
	// QuickExits counts the shells in a row that exited at once, this one
	// included.
	QuickExits int
	// Delay is how long the terminal waits before it starts the next
	// shell; 0 when it started one at once.
	Delay time.Duration
	// Stopped is true when the terminal stopped starting shells after
	// too many quick exits in a row. StartNow starts one again.
	Stopped bool
}

Exit is how a shell ended and what the terminal does next.

type InterruptGate

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

InterruptGate tells a program's signal handler that SIGINT belongs to a child that owns the terminal. While tea.Exec runs a child the terminal is in cooked mode, so C-c makes the tty send SIGINT to the whole foreground process group, the program included. The zero value is ready to use.

func (*InterruptGate) Hold

func (g *InterruptGate) Hold() (release func())

Hold marks a child as owning the terminal until release is called. release may be called more than once.

func (*InterruptGate) Swallow

func (g *InterruptGate) Swallow() bool

Swallow reports whether a SIGINT received now is meant for a child: one holds the gate, or the last one let it go less than a second ago.

type Terminal

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

Terminal is the embedded shell: the user's $SHELL on a pty the terminal owns, drawn by a terminal emulator full screen or as the one shell line under the panels. The update loop owns it: call every method there.

func New

func New(ctx context.Context, cfg Config) *Terminal

New returns a terminal that shows the shell line under the panels. Init starts its first shell. The terminal logs to the logger of ctx (logr.FromContextOrDiscard) and keeps no other use of it.

func (*Terminal) Attach

func (t *Terminal) Attach(r io.Reader, w io.WriteCloser) (tea.Cmd, error)

Attach shows a terminal emulator that draws what it reads from r and writes keys to w, in place of a shell. It is for a program that runs the other side itself, and for tests that watch what reaches the shell. Call it before Init, while no shell runs; the returned command starts the emulator's polling. Close closes the emulator, which closes w.

Example

This example follows the shell line under the panels. In place of a shell, the terminal writes keys to a buffer: a program attaches the other side of its own process this way, and a test sees what the shell would read. A program starts the user's shell with Init instead.

package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"sync"

	tea "charm.land/bubbletea/v2"

	"github.com/stokaro/kc/tui/shell"
)

// keys records what reaches the shell.
type keys struct {
	mu  sync.Mutex
	buf bytes.Buffer
}

func (k *keys) Write(p []byte) (int, error) {
	k.mu.Lock()
	defer k.mu.Unlock()
	return k.buf.Write(p)
}

func (k *keys) Close() error { return nil }

func (k *keys) String() string {
	k.mu.Lock()
	defer k.mu.Unlock()
	return k.buf.String()
}

func main() {
	term := shell.New(context.Background(), shell.Config{})
	defer func() { _ = term.Close() }()
	screen, output := io.Pipe()
	defer func() { _ = output.Close() }()
	got := &keys{}
	if _, err := term.Attach(screen, got); err != nil {
		panic(err)
	}

	for _, r := range "ls -l" {
		term.Update(tea.KeyPressMsg{Code: r, Text: string(r)})
	}
	line, known := term.Line()
	fmt.Printf("line %q, known %v, has input %v\n", line, known, term.HasInput())

	// The shell completes the line on Tab; the terminal stops following.
	term.Update(tea.KeyPressMsg{Code: tea.KeyTab})
	_, known = term.Line()
	fmt.Println("after Tab, known:", known, "has input:", term.HasInput())

	// Enter runs the line and gives the keys back to the panels.
	term.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
	fmt.Println("after Enter, has input:", term.HasInput())
	fmt.Printf("the shell read %q\n", got.String())
}
Output:
line "ls -l", known true, has input true
after Tab, known: false has input: true
after Enter, has input: false
the shell read "ls -l\t\r"

func (*Terminal) Blur

func (t *Terminal) Blur()

Blur removes focus from the terminal

func (*Terminal) ClearTyped

func (t *Terminal) ClearTyped()

ClearTyped resets the typed flag (used to return focus to panels).

func (*Terminal) Close

func (t *Terminal) Close() error

Close shuts down the underlying emulator/PTY: the emulator's read loop ends, the shell gets a hangup, the watch of its commands stops, and the command that waits for the shell returns no message.

func (*Terminal) DiscardLine

func (t *Terminal) DiscardLine() tea.Cmd

DiscardLine clears the shell's input line with C-u (kill the line in bash, zsh and fish with the cursor at the end) and returns the focus to the panels.

func (*Terminal) Down

func (t *Terminal) Down() bool

Down reports whether no shell runs: the terminal waits before it starts the next one, or stopped starting them.

func (*Terminal) Focus

func (t *Terminal) Focus()

Focus sets focus on the terminal

func (*Terminal) Focused

func (t *Terminal) Focused() bool

Focused returns whether the terminal is focused

func (*Terminal) HasInput

func (t *Terminal) HasInput() bool

HasInput returns whether the terminal has non-empty input. When the terminal knows the shell line, an erased or blank line counts as empty; otherwise any key typed since the last Enter or C-c counts.

func (*Terminal) Init

func (t *Terminal) Init() tea.Cmd

Init starts the shell.

func (*Terminal) Lifecycle

func (t *Terminal) Lifecycle(msg tea.Msg) (cmd tea.Cmd, ev Event, ok bool)

Lifecycle handles the terminal's own messages: a shell that ended, the end of a restart delay and a report on the commands the shell runs. ok is false for any other message. A program passes these messages to Lifecycle whatever covers the screen, so that a shell that ended is replaced; ev says what it may tell the user. A message about an earlier shell changes nothing.

func (*Terminal) Line

func (t *Terminal) Line() (string, bool)

Line returns the text typed on the shell line since the last command, and false when the terminal cannot know it: after a key such as Tab or an arrow, the shell's line editor changed the line in a way the terminal does not follow.

func (*Terminal) Running

func (t *Terminal) Running() (string, bool)

Running is the command the shell runs, while it shows as running (it has run for half a second), and false when none runs. The command is "" when the terminal does not know it.

func (*Terminal) SetHookRoot

func (t *Terminal) SetHookRoot(root string)

SetHookRoot sets where the status hook goes for the shells started from now on; "" starts them without it (Config.HookRoot).

func (*Terminal) SetShowPanels

func (t *Terminal) SetShowPanels(show bool)

SetShowPanels sets whether panels are visible: false draws the terminal full screen.

func (*Terminal) StartNow

func (t *Terminal) StartNow() tea.Cmd

StartNow starts a shell while none runs, as C-o does in kc. After the terminal stopped starting shells, the new one gets one try: if it exits at once too, the terminal stops again.

func (*Terminal) Update

func (t *Terminal) Update(msg tea.Msg) tea.Cmd

Update handles a message for the shell: a resize, a key, a paste, a mouse event or the emulator's output. Keys and pastes reach the shell before Update returns. Update handles the terminal's lifecycle messages as Lifecycle does, without the event.

func (*Terminal) View

func (t *Terminal) View() tea.View

View renders the terminal

Directories

Path Synopsis
Package hook makes a shell that a terminal program starts report the exit status of each command.
Package hook makes a shell that a terminal program starts report the exit status of each command.

Jump to

Keyboard shortcuts

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