Help us shape the future of Go! Take the 2026 Go Developer Survey

ochazuke

package module
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 40 Imported by: 0

README

ochazuke
Latest release Go Reference Go version License

A modal TUI framework for Go, built on Bubble Tea v2: Vim-style modes and an extensible command model, so every action in your app can be bound to a key, run from the palette or scripted from the shell.

Ochazuke is a modal TUI framework for Go. It builds on Charmbracelet Bubble Tea v2 (charm.land/bubbletea/v2, Lip Gloss v2, Bubbles v2) and adds what a keyboard-first app needs: Vim-style modes and editing, retained pages and a stack of partial-screen modals that keep their state, lists, tables and trees, a command palette, forms and a Settings page, with default Lip Gloss styling. Underneath is a generic command model: every action is a named command with typed arguments that runs the same way from a key, the palette, the CLI (over a local socket) and the Go API. Keys, settings and commands are data, so users rebind and extend them in JSON files, and apps and extensions add their own without forking the framework.

Module github.com/unixsuperhero/ochazuke; requires Go 1.26 or newer. It builds on oden for CLI resolution.

go get github.com/unixsuperhero/ochazuke@latest

Explore the architecture

Open the interactive architecture field guide locally:

open docs/architecture.html

No server, install, or internet connection is needed. Search 12 components, inspect their responsibilities and source locations, step through keyboard/CLI/picker/modal journeys, and experiment with retained modal state. The state lab illustrates ownership; it does not connect to a running Go application. The linked architecture map supports node exploration and light/dark themes; its editable specification is architecture-map.json.

The guide links to four generated pages: Actions, Default bindings, Go API, and CLI & socket. Each page has separate navigation links; the action, binding, and Go API pages have their own search. Actions and bindings reflect a fresh demo, not a running application's customized registry. Editor grammar shortcuts remain in the keyboard guide.

The keybinding execution walkthrough follows Tab through input focus, Ctrl-N through modal creation, and a configured g g sequence through timed longest-match resolution (g, g g, g g g). It includes Go excerpts, concrete state snapshots, GitHub source links, and an illustrative sequence stepper.

For a graph beside the code, open the keybinding execution explorer. Hover or focus a function to preview its source; click to pin it. Choose Tab, Ctrl-N, or the sandbox sequence path and follow highlighted source lines. This is a source-backed snapshot, not a live debugger. Rebuild it with python3 docs/keybinding-explorer/generate.py; stale source mappings must be reviewed before regeneration.

Regenerate after changing registrations or Go declarations/comments:

go run ./cmd/docgen

Go's built-in documentation also works directly in the Ochazuke project directory:

go doc
go doc -all .
go doc Runtime.Execute

The HTML API catalog uses the standard go/doc library, with no documentation-server dependency. Edit cmd/docgen/main.go for the layout; do not hand-edit the four generated pages. Keep all four HTML files beside architecture.html when copying the guide.

Run on macOS

Requires Go 1.26 or newer.

go run ./cmd/ochazuke run

For a reusable executable:

go build -o /tmp/ochazuke ./cmd/ochazuke
/tmp/ochazuke run

In another terminal:

/tmp/ochazuke operations list
/tmp/ochazuke page open --json '{"id":"playground"}'
/tmp/ochazuke input undo
/tmp/ochazuke input undo --json '{"steps":3}' --target directory
/tmp/ochazuke state get --json '{"path":"/inputs/directory/text"}'

Global --socket PATH goes before run or NOUN VERB. It selects a specific application instance. The default socket on macOS is ~/Library/Caches/ochazuke/app.sock. run --headless uses the same Bubble Tea event loop without terminal rendering.

Keybinding sandbox

Run ochazuke keybinding (or go run ./cmd/ochazuke keybinding) without starting the demo or socket server. It opens Stage 1: Define bindings:

  • a: add a binding; enter Tea key names and a dummy action identifier in separate fields.
  • e / d: edit / delete the selected binding; arrows select a row.
  • t: edit the ambiguous-binding timeout (Go durations such as 1000ms or 1s; must be positive). The current timeout is shown in setup and in the sandbox.
  • i / o: import / export JSON. Enter a path or press Ctrl-O to browse files and folders. An export folder selection proposes bindings.json; the filename remains editable.
  • Enter: Enter sandbox. In Stage 2, the left column shows the latest key, outcome, and effective bindings; the right column logs messages newest first (last 200 retained).
  • Ctrl-G: return to setup without losing bindings or history. Ctrl-C exits either stage.

Import replaces in-memory bindings only after the whole file validates. Export asks before overwriting an existing file. Changes remain in memory until exported; exiting does not autosave.

Preload setup from a file with ochazuke keybinding --bindings=path/to/bindings.json. The import/export format is:

[
  {"keys": "ctrl+s", "action": "save"},
  {"keys": "g g", "action": "go-top"}
]

Names come directly from Bubble Tea's tea.KeyPressMsg.String() (a paste shows as [text]), quoted in the log to make whitespace visible. Ctrl-C and Ctrl-G are reserved and cannot be bound. Keys that the terminal encodes identically cannot be distinguished by the sandbox.

You can also preload dummy actions with repeatable --bind 'KEYS=ACTION' options. These override matching keys from --bindings, regardless of flag order:

go run ./cmd/ochazuke keybinding \
  --bind 'ctrl+s=save' \
  --bind 'g g=go-top' \
  --bind 'alt+x=alternate'

These are real Ochazuke rows on the app noun dispatched through Runtime.Dispatch and the operation registry. Each dummy action prints ACTION: <identifier> in the sandbox's latest-result area and history, without performing any app operation. The left column lists the effective bindings; history labels unmatched keys, pending sequences, cancelled sequences, and timed-out sequences. A later definition of the same key sequence replaces the earlier one.

Timed ambiguous bindings

When a complete binding is also a prefix of a longer binding, the runtime waits instead of firing at once. With g, g g, and g g g all bound:

  • The first g is complete but ambiguous: it is deferred, and the timer starts.
  • Each valid continuation (g g, then g g g) refreshes the timer. The longest complete match so far is the fallback.
  • When no longer continuation remains possible, the third g runs g g g immediately.
  • On timeout, the fallback (the longest completed binding) runs. The sandbox updates the outcome of the last key row rather than adding a key; if nothing runs, it shows that the sequence timed out.
  • If a different key arrives, the completed fallback (if any) runs and the mismatching key is then dispatched fresh through the whole stack, so it still reaches the editor or any row that binds it.
  • A pure prefix (not itself a binding) times out and clears without running anything.
  • While a sequence waits, the focused instance is in a prefix mode named after the base mode and the keys so far (normal g); bindings.list then lists the continuations.
  • Escape cancels all deferred work. Late timer events from a cancelled or superseded wait do nothing, and context changes cancel pending sequences.

The timeout defaults to 1000ms (Neovim's timeoutlen). Set it with --timeout DURATION (for example --timeout 1s; zero or negative values are rejected) or press t in setup. The timeout is not stored in the bindings JSON, which remains a plain array, so it is not persisted by export. It is kept when bindings are imported, edited, or deleted.

Coalesced ordinary typing is split into keys, like the app's dispatcher, so multi-key sequences work during rapid typing. Bracketed paste remains one logged message and does not trigger bindings.

Full-project example

examples/full-project is a standalone application assembled from separate configuration, action, binding, and page modules. Its JSON files define pages, instances and nouns, inputs, actions, binding rows, modals, modes, and appearance. Go registries supply the handlers and renderers named by that configuration.

go run ./examples/full-project
go run ./examples/full-project --config ./examples/full-project/config
go run ./examples/full-project --smoke

The default configuration is embedded in the executable. --config reads an editable directory instead. The smaller examples/core remains a headless example of action fallback, modal restoration, and isolated undo.

CSV example

examples/csv is the lightweight second consumer from docs/CSV-APP-SKETCH.md: a modal CSV reader and editor built without touching the resolver, the editor spec or the modal stack. It brings its own component, grid, a two-dimensional cursor with one instance for the focused cell parented to a row instance parented to a column instance, so the stack under a cell is [cell, row, column, grid, sheet, app] and dd resolves on row, s on column, i on cell, ctrl+s on sheet.

go run ./examples/csv examples/csv/testdata/people.csv
go run ./examples/csv --smoke examples/csv/testdata/people.csv   # render one frame and exit
go run ./examples/csv bindings list --all > csv-bindings.json # all stored binding tables as config rows

What it shows: motions with counts (3j, 2G, gg) through the grid's move verb; a cell edit, rename, add-column, open and save-as through one prompt modal (enter commits, esc cancels, ctrl+o opens the path picker into the field); a persistent filter field below the grid, the sheet's second focus stop (} or tab from the grid lands on it ready to type, enter filters by the cursor column and returns to the cell, shift+tab, esc and { from the grid move between the two, / on a column focuses it); three visual modes (v, V, ctrl+v) that share one mode table on the grid noun with m/M/ctrl+a marks, and : inside a selection opens the palette over it without dropping it; yank, delete and paste through the shared registers with the yank's shape (V y p pastes rows, ctrl+v y p pastes columns); transform on every noun that resolves to a cell set (cell, row, column, selection) as one verb over a map of named transformations (t u, t l, t t, t i title, t s slug, f for fill-down), whose name parameter takes its pick list from transformations.list (ids with labels; ctrl+n/ctrl+p, type to filter, enter); every edit as one Patch that is also its undo record (u, ctrl+r); per-verb Confirm on dd (Delete row r1?) and D (Delete column c1 (email)?, the header carried by a row the grid puts on the column instance through grid.WithInstanceRows); verb guards, so the palette offers selection.* only during a selection and row.*/column.* only while the focus is in the grid (the grid's selecting and in-grid guards). The one core addition it needed is Runtime.StoreYank/ReadYank (yank_api.go), so a component outside the package can store a yank of a shape the editor does not know; the second is the verb guard below.

Pages and default presentation

run launches the demo in internal/demo (demo.New()), not an application you must adopt; the framework package itself holds no application pages. It starts on Overview. The framework accepts your own page IDs, renderers, state, inputs, and registered actions.

The shell around a page is one chrome, Layout.Shell: a title row with the mode badge right-aligned, a subtitle row (the page tabs, or the page title beside the sidebar), a rule, the body, a rule, the footer and a margin, inside a two-cell gutter. Layout.PageBlock renders through the same method, so a page and the application around it reserve the same rows and Layout.BodySize is the body a renderer receives (less the sidebar). The footer and every modal's hint line are BindingHints: the focused instance's binding rows in resolution order (ctrl+j page.next · : palette.open, each row its key and noun.verb, or the row's Hint; the descriptions are in BindingHelp), the same data bindings list prints, so a hint can never name a key that is not bound and rebinding a key moves its hint. The last key's error replaces the footer until the next key.

? keyboard help is a list table with prefix, key, operation, arguments, and description columns: a key sequence is split into its prefix and final key (SplitKeys; ctrl+a v reads ctrl+a | v, g c x reads g c | x), a prefix's rows sit together sorted by key after the section's single keys, and the prefix is drawn once per group (Column.Group, any table can use it); the keys, operation and description wrap inside their columns. Arguments are compact JSON, resolved against the focus and mode when help opens; values depending on a future pattern key remain $key, $digit, or $text. Long arguments truncate with … rather than wrapping. BindingHelp exposes the full preview in HelpRow.Args, the split key in HelpRow.Prefix/Final, and the request a hinted row runs in HelpRow.Request (its Hint in HelpRow.Hint); opening help never executes the bindings.

Demo page Purpose
Overview Navigation and a short framework tour
Playground Text, path and multiline paths fields, shared yanks, nested drafts, path picker
Commands Live operation catalog, argument schemas, and remembered Playground bindings
Appearance Live theme and density controls: t cycles theme, d toggles density

In normal mode, Ctrl-J advances and Ctrl-K goes back. The demo does not bind Alt-number shortcuts.

These are suggested starter/demo pages. Domain pages such as Agents, Panes, Projects, and application Settings belong to consuming applications; the framework does not require those names or behaviors.

Registering your own pages

A page is an instance of kind page under app. Page carries a title, the instance it starts focused on (Focus, the page itself by default) and a renderer; while another page is open the page remembers its focus and mode (Page.Remembered), and page.open restores both. Pages, lists, inputs and terminals share one constructor family taking the same options (Parent, Kind, Focus): r.AddPage(id, title, render, Focus(..)), r.AddList(id, items, Parent(..)), r.AddInput(in, Parent(..), Kind(..)), r.AddTerminal(id, stream, Parent(..)). RegisterPage(&Page{...}) and NewList(r, ...) are the same registrations for callers that hold the struct or the runtime as a value. Register the page's instances and inputs first when the page starts inside one of them:

r := ochazuke.NewRuntime()
r.Instance("home")                                   // noun "home" is defined with it
r.AddInput(ochazuke.NewInput("title", "", false), ochazuke.Parent("home"))
_, err := r.AddPage("home", "Home", func(r *ochazuke.Runtime, width, height int) ochazuke.Block {
    return ochazuke.Text("Welcome to your application.")
}, ochazuke.Focus("title"))
if err != nil { panic(err) }
if err := r.OpenPage("home"); err != nil { panic(err) }
model := ochazuke.NewModel(r)
if _, err := tea.NewProgram(model).Run(); err != nil { // Model.View sets AltScreen
    panic(err)
}

Registration does not activate a page; OpenPage (or page.open) sets Runtime.Page and restores the page's frame. Switching reuses the page's exact frame and input instances: selection, focus, modes, drafts, undo history, and scrolling survive a round trip. Normal-mode Ctrl-J/K cycles PageList(), app's page children in registration order. Rows bound on a page instance or its noun apply while that page holds the focus. Page tabs have no numeric shortcuts; ' (page.pick) opens a chooser of every page, the pages visited before most recent first, then the never-visited ones in registration order, then the current page last, marked current (so ' then enter goes back to the page last left; type to filter by title, enter opens), or type page in the palette to complete a page ID. When the tabs do not fit, the row windows around the active tab and shows ‹N / N› for the pages hidden on each side.

Any page can be hidden from the tabs and Ctrl-J/K: the pages.hidden setting (a list of page ids; settings set pages.hidden '["runs"]', or page hide runs / page show runs, which write it; with no id they act on the current page). A hidden page stays reachable: page.open, ' (marked hidden), the palette and OpenPage open it, and its tab shows while it is current. pages list marks each page hidden. Pages are also the things of the page noun (an instances store): page list, page get [ID], page set ID hidden true|false (or --toggle) and page watch are its standard verbs, and page hide/page show are aliases of page set with hidden preset. An application declares an opt-in page hidden by default with Page.DefaultHidden or the DefaultHidden() option (a catalog page: defaultHidden: true); those ids are the setting's default until the user sets it, and settings reset pages.hidden returns to them. page hide refuses the last page in the tabs, and Model.Init opens the first page in the tabs when the start page is hidden (Runtime.OpenVisibleStart). Runtime.HidePage, ShowPage, PageHidden, HiddenPages and TabPages are the Go side.

Ordinary modals block page switching. The palette closes before dispatching its line, so open page alpha works when no other modal is underneath it. Focusing an inactive page's input does not silently navigate; open that page first. Explicitly targeted editing operations may still update an offscreen input without moving focus.

/tmp/ochazuke pages list
/tmp/ochazuke page open --json '{"id":"commands"}'
/tmp/ochazuke page next
/tmp/ochazuke page previous
/tmp/ochazuke state get --json '{"path":"/page"}'
/tmp/ochazuke state get --json '{"path":"/pages/playground/frame/focus"}'
/tmp/ochazuke surface scroll --json '{"lines":8}'

Styling and modal behavior

  • Default styling uses restrained teal/green accents, rounded panels, heavier focused borders, page tabs, a mode badge, and a status line. The status line and modal hints are derived from binding rows (BindingHints), never written by hand; the picker's own help line is derived the same way.
  • Themes: adaptive, dark, light, mono, plus the user's colour schemes (below). Density: comfortable or compact. Adaptive follows the terminal's detected background; NO_COLOR disables theme colors. Focus remains visible through border weight and a tab marker.
  • Modals are centered, content-sized panels, at most about 80% of the terminal width (no fixed column cap) and about 75% of its height; a chooser fills that width. They leave a visible, subdued perimeter of the previous screen whenever the terminal can accommodate it. Nested modals retain the previous modal and page underneath.
  • Resizable panes: a page that draws a list/detail split passes its Layout through Runtime.PaneLayout(page, layout); Layout.Split, SplitBlock and SplitFocusBlock then follow the page's divider (Layout.Shift), and a split drawn by hand divides with layout.Divide(defaultFirst, total, ochazuke.PaneMinWidth) (PaneMinHeight stacked). Catalog pages with a detail (cli.MountPage) and the demo's Library do this already. In normal mode ctrl+w > grows the first pane (the list, left or top) by PaneStep (5%) of the split, ctrl+w < shrinks it, ctrl+w = resets; counts repeat (3 ctrl+w >). ctrl+w w and ctrl+w W walk the focus stops (focus.next/previous; Vim's count picks a window number, here there is none). The bare >, < and = no longer resize (until this release they did, even in an editor or the outline, where Vim users expect shift operators); a user restores them with bindings.json rows, {"noun": "app", "mode": "normal", "keys": ">", "request": {"noun": "ochazuke.pane", "verb": "grow"}, "when": "pane-split"}. The shift stops at PaneShiftLimit (30 points) either way and each side keeps PaneMinWidth cells (PaneMinHeight rows stacked). The keys answer, and the footer shows ctrl+w >/< resize, only on a page whose last frame drew a split; pane grow, pane shrink and pane reset (each with an optional page) work from the CLI and palette anywhere. Dividers persist per page id in panes.json in the state directory (Config.PanesPath()), replaced atomically on each change; with no state directory (Config.Disable) they last the session.
  • Tiny terminals use reduced chrome rather than overflowing the screen. Bubbles viewports handle overflowing page and modal content; PgUp/PgDn scroll the active surface.
  • In an input modal, Escape returns insert mode to normal; another Escape closes the modal. A pending normal-mode operator/count is canceled before closing. "Escape pops a modal" is one row: the modal noun's normal-mode esc, which sits inside app and outside the editor and palette tables. Ctrl-G closes demo drafts directly. Palette and picker cancellation retain their own documented behavior.
  • App-specific modal rendering is registered through Model.ModalViews[frameID] = ModalView{Title, Render}. The framework owns positioning and composition; the renderer receives the modal frame and available content dimensions.
  • Render callbacks return a Block{Text, Cursor} and may use trusted Lip Gloss ANSI styling in Text. Sanitize external text before rendering it; built-in input and filesystem labels already do so. Text(s) wraps content that has no cursor.
  • The terminal cursor is real, not painted. InputBlock(in, w, h) reports the cursor cell of the input it renders; compose it only for the focused input and use InputView for the rest. Every composer (Layout.PageBlock/PanelBlock/SplitBlock/SidebarBlock, ComposeModalBlock, the shell) moves the child's cursor by where it placed the child, so Model.View can set tea.View.Cursor: a bar in insert mode, a block in normal mode, an underline in visual modes, hidden when no input is focused or a modal without an input covers it. Wide/combining graphemes, terminal-cell clipping, and visual-selection reverse video share the same renderer; moving the cursor never shifts following text.
/tmp/ochazuke themes list
/tmp/ochazuke appearance get
/tmp/ochazuke appearance set --json '{"theme":"dark","density":"compact"}'

Theme and density changes are atomic and apply immediately to all pages and modals. appearance set changes them for the session. NewStyles(*model.Appearance) supplies the same style vocabulary to application renderers.

Colour schemes

The theme setting selects the colour scheme and persists in settings.json. The framework declares it (Runtime.EnsureConfigSettings, called by Model.Init and the CLI shell) unless the application declared a setting of that name, which it then applies itself. Its choices are the built-in themes followed by the schemes in themes.json, a file beside settings.json (themes path prints it):

{
  "kombu": {
    "background": "dark",
    "accent": "#C9A227",
    "border": "#5C4A1E",
    "error": {"light": "#B3261E", "dark": "#FF6F61"}
  }
}
Role Draws
text Body text and the title
muted Hints, inactive tabs, the dimmed backdrop under a modal, the focus beside the mode (focus-display)
accent The active tab, the badge, the subtitle, focused panel and modal borders
border Unfocused panel borders
surface The background of the active tab and the badge
error Errors. It must differ from accent and muted.

Each role is "#RRGGBB", "#RGB", an ANSI index "0" to "255" (for 16- and 256-colour terminals), or {"light": ..., "dark": ...}. background picks the side: adaptive (the default, the terminal's), light or dark. A role left out keeps the built-in palette's. The selected row stays reverse video in every scheme, so it reads without colour.

A scheme that does not validate is skipped and reported as a notice. That covers an unknown role, a bad colour, background or tone, a built-in's name holding anything but tones, and an error colour equal to the accent or muted one. A theme value that names a skipped scheme reads its default, so the screen falls back to adaptive. After editing the file, themes reload reads it again and withdraws fixed notices. Appearance.Accent still goes on top of any scheme. mono and NO_COLOR draw no colour whatever the scheme. An application can supply its own schemes with model.Appearance.Schemes = ochazuke.NewSchemeSet(...) (ParseSchemes reads the file format).

Tones

A cell, or a run of runes inside one, can carry a named tone instead of colour: ListItem.Tones (and TreeNode.Tones, and "tones" on a catalog row line) hold ToneSpan{Cell, Tone, From, To}, rune offsets into the cell's text, To 0 for its end. The theme decides what a tone looks like, so colour stays configuration:

ochazuke.ListItem{ID: "w1", Noun: "pane", Label: "work/claude",
    Cells: []string{"★ work/claude", "needs input"},
    Tones: []ochazuke.ToneSpan{ochazuke.SpanTone(0, 0, 1, ochazuke.ToneStar), ochazuke.CellTone(1, ochazuke.ToneNeedsInput)}}
Tone Light / dark Attributes
state.working #1F6FB2 / #7CB7E8
state.needs-input #9A6700 / #E3B341 bold
state.done #2E7D32 / #8BC48A
state.errored the scheme's error bold
state.idle the scheme's muted
state.exited the scheme's muted dim
marker.star #B08800 / #F2CC60 bold
marker.queued the scheme's accent
error (ToneError) background #F6D3CE / #5E2722 bold
chip (ToneChip) background #E2EAE5 / #26362F
chip.focused (ToneChipFocused) the scheme's surface on its accent bold

mono and NO_COLOR draw the attributes alone. An unknown tone draws plain. The text never changes, so tones never count toward a width or a cut. The selected row stays one reverse-video bar: inside it a tone keeps its bold and drops its colour and dim. In themes.json a scheme takes "tones", laid over the built-in ones, and an entry named after a built-in theme may hold tones alone:

{
  "dark": {"tones": {"state.working": {"fg": "#5FAFD7", "bold": true}, "build.cached": "muted"}},
  "mono": {"tones": {"state.done": {"bold": true}}}
}

A tone is {"fg": ..., "bg": ..., "bold": true, "dim": true} or a colour alone; fg and bg are a colour as a role takes it or a role's name (text, muted, accent, border, surface, error, and mode, the current mode's badge colour), which follows the scheme. A tone with a bg fills its run's cells (mono draws none). A span's Bg (ToneSpan{Cell, Tone, Bg}, "bg" in JSON) names the tone whose background goes under it while Tone keeps the foreground, so {"cell": 0, "tone": "state.working", "bg": "error"} is a working-blue key on the error background; Bg alone only fills. On the selected row the setting tones.selected-background (SelectedBackgroundSetting, drop default | keep, in settings/ochazuke.json) drops the background with the colour, or keeps the cell on its background, bold, out of the reverse bar. adaptive's entry reaches dark and light too. Styles.Tone(name) is a tone's style for an application's own text.

Chrome colour

The chrome.color setting (appearance; off, subtle, rich, default rich) says how much colour the chrome draws. rich colours every border (a pane's border by its state, the focused one by the mode), fills the mode badge with the mode's colour and draws the hint keys in the accent, bold. subtle tints foregrounds only and colours only the alert states (needs input, errored). off draws the chrome exactly as before 0.58, and is the opt-out: :set chrome.color=off, setting cycle chrome.color, the Settings page.

Every colour is a tone row named chrome.<level>.<role> (chrome.rich.border.state.working): the built-in rows are in DefaultTones(), and a theme's tones in themes.json override any of them or add one ({"adaptive": {"tones": {"chrome.rich.border.state.done": "border"}}}). A role with no row at the level draws as before; off has no rows, so it is data, not a branch. A chrome row's fg or bg may name the role mode, the current mode's badge colour, and an application's accent (Appearance.Accent) stands for accent, border and mode in chrome rows. The roles: border, border.focused, border.<tone>, border.modal, border.completion, border.split, panel.title, panel.title.focused, title.mark, title, mode.<name>/mode.pending/mode, hint.key, hint.text, hint.sep (config export writes the table). Go: Styles.Chrome(role, fallback), Styles.WithChrome(level, roles) (Model.Styles applies it), Runtime.ChromeLevel().

  • Pane borders by state. layout.WithPanelTone(tone).PanelBlock(title, body, w, h, focused) draws a panel's border in the row border.<tone>, as Card.Tone does a timeline card's; an empty tone is the usual border. A border takes the first of: its state's row, the application's accent, border.focused (focused), border, the theme's border. A pane that needs input stays amber under an application accent, and focus is still marked by heavy lines.
  • The badge takes the first of mode.<name> (the mode's name, held keys stripped), mode.pending (a pending mode), mode.<extends>, mode. The label and its width never change.
  • Hints. HintCells(r, focus) is BindingHints as {Key, Text} cells; Footer.Hints carries them, and the footer and modal hint lines draw keys in hint.key, actions in hint.text, the · in hint.sep.
  • The state tones read as ok (state.done), warn (state.needs-input), error (state.errored) and busy (state.working); no new names.
  • mono and NO_COLOR draw a row's attributes alone, so a rich badge or a needs-input border is bold where off draws it plain.
  • The markdown package's note boxes and table rules read the tones markdown.note (built in: today's #875f00 / #d7af5f) and markdown.rule (no built-in row: plain), in every level.

Compared with Vim: the roles are Vim's highlight groups for the chrome. border/border.split are hl-WinSeparator (hl-VertSplit), border.modal and border.completion Neovim's hl-FloatBorder, the title and footer rows hl-StatusLine (hl-StatusLineNC is dim-unfocused). Vim draws -- INSERT -- in one hl-ModeMsg colour for every mode; a colour per mode is what statusline plugins (lualine) add, here rows. A border coloured by its pane's state is not Vim's (tmux's pane-active-border-style is closest). themes.json with themes reload is :colorscheme and :highlight, edited in the file. Selection stays reverse video in every scheme, unlike hl-Visual.

Keyboard guide

The demo starts on Overview in normal mode. Open Playground with Ctrl-J; Tab/Shift-Tab cycle its directory, notes, and paths fields. Overview, Commands, and Appearance support j/k and up/down scrolling. Demo page shortcuts are normal-mode-only, so insert-mode Ctrl-K still kills to line end. The footer of every screen is the live version of this table for the focused instance and its mode: the rows bindings list prints, innermost first.

Macro recording consumes exactly one register character after q, except :: q: opens the palette on the last command, Vim's command-line window (:help q:; the exact : row of macro_pending beats its any register row, so : is never a register, as in Vim). Compared with Vim: there is no history window; the line holds the last command and up/down walk older ones. q/ and q? (search history) are not bound: there is no search history yet. For qq:, the first q prompts for a register, the second starts recording into q and displays REC @q, and : opens the palette. A normal-mode q stops recording. Invalid register input reports an error but does not trap later commands in register selection.

Context Keys Behavior
Normal input h j k l, arrows Rune/line movement
Normal input w b e, 0 $, gg G Word, line, and document motions
Normal input i a I A Insert here, after cursor, at first nonblank, or at line end
Multiline normal input o O Open a line below/above and insert
Normal input x, u, Ctrl-R Delete, undo, redo
Normal input Numeric prefix Count for motions, delete, undo/redo; Ngg/NG select a line
Normal input v, V, Ctrl-V Character, line, or block visual selection
Insert input (select) any text, backspace, arrows, esc After Input.SelectText/SelectAll (or outline.add {text, select: true}): typing or pasting replaces the selected text, backspace/delete removes it, a motion or esc keeps it (UX-RULES R9.6)
Normal input yy, p, P Yank a line; paste after/before
Normal app g y Open shared yank history (ctrl+y until this release; ctrl+y is now Vim's line scroll)
Normal input "a Select named register a for the next operation
Normal app/input qa … q, @a, @@ Record macro a, replay it, repeat the last macro
Insert input Ctrl-A/E, Ctrl-B/F Line start/end, previous/next rune
Insert input Ctrl-P/N, Alt-B/F Previous/next line, previous/next word
Insert input Ctrl-W/U/K, Ctrl-Y Kill path component/to line start/to line end; paste the app's current yank
Insert input Backspace, Delete/Ctrl-D, Enter Delete backward/forward; newline in multiline inputs
Insert input Escape Return to normal mode
Normal input Escape Cancel a pending operator, count, prefix or register
Normal app/input : Open the palette's command line
Any editing mode Ctrl-Space Open palette without stealing Readline Ctrl-P
Normal Playground Ctrl-O Open the shared picker using the field's filter
Normal path/paths field Enter Open picker using the current value/line
Normal Playground / draft Ctrl-N Open a draft / nest another draft
Draft modal Ctrl-G Close and restore the parent
Normal Playground Ctrl-X Inspect the handling noun
Normal app ? Open the scrollable keyboard guide
Insert (any input) Ctrl-\ Open the keyboard guide (? types itself there)
? keyboard guide Tab / Shift-Tab, S Next / previous view (here, pick, table, wrapping; bindings-help.view {step}): tab cycles the views of anything with views, and in a search line the match mode
Normal list / Filter the list's rows (see Filtering a list)
Normal list gg, G, NG/Ngg First row, last row, row N (list.goto; clamps, never spills)
Normal list Ctrl-D/U, Ctrl-F/B Half a page / a page down and up, the window moving with the selection (list.scroll; 3 Ctrl-D is 3 rows, 2 Ctrl-F two pages)
Normal cell table (CellSelect) h/l, 0/^/Home, $/End, N|, gc Move the current column: one left/right (counts), the first, the last, column N, a chooser of titles (list.column, list.choose-column); the view scrolls to show it
Normal cell table y Copy the current cell into the registers (list.yank)
Normal cell table z>, z<, z= Widen / narrow the current column by 2 cells (counts), every column automatic again; remembered per table (list.resize-column, list.reset-columns)
Normal table Y Copy the row's cells joined by tabs into the registers (list.yank {what: row})
Normal table V Visual row selection over the marks: j/k extend it, a row's verb then runs for every selected row (one confirm), esc ends it (list.visual, list.end-visual)
Normal table zl/zh Scroll the columns one right/left; the pinned columns stay (list.scroll-columns)
Normal row table (the default) l/h Scroll the columns one right/left; at the last column / the start move the focus to the next / previous stop (list.scroll-columns, focus.next/focus.previous)
Normal row table (the default) $, ^/0 Scroll to the view with the last column / back to the first (list.scroll-columns)
Normal cell table zp Pin or unpin the current column (list.toggle-pin-column); any table: list.pin-column, unpin-column, unpin-columns from the palette
Normal Appearance t, d Cycle theme / density
Normal demo Ctrl-J/K Next/previous page
Normal page with a list/detail split >, <, = Grow / shrink the list pane by 5% (counts: 3>), reset the divider; remembered per page
App or modal PgUp/PgDn Scroll the active surface
App Ctrl-C Quit (q is reserved for macro recording)
Attached terminal any key Forwarded to the pane; Ctrl-A is the leader (d detach, Ctrl-A literal, bound key runs, other key sends both, timeout sends the leader)

On terminals where Option does not send Meta sequences, configure Option-as-Meta to use Alt-B/F. Ctrl-Space is received as ctrl+space by Bubble Tea v2 (v1 spelled it ctrl+@). Every row above is a registered binding: the demo's on its nouns and instances, the editor's in editor_bindings.json. bindings list prints the rows the focus answers to in its current mode, pending modes included, so 2, d or " followed by bindings list shows the count, operator or register table.

Palette and selectors

  • : opens the palette: an ex-mode command line, one prompt input (insert pinned, the Readline rows edit it: Ctrl-W deletes a word, Ctrl-U the line). The line's text is the command; there are no stages.
  • Words resolve left to right. The first word is a verb or a noun; the second is the complement (a noun that has the verb, or a verb or instance of the noun); then the operation's parameters in order (required first, then by name). Every word may be a unique prefix (tr r up); an ambiguous prefix stays unresolved and the list shows its candidates. A first word that is a prefix of exactly one verb and one noun takes the reading the next words resolve. A value with spaces is quoted (add note "two words").
  • Omit the noun and the verb acts for the nearest instance on the focus path whose noun has it: on a CSV cell transform upper changes the cell, transform row upper the row under the cursor, transform column upper the column, transform selection upper the selection (offered only while one exists; verb guards hide verbs the focus does not answer to). The cursor never moves.
  • The list under the line completes the next word, grouped verbs, nouns, then parameter choices, narrowed by the word being typed. Typing :v, :n or :p as the word restricts the list to verbs, nouns or choices; the code is consumed, not appended, and lapses at the next word.
  • Nothing is highlighted until Ctrl-N/Ctrl-P moves onto the list; typing clears the highlight. Enter or Tab on a highlighted entry appends its word and a space. Enter with nothing highlighted runs the line as typed. A line whose verb still lacks a required word opens the args form: a field per parameter (required first, optional ones marked), the typed words filled in, the first missing one focused; choices and noun-typed words are picked from a type-to-filter chooser. enter runs the verb once every field is valid and otherwise moves to the field that still needs a value; esc (from normal mode) cancels, runs nothing and gives the line back as typed. A key whose binding row leaves a required argument out opens the same form. A path parameter's field opens the path chooser (sources browse, recent, typed and the application's; ctrl+o cycles them (alt+o back; tab cycles the match mode), enter/ctrl+l browse into a folder, alt+up or backspace on an empty query goes up, alt+enter picks the highlighted row). A choices source that declares a query parameter is called with the word typed so far, so it completes as you type. With the setting palette.missing-opens-form off, an incomplete line stays and the error names its first missing word (missing name (string, pick)). The CLI and the API still fail with NAME is required. Tab with nothing highlighted completes a word that has one completion.
  • Esc clears a non-empty line, then closes; Ctrl-C closes. Up and Down recall earlier lines from the action history (entries with the source palette, which every request a line runs is recorded with).
  • The originating interaction context is captured before the palette opens. undo input edits the originating input, not the palette's line. A failing request reopens the palette with the line and the error.
  • Commands returning a JSON array of objects open a read-only Results modal (for example, operations list or jobs list). This also accepts typed Go slices/arrays and encoded JSON. Columns with fields present in every row come first, followed by less common fields in descending occurrence count; ties sort alphabetically. Missing fields are blank, explicit nulls read null, and nested values are compact JSON. Long cells truncate and rare columns drop first at narrow widths. j/k navigate; Esc closes and restores the originating focus. Empty lists show No rows; non-object results are unchanged. Only palette execution presents results: direct bindings, API/CLI calls, refreshes, and completion sources do not open a table.
  • A verb declared with .TextResult() (Operation.Result ResultText, "text"; the catalog's result, so a host mounting another tool's verbs keeps it) answers text to read and copy: a jq program, a JSON mapping. The palette opens its answer in the text view (Runtime.OpenTextView(title, text), modal text-view): a read-only input (Input.ReadOnly, the ReadOnly() option of AddInput), one line when the text is one line, else multiline, cursor at the start in normal mode. A string shows as it is, any other value as indented JSON. The editor's motions, v/V/ctrl+v, y/y y and "ay work there; edits are silent no-ops and the editing verbs are unavailable (guards input-writable, input-operator-writable), so their rows leave the hints. q (a row of bindings/text-view.json) or esc closes it back on the focus the palette opened over. A text longer than the modal scrolls in a window of fixed height, the header saying which lines show (1–20 / 60), and the modal is as wide as the whole text's widest line, so scrolling never resizes it. Setting palette.text-results: editor (default), all (any string answer opens it too, declared or not), plain (as before: a text result shows nothing unless it is a JSON array). The CLI and the API return the value unchanged. Stories palette/text-result-*. Compared with Vim: the view is a buffer with 'nomodifiable' set (:help 'modifiable'): the same keys move, select and yank, but an edit is refused silently where Vim says E21, and i/a/o do not enter insert mode at all. A focused read-only input owns the editor's keys: the editor table answers right after the input (before the page), so its motions win over page rows in every mode and an edit key is consumed instead of reaching a page row; Input.SetText refreshes its text from the program. Opened again while open, the text view shows the new text (ReplaceOpen).
  • Pending commands present their results after delivery and their existing Then callback. Failed, cancelled, orphaned jobs, or results arriving while another modal is open do not open a table; an existing modal is never replaced.
  • Instance sources explicitly declare their default verb and ID argument: page playground runs page.open {id: "playground"}, and the instances are also the choices of that argument (open page playground). The full-project example configures these defaults in JSON.
  • Scripts drive the line through the same registry: palette set {text} replaces the line, palette run presses Enter, palette complete {value}, palette move {delta}, palette recall {delta}, palette cancel. Each returns the palette state: the line, its parsed words, the operation, missing word and the completion entries.
// The grammar, one example per form (focus on the cell r1:c1 of row r1)
"transform row upper"   // verb noun arg      -> { key: "row.transform", target: "r1",    args: { name: "upper" } }
"row transform upper"   // noun verb arg      -> same request
"tr r up"               // unique prefixes    -> same request
"transform upper"       // noun omitted       -> { key: "cell.transform", target: "r1:c1", args: { name: "upper" } }
"page playground"       // noun instance      -> { key: "page.open", args: { id: "playground" } }
"t r up"                // "t" is ambiguous: tidy, transform -> stays, list shows both
"transform row"         // incomplete         -> the args form asks for name (setting off: "missing name (string, pick)", line stays)
"transform :p"          // filter code        -> line "transform ", list shows only choices
  • The shared path picker uses an editable absolute path and a Readline-only editor. Ctrl-N/P moves through results without moving the text cursor. Other Readline bindings still edit the path; / and whitespace delimit Ctrl-W kills, while dots and hyphens remain part of a filename.
  • Tab completes the highlighted result into the picker's path input without confirming or closing it. Directories receive a trailing separator for continued browsing; the originating field stays unchanged until confirmation.
  • Escape cancels immediately without changing the originating input. Alt-Up browses the parent directory. Enter opens a directory/selects a file, and Ctrl-S confirms a path. Letters always edit the path; the picker never enters Vim normal mode.
  • Results recursively fuzzy-match the full relative path. Native Git supplies .gitignore semantics, including nested rules, negations, repository excludes, and global excludes; Git must be on PATH. Non-repositories use temporary Git metadata outside the browsed tree. .git and directory symlinks are never traversed.
  • Results are a table (path, size, modified) laid out by the same code as a list with columns (table.go): a header under the Results n/m line, the size right-aligned, … cuts, and modified then size dropping as the results pane narrows; the path takes the rest. Size and modification time are statted lazily: the index walk never stats; only the rows the table draws are looked up, off the loop in the picker's stat slot, cached per path (an LRU of 4096, cleared when a new index starts); a row draws blank cells until its stat lands, and the fixed column widths keep anything from moving. Directories show no size. The selected result keeps the picker's own > marker and is the one reversed row.
  • The picker publishes immediate children first, then builds the recursive index in the background. Listed paths remain selectable and Tab-completable while indexing continues. Query edits search the available index; recursive results preserve the highlighted path when it still matches. Canceled or stale results cannot overwrite newer results. A recursive failure keeps usable shallow results and shows Index incomplete.
  • Leading ~ and ~/ resolve to the home directory. Explicitly opening a directory excluded by an ancestor repository's ignore rule makes that directory a fresh ignore boundary, so a home-repository rule such as proj/ does not hide every project. Root-local, nested, and global ignore rules still apply.
  • Ctrl-S confirms the highlighted result; an empty query includes a current-directory entry for any/dir. The action picker.choose {current:true} explicitly chooses the root. Changing the originating text while the picker is open rejects selection instead of replacing stale offsets.
  • The split view pairs results with the selected entry's metadata and a text or directory preview. Narrow terminals retain the list and selected-entry metadata. Preview work runs outside the UI loop, limits displayed file content to 64 KiB or directory listings to 128 entries, and ignores stale deliveries after selection changes or reopening. Symlinks show their target without following it; binary and special files do not display raw contents.
  • Controls are ordinary rows of the picker noun in insert mode; the path field is a prompt input beneath it. Override or add them with r.Define("picker").Mode("insert").Bind(...) or a binding file row ("request": null removes one). The picker help is derived from bindings.list, so remapped and removed controls are reflected without changing the renderer. No function keys are assigned.
Standard verbs on the line

A noun with props and a store (props.go, standard_verbs.go) reads one grammar in the palette and the CLI (standard_grammar.go, Runtime.ReadNounWord):

"task get"                      // the focused task's props: prop and value rows in the results view
"task get t3 status"            // one prop of t3; "task get status" is the focused one's
"task set status done"          // the first word is a prop, so the subject is the focus
"task set t3 status done"       // any other first word is the key
"task set title=Ship estimate=5" // several props
"task set --id status status done" // a key that equals a prop name: --KEY (the flag named after the key prop)
"task status"                   // NOUN PROP reads it; "task status done" writes it; "task starred --toggle" flips it
"task list --where status=todo" // --NAME VALUE names any parameter, as on the CLI
  • After a noun a word is a verb, else a prop, else a key or an instance (owner decision 18): an exact verb, an exact prop, a unique verb prefix, a unique prop prefix. NOUN KEY alone keeps running a palette noun's default verb. NOUN PROP [VALUE] is a prop-shaped request ({noun, prop}, {noun, prop, value}, {noun, prop, toggle}), so history keeps it as typed; from the CLI it is bin task status done --id t3.
  • The key word after a verb is optional: when the first word is the next parameter's (a prop name, or prop=value after set; Operation.SubjectOmitted, read from the parameters' Enum and Pairs), the subject comes from the focus, a target or --KEY.
  • Completion: the props follow the verbs after a noun; after set the props come before the things; after set PROP and NOUN PROP the prop's values (Parameter.ValueOf: its Enum, a boolean's true/false, a reference's things); where (Parameter.Pairs) completes prop= (taking it leaves the cursor after the =) and then that prop's values.
  • :set NOUN ... (the set bare alias) reads only one-value nouns: a noun whose set is its own (mode, focus, palette, register, confirm, setting, settings, appearance) or whose store is a singleton. A collection's standard set is NOUN set ..., never set NOUN ..., so :set pa offers the palette.* and path.* settings and the palette noun, never a collection named parcel. A registry test checks that every declared setting reads as a setting.
  • palette.standard-verbs (a list, default [last, tag, record]) is the one opt-out for how the palette shows standard verbs: last lists a noun's named verbs first, mixed one alphabetical list, hidden leaves them out of the verb list (typing the name, the CLI and bindings still reach them); tag marks them std; record shows a get as prop and value rows. A part left out is the palette before standard verbs, so [] turns them all off. The ? help lists bound keys only, so it is unchanged.

Compared with Vim: :task status done reads like :set {option}={value} (:help :set), but it acts on a thing, not an option, and the key word is the thing's name; :set itself is unchanged and reads only settings and one-value nouns. --NAME words have no Vim counterpart on the command line; they mirror the CLI.

Configuring noun instances

NewPalette supplies live page instances with page.open as their default. Applications can replace that configuration or register sources for their own nouns:

err := model.Palette.RegisterNoun("page", ochazuke.PaletteNoun{
    Source: ochazuke.PagesPaletteSource,
    DefaultVerb: "open",
    Argument: "id",
})
if err != nil { return err }

A PaletteSource receives the runtime and originating context and returns []PaletteInstance, each with an ID, a Label and an optional Word: the word the palette offers and takes for it instead of the id (PagesPaletteSource sets it to the page title, so :page open lists JSON ext/json and takes JSON or "Pull Requests"; the id, or a prefix of it, still names the page). A choice from a Source may carry one too (Choice.Word, a word key in a {id, label, word} row). Setting palette.choice-words (word default, id the ids as before). An instance word after the noun passes its ID to the configured argument, then dispatches through the normal operation path. The source is queried live (again after every edit of the line) so newly registered pages appear without rebuilding the palette. After a noun a verb wins over an instance of the same name; the instance stays reachable as the default verb's argument (page open open).

Argument choices

A Parameter with Enum (static values) or Source (an operation key such as transformations.list whose result is []string, []{id, label} or []any of either) completes in the palette: at that parameter's word the list shows the choices (a boolean completes true/false), the word is a unique prefix of a choice's id, and Ctrl-N/P then Enter or Tab appends a highlighted one. A value outside the choices is refused, by the palette and by Execute, unless the parameter sets Free. A source is called at execution to validate; if it fails, validation is skipped rather than blocking the operation. operations.list publishes the fields, and ochazuke NOUN VERB --help prints the choices from the running app.

A Parameter with Noun (and no Source) names one of that noun's things: its choices are the rows of NOUN.list when that verb is registered, asks no confirmation and needs no argument (it then stands in for the Source, off the loop for an application verb, and cli.Catalog and cli.Mount publish it as the source), else the ids of the noun's live instances, labelled by their labels: instances in registration order, each list followed by its rows of the noun (every row, filtered out or not, in list order; the row instance id, never a foreign id in Data). Map rows give their id as id, key or name and their label as label or title; []Operation rows are noun.verb. Enum values come first and an explicit Source wins; a Noun adds no validation at execution. The framework marks page.open id (pages), mode.set/mode.enter mode (modes), confirm.set operation (operations), list.focus id (list, free) and input.focus id/modal.push input (editor, free).

// Parameters of transform.apply
{ name: { type: "string", required: true, source: "transformations.list" },
  case: { type: "string", enum: ["upper", "lower"] },
  tag:  { type: "string", enum: ["draft"], free: true } }
// transformations.list returns ["trim", "dedupe"] or [{ id: "trim", label: "Trim spaces" }]

Readline-only inputs: the prompt noun

Register an input as an instance of the prompt noun:

prompt := ochazuke.NewInput("prompt", "", false)
if err := r.AddInput(prompt, ochazuke.Kind("prompt")); err != nil {
    return err
}

prompt pins insert mode: registration starts the editor in insert mode and SetMode/mode.set keep it there. It binds nothing of its own, so the editor's Readline rows apply and Escape, which only returns insert mode to normal, has no effect; a page, modal or noun on the stack may bind Escape to cancel its own UI, as the picker does. Single-line and multiline editing, path-aware kills, shared yanks, and undo/redo use the existing implementation. Inputs of the default editor kind keep their Vim/Readline behavior.

Path fields

One picker handles files and directories. Field kind determines replacement behavior; its separate filter controls eligible results:

directory := ochazuke.NewInput("directory", "/tmp", false)
directory.Kind = "path"
directory.PathFilter = "dir"

paths := ochazuke.NewInput("paths", "/tmp\n.", true)
paths.Kind = "paths"
paths.PathFilter = "any"
Field kind Picker starting context Selection result
Empty / text Working directory or explicitly supplied path Insert at the cursor captured when opened
path Entire field value Replace the entire value
paths Current line Replace only that captured line, preserving the rest

Filters are file, dir, and any. A paths field is an ordinary multiline editor: motions, o/O, visual selection, registers, yanks, macros, and undo operate on its text. It does not serialize a JSON array or use a separate chip/list widget. Filenames containing a newline cannot be represented as one path per line and are rejected rather than silently splitting the set.

/tmp/ochazuke picker open --json '{"filter":"file","path":"/work"}'
/tmp/ochazuke picker choose
/tmp/ochazuke picker close

Applications constructing their own picker only add its modal renderer; NewPicker registers the picker instance whose Component the runtime drives through the delivery contract:

picker := ochazuke.NewPicker(r)
model.ModalViews["picker"] = ochazuke.ModalView{
    Title: "Choose a path",
    Render: func(_ *ochazuke.Runtime, _ *ochazuke.Instance, w, h int) ochazuke.Block {
        return picker.ViewBlock(w, h)
    },
}

Selectable lists

List reuses the stack walk, binding rows, and bounded row-rendering helpers. The application owns records; each row names a registered noun, and the list turns every row into an instance of that noun under the list:

r.Define("worktree").Verbs("open", "remove").Mode("normal").Bind("o", ochazuke.Do("worktree.open"))
items, err := ochazuke.NewList(r, "sidebar", []ochazuke.ListItem{
    {ID: "repository", Label: "Repository: ochazuke", Noun: "repo"},
    {ID: "main", Label: "Worktree: main", Noun: "worktree"},
}, ochazuke.Parent("workspace"))
if err != nil { return err }
if err := items.Focus(); err != nil { return err }

The id (sidebar here) identifies the list instance (r.List("sidebar") returns it); the list instance answers to the list noun (Kind picks another). Render items.View(width, height) inside an existing page or panel. It keeps the selected row visible as selection or viewport size changes. Default normal-mode j/k, up/down and Space (toggle mark) are rows of the list noun; a row's noun sits inside the list on the stack and can override them, and a row instance may carry its own rows above its noun's.

  • Focus() points the focus at the selected row (or the list when empty). Runtime.SetFocus(id) switches to another instance; the old selection remains, but its rows are no longer active. A list is one focus stop: } and tab leave it for the next stop, and jumping back lands on its selected row (FocusTarget).
  • Move(delta) and Select(itemID) change selection without stealing focus. Selected() returns the selected value and whether one exists.
  • SetItems(rows) copies the records and preserves selection by stable ID. It creates the instance of each new row under the list (Instance{ID: item.ID, Noun: item.Noun, Parent: <list>}) and removes the instances of rows that disappear; a retained row keeps its instance and marks. A removed selection falls back to its previous index, clamped to the remaining rows. An empty list focuses the list itself. An empty or duplicate ID, an unregistered noun, or an ID that is already another instance rejects the whole update.
  • Refreshes also move every focus reference (the focus, a page's remembered focus, a modal's return) that pointed at the list or a removed row to the selected row (RetargetFocus), so returning from another page/modal cannot restore a removed row's rows.
  • ToggleMark(id) and Marked() keep a multi-selection. list.apply {verb, args} runs <row noun>.verb with the row as target and args as its arguments for every marked row (the selected row when none is marked), skipping and reporting rows whose noun lacks the verb; a verb with a confirm asks once for all the rows.
  • Call these methods on the runtime's event loop. Data loading and domain actions remain application-owned. There is no tree expansion or built-in search provider.
Moving through a list

Every list (page lists, tables, trees, a catalog page's lists, the Settings page's, lists in modals such as ? help) answers the Vim paging motions in normal mode, rows of the list noun beside j/k, so a row noun, the list instance or a component that binds the same keys answers first:

Keys Operation Does
g g / G list.goto {position, row} The first / last row; with a count the row of that number (5G, 5gg), clamped
ctrl+d / ctrl+u list.scroll {delta, half} Half a page down / up; a count is rows (3 ctrl+d)
ctrl+f / ctrl+b list.scroll {delta} A page down / up; a count is pages
ctrl+e / ctrl+y view.scroll {lines} The window a line down / up, the selection staying unless it would leave the window's scrolloff margin (then it moves to the nearest row inside); a count is lines (5 ctrl+e), as Vim's CTRL-E/CTRL-Y

A page is the rows the list's own window showed in the last frame when the list windows itself, else the height of the page body it is drawn on (a list drawn at its full length on a scrolling page), else the rows it showed (a list in a modal), else 10 before any frame. The window moves with the selection by the rows moved, so the selected row keeps its line (Vim's ctrl+d), and the scrolloff margin then applies as for j/k. None of them spills to the next stop: at the list's edges they stop quietly. They are motions: off the footer, under movement in ? help. pgup/pgdn still scroll the surface without moving the focus. Story: lists/page-motions.

ctrl+e/ctrl+y are rows on app in normal mode (bindings/scroll.json) to one verb, view.scroll {lines, count}, for every scrollable: it scrolls the innermost component on the focus path that windows its lines (LineScroller: CanScrollLines, ScrollLines; a list, so tables and trees, a timeline, a markdown document; a component held by another scroller, a timeline's card list, defers to its holder), else the page's detail while it overflows (as J/K do). With nothing to scroll the verb is unavailable and the key does nothing. A component of an application scrolls the same way by implementing LineScroller. The timeline's own ctrl+e/ctrl+y rows (timeline.scroll) answer first on a timeline. Compared with Vim: the same, but a list that shows every row (drawn at its full length on a scrolling page) has no window of its own, so the key falls to the detail or does nothing; on a table with tall rows a line is a row; an editor's text does not scroll yet. Stories: scroll/ctrl-e-ctrl-y-list, tables/ctrl-e-scroll, markdown/ctrl-e-scroll, detail/ctrl-e-scrolls-detail.

Tables select rows; cell mode is opt-in

A table (a list with columns) selects rows. Only a table added with CellSelect() (an InstanceOption for AddList; for a table one reads cell by cell, such as a JSON or CSV view) has a current column as well as a selected row, the way a spreadsheet (o-csv, on grid) has a current cell. Every other table, trees' lists, the ? help modal, the Settings page and cli catalog tables included, leaves h/l to its row nouns: where the row noun does not bind them, l scrolls the view one column right until the last column shows and then moves the focus to the next stop, h scrolls back to the start and then moves it to the previous stop (the horizontal twin of the j/k spill; a modal, a NoSpill list and the page's first or last stop clamp), $ scrolls to the view with the last column and ^/0 (without a count) back, z l/z h one column (list.scroll-columns). RowSelect() is a deprecated no-op kept for code written against v0.12.0.

Pinned columns draw first, in declared order, and never scroll; the default is the columns declared Column.Pinned, else the first column. list.pin-column {column}, list.unpin-column {column}, list.toggle-pin-column {column} (z p on a cell-mode table) and list.unpin-columns change them on any table (column is a title or a 1-based number; without it a row-select table opens the column chooser), list.reset-columns (z =) puts the default back, and a user's pins are remembered per table in tables.json. When the pins leave no room for a scrolling column the view leaves pins out from the right (the saved pins stay). A table with a header whose columns do not fit reserves 8 cells and marks its edges: ‹N after the pinned columns, N› at the right edge, N the scrolling columns hidden on that side.

On a cell-mode table the row keeps the list's one highlight; the current cell is drawn underlined inside it, the header underlines the current column's title, and an unfocused table fades both with the list. Rows of the list noun in normal mode that answer only on a cell-mode table (table_cells.go), except where the table says every table:

Keys Operation Does
h l left right list.column {delta, steps} One column left / right in drawing order (pins first); a count is columns; on the first / last column focus.previous / focus.next instead (clamped in a modal, on a NoSpill list, at the page's first / last stop)
0 (no count) ^ home / $ end list.column {to} The first / last column
N | list.column {index} Column N (`3
g c list.choose-column A chooser of the column titles
y list.yank {what: cell, register} The cell's text into the registers ("ay names one)
Y list.yank {what: row, register} Every table: the row's cells joined by tabs
z > / z < list.resize-column {delta, steps} Widen / narrow the current column by ColumnWidthStep (2) cells, never below 3
N z f list.fit-column {width} The current column as wide as its widest cell over every row or its title, at most the table's width; with a count N cells (20 z f)
z F list.fit-columns Every table: every column at its content's width when they fit; else the widest narrowed first (never below its least width) so as few columns as can be are cut; answers only where it changes a width
z = list.reset-columns Every table with a width given or pins chosen: every column automatic again, the default pins back
z p list.toggle-pin-column Pin or unpin the current column
z l / z h list.scroll-columns {delta, steps} Every table that scrolls: the view one column right / left; on a cell-mode table the current column is carried along when it scrolls off
V, then esc list.visual {on}, list.end-visual Every table with marks: visual row selection (below)

j/k keep the column. Each frame scrolls the column offset as little as shows the current column: the first column stays (it names the row), a column dropped by Priority or past the right edge comes into view as the column reaches it, and the first column brings the unscrolled view back. The movement keys are motions (off the footer, under movement in ? help); y, Y, V and the width keys are hidden from the footer too and listed in ? help. A row noun that binds one of these keys answers first (the walk is inner-first): that table keeps the app's key and loses the cell key. enter is unchanged, the row's default action. The width keys need a current column, so they answer on cell-mode tables only, except z F and z =, which need none. A cell-mode table's current column, every table's widths (z >, z <, z f, z F, SetColumnWidth) and pins are remembered per table id in the state directory's tables.json (Runtime.TableState, SetTableState; in memory without a state directory; TableState.Version marks widths a row-select table may read, so widths left by v0.12.0 stay ignored there).

z f and z F are sticky: they write fixed widths, the ones z >/z < give, so moving the cursor, scrolling or filtering never reflows the table; only the next width key or z = does, and rows that arrive wider than a fitted column are cut until the next fit. The table.fit-follows-cursor setting (default off) makes a cell-mode table lay its current column out at its content's width as the cursor reaches it, the column going back to its width when the cursor leaves; nothing is written, and a width given with a width key wins. It is off because it shifts the columns as the cursor moves. Stories tables/fit-column, tables/fit-columns, tables/fit-follows-cursor.

Compared with Vim: columns stand in for windows. z f is ctrl-w _ / ctrl-w | (:help CTRL-W_|): without a count Vim makes the window as wide as it can be, here the column as wide as its content needs (at most the table's width), and N z f sets N cells as N ctrl-w | does. z F is like ctrl-w = (:help CTRL-W_=), which ignores a count too, but sizes each column to its content, not to equal shares; when they do not fit it narrows the widest first. z = keeps its meaning here, every column automatic again, and also undoes z f and z F. table.fit-follows-cursor is Vim's 'winwidth' (:help 'winwidth') set to the content's width: the current column grows on entering it; unlike Vim, the column it leaves goes back to its own width, so only the current one changes. API: List.Column, SetColumn, ColumnWidths, SetColumnWidth, ResetColumnWidths, ColumnOffset, PinnedColumns, SetPinnedColumns, PinColumn, UnpinColumn, UnpinColumns, ResetPins.

A host's own h "back" row on a table should take the guard list-first-column (cli's groups rail does): on a cell-mode table h then moves left and goes back only from the first column; on a row-select table it holds, so h goes back at once. An instance row answers before the list noun's, so a host's h back row wins over the table's scroll and spill.

V starts a visual row selection at the selected row on any table (not on a NoMarks one). It is the marks: while it lasts they are the marks V found plus every shown row between the anchor and the selection, so j/k, counts and the paging motions extend it (they clamp instead of spilling), the * gutter draws it and list.apply fans out over it. The mode stays normal, so the rows' keys still answer; a key whose row runs an application verb of the row's noun runs it for every selected row through list.apply, with one confirm when the verb has one, and ends the selection. esc (or V) ends it without running anything. Either way the marks go back to the ones V found; space during it toggles those.

The design is in docs/UI-MODEL.md "Tables". Stories: tables/cell-motion, tables/column-count, tables/column-resize, tables/visual-apply, tables/unfocused-cell-dimmed, tables/column-motions, tables/row-select, tables/scroll-then-focus-{right,left}, tables/cell-edge-focus, tables/nospill-clamps, tables/modal-clamps, tables/row-noun-l-wins, tables/edge-markers{,-start,-fit}, tables/pin-{cell,row-palette,declared,narrow}, tables/unpin-columns, catalog/groups-table-h; an o-story list opts in with cellSelect, a column with pinned.

Filtering a list

Every list filters: / on a focused list (a page list, a table, a catalog page's list, the Settings page's, a list in a modal) opens a query line above its rows, and typing keeps the rows whose label or cells hold every word of the query, in list order, comparing case as the search.case setting says (below; by default idle finds IDLE too, IDLE only IDLE):

/idle                                                                 2 of 4
pane                  harness      state    cwd
work/claude           claude-code  idle     ~/proj/matomeru
play/pi               pi           idle     ~/proj/nabe
Keys (mode list_filter) Does
printable keys, space, paste list.filter-type: add to the query
backspace / ctrl+h list.filter-erase; on an empty query list.filter-keep (leaves the line)
up/down, ctrl+p/ctrl+n list.move {clamp}: move among the matches, never spilling
enter list.filter-keep: back to normal mode with the filter kept (the line stays; / edits it again). On a list added with ClearFilterOnEnter() (or a tree), with a match: list.filter-choose, which clears the filter, keeps the selection on the match and goes back to normal mode
esc list.filter-clear: clear the filter and select the row / found
ctrl+u list.filter {query: ""}: empty the query
tab / shift+tab search.cycle-match {step}: the next (previous) match mode, below

In normal mode esc on a filtered list clears the filter (list.filter-clear, guarded off on an unfiltered list so esc there stays the outer level's). The / row is an app row guarded by list-filterable and added after the Model's defaults: an application's own / on any level (its row noun, the list, the page) answers first, and the footer's / filter is the hint a narrow footer cuts first.

Match modes

Every search matches its query one of three ways, and the / list filter, choosers and the path picker share them (search_match.go, Matcher):

Mode Tag A row matches when
substring substr it holds every whitespace-separated word of the query, in any order
fuzzy fuzzy the query's characters appear in it in order (one scorer, fuzzyScore, ranks choosers and the picker)
regex regex the Go RE2 pattern matches it; a list row's label and cells are its lines, so ^ and $ match at each cell's ends

search.match (ochazuke › Search, default substring) is the mode the list filter starts in, chooser.match (default fuzzy) the one choosers and the path picker start in, so the defaults match as before. tab in the filter line or a chooser (ochazuke.search.cycle-match {step}; shift+tab steps back) and ctrl+t in the path picker step the open search through substring, fuzzy, regex and round again; search.set-match {mode} picks one. Neither writes the setting: the mode belongs to that list's filter, that chooser or that picker open. The search line shows the mode at its right end (/al 2 of 5 substr); search.show-match off hides the tag. An invalid regex matches nothing and the line says why (regex: missing closing )), never a modal. search.case applies to all three; for a regex, folding is the (?i) flag and smart case looks for a capital outside escapes (\S, \W, \p{Lu} are syntax, not capitals). A chooser whose application passes its own Filter, or whose Live source ranks its rows itself, keeps that matching: the verbs are unavailable there and no tag shows.

Compared with Vim: Vim's / is always a regex (:help pattern) with its own magic levels (:help /magic, \v "very magic" is closest to RE2's extended syntax); ochazuke's regex mode is RE2, not Vim's dialect, and has no \c/\C (case comes from search.case). Vim has no substring or fuzzy search mode; fuzzy matching is matchfuzzy() (:help matchfuzzy()), used by plugins and completion. Vim's smartcase likewise ignores the letter after a backslash (:help 'smartcase').

Case in searches

Every search and filter the framework runs compares case the same way: the / list filter (tables and trees too), choosers (matching, ranking and word spelling), the path chooser's browse and typed completion, and the path picker's fuzzy search. The setting search.case (ochazuke › Search) says how: smart (the default) ignores case unless the query holds an upper-case letter, then matches case exactly (readme finds README.md and readme.txt, README only README.md); ignore always ignores it (the behaviour before the setting); sensitive always matches it. A capital is any letter unicode.IsUpper reports (É, Σ), never a separator, digit or punctuation; in typed path completion only the name being completed counts, so Docs/read still finds readme.txt in Docs. With no capital in the query, smart ranks the picker's results exactly as ignore does. Identifiers are not searches and keep their own case-insensitive lookups: palette words, verb, noun and setting names, :set completion, column titles, key names. An application's own search reads the same rule with Runtime.CaseFor(query) (a CaseMatch with Contains, HasPrefix, String, Rune), or CaseFor(mode, query) with Runtime.SearchCase() read on the loop for work that runs off it; examples/csv's column filter does. Stories: lists/filter-smart-case, lists/filter-ignore-case, forms/path-smart-case-browse, forms/path-smart-case-typed, forms/path-ignore-case.

Compared with Vim: smart is :set ignorecase smartcase (:help 'ignorecase', :help 'smartcase'), ignore is ignorecase alone and sensitive is noignorecase; the capital test is Vim's (an upper-case letter typed in the query). Vim applies smartcase only to typed patterns, not to */#, which ochazuke does not have yet. Not here: the \c/\C pattern overrides (:help /\c), and Vim's separate 'wildignorecase'/'fileignorecase' for file-name completion: the path chooser and picker follow search.case like every other search.

The filter hides rows from drawing and from motions (j/k, counts, spills) and never removes them: their instances, marks and data stay. SetItems and List.Patch (which patches every row, hidden ones included) while filtered filter the new rows and keep the selection by id; list.apply fans out to the marked rows the filter shows (a mark on a hidden row waits); a command that lands on a hidden row (Select, focus.set, a job's focus) clears the filter. Items() and Len() are every row; Shown() counts the shown ones, Filter() is the query, Filtering() reports the line, SetFilter(q) sets it, and Height() (Len() plus the line) is what a host sizing a list to its rows passes to View. The CLI form is list filter --target LIST --query Q (an empty query clears); the state at /lists/<id> then has filter and total, and its items are the shown rows. Stories: lists/filter-*, catalog/filter-setitems, tables/filter-by-cell, settings/filter.

The operation equivalents are list.focus {id}, list.move {id?, delta, clamp?}, list.goto {id?, position?, row?}, list.scroll {id?, delta, half?, steps?}, list.scroll-columns {id?, to?, delta?, steps?}, list.column {id?, to?, index?, delta?, steps?}, list.choose-column {id?}, list.yank {id?, what?, register?}, list.resize-column {id?, delta, steps?}, list.reset-columns {id?}, list.pin-column {id?, column?}, list.unpin-column {id?, column?}, list.toggle-pin-column {id?, column?}, list.unpin-columns {id?}, list.visual {id?, on?}, list.select {id?, item}, list.mark {id?, item?}, list.apply {id?, verb, args?} and list.filter {id?, query}. Omit id to operate on the list on the focus stack. State is inspectable under /lists/<id> (rows show their noun, marked lists marks) and /instances/<rowId>. The full-project example's Items page mixes repo, worktree and branch rows in one list: each row answers to its noun's verbs and keys, ? lists the focused row's rows, and Space plus list.apply fans one verb out over several rows.

Outline nodes that refuse a change

In normal mode an outline nests a line with tab or Vim's > > (outline.indent) and takes it out with shift+tab or < < (outline.outdent); > >/< < are rows of bindings/tree.json (story tree/outline-shift-operators). Compared with Vim: one line per press, no count or motion (3>>, >j) yet.

An editable tree (AddTree with OnChange) writes every add, rename, move and delete as a TreeChange. A node refuses changes by data: TreeNode.Fixed lists rename, move (move, indent, outdent) and delete (deleting it or any ancestor), so a document root is {"fixed": ["rename", "move", "delete"]} and an array item, whose key is its index, {"fixed": ["rename"]}. The verbs a node refuses are not available on it (guards outline-renamable, outline-movable, outline-deletable): their keys do nothing, their hints drop out, the palette does not offer them, and the API and CLI are refused. Tree.Refuse func(node TreeNode, change TreeChange) error is the application's own check on any change (for an add, the node is the parent); its error is the reason the status line shows. Undo and redo are not checked.

Terminal instances

A terminal is an instance of the terminal noun whose component shows a pane the application streams in. The framework owns no PTY, shell or daemon: AddTerminal(id, stream, Parent(page)) takes a TerminalStream (Next(ctx) blocks for the next TerminalFrame{Lines, Cursor, Shape, Hidden}, Send(keys...) forwards key names as bindings spell them, Paste(text), Resize(cols, rows)), which is the application's daemon client; the examples use an in-process echo stream. A stream that also implements TerminalReleaser (Release() error) is released once when the terminal closes (Pop, SetItems, RemoveInstance), so a daemon size lease is given back without an app override. terminal.detach only moves focus and keeps the pane for a later attach; AddTerminal(id, stream, Parent(page), CloseOnDetach()) makes detach remove the instance too, releasing the stream. Frames arrive through the delivery contract: each read is work owned by the instance (Runtime.Start), its completion is delivered to the component when still current, and a frame that completes after the instance closed or a newer read started is dropped. term.ViewBlock(width, height) renders the pane into the area a page gives it, tells the stream that size when it changes, and reports the pane's cursor; while the terminal is focused the shell places the real terminal cursor there, shaped as the pane reports (bar, underline, else block).

The instance starts in the terminal base mode, where the noun's any and paste rows forward every key and paste to the pane, so nothing on the page or the application answers keys while a pane is attached. The leader ctrl+a is an Enter("leader_pending", Payload{Prefix: "{terminal-leader}", Request: send {terminal-leader}}) row keyed {terminal-leader}: leader_pending is a one-shot exclusive mode, the prefix makes it a pending sequence like any other (sequence-timeout, sequence-unknown) and the stored request is its shorter match:

Keys Behavior
any key, paste Forwarded to the pane unchanged (Escape and Ctrl-C included)
ctrl+a then d terminal.detach: focus returns to the terminal's parent; the pane keeps running
ctrl+a then ctrl+a Sends one literal ctrl+a
ctrl+a then a bound key Runs that row's request (bind rows into the terminal noun's leader_pending table in code or config)
ctrl+a then an unbound key sequence-unknown pass (default): sends the leader, then handles the key as if typed alone (it reaches the pane), back in terminal mode; swallow: sends neither and says ctrl+a x is not bound
ctrl+a alone Waits for the next key (sequence-timeout 0, the default); with a positive sequence-timeout it sends the leader alone when that passes, and the next key starts fresh

Every row under the leader is a Request: d runs terminal.detach, {terminal-leader} runs terminal.send {keys: "{terminal-leader}"}; there is no catch-all row, since an unbound key is the sequence mechanism's (sequence-unknown), and a paste after the leader is one too (pass: the leader, then the paste). The leader is a setting: terminal-leader (TerminalLeaderSetting, default ctrl+a in settings/ochazuke.json, one ctrl+ or alt+ key) is declared by Runtime.EnsureTerminalLeader() unless the application declared it (an application with terminals calls it at setup; cli.AddCommands does; an application without terminals never shows the setting), read from settings.json and followed on every change (settings set terminal-leader ctrl+b, the Settings page, another process's write). The rows follow it because they name it: a binding row's keys, hint, help and string arguments may hold {setting-name}, resolved when the row is installed and again whenever the setting is declared or changes (binding_settings.go; before the setting is declared, its embedded default). The framework's leader rows are keyed {terminal-leader}; an application's own leader row (a richer hint) or a user's bindings.json row writes the same {terminal-leader} in its keys, prefix and request and moves with it. A row that writes ctrl+a literally stays on ctrl+a. A row whose new key takes the identity of another row of its table replaces it, as a file row does. The old leader becomes ordinary input that reaches the pane. Runtime.TerminalLeader() reads the setting; Runtime.SetTerminalLeader(key) sets it. terminal.attach {id} focuses a pane from anywhere on its page; terminal.send {keys} and terminal.paste {text, keys?} are the operations the rows run and are available to the CLI. bindings list in terminal mode prints the terminal table alone (the leader, any, paste); in leader_pending it prints the leader table, so the footer shows exactly what the pane will do with the next key. The leader row carries a hint (Binding.Hinted, config field hint), so the attached footer reads ctrl+a leader: d detaches, ctrl+a sends ctrl+a instead of its mode.enter operation; any row may set one, and bindings list returns it with the row. The full-project example's Console page is a terminal page added from config rows and the public API only.

Markdown and checklists

The markdown package renders Markdown with Charm's Glamour v2 and edits task lists in place. It is a package of its own, built on the public API like grid, so only an application that imports it carries Glamour, goldmark and chroma (the demo binary, cmd/ochazuke, grows from 10.2 MB to 19.9 MB, mostly chroma's lexers; a binary that does not import markdown, such as examples/hello, is unchanged).

  • markdown.Block(text, width, appearance) renders text in Glamour's standard dark or light style, chosen from the appearance's background (Appearance.Background(): an adaptive theme follows Dark), and the plain notty style under the mono theme and NO_COLOR (markdown.StyleOf). Glamour's blank first and last lines are dropped and every line is cut to the width. Renderings are cached by text, width, style and options. markdown.Block(text, w, a, markdown.PreserveNewlines()) keeps every newline inside a paragraph a line break (Glamour's WithPreservedNewLines), for notes written as plain lines; code blocks and tables draw the same either way, and markdown.New(r, id, parent, src, markdown.PreserveNewlines()) gives a Doc the same rendering without changing its items or toggles. For a read-only preview, put it in a detail so J/K scroll it: body, marker := detail.Window(markdown.Block(text, w, *m.Appearance).Text, w, h).
  • markdown.New(r, id, parent, src) is a *markdown.Doc: a rendered document with a line cursor, edited in place, vim style. Draw it with doc.Block(width, height, *m.Appearance) (or View for the text alone; Block carries the terminal cursor while a block is open). The document is a sequence of elements (markdown.Elements(text): heading, paragraph, bullet, numbered, task, table (one per row), code, quote, rule, note), each a range of whole source lines. The cursor sits on a drawn line: the stop is a list child (doc.ListID(), id + "/lines", added NoMarks) with a row per line an element covers (markdown-line; a checklist item's lines are markdown-task rows, a note's markdown-note rows), so j/k, g g/G, ctrl+d/ctrl+u, ctrl+f/ctrl+b, counts and spills are the list's. The cursor's line is the one reverse-video highlight while the Doc holds the focus. With height 0 every line is drawn and the page scrolls; with a height the Doc windows itself and draws a position marker. A drawn document is a stop; an empty read-only one is not (an empty editable one has one blank line to stand on).
  • Motions on the markdown noun in normal mode (all motions, all with counts): }/{ markdown.next-block/previous-block move between components (a heading, a paragraph, a whole list, an item's notes, a table, a code block, a quote); ] ]/[ [ markdown.next-same/previous-same to the next or previous element of the kind under the cursor; ] or [ and a kind letter markdown.next-kind/previous-kind {kind}: h heading, t table (a table counts once), x checklist item, l list item, c code, q quote, n note, p paragraph. At an edge they do nothing. g O markdown.outline is a chooser over the headings.
  • Editing: i a I A (markdown.insert {at: cursor|after|start|end}) open the cursor's element in the ochazuke editor as its raw Markdown, in place: only that element switches to source (markdown-edit input, insert mode), the rest stays rendered; esc (markdown.leave) writes it, tidies it (a table's pipes aligned, an ordered list renumbered) and draws it again. o/O (markdown.open {where}) open a new line below or above that continues the structure: a list item with the same marker and indent (numbered one on, the list renumbered unless numbered 1. throughout; a checklist item unchecked; below an item's whole subtree), an empty table row, a note line on a note, else a paragraph. In the editor: enter on an item ends it at the cursor and starts the next (markdown.continue-item), on an empty item ends the list (markdown.end-list), on a row starts a row (markdown.next-row), after a heading starts a paragraph, in a quote quotes the next line; tab/shift+tab nest or take out a list item (markdown.indent/outdent) and move between table cells (markdown.cell; past the last cell a new row); backspace on an empty marker (markdown.unmark) leaves an indented continuation line; / on an empty line (markdown.insert-block) is a chooser of block kinds (table asks for its columns, checklist, bullets, numbered list, heading 1 to 3, code block, quote, rule). Each insert-mode key is a guarded row, so elsewhere the editor's own key answers. Normal mode: x markdown.toggle (on a checklist item), d d markdown.delete (the cursor's line of a paragraph, quote or code block; an item with its notes and nested items; a heading's line only; a table's header the whole table), y y markdown.yank and p/P markdown.paste (lines, the shared registers), u/ctrl+r markdown.undo/redo (every edit, each written), markdown.reload.
  • Notes: a blockquote nested directly under a list item whose first line has the shape > **author** date: holds notes (any other blockquote is a quote); each **author** line starts a note, the lines after it continue it; ✓ after the date marks it resolved and · sent sent (> **owner** 2026-10-27 ✓ · sent: text). The Doc draws an item's notes in a box of their own (author bold, date faint, the note colour on the border and author in the dark and light styles, none in mono). n markdown.note opens a new note line under the item after its notes, signed by Doc.Author, else the markdown.note-author setting (default owner), and dated today (Doc.Now); an untouched note writes nothing. x on a note row markdown.resolve toggles resolved; z a markdown.fold folds an item's notes to · N notes (the open ones; , M resolved after). Editing a sent note's text clears its sent marker. For a CLI: markdown.Notes(text) (ids ITEM.N: the item's place among list items and the note's under it), AddNote, ReplyNote, SetResolved, SetSent, SetFlags, FindItem, CleanNote (control characters dropped, NoteMax 4 KiB refused, never cut), ItemText, ItemPath, NoteElement.
  • markdown.Source{Load, Save} is the store. markdown.File(path) reads the file and writes it atomically (a temporary file beside it renamed over it, permissions kept, a symlink written through; markdown.WriteFile is the same write). A custom Source, such as a note in a database, gets the whole edited text from Save. Without a Save the Doc is read-only and every edit is refused. Doc.SetSource points a Doc at another source (a buffer named with save as).
  • Commit on change, no save key: typing is written after a pause (Doc.Debounce, default 400 ms, markdown.DebounceMsg) and when the element is left; every other edit at once. An edit rewrites only the bytes of what it changes (a toggle the box byte). Before writing, the Doc loads the source again; when it changed since the Doc read it, the element is found again by its text (and its place among elements with that text) and the edit is made on the new text; when it is gone, changed or ambiguous the edit is refused with an error wrapping markdown.ErrRefused (the footer status in the TUI, a non-zero exit on the CLI) and nothing is written. A write that fails while a block is open leaves the typed text in the unnamed register.
  • markdown.Tasks(text) lists the checklist items as goldmark parses them (GFM, the parser Glamour uses), each with Box (the byte offset of the box character), Checked, Text (its first line) and Line. Every list form (-, *, +, 1., 2)) and nesting count. A - [ ] in a code block, or outside a list item, is not a task.

How rendered lines map to elements: before rendering, each element's text gets a start marker and an end marker, single private-use runes (one per element, so wrapping cannot split one); a blockquote of notes is replaced by one placeholder quote line, which the Doc replaces with its note box. The Doc searches the rendered lines for the markers and strips them, giving a space back at the end of the line. An element covers the lines from its start marker to its end marker; one Glamour draws without text to carry a marker (a rule, an empty row) takes a line from the gap between its neighbours. The demo's Checklist page, the markdown o-story stories and o-md show it working.

Input modes

Every Input has a noun and two field settings, plus behavior all inputs share. Modes are names, not an enum; these are the ones the built-in editor enters.

Setting Value Effect
noun (Kind) editor (default) Vim editing. Starts in normal. i a I A o O enter insert; Escape returns to normal. v V Ctrl-V enter visual, visual-line, visual-block. Counts, operators, g, ", q and @ enter the pending modes count_pending, operator_pending, g_pending, register_pending, macro_pending, replay_pending.
noun (Kind) prompt Insert only. Starts in insert and mode.set keeps it there. Escape has no effect of its own, so a noun on the stack can bind it, as the picker binds cancel.
Kind "" or text Picker opens at the working directory or a supplied path and inserts at the cursor captured when it opened.
Kind path Picker opens at the whole value and replaces it.
Kind paths Forces Multiline. Picker opens at the current line and replaces only that line.
PathFilter any, file, dir Which picker results are eligible. Does not change editing keys.

Shared by every input regardless of these settings:

  • Readline keys in insert mode (Ctrl-A/E/B/F/P/N, Alt-B/F, Ctrl-W/U/K/Y, Ctrl-H/D). They are rows of the editor noun, the fallback of every stack; a row with mode: insert on any noun or instance on the stack, or a binding-file row on editor itself, overrides a key. There is no plain mode without them.
  • Ctrl-W kills one path component, treating / and whitespace as boundaries, in every input, not only path kinds.
  • One undo tree, named registers, shared yanks, and macros.

Mode resolution for key dispatch: the mode is global, like Vim's: Runtime.Mode is {Name, Payload} and mode.set (Runtime.SetMode) writes it. A pending mode is entered on it with a typed Payload (Count, OpCount, Op, Prefix, Request, Shadow) and leaves back to the base mode it replaced (Payload.Return, read as BaseMode()); a key-sequence prefix carries the count, so 3gg reaches line 3. A focused input is in the global mode; Input.Mode is the editing mode (normal, insert or a visual mode) the editor code reads, kept equal to the base mode while the input is focused. A focus change that leaves the current focus stop resets the mode to normal with an empty payload, or to the pinned mode of the newly focused noun (prompt pins insert, terminal pins terminal); a move inside one stop (a grid's cell to the next, a list's row to the next) keeps it, so a visual selection survives cursor moves. Closing a modal and reopening a page restore the mode they left. A component that follows the mode implements ModeObserver (ModeChanged(from, to)), called when the base mode changes while the focus is on or beneath it. A pending mode on a focus without an input still works for what needs no input: 2@a replays a macro from a page.

API and ownership

Every keyboard action dispatches a registered operation. The CLI is a generic NOUN VERB adapter over that same registry; it has no separate list of supported actions. operations list returns the current catalog and argument specifications.

cli.Mount maps every registered noun and operation into oden command groups and dispatch metadata, including parameter schemas. Oden owns contextual help rendering and command resolution: BIN NOUN and BIN NOUN -h/--help show that noun's verbs and schemas; BIN NOUN VERB --help describes only that operation. The adapter only maps the registry and delegates execution to cli.Shell. Help never enters Shell.Prepare, so it does not start a daemon or execute an operation.

r := ochazuke.NewRuntime()
input := ochazuke.NewInput("title", "Example", false)
if err := r.AddInput(input); err != nil { // Parent("app") and Kind("editor") by default
    panic(err)
}
if err := r.SetFocus("title"); err != nil {
    panic(err)
}
result, err := r.Execute(ochazuke.Request{
    Verb: "undo", Noun: "input", Target: "focused-input",
    Args: ochazuke.Arguments{"steps": 1},
})

Runtime is single-owner state and holds exactly: the operation registry (Operations, Modes, guards), the nouns and instances with their parent links, three plain interaction fields (Focus, Mode, Page), the chain of open modals (each modal instance's Payload.Return is the focus it opened over; read it through Modals, TopModal, ModalFocus, BaseFocus), the pending key-sequence state (Pending, BindingTimeout), Quit and the queue of off-loop commands the adapter drains. It holds no component fields: inputs, lists, pages, the picker and the registers are instances whose Component is the typed object, read through r.Input(id), r.List(id), r.Inputs(), r.Lists(), r.PageOf(id) and r.Registers(). In a running application, call it from Bubble Tea's update loop; external goroutines/processes use Call/CallMsg, not concurrent Execute calls. Request.Target names any instance: an input, a list, a list row, a page or a modal body; the request then runs in the context that addresses that instance (its ancestry, plus InputID for an input). focused-input means the current focus. ExecuteAt accepts a captured context for explicit originating-target dispatch. Input.SetMode is the mode transition hook; do not assign Input.Mode directly.

File Responsibility
runtime.go Registry (operation kinds), the global mode (Mode, SetMode, BaseMode, ModeObserver), ExecuteAt through noun actions and confirm, typed lookups, JSON inspection
focus.go Runtime.Focus, the modal chain (Push, OpenModal/WithInput, Pop), the mode rule on focus change, RemoveInstance, RetargetFocus, focus jumps (focus.next/focus.previous/focus.set, JumpFocus)
delivery.go The component delivery contract: Component, Ticket, Completion, Start, Deliver, PendingCommands; application verbs (Ctx, Result, Done/Failed/Pending)
confirm.go The confirm noun, SetConfirm, prompt templates
verb_checks.go Verb checks (AddVerbCheck, VerbCheck, Verdict: Allow, AskFirst, Refuse), the quit hook BeforeQuit
noun.go, instance.go Define builder, binding rows, key classes and guards; instances, parent links, Payload, targets
resolve.go, bindings.go The stack walk, pending modes, key-sequence prefixes and their timer, bindings.list
bindings/*.json, default_bindings.go, editor_keys.go The default key bindings as data (one file per area: the editor noun's mode tables, the app noun's count, register and macro rows, lists, tables, trees, timelines, forms, the terminal, ...), loaded at startup; LoadDefaultBindings, bindings defaults
configuration.go bindings.load, mode.register, context.select
input.go, editing.go, editor*.go Input-owned undo, the editor handlers (motions, operators, kills, insert, paste), visual geometry
list.go Flat selectable rows as instances of their nouns, marks and fan-out, stable-ID refresh, viewport scrolling, row focus
registers.go, macros.go, yank_history.go The registers component: yanks, named registers, history, active register, key recording/replay, history modal
palette.go, palette_parse.go, palette_editing.go, palette_nouns.go, palette_choices.go The ex-mode command line: its operations and rows, the grammar (verb/noun either order, prefixes, omitted noun, parameters), completions and filter codes, history recall, instance sources and defaults, parameter choices, originating context
palette_results.go Palette-only JSON object-array results: inferred frequency-ranked columns, read-only table modal, empty results
params.go Parameter choices: Choice, ParseChoices, Runtime.Choices, Enum/Source validation at execution
picker.go, picker_search.go Contextual path selection, asynchronous fuzzy indexing, native Git ignores
pages.go Pages as instances of kind page (AddPage, RegisterPage), Runtime.Page, remembered focus and mode, navigation, the page picker (page.pick), and focus isolation
chooser.go The chooser: a palette-shaped modal of rows (OpenChooser, ChooserSpec, ChooserRow), its ranking and its rows on the chooser noun
chooser_sources.go Chooser sources: ChooserSource{Name, Label, Load(query), Live, Empty, Open, Up, Create, CreateLabel}, cycling (ctrl+o/alt+o), opening a row inside its source and stepping out, the remembered source per kind (chooser.remember-source), chooser.enter
path_chooser.go Path parameters (Type: "path", Path, Base, New) and the path chooser (OpenPathChooser): browse, recent, typed, then AddPathSource sources (each may set ChooserSource.Keep, its columns cut last); PathChooserSpec.Source names the source it opens on (else chooser.remember-source's); PathStart, SetPathBase, SetRecentPaths; settings path.start, path.field, path.hidden, path.no-auto-list
completion.go, completion_list.go Inline completion: an input's triggers and searches (Completions, NounBuilder.Completions, CompletionTrigger, Suggestion, SearchStrings), the token rule (FindCompletionToken) and the Completer, the suggestion list that answers as the input's inner level while typing keeps editing it
terminal.go The terminal noun: AddTerminal, TerminalStream, frames through the delivery contract, the leader contract, pane cursor
layout.go Layout.Shell, the one page chrome (title row with badge, tabs or subtitle, body, footer), panels, splits, sidebar
panes.go Resizable list/detail splits: the divider per page (Layout.Shift, read through Runtime.PaneLayout(page, layout), applied by Layout.Divide and every Split*), Runtime.PaneShift/SetPaneShift, pane.grow/pane.shrink {steps, page} and pane.reset {page}, the ctrl+w > ctrl+w < ctrl+w = rows guarded by pane-split, panes.json in the state directory
theme.go, surface.go Appearance operations, Lip Gloss styles, bounded modal composition on a Lip Gloss canvas
block.go Block and Pos: rendered text plus the focused input's cursor cell
model.go Bubble Tea adapter (delivers messages and drains commands through the runtime), renders through Layout.Shell, BindingHints, Bubbles viewports, modal renderers, terminal cursor
transport.go, cli.go, cmd/ochazuke Private Unix socket and generic CLI dispatch
internal/demo, examples/core, examples/full-project Runnable demo (demo.New()), noninteractive foundation example, configured application with list, modal, confirm and terminal pages
Nouns and instances

A Noun is the behaviour of one kind of thing: its verbs, a binding table keyed by mode ("" for every base mode), an optional pinned mode, and the action handlers that override an operation's default while the noun is on the stack. An Instance is one addressable thing on screen (ID, Noun, Parent, Payload for a modal body's data, optional Bindings of its own, Unfocusable to opt out of being a focus stop); it holds no mode; walking Parent links from the focused instance outward (Ancestry, InstancePath) is the stack keys resolve through and what Context.Path spells out. Declare with the builder and register instances with options:

r.Define("worktree").
    Verbs("open").
    Verb("remove", removeWorktree).                        // registers worktree.remove, or overrides it on this noun
    Action("selection.inspect", inspectWorktree).          // overrides another operation while a worktree is focused
    Mode("normal").
        Bind("o", ochazuke.Do("worktree.open")).
        Bind("d", ochazuke.Enter("operator_pending", ochazuke.Payload{Op: "d"})).
        Pattern(ochazuke.Digit, ochazuke.Do("count.append").FromPayload("digit", ochazuke.SourceDigit)).
        Bind("enter", ochazuke.Do("worktree.open")).When("self").
        Unbind("x")
r.Instance("sidebar", ochazuke.Parent("home"), ochazuke.Kind("panel"))
r.AddInput(ochazuke.NewInput("path", "", false), ochazuke.Parent("sidebar"), ochazuke.Kind("prompt"))

Runtime.Focus names the focused instance and is the source of truth; Context() is derived from it. Request.Target and context.select {instance} address any instance; ActionFor resolves noun overrides innermost first. A row that matched at an outer level addresses that level's instance when its operation is the level's own (d d → row.delete bound on the row noun runs on the row, and its confirm names it); shared operations a level binds (mode.set, input.*, focus.*) keep addressing the focus. ModeBuilder.Extends(parent) gives a mode table inheritance: Define("grid").Mode("visual-row").Extends("visual-block") reads its own rows, then the parent's, including rows bound on the parent later. state.get exposes /nouns, /instances/<id>/{noun,payload,parent}, /mode, /modeState, /modals, /inputs/<id>, /lists/<id>, /components/<id>, /jobs, /focus and /page.

Operation kinds and application verbs

Every operation has a Kind: interaction (the default; Run executes synchronously on the loop) or application. An application verb is declared with the same builder but an AppHandler:

r.Define("worktree").
    Verb("sync", func(c ochazuke.Ctx) ochazuke.Result {          // c.Instance is the worktree row: ID, Noun, Payload
        id := c.Instance.ID
        return ochazuke.Pending(func(ctx context.Context) (any, error) {
            return git.Fetch(ctx, id)                           // off the loop; ctx is cancelled if the row closes
        }).Then(func(c ochazuke.Ctx, v any, err error) {        // back on the loop, only while the job is current
            c.Runtime.List("worktrees").Select(id)
        })
    }).
    Verb("status", func(c ochazuke.Ctx) ochazuke.Result { return ochazuke.Done("clean") })

Done(v) and Failed(err) answer at once; Pending(work) returns a Ticket{Owner, Job, Slot} to the caller and schedules the work as a tea.Cmd. The framework never blocks the loop on application I/O. The palette, operations.list, the generated docs and the example's ? modal show the kind.

Jobs on one owner accumulate by default: five independent verbs on one row (fetch, commit, push...) all deliver, in finish order, each with its ticket. Pending(work).Replacing("preview") opts into replacement: a newer job in the same slot on the same owner cancels the older one, which is what a preview or a search wants. Pending(work).ReplacingAt(listID, "preview") scopes the slot to an ancestor instead: the newest job in (list, preview) cancels the older whichever row asked, so j p j p keeps one capture per list, while the job still belongs to the row (its completion and Then land there). The scope must be the owner or one of its ancestors; per owner remains the default (Replacing(slot) is ReplacingAt(owner, slot)). A job is dropped only when its owner instance closes or a newer job claims its slot, never because the user did something else meanwhile. A Then that removes its own owner (a kill verb dropping its row) is safe: the job is settled first and the completion is not offered to the gone component.

ticket = { owner: "repo-1", job: 42 }                      // accumulate: delivered whenever it finishes
ticket = { owner: "pane-7", job: 43, slot: "preview" }     // replace: job 44 in slot "preview" on pane-7 cancels 43
job    = { owner: "row-3", job: 45, slot: "preview", scope: "panes" } // ReplacingAt: job 46 from row-5 under panes cancels 45

jobs.list returns the jobs list, [{job, owner, verb, slot?, scope?, started, state, error?}] (scope is the slot's scope: the owner for Replacing, the ancestor for ReplacingAt) with state one of running, done, failed, cancelled; verb is the operation key for an application verb (sync.worktree), read for a terminal frame and the slot name for the picker. Finished entries stay in the list until a jobs.list read returns them (bounded to the last 32 meanwhile), so a status rail or toast reads each outcome once; state.get /jobs shows the running jobs only.

History eviction does not suppress completion delivery: a slow job still runs its Then callback and reaches its owning component even when newer jobs fill the retained history before it finishes.

Delivery contract

Work that completes later reports through one contract. A component is any Instance.Component implementing

type Component interface {
    HandleMessage(tea.Msg) bool // apply a result on the loop; true when it was for this component
    PendingCommand() tea.Cmd    // the work scheduled since the last drain
    Close()                     // cancel outstanding work, release what is held
}

Results carry their owner instance id, job id and slot (Completion{Ticket, Value, Err}); Runtime.Launch(owner, verb, result, ctx) starts a Pending result as a job and queues its tea.Cmd (Start(owner, work, then, ctx) is the accumulating shorthand), Runtime.Deliver(msg) settles a running job's completion and hands it to its owner, dropping a stale (cancelled) or orphaned one, and Runtime.PendingCommands() batches every component's pending work. A component that runs its own commands uses the ticket-level form: Issue(owner, verb, slot, ctx) returns the ticket and the work context, Accepts(ticket) asks whether the job is still running and Settle(ticket, err) records its outcome. Closing an instance (Pop, a row dropped by SetItems, removeInstance) cancels its jobs and calls Close. The Model drives components from the instance registry, so an application registers one by setting Instance.Component and nothing else. The picker is a component whose index, search and preview are three replacing slots on the picker instance; the registers are one too (its only cancellable work is a recording in progress); a terminal's frame reads are one replacing read slot.

Per-verb confirm

Confirmation is a property of a verb, declared once rather than at each call site:

r.Define("worktree").Verb("remove", removeWorktree).Confirm("Remove {{id}}?")

It compiles to the framework confirm noun: running worktree.remove opens a confirm modal instead, a modal instance parented at the focus with Payload{Prompt, Request}; y (or Enter) runs the stored request in its original context, n or esc pops, every other key is swallowed. Templates expand {{id}}, {{noun}}, {{label}} (a label argument on the request, else the instance's Label, a list row's label, else its id) and {{<arg>}}. A request that addresses no instance of the verb's noun (no target, none on the focus path: worktree remove /src/a on the command line) reads the request instead of naming app: {{noun}} is the verb's noun, {{id}}, {{target}} and {{label}} the argument of that name, else the first argument in parameter order (Operation.ParameterOrder, positional first). A request without a target addresses the nearest instance of its operation's noun on the focus path (row.delete chosen in the palette while a cell is focused acts for the row, so its prompt names the row); a binding row's own request keeps the row rule (the level it matched at, else the focus). A verb guarded off where it would act is refused (<noun.verb> is not applicable now) from every caller, and its rows drop out of bindings list and the hints. confirm.set {operation, prompt} adds or removes a prompt at run time (an empty prompt removes it; the full-project example sets one from actions.json), and a request with "confirmed": true skips the prompt for scripts.

Verb checks and the quit hook

A verb can carry checks an application hangs on it (verb_checks.go): each runs before the verb from every path (keys, the palette, the CLI, the API), after its guard and before its Confirm prompt, and returns a Verdict: Allow(), AskFirst(prompt) (the confirm modal asks; y runs the request marked Confirmed, so no check or prompt asks again) or Refuse(reason) (the request fails with the reason, the status line shows it). Checks run in the order added; the first that does not allow decides. A request with "confirmed": true or force: true skips them.

r.BeforeQuit("unsaved", func(r *ochazuke.Runtime, c ochazuke.Context) ochazuke.Verdict {
	if app.unsaved() {
		return ochazuke.AskFirst("Quit without writing? The edits no write saved are lost.")
	}
	return ochazuke.Allow()
})

BeforeQuit(name, check) is AddVerbCheck("app.quit", VerbCheck{Name, Check}); app.quit declares force (boolean), so a row {"key": "Q", "action": "app.quit", "args": {"force": true}} quits without asking, as vim's :q!. RemoveVerbCheck(key, name) takes one off, VerbChecks(key) names them. A check of the same name replaces the earlier one in place.

Local checks:

make test       # every module: the root, cmd/o-story (the stories) and examples
OCHAZUKE_NESTED_TESTS=1 go test -race ./...
go run ./examples/core

The integrated implementation was checked locally on macOS with the test suite and live terminal/CLI sessions. Checks covered retained page edits and scroll, page-specific bindings, blocked navigation under modals, nested restoration, palette-driven page navigation, live appearance changes, and a narrow 56×18 modal. Regression tests and a live rapid-input check cover Bubble Tea's coalesced typing events without treating bracketed paste as commands.

The editor/picker expansion also passed the full suite and race detector. Live terminal/CLI checks exercised all three visual shapes, cross-field block paste and undo, named registers, counted macro replay, history selection without insertion, o/O, slash-delimited kills, contextual path replacement, recursive fuzzy ignore-aware picking, and a 48×15 layout.

Requirements

  • General UI infrastructure with a stack of stateful modals.
  • First-class pages retaining their interaction state across navigation.
  • Styled partial-screen modal overlays that leave the preceding screen visible.
  • Pushing a modal preserves the previous modal's state; popping restores the previous interaction exactly.
  • Vim-style interaction with arbitrary, application-defined modes.
  • Customizable keybindings scoped to modes, components, or the application, plus global bindings.
  • Public operations available through an API and CLI tools, including a central CLI with subcommands.
  • JSON export of application state and individually addressable public values.
  • Ex-mode command line over the verbs and nouns: either word first, prefixes, completion of the next word.

Stateful modal stack

Preserve modal instances rather than destroying and reconstructing them. Each frame owns its interaction state: mode, focused field, draft values, cursor, selection, and scroll position.

Illustrative state (JavaScript notation, not a Go API contract):

{
  id: "edit-task",
  component: "task-editor",
  mode: "insert",
  focusedField: "description",
  values: {
    title: "Build UI framework",
    description: "Preserve nested modal state"
  },
  cursor: { row: 1, column: 12 },
  selection: null,
  scroll: { x: 0, y: 3 }
}

Opening a directory picker opens another modal. Closing it restores the editor's interaction state. A child can return a result to its parent, such as a selected directory.

In the Go API there are no frames: Runtime.Focus is the one focus and an open modal is an instance on the modal chain. Push(id, focus) opens modal id focused on focus and stores the focus (and mode) it opened over in the modal's Payload.Return; Pop restores both, falling back to the nearest surviving ancestor (ending at the page) when that focus was removed. An id that is not already an instance becomes one of the modal noun for as long as it is open, so "Escape pops a modal" is that noun's normal-mode esc row and a modal body may carry rows of its own. OpenModal(kind, Payload{...}, opts...) is the payload-carrying form: it creates a body instance of noun kind parented at the current focus, with the payload (Prompt, a stored Request, ...) the kind's rows read through FromPayload and request.run, and removes it (with what it holds) on Pop after closing its component. WithInput(in, Kind("prompt")) puts an input inside the body and focuses it, so a one-field prompt is one call; the *Input keeps its text for the next open. The confirm noun is built this way. RemoveInstance(id) closes and drops an instance with its descendants and moves every focus reference into it to the nearest surviving ancestor. Cursor, drafts, selection and undo live on the instances; the mode is global; scroll offsets live on the Model; application data lives with the application.

Focus moves between focus stops: instances of nouns declared Focusable() (list, grid, palette, terminal) and every input, unless the instance sets Unfocusable. focus.next and focus.previous {steps, scope} walk the top modal (else the page) in drawing order (the order the page's last frame drew its stops: List.View, InputBlock, Terminal.ViewBlock, grid.View and Runtime.Placed(id) record it; stops no frame drew follow in tree order), without descending into a stop (a grid is one stop, not its cells), wrap, and land on the stop's remembered child (its FocusTarget, such as the list's selected row, else the focus last held inside). Scope region jumps between instances of nouns declared Region() (panels, never stops themselves). The app noun binds } { and tab shift+tab to stops and ) ( to regions in normal mode, all taking a count; an inner level (a multiline editor's insert table, a palette field) binds its own. focus.set {id} is how handlers move focus. On a page, list.move (j k down up) past a list's last row moves the focus to the next stop in drawing order (a list on its first row), before its first row to the previous stop (on its last row), and stays put at the page's ends; AddList(..., NoSpill()) keeps a list's motions inside it, and lists in modals never spill. Focus never rests on what the last frame did not draw: after the Model draws the page, a focus whose stop the frame did not place (a tab switched away from it, a collapsed panel; a list row counts as drawn when its list is) moves to its nearest ancestor below the page that was drawn, else to the page's first stop in drawing order, else to the page, and the page is drawn again before the footer, so the hints and the next key are what is on screen. It is a plain focus change (the mode rule applies; } goes back once the stop is drawn again) and waits while a modal is open, before the first frame and after a frame that placed no stop (UX-RULES R3.13).

Invariants:

  • Only the focus (inside the top modal while one is open) receives keyboard input.
  • Covered modals retain local editing state.
  • Background results target the originating instance, not whichever modal is currently on top.
  • Shared application data is separate from modal-local state. Pop restores an interaction, not a stale copy of the entire database.
  • In-memory preservation and persistence across process restarts are separate capabilities. Restart persistence is not yet specified.

Extensible interaction modes

Modal windows and editing modes are different concepts. A modal is an instance on the modal chain; the mode is one global value that determines input behavior.

{
  modes: ["normal", "insert", "visual", "command", "directory-search"],
  focus: "edit-task-field",
  mode: { name: "insert", payload: {} },
  modals: ["edit-task"]           // edit-task.payload.return = "task-list"
}

Applications and extensions register mode names (mode.register {name, pending?} or DefineMode); the framework does not restrict them to a fixed enum. A base mode reads a noun's mode table and its any-mode table; a pending mode reads only its own table and is left by the key that answers it (see Scoped, customizable keybindings). Rows can be bound inside any mode, pending ones included, on any noun or instance.

Text fields, single-line text inputs, and multiline text areas support the basic Vim motions and Readline bindings listed above. Normal mode interprets Vim keys; insert mode interprets Readline keys. Full Vim compatibility is not implied.

Input-local editing and undo

Each text input owns its editing state and undo tree. Histories are independent between fields and remain part of preserved modal-local state. An insert session is one undo change, including kills/yanks and open-line creation. Editing after undo creates a new branch without deleting alternatives. input.redo accepts optional steps and a zero-based branch index for its first step; omitted branch selects the newest child. API edits outside insert mode create separate changes.

Inputs expose editing verbs through the shared operation registry. In particular, undo accepts an optional number of steps, defaulting to one change. The input handles its own history; outside callers do not manipulate the tree.

The application supports dispatching an editing operation to the focused input without requiring callers to know its identity or implementation. JSON requests:

[
  { target: "focused-input", verb: "undo", noun: "input" },
  { target: "focused-input", verb: "undo", noun: "input", args: { steps: 3 } }
]

The first request undoes the focused input's last change; the second requests three undo steps from that same input's history. These operations are available through the shared API and CLI as well as UI bindings. Normal/insert modes determine keyboard interpretation, not whether an external caller can invoke the input's editing verbs.

Shared yanks, registers, and macros

Selection and undo belong to each input. Yanks, history, registers, the active register and macro state belong to the registers component, one instance under app (r.Registers() returns it: Named, History, Active, Macro), so a yank from notes can be pasted into paths or a modal editor. It is reached through the register, macro and yank-history operations, never through Runtime fields.

The system clipboard: the clipboard register + (and *, the same register here) always copies its yank to the system clipboard, and the clipboard setting says which other yanks do: yanks (default: every yank, not a delete), unnamed (every yank and delete, Vim's clipboard=unnamed) or none. The copy is a command the registers component schedules (PendingCommand): Registers.Copy(text) tea.Cmd when an application sets it (a clipboard program such as pbcopy), else OSC 52 through tea.SetClipboard, which TUIOS and ssh pass on. Reading "+p pastes the last text yanked into +, not the system clipboard's current contents. Compared with Vim: "+ and "* are Vim's clipboard and selection registers (:help quoteplus), one register here; clipboard takes Vim's unnamed (:help 'clipboard'), plus yanks, which Vim lacks.

{
  registers: {
    '"': { yank: { text: "ab\nef", shape: "block", width: 2 } },
    a: { yank: { text: "alpha", shape: "char" } }
  },
  yankHistory: [
    { text: "ab\nef", shape: "block", width: 2 },
    { text: "alpha", shape: "char" }
  ]
}
  • v, V, and Ctrl-V select characters, whole lines, and display-cell rectangles. Motions extend selections; y/d/c/p yank/delete/change/replace. Escape cancels selection. Normal yy/dd/cc act on whole lines; motion operators and counts work too.
  • p/P preserve the yank's shape. Block operations handle ragged rows and wide glyphs; block change repeats a contiguous first-row insertion across selected rows when leaving insert mode. Each block edit is one undo step. Single-line inputs reject line/block-shaped pastes rather than flattening them.
  • "a selects register a for the next operation; "A appends. The unnamed register is shared; 0 holds the last yank, 1–9 hold line/multiline deletions, and - holds small deletions. "_ discards without changing shared yanks or history.
  • Normal g y or yank-history.open opens history (an editor reaches it through its g prefix, g_pending y; the app row is guarded no-input so an editor's 5gg keeps its count). j/k or arrows highlight an entry; Enter makes it the unnamed yank and closes without inserting. Then use p/P or insert-mode Ctrl-Y to paste. Escape cancels. History keeps the newest 100 entries, including duplicates.
  • qa … q records into register a; qA appends. @a replays, 3@a repeats three times, and @@ repeats the last macro. Mode changes, bindings, focus changes, and modal/palette interactions use the same dispatcher as live keys. Register yanks and macro recordings share storage: replacing one replaces the other.
  • Macro replay is bounded to 16 nested calls and 10,000 dispatched keys. Errors are reported, not swallowed; earlier edits remain undoable rather than being rolled back as a transaction. Recording is the macro_recording shadow mode on the app noun: each key is appended, then dispatched again in the mode it shadowed; replay runs at depth and is not re-recorded. The q, @, " and count rows are app rows too (registers_bindings.json), so a page or list focus records, replays and counts without an input.
/tmp/ochazuke yank-history open
/tmp/ochazuke yank-history select --json '{"index":0}'
/tmp/ochazuke register get --json '{"name":"a"}'
/tmp/ochazuke register set --json '{"name":"a","text":"shared","shape":"char"}'
/tmp/ochazuke input paste --json '{"register":"a"}'
/tmp/ochazuke macro replay --json '{"register":"a","steps":2}'

input.yank captures a selection/current lines; input.paste inserts a stored yank. Insert Ctrl-W/U/K publish shared kills and Ctrl-Y pastes the unnamed text literally. These operations use the same registry as the keyboard, palette, and CLI. All this state is in memory.

Scoped, customizable keybindings

Bindings are rows of mode tables. A row names the noun (or one instance) it belongs to, the mode table, an exact key or key sequence or a key class, and the request it runs; the shape is identical in Go, in bindings list output and in a binding file:

[
  { noun: "directory", mode: "normal", keys: "U",
    request: { verb: "undo", noun: "input", args: { steps: 3 } } },
  { noun: "editor", mode: "insert", keys: "esc", request: null },          // unbind a default
  { instance: "notes", mode: "normal", keys: "g s",
    request: { verb: "summarize", noun: "workspace" } },
  { noun: "editor", mode: "macro_pending", pattern: "alpha",
    request: { verb: "start", noun: "macro" }, from: { register: "key" } },
  { noun: "editor", mode: "insert", keys: "enter", when: "multiline",
    request: { verb: "insert", noun: "input", args: { text: "\n" } } }
]

bindings list --all returns every stored noun and instance binding row across every mode, including inactive contexts, guarded rows, and bindings shadowed at the current focus. Noun names, their mode tables, and instance IDs have deterministic order; row order within each table is preserved. The result is a JSON array in the format accepted by bindings load, not an operation catalog or a full application snapshot. Operations, guards, instances, mode definitions, and mode inheritance must already exist in the receiving application. Without --all, the operation still lists only the rows the current focus and mode answer to. The socket CLI accepts ochazuke bindings list --all or --json '{"all":true}'.

bindings stops is the app-wide effective keyboard: one entry per focus stop, {page, stop, focus, mode, bindings}, the rows bindings list would print with the focus on that stop. The order is fixed: the pages in tab order, each page's stops in drawing order (as } walks them), the open modals' stops, then app in normal mode. Each stop is read at the focus a jump lands on and in the mode the focus would have there (the current mode at the current focus, else the stop's pinned mode, else normal); nothing moves. The two differ in kind: --all exports what is stored (every table, every mode, shadowed and inactive rows included, loadable with bindings load), stops reports what answers (after shadowing, guards and the modal boundary), per place.

Patterns are digit, alpha, printable, paste, any, a class minus keys (alpha-q) or a set (one-of:h j k l). from fills an argument from the key (key, digit, text) or the mode payload (count, line, steps, op, opcount, prefix); several sources separated by spaces ("keys": "prefix key", Join in Go) join their texts with a space. when names a guard (input, no-input, multiline, count, no-count, self, shadow-idle, op:<key>, or one the application registers with DefineGuard). A verb takes a guard too: Define(noun).Verb(verb, h).When(guard) (Noun.Guards, Runtime.VerbGuard, Runtime.VerbShown) keeps the palette from offering the verb while the guard is false at the focus and mode the palette opened over; a palette noun's default verb is never guarded (RegisterNoun refuses one). The palette lists the nouns of that focus stack first, the focused noun first. A row's identity is its noun or instance, mode, keys or pattern, and when: a row with the same identity replaces the default in place, a new one adds (a new guarded row goes before the unguarded row on its keys, so it answers while its guard holds), request: null unbinds the row with the same identity. A row without when therefore never replaces or unbinds a guarded row on the same keys: give it the guarded row's when (bindings list --all shows every row's guard); the bindings.json loader reports a row a guarded default still answers before as a notice. The input guard the framework adds to the editor's input.* rows (ImplicitGuard) is not part of the identity, so {noun: "editor", mode: "normal", keys: "x", request: null} unbinds x, and an editor row of the user's that runs an input.* operation gets the same guard. ModeBuilder.Unbind removes the unguarded row, UnbindGuarded(keys, guard) the guarded one. Load a file of rows with bindings.load {path} or Runtime.LoadBindings; Runtime.Bind installs rows from Go and the Define(...).Mode(...).Bind/Pattern/Unbind builder writes the same tables.

The resolver is one stack walk. For each level from the focused instance outward to app (the modal noun's level sits just inside app while a modal is open) and then the editor noun as the fallback every stack ends with:

for (inst of stack(focus)) {
  table = rows(inst) + nouns[inst.noun].bindings[mode] + nouns[inst.noun].bindings[""]   // the last only in a base mode
  hit = table[key] ?? table[classOf(key)] ?? table.any
  if (hit) return hit(key, mode.payload, inst)
}

Within one level the instance's own rows sit above its noun's, the mode table above the any-mode table, and an exact key beats a class beats any; between levels the inner one wins. Key sequences are the exception (Vim typeahead): a sequence extending the keys typed so far at any level, inner or outer, makes the walk wait, with the innermost exact match as the fallback (inner x with outer x x: x x runs the outer row, x alone runs the inner one after the timeout); a level answering with a key class (a terminal's any) ends that scan. A row whose verb is guarded off at the focus is skipped and the walk goes on. Application rows therefore beat the editor's defaults for a fresh key, while a pending mode (an operator, a count, a register, a macro prefix, a key sequence) is exclusive: only that mode's tables answer, so dw reaches the editor even when the app binds w. A pending mode is one-shot: the key that answers it consumes it before the request runs, so d then w leaves operator_pending and the operator's own request decides the next mode; a row whose request is mode.enter or count.append stays or moves on. Every pending condition is such a mode with a small typed payload:

normal:           { i: mode.set insert, d: enter operator_pending {op: "d"}, g: enter g_pending, "<digit-0>": enter count_pending {count: digit}, q: enter macro_pending, '"': enter register_pending }
count_pending:    { "<digit>": count.append, ...normal rows with steps from the count, esc: cancel, any: leave and re-dispatch }
operator_pending: { w: operator {motion: "word-forward", steps}, d: operator {motion: "line"} when op:d, g: enter operator_g_pending, any: cancel }
g_pending:        { g: move first-line {line: count}, any: cancel }
macro_pending:    { any: macro.start {register: key}, esc: cancel }
macro_recording:  { q: macro.stop when shadow-idle, any | paste: macro.record {key} = macro.append then key.dispatch {mode: "shadow"} }
"normal g":       { "g g": … the continuations of the sequence; a timer leaves the mode and runs the completed match }

The editor noun's tables (Readline rows in insert, Vim rows in normal and the visual modes, the pending modes above) are bindings/editor.json, one of the embedded default files (see Default bindings are data). bindings list prints the rows the focus answers to in its current mode, so every Readline and Vim key appears there for its mode, and the help modal of the full-project example is built from it. Multi-key sequences such as g g wait in a prefix mode named "<mode> <keys so far>" on the focused instance for for a configurable timeout (sequence-timeout, default 0: wait for the next key with no deadline; Neovim's timeoutlen is 1000ms, set sequence-timeout to 1s for that); the timer and a mismatching key leave the mode, run the longest completed match, and the mismatching key is then dispatched fresh. Escape cancels the sequence through a row like any other: every table that binds a sequence keeps a generated "<prefix> esc" → mode.leave row for each prefix (bindings list shows it in the prefix mode), so the resolver itself never names a key. A paste is one event that matches only paste rows, so insert mode inserts it and normal mode ignores it.

Capture rows

The walk above bubbles: the inner level wins. A row may set capture: true (Captured() in Go) to be consulted in a capture pass before it, outer-first (app first, the editor fallback last), for the few app-level keys an inner component must not swallow. The first capture row that answers wins; bindings list shows capture rows first.

{ noun: "app", mode: "", keys: "ctrl+c", capture: true, when: "no-modal", request: { verb: "quit", noun: "app" } }

That row is the only default capture row: NewModel installs it (with the bubbling ctrl+c row it always had) so an inner any row cannot swallow quit. The no-modal guard stands it aside while a modal is open, so the palette's own ctrl+c still closes the palette. A passthrough mode (DefinePassthrough, the terminal mode) has no capture pass at all: while it is the base mode, ctrl+c goes to the attached pane, and quitting means detaching first (ctrl+a d) or a leader row bound to app.quit. To rebind ctrl+c, bind it on app before NewModel (then neither row is installed), or override or unbind each row on its own: an unbind or rebind without when touches the bubbling row only (the loader's notice says the capture row still answers first), and {noun: "app", keys: "ctrl+c", when: "no-modal", request: null} removes the capture row.

Default bindings are data

Every default key is written once, in an embedded file in the grouped bindings format (see The bindings file format): the framework's in bindings/*.json, one per area (editor.json, registers.json, list.json, table.json, list-modes.json, tree.json, timeline.json, form.json, terminal.json, app.json, palette.json, picker.json, ...), the markdown, grid and Commands nouns' in markdown/, grid/ and cli/bindings.json. A group may also carry "fallback": true: its rows are skipped on the keys its table bound before the file loaded (the app noun's :, ?, ctrl+c: an application's row bound before NewModel keeps its key).

An application ships its defaults the same way:

//go:embed bindings/*.json
var defaultBindings embed.FS

// after the verbs and guards the files name are registered, before Model.Init
if err := r.LoadDefaultBindingsFS(defaultBindings, "bindings/*.json"); err != nil {
    return err
}

The rows go into the default layer exactly where the same rows bound in Go would sit (a row replaces the row with its identity, a guarded row goes before the unguarded row on its keys, sequences get their prefix cancels), below the user's bindings.json. Unlike a user file, an embedded file is strict: an unknown operation, argument, source, guard, mode or instance is an error naming the file, the table and the key (MustLoadDefaultBindings panics), so a test that builds the app catches it. Runtime.CheckDefaultBindings(source, data) is the rule check for a test: every name exists, every mode.enter goes into a pending mode, no two rows of a table share a key and guard.

BIN bindings defaults (ochazuke.bindings.defaults, Runtime.DefaultBindings) prints the default layer as a bindings file, without the user's rows and with the rows they replaced back in place; every group carries "source": the embedded file (ochazuke/bindings/list.json, an app's own path), go for a row bound in Go (an instance's rows, a row computed from a spec) or generated for a sequence's prefix cancel. Go Bind stays for rows that are computed at runtime.

Atomic bindings

A binding row is atomic. A row is a Request (one registered operation, its arguments from the row, the key or the mode payload), a mode transition (Enter, Leave) or null (an unbind). There is no row that runs Go code with the key: Binding has no such field, and TestBindingRowsAreAtomic validates every table of the framework, the model, the picker, the demo and the full-project example (Runtime.ValidateBindings) and parses the resolver to check it names no key. The only code that compares key names is the key classifier (printableKey) and one key-name-to-text table (keyText).

The rule is recommended to any application built on the framework that wants to stay extensible and scriptable. Because every row is a Request, every key the user can press is also a CLI command (NOUN VERB --json), a palette entry, a macro step, a config override (the same row shape in a binding file replaces or unbinds it) and a help line (bindings list, the footer, the help modal), with no hidden branch in Go that a script cannot reach. Composite behavior is an operation that calls operations, so a script or an agent can call the pieces on their own; a condition is a named guard, so a config row can carry it ("when": "shadow-idle") and bindings list can show it.

The macro recorder's q row, before and after:

// Before: a Func row that reads the mode and the key in Go. Not a CLI command,
// not a palette entry, invisible to bindings list and to a binding file.
Bind("q", Func(func(r *Runtime, ev KeyEvent) error {
	shadow := ev.Mode.Payload.Shadow
	if shadow.Name == "normal" && shadow.Payload.empty() {
		_, err := r.Execute(Request{Verb: "stop", Noun: "macro"})
		return err
	}
	return record(r, ev)
}))

// After: two atomic rows. q stops under a named guard and falls through to
// the any row otherwise; recording is an operation that calls two operations.
Bind("q", Do("macro.stop")).When("shadow-idle").
Pattern(Any, Do("macro.record").FromKey("key"))      // macro.append {key}, then key.dispatch {key, mode: "shadow"}

The same row in a binding file is {"noun": "app", "mode": "macro_recording", "keys": "q", "when": "shadow-idle", "request": {"verb": "stop", "noun": "macro"}}, and ochazuke macro record --json '{"key": "j"}' is the recorder's step from the command line.

Verb/noun command line

The palette's vocabulary is the registry's verbs and nouns, not a flat list of complete commands. One command line accepts either order:

  • A verb first, then a noun that supports it (or no noun: the focus path supplies it).
  • A noun first, then one of its verbs (or one of its instances, for a noun with a source).
  • Both orders name the same registered operation; the order does not change its meaning.

Illustrative relationships (JavaScript notation, not a Go API contract):

{
  operations: [
    { verb: "create", noun: "task" },
    { verb: "edit", noun: "task" },
    { verb: "edit", noun: "project" }
  ],
  firstWord: { verbs: ["create", "edit"], nouns: ["task", "project"] },
  "edit ":    { nextNouns: ["task", "project"] },   // the complement of the verb
  "task ":    { nextVerbs: ["create", "edit"] },    // the complement of the noun
  "edit task": { key: "task.edit" },
  "task edit": { key: "task.edit" }
}

Both completions derive from the shared operation registry, so they expose the same supported verb/noun pairs.

Shared command and query API

One registry describes supported operations, validated argument types/requiredness, and result descriptions. Commands mutate state; queries inspect it. Unknown operations, unknown arguments, and invalid argument types are rejected before handler execution.

An operation key is noun.verb (input.undo, worktree.remove): the same string the CLI spells NOUN VERB, the same order as Define(noun).Verb(verb), and ownership reads as a path, so a catalog sorted by key groups by noun. Rows written in the earlier verb.noun spelling are rewritten on load for one release and reported by ValidateBindings (two-word keys only: a longer key is never swapped).

Noun namespaces

A noun may be dotted (ochazuke.settings, ai.skills), and so may a verb (dirs.base.add): the action table is flat, a key is a name looked up whole, and a registered action carries its own noun and verb. A name nothing is registered under splits on its last dot (ochazuke.SplitKey: ochazuke.settings.set is noun ochazuke.settings, verb set). See "Action aliases" below. The framework's own nouns live in the ochazuke namespace (FrameworkNamespace): everything NewRuntime, NewModel and the framework constructors register (inside Runtime.Builtin) is ochazuke.<noun> (ochazuke.list, ochazuke.settings, ochazuke.page; app itself stays app, so the app noun's verbs (app.quit, an application's own app.state) never collide with a framework noun such as ochazuke.state), with the short name as an alias (Runtime.Alias, Runtime.Aliases). So:

  • Input accepts either name. Do("list.move"), Request{Noun: "settings"}, a bindings.json or actions.json row naming list, a palette word (settings names or ochazuke.settings names, one word each) and the CLI (bin settings list, bin ochazuke settings list, bin ochazuke.settings list) all reach ochazuke.list / ochazuke.settings (Runtime.CanonicalNoun, CanonicalKey, Operation(key), NounWords).
  • Output is canonical. History (and history.jsonl, which reads old short-named lines as canonical), bindings.list, operations.list, the snapshot and the catalog print ochazuke.settings.set; the footer's hints, the ? help, the jobs ticker and confirm prompts draw the shortest name that reaches the noun (DisplayNoun, DisplayKey: list.move).
  • Define extends, DefineOwn claims. Define("terminal").Verb("copy", …) (or Register with noun terminal, or Kind("prompt")) adds to the framework's ochazuke.terminal. An application with a noun of its own under a framework name declares it with DefineOwn("settings"): from then on settings (keys, files, palette, CLI) is the application's noun and the framework's stays reachable as ochazuke.settings, its verbs intact; nothing is deleted to make room. A noun the application registers under the short name before the framework registers its alias (an instance made before NewModel) owns the name the same way.
  • The v0.16.0 spelling still loads, for one release. v0.16.0 named the framework's nouns app.<noun>; app.settings, app.list.move, bin app settings list and binding, actions and history files holding them are read as ochazuke.<noun> (deprecated) unless a noun of that exact name exists or app has a verb of that name (an application's app.state verb keeps app.state). History reads them back canonical.
  • No overlap. A noun x and a noun x.y coexist, but a verb y on x beside a noun x.y (or the reverse) is refused when registered.
  • Extensions in a host. A host mounting an extension's catalog names its nouns under the extension (cli.Namespace("ai") as PageConfig.Noun: skills is the host's ai.skills; cli.Local reads it back), the namespace taken from the binary with cli.ExtensionNamespace(bin) (its base name lower-cased without a leading o-: o-ai is ai, o-qbt is qbt, mtm-mermaid stays; an error when that is not one noun word or is ochazuke, app or a framework noun's short name), so every host mounts an extension under the same name and two extensions and the host never clash; the extension's own binary keeps its short names. The catalog publishes the active aliases (CatalogDoc.Aliases, CatalogDoc.CanonicalNoun).
  • Short names for any noun. A host gives a mounted noun a bare alias (Runtime.Alias("doc", "json.doc")), keeps an old spelling as a deprecated one (Runtime.AddNounAlias(NounAlias{Alias: "json-doc", Noun: "json.doc", Since: "v0.57.0", RemoveAfter: "v0.58.0", Note: "…"})) and takes a name back while it runs (Runtime.Unalias("doc"), then Alias the new one). NounAliasesOf(noun) lists a noun's names (live shortest first, then deprecated). Every path reads them alike: the palette and the CLI take doc rows, json doc rows, json.doc rows and json-doc rows.
    • Display. A noun is drawn by its shortest live alias (DisplayNoun: doc), never a deprecated one; setting nouns.display (shortest default; framework shortens only the framework's nouns, as before v0.57; canonical draws every noun by its registered name).
    • Deprecated aliases run with one notice per runtime (json-doc is an old name of doc (renamed in v0.57.0; removed after v0.58.0), NoteNounAlias, NounAliasNotice; the CLI prints it as notice:), are noted by bindings check on a row naming them, and are never completed, listed in CLI help or published in the catalog's aliases.
    • In the palette a noun's other names (its canonical spelling and every alias) are taken typed whole and never completed, and an exact name beats a prefix (doc is json.doc's alias though it is a prefix of docs). Leading words that join with dots into a noun are that noun (json doc rows), and after a namespace's words its nouns' next words complete (json offers doc · json.doc; a typed prefix offers json · namespace): setting palette.namespace-words. A word no noun or alias claims reads as the namespaced nouns whose last part it is (palette.noun-tails): one is taken (schema for json.schema), several are offered by their full names and none is picked ("doc" is ambiguous: json.doc, md.doc).
    • Compared with Vim. Vim's Ex commands resolve the same way: a full name wins over an abbreviation, and an abbreviation two commands share is an error (:help 20.2, E464) rather than a guess. Vim has no namespaced commands, so the namespace words and the tail reading are ochazuke's; a deprecated alias is like an option's old name kept working, with a notice Vim does not give.
  • A noun's row source. A host's list of a catalog noun with no source loads the noun's row source (cli.CatalogDoc.RowSource): its list verb when that declares the noun's own rows (NounBuilder.Rows), else another verb declaring the noun's own rows, else a list declaring no rows (its answer is the noun's own rows), and only then a verb declaring another noun's rows (mtm's store.tables); inside a step, sorted order. A verb listing something else (slack-channel.history, the channel's messages) can declare its rows without taking the noun's list over.

Public user actions and registered state are the compatibility surface. Implementation helpers and handler functions are not remotely callable code.

The same registered operation is accessible through:

  • The Go API.
  • Keybindings.
  • The command palette.
  • A central CLI with subcommands.
  • Optional individual CLI executables delegating to the same interface.

Live CLI examples:

/tmp/ochazuke modal push --json '{"id":"draft","input":"dialog"}'
/tmp/ochazuke modal pop
/tmp/ochazuke mode set --json '{"mode":"insert"}'
/tmp/ochazuke bindings list
/tmp/ochazuke state get --json '{"path":"/modals"}'
/tmp/ochazuke state get --json '{"path":"/inputs/directory/text"}'
/tmp/ochazuke mode register --json '{"name":"directory-search"}'

JSON inspection covers registered pages (page, pages), inputs and histories, the focus and the open modals (focus, modals, each modal instance's payload.return), the global mode (mode, modeState) and the registered modes (pending modes included), nouns with their tables, instances with their payload, and the rows the focus answers to (bindings). state.get accepts a JSON Pointer ("" for the full state; ~1 escapes / and ~0 escapes ~ in a key). Appearance has its own appearance.get query. All registered inputs are public state: do not register secrets without adding an explicit export policy. Handlers, renderers, and terminal handles are not serialized.

Telling the user: notices and status

A handler says what to tell the user and the host decides how it looks. There are three things to say:

  • ctx.Notify(text) posts a persistent notice and returns its NoticeID; ctx.ClearNotice(id) takes it back. It stays until cleared.
  • ctx.Info(text) sets the status line to a plain message ("copied 3 rows", "queued"): drawn before the hints until the next key, a status: line on the CLI.
  • ctx.Error(text) sets the status line to an error: Error: TEXT in the error style in place of the hints until the next key, an error: line on the CLI. A verb that fails returns Failed(err) (drawn the same way); Error is for what fails beside the result (a job's Then, a refresh, a daemon event).

The status line is one slot: Info and Error replace each other and "" clears it. Choose by what happened, never by habit: a failure is Error, anything else (progress, success, "nothing to do", a hint) is Info. ctx.Status(text), the older spelling of Error, is deprecated: the name read as "any status", so plain messages posted through it were drawn Error: …. It works for one release; strictcheck.Check(t) (below) fails an app's tests on any use. Code without a Ctx (setup, a daemon event) posts the same through r.UI(): Notify, ClearNotice, Info, Error. A job's Then already gets a Ctx.

r.Define("worktree").Verb("sync", func(ctx ochazuke.Ctx) ochazuke.Result {
	id := ctx.Notify("syncing " + ctx.Instance.Label)
	return ochazuke.Pending(sync).Then(func(ctx ochazuke.Ctx, _ any, err error) {
		ctx.ClearNotice(id)
		if err != nil {
			ctx.Error("sync failed: " + err.Error())
			return
		}
		ctx.Info("synced")
	})
}, "Sync the worktree")

Each host attaches a sink (ochazuke.UISink: Notify(id, text), ClearNotice(id), Status(text) for the error tone, Info(text) for the plain one; every sink has both, so no message falls back to the error tone, and a sink that wraps another forwards each message with UIMessage.Apply(next); InfoSink is deprecated) with r.UI().Attach(sink):

Host Shows
NewModel notices in the footer (Model.Notices, notice.list, notice.clear); the status line: an error (Model.Status) as Error: TEXT in place of the hints, a plain message (Model.Info) before the hints cut to half the width; the next key clears either, what a key's handler sets stands
cli.Shell notice: TEXT, error: TEXT (Error) and status: TEXT (Info) lines on stderr beside the warning: lines, while the command runs (a job's Then included); UIMessage.Line
A socket or API call (HandleCall) the call's messages in Response.Messages ([{kind, id, text}], kinds notice, clear, status (UIError, the error tone; UIStatus is its deprecated name) and info, omitted when empty) as well as the runtime's sink; CallResponse returns them and ochazuke NOUN VERB prints them on stderr as the shell does
Tests ochazuke.RecordingSink (Messages, Notices, LastError, LastInfo; LastStatus is deprecated)

Deprecated names and the strict check

Every name ochazuke deprecates lives in deprecated.go, built only without the ochazuke_strict tag: it keeps working for one release, then goes. An application adds one test and its suite fails on any use, at the line, with the compiler's message (type-checked, so a Status method of the app's own types is never flagged):

import "github.com/unixsuperhero/ochazuke/strictcheck"

func TestNoDeprecatedOchazuke(t *testing.T) { strictcheck.Check(t) }

Check runs go vet -tags ochazuke_strict ./... from the module root (pass patterns to narrow it), so a vet finding fails it too. Deprecated now: Ctx.Status and UI.Status (use Error for a failure, Info for anything else), UIStatus (UIError), InfoSink (Info is on UISink), RecordingSink.LastStatus (LastError).

With no sink attached messages are discarded, except that until the first sink attaches the UI keeps the last 32 (the startup ring) and replays them, in order, into that sink, then drops them; memory stays bounded whether or not a sink ever attaches. The UI is a component on an instance under app; Runtime has no field for it. Model.Notify(text) still works and posts through the same path.

Tree queries

The instance tree is queried with predicate values, never a selector string. A query is a list of predicates, ANDed; the result is in tree order (app first, depth-first, siblings in the order they were added).

// Go: r.Query(ByNoun("worktree"), Within("sidebar"), Not(Where("marked", "")))
instances.query({ where: [["noun", "worktree"], ["within", "sidebar"], ["not", [["marked"]]]] })
// → [{ id: "wt1", noun: "worktree", parent: "sidebar" }, ...]

Predicates: noun, id, kind (the component an instance fronts, lowercased: input, list, page, terminal; row for a list row, modal for a modal body, else instance), within (any ancestor), child-of (the direct parent), focusable, region, state (the global mode), and the combinators any, all, not over nested lists. A predicate is Predicate{Name, Arg, Of}; an application adds its own with RegisterPredicate(name, func(inst, r, arg) bool) and the CLI can use it at once.

Action history and dot-repeat

Every executed request is one entry in the action history, with a kind:

{ seq: 42, at: "2026-10-24T10:00:00Z", kind: "change",                          // action, change or fetch
  request: { verb: "operator", noun: "input", args: { operator: "d", motion: "word-forward", steps: 1 } },
  context: { focus: "editor", page: "main", mode: "normal", source: "key:w" },   // or "macro:a", "palette", "cli", "api"
  result: { ok: true },                                                         // or { ok: false, error: "..." }
  moved: { from: { focus: "row-a", page: "main", mode: "normal" },              // when the request moved the focus, page or mode
           to:   { focus: "row-b", page: "main", mode: "normal" } },
  job: 7 }                                                                      // when an application verb launched work

An entry is the user action, not the data: the value the operation returned stays with the caller (the CLI prints it) and is never encoded into the history, so j over a list of ten thousand rows records the same small entry as over ten. A move is the ids it went between (moved).

Kind What Examples
action The user's interaction: motions, focus, page and modal moves, modes, the palette's own keys list.move, focus.next, page.open, modal.pop, mode.enter
change Edits and verbs that change something; dot-repeat reads these input.delete, settings.set, an application verb (worktree.remove)
fetch Requests for data: state, list and show verbs, reloads, a host calling an extension state.get, jobs.list, bindings.list, a verb declaring Rows or State
system Reserved for what the runtime does on its own (a resize, a finished job); nothing records it yet

The kind comes from the operation (Operation.HistoryKindOf): its HistoryKind when set (NounBuilder.Fetch() sets fetch; actions.json and the catalog carry it as history), else fetch for a verb declaring Rows or State, change for a Repeatable one, action for a Motion, change for any other application verb (an extension verb that declares nothing may change something, so it is kept with the user's entries), and action for any other interaction verb. A host that mounts another CLI's verbs copies each catalog verb's history to its operation.

The ring keeps the last 500 actions and changes (history-limit) and, apart, the last 100 fetches (HistoryFetchLimit), so a host polling a state verb never pushes the user's entries out. A fetch typed into the palette is the user's line: it stays with the actions and changes, and palette Up/Down recalls it.

Read it with history.list {last, kind} (default the last 50 actions and changes; kind is a comma list or all) or state get /history (the last 50 actions and changes); Runtime.History(n) returns every kind and Runtime.HistoryOf(n, kinds...) the ones named. The resolver records key:<keys>, a macro replay macro:<register>, the transport cli, everything else api; a caller sets its own with Runtime.Sourced(source) (outermost caller wins, so keys inside a replay stay macro:a).

Dot-repeat rides on it. . on app in normal mode runs history.repeat {steps}: the last successful change whose operation is Repeatable runs again with its arguments kept, at the current focus (the recorded target is dropped unless the request came from the CLI and the instance still exists), with a count on . replacing the recorded steps (3.). A confirmed request repeats without asking again (confirmed: true is in the record). The repeatable operations are the editor's changes: input.insert, input.delete, input.kill, input.paste, input.operator, input.replace; motions, focus, pages, modals, lists and the history are not. An application marks its own with Operation.Repeatable on Register. Dot repeats one request, so after typing hello in insert mode . inserts the last o, not the whole insert; macros stay key-based.

Standard writes: one simple-value test

A noun with props and a store (props.go, standard_verbs.go) gets the standard writes create, set (alias patch) and delete beside get and list, and its props are reachable as prop-shaped requests: {noun, prop} reads, {noun, prop, value} writes, {noun, prop, toggle: true} flips a boolean, from the API, a key (SetProp/ToggleProp, a bindings file row's "request") or .. One test decides both what . repeats and what the history file keeps: a write is simple when every prop it writes is an enum, a boolean, a number or a duration, and none is secret or multiline. A simple set (or prop write) repeats on the new focus with its value and persists whole; any other write stays in the ring but never repeats and writes no line (a line without its value would read back as another request). So . after editing a title repeats the status change before it. create and delete never repeat; delete asks first (DefaultDeleteConfirm, naming the thing by its label prop, else its Fallback) unless its store names another prompt. Over a visual selection set and delete run once per row, one undo group.

Compared with Vim: . repeats the last change on the new place as Vim's does (:help .), but only simple-value writes: text, lists and secrets are never repeated, where Vim's . repeats text changes too. A prop row such as x → {task status done} is closer to a mapping than to an operator: it takes no motion or count.

Undo of the standard writes: history.undo

Every standard change entry (create, set, delete, a prop row) records what it did to each thing in HistoryEntry.Changes: the noun, the key, and the changed props before and after, read with the store's Get around the write (a create has no before, a delete no after). A store that does not declare Undo is not read around its writes: its change is a mark (noun and key, no values) that history.undo stops at. A visual selection's write is one entry, so its changes are one group. history.list shows them; the history file keeps them only when every value is simple, by the same test as the line.

A store opts in with Store.Undo. Then history.undo reverts the newest change not yet undone: a set writes before back (Patch), a create is undone by Delete, and a delete by Create with the old key, which needs Store.AcceptsKey (the store's Create keeps a key it is given). The inverse is another write, not recorded as a change to undo, so each run goes one change further back; one notice names the things. When the newest change is on a store without Undo (or a delete on a store without AcceptsKey), history.undo is unavailable: it never skips that change to undo an older one. With nothing left it says nothing to undo; in an application where no store declares Undo it is unavailable, so it is never offered there. Changes restored from the history file (an earlier session) are never undone, as . never repeats them. history.undo has no default key (u is taken by lists and trees); the palette, the CLI and a bindings.json row reach it.

Compared with Vim: u (:help undo) reverts the last change and walks back one change per press, and a change made over a visual selection undoes as one, as here. Vim's undo is per buffer and covers every edit, and has redo (ctrl-r) and an undo tree (:help undo-tree); history.undo covers only the standard writes of stores that declare Undo, across nouns, and has no redo yet. Component undo (a tree's u, the Settings page, inputs) stays where it was.

Persisted history

A TUI's history survives restarts. Model.Init calls Runtime.EnsureHistory, which reads history.jsonl from the application's state directory and keeps appending to it:

File $XDG_STATE_HOME/<app>/history.jsonl, else ~/.local/state/<app>/history.jsonl (Config.StateDir overrides the directory; history path prints it)
Format One entry per line, in the shape above.
Kept Palette lines: entries with the source palette, the commands the user ran, failed ones included. Other operations that completed, such as page.open, list.select, settings.set and an application's verbs. Fetches only while the history-fetches setting is on (default off: a host polling would fill the file, and nothing reads a fetch back after a restart).
Never kept Text editing and its plumbing: every operation of the input, editor, key, count, register, macro, yank-history, mode, palette and terminal nouns, so nothing typed or pasted into an input, a prompt, the palette line or a terminal reaches the file. Failed operations that did not come from the palette.
Arguments An argument whose name contains text, value, keys, password, secret or token is left out of the line. An operation keeps them only when it sets Operation.PersistArgs (NounBuilder.PersistArgs()). settings.set does, so set settings theme kombu comes back whole.
Bound The history-limit setting (integer, default 500, 0 keeps nothing). The framework declares it when the history is persisted, unless the application declared a setting of that name. It also bounds the ring.
Restore The last history-limit entries go into the ring before the session's own, marked restored: true. Palette Up/Down recalls their lines; dot-repeat skips them.
Writes Each entry is marshalled on the loop and appended by one writer goroutine, never on the loop. When the file reaches twice the limit, and at load, it is rewritten with the last history-limit lines through a temp file and a rename. Config.Flush (the Model calls it on quit) drains the writer.
Problems Lines that do not parse are skipped. The file gets one notice and is rewritten without them. A write error is one notice, and later entries are not saved.
Off No file without a state directory: Config.Disable() (o-story sessions), a test binary, or an application that sets Config.NoHistoryFile. The CLI shell neither reads nor writes the file.

The in-memory ring still records every kind for history.list and dot-repeat. Only the file is filtered. NoHistoryFile turns the file off entirely.

User actions (actions.json)

actions.json sits beside bindings.json in the config directory (actions path prints it). Each entry adds a verb to a noun the application already defines; the verb runs an external command. It is an ordinary application verb (noun.verb), so a bindings.json row, the palette, the CLI (APP NOUN VERB), ? help and the catalog all see it. Model.Init, cli.Mount and the CLI shell install the file before the user bindings, so a row can name an action.

[
  {"noun": "worktree", "verb": "open", "description": "Open in the editor",
   "command": ["code", "--goto", "{{data.path}}"], "label": "{{label}}"},
  {"noun": "worktree", "verb": "prune", "base": "wt", "target": "{{data}}",
   "confirm": "Prune {{label}}?", "parameters": {"force": {"type": "boolean"}}, "timeout": "30s"},
  {"noun": "app", "verb": "deploy", "command": ["deploy", "{{env}}"], "json": true,
   "parameters": {"env": {"type": "string", "required": true, "enum": ["staging", "prod"]}},
   "positional": ["env"], "confirm": "Deploy to {{env}}?"}
]
Field Meaning
noun, verb The existing noun and the new verb (one word). A verb the noun already has is refused
command An argv template, run directly, never through a shell. A string is split on spaces
base The JSON convention instead of command: BASE NOUN VERB --json ARGS [--target TARGET], the shape every ochazuke CLI accepts. call ("noun verb", the noun's words first: "app settings list") names another noun and verb, target is a template for --target (left out when it expands to nothing)
json With command: append --json ARGS
parameters, positional Parameters in the Parameter shape (string, integer or boolean; required, enum, source, free, description) and the order bare words fill them, so the palette, the CLI and help show them
confirm A confirm prompt, as NounBuilder.Confirm takes ({{label}}, {{target}}, {{<arg>}})
label The job's label on the ticker and in jobs list (default the program's name)
dir, timeout, quiet, description Working directory, a duration after which the command is killed, keep the job off the ticker, the help line
foreground true hands the command the terminal (Foreground): the TUI suspends while it runs (o-csv {{data.path}}, an editor) and resumes when it exits; the exit is told on the status line (sh exited, Error: sh exited with status 3, the job failed). No timeout and no captured output; on the CLI it runs on the shell's own terminal

Templates ({{name}}) in command, base, target, label and dir expand to target or id (the instance the verb runs on), label (its label, else its id), noun, verb, data (the instance's Data: a string as is, else JSON), data.KEY (one field of Data as a JSON object), args (the arguments as one JSON object) or a declared parameter. An unknown placeholder makes the entry malformed. An argv word that is one placeholder and expands to nothing is left out, so an optional parameter disappears instead of passing "". The command also gets OCHAZUKE_ACTION, OCHAZUKE_TARGET, OCHAZUKE_LABEL and OCHAZUKE_ARGS in its environment and no standard input.

The work runs off the loop as a job (Pending(...).Label(label)): the ticker shows noun.verb label running, the context is cancelled when the owning instance closes, and the command's standard output is the job's result: one JSON document, a list when every line is JSON (JSON Lines), else the trimmed text. A non-zero exit fails the job with the last line of standard error. The CLI shell prints the result as it prints any job's.

A malformed entry (an unknown field, noun or placeholder, a bad type, command and base together) is skipped and is a persistent notice (a CLI warning:); the rest still install. actions reload reads the file again (the last load's verbs go first) and reapplies the user bindings; actions list prints the installed entries.

Security: commands come only from the user's own actions.json in the config directory. A catalog, a binding row, a socket call or an application's data can name an action's verb, as they can any verb, but never define or change what it runs: there is no operation that loads actions from another path, the catalog publishes the verb's parameters and never its command, and a sandbox (Config.Disable, o-story, a test binary) reads no file. Values reach the command as argv words, not shell text; if an entry runs sh -c itself, pass values as positional arguments ("sh", "-c", "git log \"$1\"", "sh", "{{data.path}}") rather than inside the script.

Foreground programs

A verb hands the terminal to another full-screen program by returning Foreground(cmd *exec.Cmd) (foreground.go): the runtime admits it as a job of the verb (the ticker shows it, Label and Then work as on Pending), the Model answers its ForegroundMsg with tea.ExecProcess (the TUI suspends; Model.Foreground replaces that, as o-story does to run it headless), and the program's exit is the job's completion, a ForegroundExit{Program, Code}: status 0 posts ctx.Info("PROGRAM exited"), another status fails the job with ctx.Error("PROGRAM exited with status N"). A host with no Model (the CLI shell, a test) hands the message to Runtime.Deliver, which runs it in place on the process's standard streams (ForegroundMsg.Run). A command's stdio left nil is the terminal's.

r.Define("export").Verb("open", func(c ochazuke.Ctx) ochazuke.Result {
	return ochazuke.Foreground(exec.Command("o-csv", path)).Label("o-csv")
})

Action aliases

The action table is flat: Runtime.Operations maps a name (noun.verb) to its action, and an alias is one more name for the same action. Nothing is generated or duplicated, so the names cannot drift.

r.Define("pane").
	Verb("kill", app.Kill, "Kill the pane").Alias("forget").          // pane.forget, permanent
	Verb("associate", app.File, "File the pane").AliasOn("project", "associate"). // the same operation under project
	Verb("add-base", app.AddBase).Renamed("base.add", "v0.27.0", "v0.28.0")        // an old name, kept one release
r.AliasAction("pane.zap", "pane.kill")                                // the same, by keys
  • Running. A request, binding row, palette line or CLI call named by an alias runs the canonical action. canonicalRequest rewrites it (Request.Via keeps the alias, and history shows it); the handler reads Ctx.Invoked (application verbs) or Runtime.Invoked() (interaction handlers): Invocation{Name, Noun, Verb, Alias}, where Noun is the alias's noun, the subject side (project for project.associate).
  • Listing. An alias is never an entry of its own. operations.list and the catalog carry aliases on the canonical verb (CatalogVerb.Aliases, ActionAlias objects); the CLI makes a same-noun alias an oden alias of the verb's command (show, display in help) and an alias under another noun a command of that noun's group that says alias of pane.associate; the palette lists the canonical verb with · also NAME and a typed alias narrows to it; ? help names the canonical operation and ends its description with · also: NAME; bindings list rows carry aliases. actions aliases lists every alias with its action and source.
  • Old names. Renamed(old, since, removeAfter) is a deprecated alias (Keep actions: an old name stays one release, recorded in the CHANGELOG). Its first use in a runtime posts one notice, OLD is an old name of NEW (renamed in SINCE; removed after AFTER) (a CLI notice: line).
  • Rules. An alias names a registered noun and a verb (the longest registered noun prefix is the noun, so dirs.base.add is dirs and base.add); it may not be the name of an action (would shadow the action) or of another alias for a different action. An action registered later under an alias's name takes the name: the alias is dropped and the drop recorded (ActionAliasProblems), never a panic, so a host mounting a newer catalog keeps starting.

Alias rows in actions.json

A user adds names without code: an actions.json entry with an alias field is an alias row.

[
  {"alias": "pane.k", "action": "pane.kill", "note": "my short name"},
  {"alias": "list.walk", "action": "list.move"},
  {"alias": "w!", "action": "restructure.write", "args": {"force": true}}
]
Field Meaning
alias The new name, noun.verb on a registered noun (a short framework noun name such as list works)
action The action it runs: a registered key, or another alias (which resolves to its action)
note Free text, listed with it in actions aliases
args Preset arguments the alias runs its action with ({"force": true}); a typed word, a flag or a row's own argument of the same name wins. Checked against the action's parameters at load
paramAliases Old names of the action's parameters the alias still takes ([{"alias": "starred", "param": "value", "since": "v2", "removeAfter": "v3"}], ActionAlias.ParamAliases, ParamAlias). See "Old parameter names" below

Old parameter names. An alias's ParamAliases keep a renamed parameter working for one release (Keep actions, for a flag): pane.star declares {Alias: "starred", Param: "value"}, so bin pane star w1 --starred=false runs as --value=false. The old name is read wherever the alias is: a CLI flag (typed as its parameter), a palette --starred word, a request's or a bindings.json row's args. It is renamed before the alias's presets apply, so a preset the parameter excludes gives way (--starred=false drops star's toggle); when both names are given the parameter's own wins. A dated one (since, removeAfter) posts one notice per runtime on first use, ALIAS: OLD is an old name of NEW (renamed in SINCE; removed after AFTER) (a CLI notice: line), and bindings check notes a row whose args use it with the name to rename the arg to. Help never lists an old name and the palette never completes it. An old name must name a parameter of the alias's action and must not be one. The action itself, named directly, does not take it.

A bare alias has no noun (w!, q, x: a word without a dot; ! and other punctuation are fine, the palette splits only on spaces): its noun is its action's, its full name is noun.alias (restructure.w!, ActionAlias.Bare, ActionAlias.Name() the word), and the word alone runs it: :w! in the palette, bin w! on the CLI, Request{Verb: "w!"} or Do("w!") in code. A bindings.json row names it by its full name ({"noun": "restructure", "verb": "w!"}). A bare alias may not be a noun's name; one named like a registered verb (save, mark) follows the setting aliases.shadow (AliasShadowSetting, in settings/ochazuke.json): refuse (the default) skips and reports the row, allow loads it, and typed alone in the palette or on the CLI the word runs the alias while the verb stays reachable as noun verb. On the CLI an alias with presets is a command of its own whose preset parameters are not required (help lists Presets:).

A bare alias row with shadows: true (ActionAlias.Shadows) may take a verb's name without aliases.shadow and yields to it by what follows (ReadBareAlias, one rule for the palette and the CLI): followed by a noun that has the verb of its name, the line is that noun's verb; an exact noun wins, then the reading of the action's rest parameter (its source offers the word exactly, then as a prefix); a word that is both a noun's prefix and offered by the rest is an error naming both. Its name is the bare word (set), since NOUN.VERB is the verb it shadows. Bare aliases of the same action after the first add their presets (verbose set opt?).

A parameter with Rest: true (Parameter.Rest) takes the rest of the line verbatim: the palette hands it the text from its first word to the end (quotes and spaces as typed), the CLI joins the remaining words with spaces. A verb has at most one, a string with no required parameter after it. Its Source is asked with the text as query and, when it declares cursor (ChoicesCursorParameter), the cursor in it; each choice's id is the text up to the cursor completed, which tab splices in place with no space after.

Alias rows install after the file's actions, so a row may name a verb the same file adds; bindings.json rows may use the alias. A row that would shadow an action or another alias (the framework's, the application's or an earlier row's), names an unknown action or noun, or has an unknown field is skipped and reported like a bad bindings row: a persistent notice at load (a CLI warning:), the result of actions reload, and the lines of actions check and bindings check. bindings check also accepts a bindings.json row spelled by an alias and says what it resolves to (bindings.json: row 2 C: pane.close resolves to pane.kill (an alias, app), plus the new name for an old one).

Writes are never filled silently

A request whose required parameter is missing fails naming it (NAME is required, from the API and the CLI) and the palette asks for it (missing NAME) instead of running. Nothing fills a write's slot from the focus or a guess; a binding row that fills one declares it (FromRow).

Settings and the Settings page

An application declares its settings (Runtime.DeclareSetting(Setting{Name, Type, Default, Description, Enum, Owner, Section, Group, Deprecated}); Deprecated lists older names that settings get|set|reset, Value, a declaration and a settings.json key still reach for one release, each warning once, a write moving the file's value to the current name); the framework's own settings that the key resolver reads are rows of the embedded settings/ochazuke.json (sequence-timeout, duration, default 0s = wait until a key comes, old name terminal-leader-timeout; sequence-unknown, pass or swallow, default pass; sequence-inherit, drop or keep, default drop: a sequence a mode inherits from the mode it extends does not wait over the mode's own row for the keys typed; terminal-leader, default ctrl+a; rename.select, boolean, default true: a rename (outline.edit without select, a RecordSpec with Rename) opens with its text selected, Runtime.RenameSelect), declared when the runtime is made (NewRuntime), so an application can read or set them at startup and a user's settings.json naming them loads with no warning; an application that declares the name itself, before or after, replaces the row with its own default (the embedded check kept when it gives none), and its settings list before the framework's. The leader is a row of settings/terminal.json, declared by EnsureTerminalLeader. A setting declared after settings.json was read (an extension's, a segment's) takes back the file's unknown setting warning for its name. Runtime.BindingTimeout, when positive, fixes the sequence timeout in code in place of the setting. Their values live in settings.json beside bindings.json, and the settings noun reads and writes them from the CLI and the palette (settings list|get|set|reset|reload|path). The declared settings are also the things of the setting noun, a read-only store keyed by name: setting list (with --where owner=app, origin=session, ...), setting get NAME [--prop value] (the focused Settings row when the name is omitted) and setting watch are standard verbs, each setting's props name, type, default, value, enum, description, section, owner (the Settings tab it files under: app, ochazuke or an owner the application declares), group and origin (default, file or session); setting set, show, reset and the other value verbs stay the :set verbs. Each change is checked against the type and the allowed values and written at once. The types are string (with Enum, one of a set), integer, number, boolean, duration ("400ms") and list (SettingList: strings, a JSON array in the file; settings set paths '["~/proj","~/hub"]'; Settings.Strings reads a copy).

settings.edit opens the Settings page, or switches to it when it is already a tab. There is no default key: an application binds it (matomeru binds ,, the demo s on Appearance), and pressing it on the Settings page does nothing.

 › app  extensions  ochazuke
╭─ Sections ─────╮ ╭━ General (6) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╮
│ General      6 │ ┃ scrolloff •  ‹ 3 ›                                    ┃
│                │ ┃ theme        ‹ dark ›                                 ┃
│                │ ┃ wrap         ‹ false ›                                ┃
│                │ ┃ paths        2 items                                  ┃
│                │ ┃              ~/proj                                   ┃
│                │ ┃              ~/hub                                    ┃
│                │ ┃ ignore       (none)                                   ┃
│                │ ┃ editor       vi                                       ┃
│                │ ╰━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╯
│                │ ╭─ theme ───────────────────────────────────────────────╮
│                │ │ Colour theme                                          │
│                │ │                                                       │
│                │ │ Default is dark. Not in settings.json, so the default │
│                │ │ applies.                                              │
│                │ │ Takes one of dark, light, mono.                       │
╰────────────────╯ ╰───────────────────────────────────────────────────────╯
Part What it shows
Tabs One tab per owner (Setting.Owner, settings_owners.go): the application (app, titled by its name), the owners it declares (an extensions tab with a section per extension), then ochazuke, by SettingOwner.Order and declaration order. No tab row with one owner. ] and [ (and g t/g T, hidden) show the next or previous tab on the section it last showed (`settings.tab {step
Sections The shown tab's sections, a list on the left (__settings/sections, rows of the ochazuke.settings-section noun): each section's title (declared by SettingSection, else its ID) and its count, ◦ after a title with a session value. A setting's section is its Section, else its name before the first dot (tree.zoom.root is in tree), else general (titled General). j/k move the shown section with them; j past the last section spills into the settings (R3.4) and k on the first setting comes back to the shown section (the list is SpillToSelection); l/enter open a section (settings-section.open), h on a setting row that does not step goes back to it. tab and shift+tab walk every section in drawing order across the tabs, wrapping (settings.section {step, across}); {name} from the palette takes a title or an ID. While the list has the focus the description is the section's line. The section verbs open, reset (one undo step), write, revert, copy (yank its non-default values as set NAME=VALUE lines) and pick have twins on ochazuke.settings-tab (owner parameter) sharing the handlers
Narrow Below settings.narrow-width columns (default 72; 0 never folds) the section list folds into a selector line at the top of the settings panel, Section ‹ Keys ◦ 2/11 ›, the panel titled owner › Section (n): it is the list's stop, h/l step the section, j goes down into the settings, s or enter picks one from a chooser (settings-section.pick)
Rows One row per setting, no header: the full name on the left (the word :set takes; a • after it when the value is not the default), the value on the right. Settings with the same Group sit together under a heading row (ListItem.Section), after the ungrouped ones. ‹ value › marks a value h/l steps (boolean, enum, number); text and durations show as they are, empty text as (empty). A list setting's row shows its item count (2 items, (none) when empty), and each item is a row directly beneath it with the name column blank
Description The selected setting's description, then Default is X. and where the value comes from: Not in settings.json, so the default applies., Set in settings.json., or settings.json holds an invalid value (why), so the default applies.; then what it takes. On an item row it starts with Item 2 of 3. J/K scroll it when it overflows, and >/< move the divider

settings.layout (default tabs+sections) turns the layout off: tabs is the page before owners (a tab per section, every owner's, no section list), sections drops the tabs and lists every owner's sections under a heading per owner, as Vim's :options lists its topics. ]/[ then step what the tabs hold (the sections with tabs; with sections, they jump to the next owner's first section). settings.mark-session off drops the ◦ marks with the bold values. The owners and sections are data: settings.owners and settings.sections {owner} list them, settings list --json gives each setting's owner, section and group, and an application titles and orders its own with DeclareSettingOwner/DeclareSettingSection (the framework's are settings/sections.json). Stories settings/tab-step, sections-spill, narrow-selector, layout-sections, page-tabs (the tabs layout).

Compared with Vim:

Vim :help ochazuke
:options window :options similar: a page, not a buffer; the section list is its contents
Numbered topic sections (26) optwin.lua headers similar: topic sections inside each owner, not numbered
One flat namespace, plugins' options inside the topics options.txt different: owners are tabs, because extensions are separate programs with their own settings files
<CR> on a contents line jumps to the section :options same idea: l/enter on a section row
A set line per option, edited in place :options similar: the row is edited in place (h/l, enter), and settings-section.copy yanks set lines
gt/gT step tab pages :help gt similar: g t/g T (and ]/[) step the tabs

Where the focus is: focus-display

The framework declares focus-display (FocusDisplaySetting, a row of settings/ochazuke.json, declared when the runtime is made; an application declaring a setting of that name replaces it). It shows where the focus is just left of the mode badge on the title row (the badge stays the right end of the row, so the path grows and shrinks leftward and never moves it), dim (the muted role; faint in mono), so it is clear where a motion landed. The text alone carries the meaning under mono and NO_COLOR.

Value Title row
off (default) NORMAL, as before
noun pane NORMAL: the focused instance's noun as DisplayNoun (list, not ochazuke.list)
stack panes › pane-list › pane NORMAL: the focus path from the outermost level to the innermost, app left out, each level its label when it has one of at most FocusLabelMax (16) cells (a page's is its title), else its noun. Open modals are levels too, after the focus they opened over (work › list › a2 › confirm)

When the path is wider than the room the badge and the title's first quarter leave, it is cut from the left a level at a time behind … › (FitFocusPath), so the innermost level stays; with less room still the innermost level alone follows …. The row is redrawn on every frame, so a focus change, a modal, a mode change or a spill shows at once, and so does a new value: settings set focus-display stack, the Settings page, or the verb focus.display {mode} (off, noun or stack; with no mode, the next in that order). The verb has no default key; it is in the palette (display focus, display focus stack) and the CLI (BIN focus display), and a user binds a key in bindings.json:

[{"noun": "app", "mode": "normal", "keys": "g f", "request": {"noun": "focus", "verb": "display"}}]

Stories chrome/focus-*.

The keys being pressed: keys.echo

keys.echo (KeyEchoSetting, settings/ochazuke.json) shows the last few keys the application received, as a screencast mode does: for recordings (VHS tapes), demos, screen sharing and bug reports. off is the default; footer draws it at the right end of the footer line, badge on the title row before the mode badge. The verb key.echo {placement} sets it, or with no placement takes the next of off, footer, badge (no default key; :echo key, BIN key echo footer).

The echo reads what the dispatcher did with each key (Model.handleKey: the mode before and after the key, and the requests the key ran, from the action history), never the terminal's bytes, so keys read in ochazuke's names (ctrl+w, esc, space) and group as typed:

Typed Shown
5 j 5j (a count joins what follows it)
g (waiting) then g g…, then g g
ctrl+a d (the terminal leader) ctrl+a d
j j j j ×3
h e l l o in an input "hello", or typed 5 with keys.echo-typing count
anything in a secret input (Input.Secret, a Secret prop's record field) nothing at all
: then page open docs enter :page open docs (keys.echo-commands off: :…)
keys an attached terminal pane receives nothing, unless keys.echo-terminal is on

Typing is a property of the verb (Operation.Typing: input.insert, terminal.send, terminal.paste), and a passthrough mode decides what counts as a pane's key, so no key or mode name is special-cased. keys.echo-width (default 28) is the cells the echo reserves, at most half the line, whether or not it holds keys, so the line never reflows; the oldest entries give way to …, the newest is drawn in the accent. keys.echo-count (5) entries are kept, each for keys.echo-linger (3s; 0s keeps them) after its last key, on the Model's one linger timer (JobLingerTick), so a story's fake clock moves it. Stories chrome/keys-echo-*.

Compared with Vim: Vim's 'showcmd' (:help 'showcmd') shows the command being typed (a count, an operator, a pending g) and clears it once the command completes; 'showcmdloc' (:help 'showcmdloc': last, statusline, tabline) places it. keys.echo is the same idea with the placements footer (like last) and badge (like tabline), but it keeps the last few commands after they ran, which a recording needs, collapses typed text and palette lines, and never shows a secret input's keys. Vim has no counterpart to the linger, the entry count or the terminal setting.

Editing saves each change as it is made; there is no save key.

Keys On a setting row On a list item row
enter flip a boolean, take an enum's next value, add an item to a list, else open a one-line prompt prefilled with the value edit the item (i too)
l right space / h left step a boolean, an enum or a number forward / back (one h/l setting.cycle hint)
n on a list, add an item at the end add an item after this one
d d delete the item
r reset to the default (backspace, delete too) reset the whole list
u take back the last change made on the page (ctrl+z too; offered only when there is one) the same

The prompt (setting-prompt): enter sets the value; one that does not validate (or an empty item) keeps the prompt open with the error in the status; esc closes it unchanged. A value another process writes (the CLI's settings set) shows within a second.

q or esc (settings.close) goes back to the page the Settings page was opened from, with the focus and mode it was left in; the next settings.edit reopens on the section and row it was left on. settings.edit registers the page (SettingsPageID, title Settings) when it opens and settings.close removes it, so it is a tab, in the page picker and on page.next only while it is open. An application that wants a permanent Settings tab calls Runtime.AddSettingsPage() where it registers its pages; settings.close then goes back without removing it.

Session values

Settings have three layers, lowest first: the declared default, settings.json, and the session (settings_session.go). A session value is set for this run and not written, as Vim's :set changes the running editor while the vimrc persists; the effective value is the session's, else the file's, else the default. Settings.SetSession(name, value) writes it, Revert/RevertAll (verbs setting.revert {name}, settings.revert) drop it, Write/WriteAll (verbs setting.write {name} and settings.write, aliases save on both nouns and the bare mksettings, after :mkvimrc) move it into the file, and settings.diff lists each setting whose session value differs from the saved one (name, saved value and where it is saved, session value, origin). settings.reset-all resets every setting by the same rule, after asking.

The writes-through rule: a session write goes to settings.json at once when the runtime has no session (no Model's Init ran: a one-shot CLI process, a script) or settings.autosave is on (default off). Writing the file (the Settings page, settings set, Set, Reset, the page's undo) drops that setting's session value, so what was written is what shows. A value another process writes (the poll) stays beneath a session value, and the setting is marked changed on disk. From a CLI process, settings set, reset, write and reset-all ask before they write the file (--yes or -y answers).

Settings.Origin(name) says where the value comes from (Origin{Layer, Path, Line, By, Source, Via, At, Disk}, Origin.String()): "default, settings/ochazuke.json (ochazuke)", "default, declared by the application at main.go:42", "set in ~/.config/APP/settings.json line 3", "set this session by NAME (palette, 14:02)", followed by "; settings.json changed on disk at 14:05" when another process changed it.

The Settings page draws a session value bold with the saved value beside it while the two differ (settings.mark-session, default on):

┃ stack •             ‹ stack ›  (saved: grid)                             ┃
┃ editor              vi                                                   ┃
┃ paths •             2 items  (saved: 1 item)                             ┃

and its description reads Set this session (palette, 14:02); settings.json holds grid. setting.write saves it, setting.revert drops it. Stories settings/session-marker*.

Reviewing session values: settings.review

settings.review (:settings review, BIN settings review; settings_review.go) opens a modal over whatever is open, one row per settings.diff entry: the setting, its saved value and where it is saved (grid (file), vi (default)), the session value (in the session tone) and its origin (Origin.String()). Under the rows the selected setting's description, its default and origin, and what writing or reverting changes ("Writing puts stack in settings.json in place of grid; reverting shows grid again"; a reset session value says writing removes the key).

│ 2 session values differ from the saved ones                  │
│ Setting  Saved         Session  Origin                       │
│ stack    grid (file)   stack    set this session (api, 00:0… │
│ editor   vi (default)  nvim     set this session (api, 00:0… │
│ ──────────────────────────────────────────────────────────── │
│ stack: How panes are laid out                                │
│ Default tabs. Set this session (api, 00:00).                 │
│ Writing puts stack in settings.json in place of grid;        │
│ reverting shows grid again.                                  │

The rows are the setting-change noun; their keys (bindings/settings-editor.json) run the setting verbs with the row's name ("from": {"name": "row:name"}): w setting.write, r setting.revert, s (or space) skip, which moves to the next row and changes nothing; on the modal W settings.write, R settings.revert (it asks first, naming the values, from every path: nothing takes a revert back), q and esc close it. j/k move as in any list. A written or reverted row drops out and the next one is selected; when none is left the review closes with "No session changes left to review". With nothing to review it opens nothing and says "No session changes to review"; a CLI process has no session, so BIN settings review says so and points at settings diff. It is a modal rather than a page because it is a short decision over values that belong to wherever you were, and closing it returns to that focus. Compared with Vim: Vim has no review screen; :set values are never compared with the vimrc, and :mkvimrc writes them all at once (here settings.write, mksettings). Stories settings/review-*.

Setting verbs and settings.apply

Every setting value change is a verb of the setting noun (setting_verbs.go), each with name (default: the focused Settings row) and, where it writes, scope (session, the default, by the writes-through rule above; or file): show {verbose} (the status line: name=value, a boolean name or noname; verbose adds the origin), set {value}, toggle, cycle {step}, reset, increase/decrease/multiply {by} (integers, numbers, durations; multiply not durations), append/prepend/remove {value} (text, or list items as a,b or a JSON array; a list skips items it holds, an absent item or text is not an error). Which verb fits which type is read from the :set type table, so setting.toggle on an integer says what it is for. A verb computes the new value and checks it whole (type, Validate, enum) before it writes; each write is one step of the Settings page's undo. The page's keys run these verbs with scope: file in their binding rows (bindings/settings-editor.json), so the page saves each change at once, as before; the same verb from the palette or the CLI without a scope writes the session.

settings.apply {line, verbose, scope} runs a :set line (set_line.go): BIN settings apply 'scrolloff=5 nowrap'. Every word is checked first, each over what the words before it left its setting at, then each runs as a request to its verb; a refused word changes nothing (level: must be at most 9; nothing was changed), and the whole line is one undo step. Show words reach the status line together (scrolloff=5 nowrap); a leading verbose (or verb, unless a setting has that name) adds each value's origin; the empty line (settings.diff) and all (settings.list) answer their lists, which the palette opens as results; all& asks first. From a CLI process one question names every change (Write scrolloff = 5, wrap = false to PATH? [y/N]; -y answers). Stories settings/set-line-*.

On the palette the line is :set … (set, se, setlocal, setl, setglobal, setg are aliases of settings.apply; line is a rest parameter, so no quotes): :set scrolloff=5 nowrap, :set alone for what differs, :verbose set scrolloff? (verbose, verb) for where a value was set, :options (opt) for the Settings page. set is also the verb of mode, focus, confirm, appearance, palette, register, setting and settings, so set NOUN … runs that noun's verb (set mode normal is mode set normal; the alias row has shadows: true); a word that is a noun's prefix and a setting's (set foc) is an error naming both. tab completes the word under the cursor (settings.complete {query, cursor}): setting names (noNAME/invNAME for booleans, all, all& first), the current value after = (:set scrolloff= and tab gives scrolloff=2), an enum's values or true/false, a list's items after -=. Stories settings/set-line-bare, set-complete, set-ambiguous, set-verbose.

Compared with Vim

:set reads like Vim's: opt, noopt, invopt, opt!, opt?, opt&, opt<, opt=v, opt:v, opt+=v, opt-=v, opt^=v, all, all&, several options on a line, :se, :setl, :setg, :verbose set opt?, :options, and the same <Tab> completion (names, no/inv forms, the current value after =, fixed values, list items after -=). Each type takes the forms in the plan's type table (a boolean the on/off forms; numbers and durations +=/-=/^=; text and lists append, prepend and remove). The differences a Vim user will hit:

  • :set changes this session only, as Vim's does; mksettings (settings.write) saves the session values to settings.json (Vim's :mkvimrc writes a file of :set lines), and settings.autosave makes every :set write it.
  • Several options on a line are all or nothing: one refused word changes none of them (Vim keeps the ones before the error), and the line is one undo step.
  • Settings are global, so :setlocal and :setglobal are :set (Vim's rule for a global option).
  • A short name is any unique prefix (foc for focus-display), not a fixed abbreviation; errors have no E-numbers.
  • set NOUN … runs that noun's set verb when NOUN is a noun (set mode normal).

Not supported: opt&vi (one default per setting), | and " (the palette runs one command), $VAR in values, and hex or octal numbers.

Status segments

Live items (CPU, memory, disk free, a build state) ride the rule under the header, right-aligned, and take no row. Each is a data row:

sysstat.Register(r, sysstat.Options{Enabled: true, DiskPath: dataDir}) // cpu, ram, disk
r.SegmentProvider("build", func(ctx context.Context, s ochazuke.Segment) (ochazuke.SegmentValue, error) {
	return ochazuke.SegmentValue{Text: "green", Tone: ochazuke.ToneDone}, nil
})
r.AddSegment(ochazuke.Segment{ID: "build", Label: "ci", Provider: "build", Every: 10 * time.Second})
r.AddSegment(ochazuke.Segment{ID: "cpu", Every: 5 * time.Second}) // change a row by id

A user adds or changes rows in segments.json beside settings.json (a command runs only from here or from Go, never from a catalog):

[
  {"id": "branch", "label": "git", "command": ["git", "branch", "--show-current"], "every": "10s", "timeout": "1s"},
  {"id": "cpu", "label": "CPU", "order": 1}
]

Sources are provider (Go), command (first line of its output, killed at timeout) or verb (NOUN.VERB, run outside the history); an answer may be {"text": ..., "tone": ...}. Refreshes run off the loop, one per segment at a time, so a slow source never blocks a key. Every part can be turned off: status.segments (all), status.segments.<id> (one), and status.segment-order holds the order. The segment noun lists, shows, enables, disables, toggles, moves and refreshes them from the palette and the CLI. An extension declares verb-sourced segments in its catalog (segments); a host mounts them with cli.CatalogSegments.

Configuration reference (config export)

Every application has a config noun. config path prints where the user files live; config export [DIR] writes a complete reference of the user configuration to copy from; config reload reads every config file again:

APP config path                  # {"config": "~/.config/APP", "state": "~/.local/state/APP", "reference": "~/.config/APP/reference"}
APP config reload                # themes, settings, actions, bindings, then the app's own files: the problems
APP config export                # writes ~/.config/APP/reference/
APP config export ./ref          # anywhere else
APP config export ~/.config/APP --force   # into the live directory: only with --force
File written What it holds
README.md What each file is, where the live files are (Config.Directory()), and the warning below
settings.json Every declared setting at its current value, in declaration order; valid to copy in as is
settings.reference.json Per setting: name, type, default, enum, description, value, set (the settings list shape), one setting per line
bindings.reference.json Every stored key row of every noun, instance and mode in the bindings.load row shape (bindings list --all), in the grouped bindings format below (bindings export), to copy into bindings.json
props.reference.json {standardVerbs, nouns}: the standard verb table (kinds, what each needs, aliases, subject, many, repeat, history, confirm) and every noun with props (its store's kind, each prop's type, flags and default, its verbs with their standard), one per line; the standard-verbs reference page as data
actions.example.json Two actions on the app noun (example-run in the command form, example-call in the base form) using every field, one action per line; installs with no notice
themes.example.json example (the built-in palette, every role as {light, dark}) and example-dark (one colour per role); installs with no notice

The framework's settings (theme, focus-display, history-limit) are declared before the export, so they are in the files. Each file is written atomically (a temp file renamed over it), and a file that would land on a live config file (bindings.json, settings.json, actions.json, themes.json in the config directory, through a symbolic link too) is refused before anything is written unless --force. The result is {dir, files, config, state}. Without a config directory (Config.Disable, a test binary) the export needs a DIR. The README lists the action placeholders and the theme roles.

Config files are JSONC

Every config file ochazuke reads (bindings.json, actions.json, settings.json, themes.json, a file given to bindings load, the embedded default specs) is JSONC: JSON with // line comments, /* */ block comments and trailing commas (read with github.com/tailscale/hujson). The files keep their .json names. A file without a / that is valid JSON skips the JSONC parse (about 0.1 ms against 2.5 ms for 100 KB). An error names the line and column in the file as written, comments counted. settings set edits an existing settings.json in place: the comments, layout and member order stay; a changed value is replaced where it stands, a new one appended at the file's indent. Go: StandardizeJSONC(data), DecodeJSONC(data, &v).

The bindings file format

bindings.json is a grouped table, one group per mode table, one row per line (config export's bindings.reference.json, bindings export PATH, bindings defaults and the cmd/ochazuke keybinding tool write it; FormatBindings):

// ochazuke bindings (JSONC): groups by "noun/mode" context; one row per line, ...
{
  "modes": {
    "leader_pending": {"pending": true},
    "terminal": {"passthrough": true}
  },
  "bindings": [
    {"context": "ochazuke.timeline/normal", "bindings": [
      {"key": "l", "action": "ochazuke.timeline.open"},
      {"key": "l", "action": "ochazuke.timeline.enter"},
      {"key": "enter", "action": "ochazuke.focus.next", "hint": "edit"}
    ]},
    {"context": "ochazuke.editor/visual_count_pending", "extends": "visual", "bindings": [
      {"key": "digit", "action": "ochazuke.count.append", "from": {"digit": "digit"}}
    ]},
    {"context": "pane/normal", "bindings": [
      {"key": "]", "action": "panes.tab", "args": {"delta": 1}},
      {"key": "x", "unbind": true},
      {"key": "u", "when": "busy", "unbind": true}
    ]},
    {"instance": "work/agent", "mode": "normal", "bindings": [
      {"key": "ctrl+r", "action": "pane.restart"}
    ]}
  ]
}
  • Group: "context": "noun/mode", split at the last /; a bare "noun" is the noun's any-mode table (mode ""). An instance's table is {"instance": "ID", "mode": "MODE"}. "extends": "MODE" on a noun group says its table reads that mode's rows after its own.
  • Row: one small object per line, its fields in the order key, action, args, then hint, when, from, hidden, help, replay, capture, target, confirmed, unbind. key is a key or a sequence as everywhere else ("g c", "ctrl+a v"); a key that names a class (digit, alpha-q, one-of:h j k l, paste, any, upper, ctrl+alpha) is a pattern row. action is noun.verb, split at the last . (an alias works, as in a row). {"key": "x", "unbind": true} unbinds the default (with when for a guarded one).
  • A key may repeat. A table's rows are in line order, and on a keypress, at each level of the focus path (innermost first), the first row on the key whose action is available answers (Runtime.Available: the action's own availability, such as timeline.open on a closed card only); when none is, the key goes on to the next level out. A container that must keep a key binds it to the always-available noop (ochazuke.key.ignore, NoopAction): the key is consumed there. A row needs no condition: when (a guard on the row) still works, and bindings check lists such rows as debts.
  • Replacing: a file is one batch. Its first row on a table, mode, key and when replaces every row the defaults had there (so {"key": "l", "action": "my.verb"} on ochazuke.timeline/normal replaces both default l rows), its later rows on the same key are alternatives after it.
  • modes: properties global to a mode, {"pending": true} or {"passthrough": true}. The export writes the application's own; in a user file a mode or an extends that differs from the application's is reported and ignored (a user file cannot define a mode).
  • Writing: one header comment line, then modes (names sorted), then one group per table: nouns by name, each noun's modes by name (the any-mode table first), then instances by ID and mode, the rows in exact table order. A row spelled by an alias is written as spelled.
  • Reading: the grouped format, the v0.33 form of a group ("bindings": {"KEY": "noun.verb" | {action, args, hint, when, ...} | null | [those]}, a key once per object) and the older array of rows ([{"noun", "mode", "keys", "request": {"noun", "verb", "args"}, ...}], any field order) all load; the top level tells rows from groups, each group's bindings tells lines from a key map. A bad group or row is skipped and reported (bindings.json: pane/normal q: ...), the rest loads. bindings check names the format it read on the status line (status: bindings.json: grouped format). A hand-written file is never rewritten: only files the tools write follow this layout.
  • Checking: bindings check also warns (warning: lines) about each guard row of the file (a debt) and each merged row that can never answer, because an earlier row on its key in its table is available whenever it is (two always-available actions on one key: the second is dead). bindings check --debts lists every table's guard rows and their count. The default files' rule check (CheckDefaultBindings) reports a dead row as an error.
  • Rows elsewhere: bindings list --json still answers the array of rows (an API result); settings.reference.json and actions.example.json are arrays written one row per line (FormatRows).

Go: ParseBindings(data) (BindingsDoc, format, error), FormatBindings(doc), Runtime.BindingsDoc() (every stored table), GroupBindings(rows), BindingsDoc{Modes, Groups}, BindingGroup{Noun, Instance, Mode, Extends, Rows}, ModeSpec{Pending, Passthrough}, Config.BindingsFormat(), constants BindingsGrouped, BindingsRows, BindingsHeader; availability: Runtime.Available(request, focus, mode), Runtime.SetAvailability(key, guard), Runtime.AddVerbAvailability(key, guard) (an app's guard beside a verb's own, a framework verb's included; RemoveVerbAvailability, VerbAvailability), NounBuilder.When, KeyEvent.Args; outcomes: Runtime.DispatchOutcome (KeyHandled, KeyUnhandled, KeyConsumed), NoopAction; checks: Runtime.UnreachableBindings(), Runtime.BindingDebts().

Copying a default into a live file pins it: a later version that changes the default does not reach that user. Copy only what you change. A row's guard is part of its identity: a bindings.json row replaces only the rows with the same noun or instance, mode, keys (or pattern) and when, so a guarded row and the unguarded row on the same keys (such as 0 in operator_pending: the count digit with when: count and the line-start motion) are changed one at a time, and the reference loads back unchanged.

config reload reads, in order, themes.json (so the theme setting's choices are current), settings.json (observers see each changed value), actions.json, bindings.json (once; a row can name an action's verb), each only when the application uses it, then the files the application joined with Runtime.OnConfigReload(name, fn). A bad file or entry is skipped and is a notice, never fatal; each file's previous notices are withdrawn first. The result is every problem, each naming its file; without a config directory it is an error. The single-file reloads (themes reload, settings reload, actions reload, bindings reload) stay.

r.OnConfigReload("directories.json", func() []string {
	return app.LoadDirectories() // problems, each prefixed "directories.json: " unless it already is
})

Go: Runtime.ExportConfig(dir, force) (ConfigExport, error), Config.Paths() ConfigPaths, Runtime.ReloadConfig() ([]string, error), Runtime.OnConfigReload(name, fn); constants ReferenceDir, ReferenceReadme, SettingsReferenceFile, BindingsReferenceFile, ActionsExampleFile, ThemesExampleFile.

Catalog inspector (catalog inspect)

Every app mounted with cli.Mount has BIN catalog inspect: one self-contained HTML page for browsing the app's nouns, verbs, key rows, user actions and the framework nouns, plus any other tools' catalogs. It reads only; it never writes the live config.

APP catalog inspect                      # writes <state dir>/catalog-inspect.html (the temp dir without one), prints the path
APP catalog inspect --out page.html --open
APP catalog inspect --bin o-ai --bin ~/bin/o-git --catalog saved.json    # merge other tools' catalogs
APP catalog inspect --annotations notes.json                            # fill the Gaps view
APP catalog inspect --audit ~/hub/o-plans/lists/verb-audit.md           # the family verb-audit.md format
Flag What it adds
--out FILE Where to write the page (default <state dir>/catalog-inspect.html)
--open Open the page once written (open, xdg-open)
--bin PATH Another tool: runs PATH catalog, with the ochazuke version from its build info (repeatable). A tool already read (by its executable or its catalog's name) is skipped; a failing one shows as a failed row
--catalog FILE.json A saved BIN catalog answer (repeatable; read before --bin, so a file pins its catalog name)
--namespace PREFIX A prefix the app mirrors a tool's nouns under (ai for ai-agent) when that tool is not read; a read tool's short name is one already (repeatable)
--annotations FILE.json Notes for the Gaps view: per noun, suggested verbs (verb, params, maybe, note, group) and a dated source (inspect.Annotations documents the JSON)
--audit FILE.md The same from the family's verb-audit.md format (inspect.AuditAnnotations); not with --annotations
--json FILE Also write the merged data as JSON
--timeout D Per --bin catalog (default 20s)

The app's own key rows are its effective rows, what config export writes to bindings.reference.json (the live bindings.json included); every other tool's are its catalog's defaults. Its actions.json verbs are marked as user actions. Framework nouns are kept once under an ochazuke pseudo-tool whichever catalogs carry them, the newest ochazuke's definition winning (an older catalog's bare list folds into ochazuke.list); each verb lists the tools that carry it. A noun named with another read tool's short name and a dash or dot (ai-agent, ai.agent) groups as that extension's mirror and links to its noun. The page has the data inlined, plain JS and no network, works from file://, and has four views (1 By noun, 2 By key with duplicate and shadowing checks, 3 Relations with missing mirrors, 4 Gaps, shown only with annotations); ? lists its keys.

The family-wide page (mtm, every o-* tool mtm extension available finds, nabe, and the verb audit):

mtm catalog inspect $(mtm extension available | jq -r '.[] | select(.status != "missing" and .bin != "") | "--bin=" + .bin') \
  --bin nabe --audit ~/hub/o-plans/lists/verb-audit.md --out ~/hub/o-plans/inspector/index.html

Go: package cli/inspect (standard library only): ParseCatalog, Collector (Add, AddBin, AddFile, SeeBin), Namespaces, Merge(sources, namespaces, actions, host) *Data, Write(data, w), Annotations (ReadAnnotations, Normalize, Match), AuditAnnotations(markdown). node cli/inspect/smoke.mjs PAGE.html [DIR] is the page's headless Chrome check; OCHAZUKE_INSPECT_OUT=/tmp/demo.html go test ./examples/demo -run TestCatalogInspect writes a page to run it on.

Live CLI control

The live transport is a local Unix socket. Its parent directory must be owned by the current user and have no group/other access; the socket is mode 0600. Startup refuses to overwrite an existing socket. Use different --socket paths for different instances. After an unclean exit, verify the old instance is stopped before removing a stale socket.

CLI commands enter Bubble Tea's message loop. The event loop remains the sole owner of UI state; transport handlers do not mutate models concurrently. Queries must also obtain a consistent view through the runtime.

Keyboard, Go API, palette, and CLI use the same command semantics. Queries run through the same event loop and return detached JSON values. The wire protocol accepts one newline-terminated request per connection and returns { "result": ... } or { "error": "..." }, with "messages" when the call posted notices or a status (see Telling the user). The CLI prints the result as JSON and returns a nonzero exit code for errors.

Output formats

Every command of an importable shell (cli.Shell, an app built with cli.Mount) takes --format json|table|markdown|toon (cli.Formats). json is the default and prints exactly what the shell always printed. For a list or state verb's rows (an array of objects, or Lines of Row) the other formats print one table per noun: the noun's declared columns over the rows' cells, else the records' fields with id and label first. table cuts cells with … and drops columns by Priority only when stdout is a terminal (Shell.Width overrides); markdown is a GitHub table; toon is NOUN[N]{col,...}: and one line per row, quoting only values with a comma, a quote or a line break. A result that is not tabular prints JSON with a note on stderr. --format combines with --json '{...}'; a verb with its own format parameter keeps --format as that argument. ochazuke.TableText(cols, rows, width) is the same layout for Go callers.

A TUI for an oden tool

cli.TUI(app) as an oden Default gives any oden tool a Commands page over its catalog (inline commands and <bin>-<name> executables on PATH): command run opens the command in a terminal under its row, attached (ctrl+a d detaches), command help shows its help in the detail beside the list. The terminal is a local pseudo-terminal (cli.StartPty). Its emulator is the terminal.engine setting: tuios-vt (tuios.dev/vt, the default), x-vt (charmbracelet/x/vt) or, in a build with -tags ghostty, ghostty; a change applies to terminals opened after it. Engines are rows (cli.RegisterTerminalEngine) behind one interface, cli.Emulator. examples/hello is the smallest such tool (go run ./examples/hello).

Scope and limits

  • Standalone Go module and example application; no gmtm/Matomeru integration.
  • Vim-style editing, not a complete Vim implementation; no promise of text objects, dot-repeat, or full Vim scripting compatibility.
  • Cursor and edit offsets count Unicode runes, not grapheme clusters. Rendering accounts for terminal cell width.
  • Undo trees, yank history, registers, and macros are in memory; they do not persist across restarts.
  • Custom modes are registered names. Applications supply their mode-specific bindings; unknown modes are not silently interpreted as normal or insert.
  • Modals preserve their own state and existing input instances. Closing a modal restores interaction state, not a stale copy of shared application data.
  • Handler registration and widget construction are Go APIs. User-facing operations, including configuration, palette navigation, field editing, and picker actions, are registered and available through the CLI.
  • Terminals are display and input ownership only: the framework ships no PTY, shell, emulator or daemon client. A TerminalStream is the application's; frames are rows of trusted ANSI with a cursor cell, not a cell buffer the framework interprets. Resize, reconnect and session lifetime belong to the stream.
  • The framework package holds no application pages; the demo lives in internal/demo and every example is built on the public API. The examples are a nested module (examples/go.mod), as is cmd/o-story; they build through the untracked go.work (go work use . ./cmd/o-story ./examples ../monogatari ../oden).

Documentation

Index

Examples

Constants

View Source
const (
	AliasFramework = "framework" // the framework's own old names (registered inside Builtin)
	AliasApp       = "app"       // an application's NounBuilder.Alias, Renamed or Runtime.AliasAction
	AliasConfig    = "config"    // a row of the user's actions.json
	AliasStandard  = "standard"  // generated with a standard verb (NOUN.patch for NOUN.set); gives way, unrecorded, to an application verb of its name
)

Alias sources: who declared an alias.

View Source
const (
	AliasShadowRefuse = "refuse"
	AliasShadowAllow  = "allow"
)

The values of AliasShadowSetting.

View Source
const (
	SinglePathChooser = "chooser"
	SinglePathAlone   = "alone"
	SinglePathForm    = "form"
)

The values of SinglePathSetting.

View Source
const (
	BindingsGrouped = "grouped"
	BindingsRows    = "rows"
)

Bindings file formats, as ParseBindings and bindings check report them.

View Source
const (
	// ChooserRememberSourceSetting reopens a chooser with sources on the
	// source last used for its kind (on), or on its first source (off).
	ChooserRememberSourceSetting = "chooser.remember-source"
	// ChooserEnterSetting is what enter does on a row that can be both
	// opened and picked (a folder in a folder chooser): "open" (the
	// default; alt+enter picks) or "pick" (ctrl+l opens).
	ChooserEnterSetting = "chooser.enter"
)

Chooser settings: rows of settings/ochazuke.json.

View Source
const (
	ChooserSourcesGuard    = "chooser-sources"     // more than one source
	ChooserOpensGuard      = "chooser-opens"       // the highlighted row opens
	ChooserEnterOpensGuard = "chooser-enter-opens" // enter opens it (ChooserEnterSetting, or a row that only opens)
	ChooserUpGuard         = "chooser-up"          // the source can step up
	ChooserUpEmptyGuard    = "chooser-up-empty"    // it can, and the query is empty (backspace)
)

Chooser guards: the rows of chooser.json name them.

View Source
const (
	// ChromeColorSetting is the chrome colour level, a row of
	// settings/ochazuke.json (appearance).
	ChromeColorSetting = "chrome.color"
	ChromeOff          = "off"
	ChromeSubtle       = "subtle"
	ChromeRich         = "rich"
)

Chrome colour: how much colour the chrome (borders, the mode badge, the hint lines) draws is the setting chrome.color, a level: off, subtle or rich. A level is a family of tone rows, chrome.<level>.<role> (the role border.focused at rich is the tone chrome.rich.border.focused), so every colour is data: the built-in rows are in chromeTones, and a themes.json entry overrides any of them as it does any tone. A role with no row at the level draws as it did before the levels existed, so off, which has no rows, is that look exactly.

A chrome row's colours may name the palette roles a tone names, plus mode: the colour of the current mode's badge (its row's background, else its foreground). An application's accent (Appearance.Accent) replaces the accent, border and mode roles in chrome rows, as it replaces the accent everywhere else.

Roles (the fallback is the look before the levels):

border                      an unfocused panel's border
border.focused              a focused panel's border (heavy lines stay)
border.<tone>               a panel given a tone (Layout.WithPanelTone), a card's (Card.Tone)
border.modal                a modal's border
border.completion           the completion popup's border
border.split                the path picker's split rule
panel.title                 an unfocused panel's title
panel.title.focused         a focused panel's title
title.mark, title           the title row's ◆ and the title
mode.<name>, mode.pending,  the mode badge: the first row that exists of
mode.<extends>, mode        the mode's own, pending (a pending mode),
                            the mode it extends, then mode
hint.key, hint.text,        the footer's and every modal's hint line:
hint.sep                    a row's key, its action, the " · " between
View Source
const (
	SettingsReferenceFile = "settings.reference.json"
	BindingsReferenceFile = "bindings.reference.json"
	PropsReferenceFile    = "props.reference.json"
	ActionsExampleFile    = "actions.example.json"
	ThemesExampleFile     = "themes.example.json"
	ReferenceReadme       = "README.md"
)

The files config.export writes.

View Source
const (
	BindingsFile = "bindings.json"
	SettingsFile = "settings.json"
)

BindingsFile and SettingsFile are the file names in the config directory.

View Source
const (
	// SourceGo is a default row bound in Go (Bind, ModeBuilder.Bind): an
	// application's own, or one computed at runtime (an instance's rows).
	SourceGo = "go"
	// SourceGenerated is a key sequence's prefix cancel ("g esc"), which
	// the framework adds to every table with a sequence.
	SourceGenerated = "generated"
)

Source labels of bindings defaults for rows no file declared.

View Source
const (
	JobRunning   = "running"
	JobDone      = "done"
	JobFailed    = "failed"
	JobCancelled = "cancelled"
)

Job states as jobs.list and the snapshot report them.

View Source
const (
	KindInteraction = "interaction" // runs synchronously on the loop (default)
	KindApplication = "application" // an AppHandler; pending work runs off the loop
)

Operation kinds.

View Source
const (
	FocusDisplayOff   = "off"
	FocusDisplayNoun  = "noun"
	FocusDisplayStack = "stack"
)

The focus-display values, in the order focus.display cycles them.

View Source
const (
	HelpHere  = "here"
	HelpPick  = "pick"
	HelpTable = "table"
)

The ? help's views. Here is what the focus answers to now (BindingHelp, the default). Pick is the same table for a chosen noun and mode, as if the focus were on that noun in that mode (NounHelp). Table is a chosen noun's keys by mode: a row per key or key class, a column per mode with rows for the noun or app, each cell the operation that answers there. S and tab (bindings-help.view {step}; shift+tab backwards) cycle the views the settings leave on; n (bindings-help.noun) chooses the noun of pick and table, m (bindings-help.mode) the mode of pick, p (bindings-help.place) the place of pick and table: one of the noun's recorded places (NounPlaces), whose chain gives the walk the levels between the noun and app, or no place. All four are rows on the help modal's noun, guarded so they answer, and are hinted, only where they do something.

View Source
const (
	HelpPickSetting    = "help.pick-view"
	HelpTableSetting   = "help.table-view"
	HelpPendingSetting = "help.pending-modes"
)

The help's settings, rows of settings/ochazuke.json (section help): whether pick and table are in S's cycle (both default on; with both off S does nothing and is not offered) and whether the pending modes (counts, operators, registers, the terminal leader, key-sequence prefixes) are pick's mode choices and table's columns (default off).

View Source
const (
	HistoryAction = "action"
	HistoryChange = "change"
	HistoryFetch  = "fetch"
	HistorySystem = "system"
)

The kinds of history entry (HistoryEntry.Kind, Operation.HistoryKind). An action is the user's interaction (a motion, a focus, page or modal move, a mode, the palette's line), a change is an edit or a mutating verb (what dot-repeat reads), a fetch asks for data (a state, list or show verb, a reload, a host calling an extension). HistorySystem is reserved for what the runtime does on its own (a resize, a job that finished); no entry has it yet.

View Source
const (
	KeyEchoSetting         = "keys.echo"
	KeyEchoWidthSetting    = "keys.echo-width"
	KeyEchoCountSetting    = "keys.echo-count"
	KeyEchoLingerSetting   = "keys.echo-linger"
	KeyEchoTypingSetting   = "keys.echo-typing"
	KeyEchoCommandsSetting = "keys.echo-commands"
	KeyEchoTerminalSetting = "keys.echo-terminal"
)

The key echo settings.

View Source
const (
	KeyEchoOff    = "off"
	KeyEchoFooter = "footer"
	KeyEchoBadge  = "badge"
)

The keys.echo placements, in the order key.echo cycles them.

View Source
const (
	KeyEchoTypingText  = "text"
	KeyEchoTypingCount = "count"
)

The keys.echo-typing values.

View Source
const (
	PaneStep       = 5
	PaneShiftLimit = 30
	PaneMinWidth   = 16
	PaneMinHeight  = 3
)

The pane limits: PaneStep is the percent points one pane.grow or pane.shrink moves a divider; PaneShiftLimit bounds Layout.Shift either way; Divide keeps PaneMinWidth cells on each side of a side-by-side split and PaneMinHeight rows on each side of a stacked one, so neither panel collapses.

View Source
const (
	ModeBadgeKeysUpper   = "upper"
	ModeBadgeKeysAsTyped = "as-typed"
)

The mode-badge.key-case values.

View Source
const (
	ModeBadgeWidthWidest = "widest"
	ModeBadgeWidthFit    = "fit"
)

The mode-badge.width values.

View Source
const (
	NounsDisplayShortest  = "shortest"
	NounsDisplayFramework = "framework"
	NounsDisplayCanonical = "canonical"
)

The nouns.display values: shortest (the shortest live alias, any noun), framework (only the framework nouns' short names, before v0.57) and canonical (every noun by its registered name).

View Source
const (
	SourceKey     = "key"
	SourceDigit   = "digit"
	SourceText    = "text"
	SourceCount   = "count"
	SourceLine    = "line"
	SourceSteps   = "steps"
	SourceOp      = "op"
	SourceOpCount = "opcount"
	SourcePrefix  = "prefix"
	SourceLetter  = "letter"
	SourceRow     = "row"
)

Sources a From entry may name: "key" (the key name), "digit" (the key as an integer), "text" (pasted or typed text), "count" (payload count, at least 1), "line" (payload count, 0 when absent, else the operator count), "steps" (count times operator count), "op" (payload operator), "opcount", "prefix" (the key sequence the pending mode holds), "letter" (the key's letter, lowercased, without ctrl+ or shift+: f, F, shift+f and ctrl+f all read f; "" for a key that is not one letter), "row" (the row's Data, see FromRow) and "row:<field>" (one field of it). A From value may name several sources separated by spaces ("prefix key"): their texts are joined with a space, the way terminal.send reads a key list.

View Source
const (
	Digit     = "digit"
	Alpha     = "alpha"
	Printable = "printable"
	// Upper is one uppercase letter (A to Z, any script's capital): it
	// answers before Alpha, which an uppercase letter also belongs to.
	Upper = "upper"
	// CtrlAlpha is one ctrl+letter, ctrl+a to ctrl+z: one row for every
	// control letter, the letter read with the letter source. A legacy
	// terminal sends ctrl+h, ctrl+i, ctrl+j and ctrl+m as backspace, tab
	// and enter, and ctrl+[ as esc, so those never reach the row there;
	// labels a row reads this way should avoid h, i, j and m.
	CtrlAlpha = "ctrl+alpha"
	Paste     = "paste"
	Any       = "any"
)

Pattern names.

View Source
const (
	SelectionChar  = "char"  // characters from the anchor to the cursor (visual)
	SelectionLine  = "line"  // whole lines or list rows (visual-line, V)
	SelectionBlock = "block" // a rectangle (visual-block)
)

Selection shapes: a mode that holds a selection says which shape it selects (DefineSelection, a bindings file's "modes" entry {"selection": "line"}). Code asks the shape, never a mode's name: the editor draws and edits by it, a list starts its row selection when a line-shaped mode is entered on it (list_visual.go).

View Source
const (
	PathFile = "file" // the default
	PathDir  = "dir"
)

Path variants (Parameter.Path).

View Source
const (
	PathStartSetting      = "path.start"
	PathFieldSetting      = "path.field"
	PathHiddenSetting     = "path.hidden"
	PathNoAutoListSetting = "path.no-auto-list"
)

Path settings: rows of settings/ochazuke.json.

View Source
const (
	PathSourceBrowse = "browse"
	PathSourceRecent = "recent"
	PathSourceTyped  = "typed"
)

The path chooser's own sources, in order.

View Source
const (
	// Collection is many things with keys, held by the application
	// (note, task, project).
	Collection = "collection"
	// Singleton is one thing per runtime (app, appearance): get takes no
	// subject.
	Singleton = "singleton"
	// Instances is things that are live runtime instances (pages, panes):
	// the things are the noun's instances, in registration order, and the
	// subject is an instance id (instancesStore). The store's Get, when
	// set, adds the props an instance does not hold; List is the
	// instances unless the store gives its own.
	Instances = "instances"
)

The kinds of store (Store.Kind): what the subject is and which standard verbs make sense.

View Source
const (
	// RoleLabel is the prop a thing is shown by: list rows' label,
	// {{label}} in a confirm or an action template, and choosers.
	RoleLabel = "label"
	// RoleOwner is the reference prop naming the thing that holds this one
	// (move writes it).
	RoleOwner = "owner"
	// RoleArchive is the boolean prop that says a thing is archived
	// (archive and restore write it; delete reads it under the
	// delete.archive setting).
	RoleArchive = "archive"
)

The prop roles (PropSpec.Role): one prop per role.

View Source
const (
	FormNoun       = "ochazuke.form"
	FormFieldNoun  = "ochazuke.form-field"
	FormTextNoun   = "ochazuke.form-text"
	FormChoiceNoun = "ochazuke.form-choice"
	FormOptionNoun = "ochazuke.form-option"
	// FormSuggestNoun is a free text field with suggestions: an input
	// whose enter (normal) and ctrl+space open the suggestions chooser.
	FormSuggestNoun = "ochazuke.form-suggest"

	// FormSuggestionsKind is the suggestions chooser's modal kind
	// (Runtime.Chooser(FormSuggestionsKind) while it is open).
	FormSuggestionsKind = "form-suggestions"
)

Form nouns: the editor, its text fields (single- and multi-line), its choice fields, and the chooser's rows. ("form", not "record", so the palette's words do not collide with the macro verb record.)

View Source
const (
	FormRunnableGuard = "form-runnable"
	FormMissingGuard  = "form-missing"
)

Form availability: form.run is available on a form that runs once (Submit) whose every field is valid (form-runnable), form.next-missing on one with a field still not valid (form-missing). On such a form one of the two always is, so enter's rows (run, next-missing, the field's own action) never fall through to the field's own; on an editor that writes each change neither is, and enter keeps its old action.

View Source
const (
	// SearchCaseSmart ignores case unless the query holds an upper-case
	// letter, then matches case exactly (Vim's ignorecase with smartcase).
	SearchCaseSmart = "smart"
	// SearchCaseIgnore always ignores case (Vim's ignorecase).
	SearchCaseIgnore = "ignore"
	// SearchCaseSensitive always matches case (Vim's noignorecase).
	SearchCaseSensitive = "sensitive"
)

The values of search.case.

View Source
const (
	// SearchMatchSetting is the "/" list filter's starting mode.
	SearchMatchSetting = "search.match"
	// ChooserMatchSetting is the starting mode of choosers and the path
	// picker.
	ChooserMatchSetting = "chooser.match"
	// SearchShowMatchSetting draws the mode's tag on the search line.
	SearchShowMatchSetting = "search.show-match"
)

The match settings: rows of settings/ochazuke.json.

View Source
const (
	MatchSubstring = "substring"
	MatchFuzzy     = "fuzzy"
	MatchRegex     = "regex"
)

The match modes.

View Source
const (
	// SegmentsSetting shows (true, the default) or hides the whole
	// segments area.
	SegmentsSetting = "status.segments"
	// SegmentOrderSetting is the order the user gave the segments
	// (segment.move): ids first to last; segments it leaves out follow in
	// their rows' order.
	SegmentOrderSetting = "status.segment-order"
	// SegmentsFile is the user's segments file in the config directory:
	// a JSON array of Segment rows. A row naming an existing id changes
	// that segment's fields; a new id adds a segment.
	SegmentsFile = "segments.json"
)

The segment settings.

View Source
const (
	DefaultSegmentEvery   = 5 * time.Second
	MinSegmentEvery       = 250 * time.Millisecond
	DefaultSegmentTimeout = 2 * time.Second
	// SegmentMaxWidth is the most cells one segment's text takes.
	SegmentMaxWidth = 32
)

Segment defaults and bounds.

View Source
const (
	ScopeSession = "session"
	ScopeFile    = "file"
)

The scopes a setting verb writes (the scope argument).

View Source
const (
	SettingString   = "string"   // string; Enum limits it
	SettingInteger  = "integer"  // int
	SettingNumber   = "number"   // float64
	SettingBoolean  = "boolean"  // bool
	SettingDuration = "duration" // time.Duration, written as "400ms"
	SettingList     = "list"     // []string, written as a JSON array
)

Setting types: the value a setting holds, as its getter returns it.

View Source
const (
	// SequenceTimeoutSetting is how long every pending key sequence (a
	// multi-key row's prefix such as g of g g, and a row entering a
	// pending mode with a prefix, such as the terminal leader) waits for
	// its next key before the shorter binding runs: a duration, 0 (the
	// default) waits until a key comes.
	SequenceTimeoutSetting = "sequence-timeout"
	// SequenceUnknownSetting says what a key no row continues a pending
	// sequence with does: SequencePass (the default) or SequenceSwallow.
	SequenceUnknownSetting = "sequence-unknown"
	// SequencePass ends the sequence, runs its shorter binding (the
	// leader alone: send it to the pane) and handles the key as if it
	// were typed alone.
	SequencePass = "pass"
	// SequenceSwallow drops the sequence and the key, with a notice
	// naming the keys.
	SequenceSwallow = "swallow"
	// SequenceInheritedSetting says whether a sequence a mode inherits
	// from the mode it extends (a row noun's normal d d, read in
	// visual-line) waits over a row the mode binds on its own for the
	// keys typed (the list's visual-line d): SequenceDrop (the default)
	// lets the mode's own row answer at once, SequenceKeep lets the
	// inherited sequence wait, as before.
	SequenceInheritedSetting = "sequence-inherit"
	// SequenceDrop: an inherited sequence never shadows the mode's own
	// shorter row.
	SequenceDrop = "drop"
	// SequenceKeep: an inherited sequence waits as any other does.
	SequenceKeep = "keep"
	// RenameSelectSetting opens a rename (outline.edit without select, a
	// RecordSpec with Rename) with the whole text selected (Input.SelectAll):
	// typing replaces it, a motion keeps it. Default on; off opens it with
	// the cursor at the end.
	RenameSelectSetting = "rename.select"
	// CreateFromFocusSetting lets the standard create fill a reference
	// prop declared FromFocus from the focused thing of its noun when the
	// request omits it, the fill shown in the palette slot, the args form
	// and create's notice. Default on; off fills nothing and the reference
	// stays empty (never a refusal).
	CreateFromFocusSetting = "create.from-focus"
	// DeleteArchiveSetting makes the standard delete archive a live thing
	// of a noun with a RoleArchive prop (it sets the prop) and delete an
	// archived one for real; nouns without the role are unchanged. Default
	// off: delete is the store's delete.
	DeleteArchiveSetting = "delete.archive"
	// DeleteArchiveConfirmSetting is whether a delete that will only
	// archive (DeleteArchiveSetting) asks first, with DefaultArchiveConfirm.
	// Default on; off archives without asking (archive is undone by
	// restore). The real delete of an archived thing always asks.
	DeleteArchiveConfirmSetting = "delete.archive-confirm"
	// CLIStandardVerbsSetting is how the CLI's help shows a noun's
	// standard verbs (cli.Mount): CLIStandardVerbsLine (the default,
	// owner decision 24) names them on one line of the noun's help and
	// after "· std" in its summary, its named verbs keeping their
	// entries; CLIStandardVerbsList lists each as its own entry, as
	// before standard verbs. Every verb runs either way.
	CLIStandardVerbsSetting = "cli.standard-verbs"
	CLIStandardVerbsLine    = "line"
	CLIStandardVerbsList    = "list"
	// VisualAfterActionSetting is what a key acting on a visual selection
	// of list rows leaves: VisualAfterEnd (the default, as in Vim) or
	// VisualAfterKeep.
	VisualAfterActionSetting = "visual.after-action"
	// VisualAfterEnd ends the selection and leaves visual-line.
	VisualAfterEnd = "end"
	// VisualAfterKeep keeps the selection over the rows still shown.
	VisualAfterKeep = "keep"
	// VisualListSetting is what V does on a list: VisualListMode (the
	// default) enters visual-line; VisualListMarks selects in normal
	// mode, the older selection.
	VisualListSetting = "visual.list"
	// VisualListMode enters visual-line.
	VisualListMode = "mode"
	// VisualListMarks selects in normal mode.
	VisualListMarks = "marks"
	// RepeatEmptySetting is what dot-repeat with nothing to repeat at the
	// focus does: RepeatEmptyInfo (the default) or RepeatEmptySilent.
	RepeatEmptySetting = "repeat.empty"
	// RepeatEmptyInfo says "nothing to repeat" on the status line, plain.
	RepeatEmptyInfo = "info"
	// RepeatEmptySilent shows nothing.
	RepeatEmptySilent = "silent"
)

The framework settings the key resolver reads.

View Source
const (
	// OwnerFramework owns the framework's settings: the embedded rows and
	// what a framework feature declares (inside Runtime.Builtin).
	OwnerFramework = FrameworkNamespace
	// OwnerApp owns a setting that names no owner: the declaring
	// application's. Its title, unless declared, is Config.App.
	OwnerApp = AliasApp
	// SettingsGeneralSection is the section of a setting whose name has
	// no dot and that names no section.
	SettingsGeneralSection = "general"
)

Owners and sections: where the Settings page files each setting. A setting's owner (Setting.Owner, resolved by Settings.OwnerOf) is a tab of the page; its section (Setting.SectionName) is a row of the tab's section list; its group (Setting.Group) a heading inside the section. Which owner, section and group a setting has comes only from these fields: no code looks at a setting's name beyond the first-dot rule of SectionName.

SettingOwner and SettingSection declarations give an owner or a section its title, a one-line description and its place in the order; without one the title is the ID and the order is the order the owner's or the section's first setting was declared. The framework's own declarations are the embedded settings/sections.json; an application adds its own with Runtime.DeclareSettingOwner and Runtime.DeclareSettingSection.

View Source
const (
	// SettingsLayoutSetting is the Settings page's layout:
	// SettingsLayoutTabsSections (the default), SettingsLayoutTabs or
	// SettingsLayoutSections.
	SettingsLayoutSetting      = "settings.layout"
	SettingsLayoutTabsSections = "tabs+sections"
	SettingsLayoutTabs         = "tabs"
	SettingsLayoutSections     = "sections"
	// SettingsNarrowWidthSetting is the page width below which the section
	// list folds into a selector line; 0 never folds.
	SettingsNarrowWidthSetting = "settings.narrow-width"
)

The Settings page's layout (settings.layout): which owners and sections (settings_owners.go) are tabs across the top and which are rows of the section list on the left.

  • tabs+sections (the default): a tab per owner (drawn with more than one), the shown tab's sections in the section list, the shown section's settings over the detail on the right. Below settings.narrow-width columns the section list folds into a selector line at the top of the settings panel.
  • tabs: a tab per section, every owner's, and no section list (the page before owners).
  • sections: no tabs; the section list holds every owner's sections, each owner's under a heading row (Vim's :options contents).

The section list (settingsSectionsID) is an ordinary List whose rows are the ochazuke.settings-section noun; it is drawn before the settings list, so j past its last row spills into the settings (R3.4). A section row's verbs (open, reset, write, revert, copy, pick) have twins at owner level on ochazuke.settings-tab, sharing the handlers. ] and [ (settings.tab) step the tabs; tab and shift+tab (settings.section {across}) walk every section in drawing order.

View Source
const (
	// SettingsAutosaveSetting makes every session write go to
	// settings.json at once (boolean, default false: session values stay
	// in memory until settings.write).
	SettingsAutosaveSetting = "settings.autosave"
	// SettingsMarkSessionSetting draws a session value bold on the
	// Settings page with the persisted value beside it (boolean, default
	// true).
	SettingsMarkSessionSetting = "settings.mark-session"
)

The framework settings of the session layer.

View Source
const (
	OriginDefault = "default"
	OriginFile    = "file"
	OriginSession = "session"
)

The layers a setting's value comes from (Origin.Layer).

View Source
const (
	// SettingsPageID is the Settings page's instance id.
	SettingsPageID = "__settings"
	// SettingsGeneral titles the section of the settings without one.
	SettingsGeneral = "General"
)

The Settings page: settings.edit opens (or switches to) a framework page of the declared settings, laid out by settings.layout (settings_page_layout.go): by default the owners are tabs across the top (the application, its declared owners, ochazuke; ] and [ step them), the shown tab's sections a list on the left (tab and shift+tab walk every section in drawing order, across the tabs), and the shown section one list of rows on the right, a setting a row: its full name on the left (a • after a name whose value is not the default), its value on the right (‹ value › for one h/l steps); a group's rows sit under its heading. A list setting's row reads its item count, and each item is a row beneath it with the name column blank. Under the list the selected setting's description says what its default is, where its value comes from (the default, settings.json, or the default because settings.json holds an invalid value) and what it takes; J/K scroll it.

Every change is saved as it is made; there is no save key. On a setting row enter edits (a boolean flips, an enum takes its next value, a list takes a new item, any other type opens a one-line prompt prefilled with the value), l/h and space step a boolean, an enum or a number, n adds an item to a list, r (or backspace, delete) resets to the default. On an item row enter or i edits the item, n adds one after it, d d deletes it, r resets the whole list. u (or ctrl+z) takes back the last change made on the page. q or esc (settings.close) goes back to the page the Settings page was opened from, with its remembered focus and mode; the page reopens on the section and row it was left on. A value another process sets (the poll) redraws the open lists.

settings.edit registers the page on first use and settings.close removes it again, so it is a tab only while it is open; an application that wants it as a permanent tab calls AddSettingsPage.

View Source
const (
	NounWordVerb = "verb"
	NounWordProp = "prop"
)

Word kinds ReadNounWord answers.

View Source
const (
	StandardVerbsSetting = "palette.standard-verbs"
	// StandardVerbsLast lists a noun's named verbs before its standard
	// ones in the palette's verb column (the default).
	StandardVerbsLast = "last"
	// StandardVerbsMixed lists them in one alphabetical list.
	StandardVerbsMixed = "mixed"
	// StandardVerbsHidden leaves standard verbs out of the verb column;
	// typing the name, the CLI and bindings still reach them.
	StandardVerbsHidden = "hidden"
	// StandardVerbsTag marks a standard verb "std" in the verb column.
	StandardVerbsTag = "tag"
	// StandardVerbsRecord shows a standard get's answer (one thing) as
	// prop and value rows in the palette's results view.
	StandardVerbsRecord = "record"
)

The palette.standard-verbs setting (plan 2.10, owner decision 25): one list setting for every standard-verb change to the palette. Its parts are an ordering (StandardVerbsLast, StandardVerbsMixed or StandardVerbsHidden; none is mixed, today's one alphabetical list) and the flags StandardVerbsTag and StandardVerbsRecord. A part left out returns its piece to today's behaviour, so [] turns them all off.

View Source
const (
	WatchAdded    = "added"
	WatchModified = "modified"
	WatchDeleted  = "deleted"
)

The types of a WatchEvent.

View Source
const (
	TerminalLeaderSetting = "terminal-leader"
	DefaultTerminalLeader = "ctrl+a"
)

The terminal leader setting: the key that enters leader_pending. Its default is in settings/ochazuke.json; DefaultTerminalLeader is the fallback when the setting holds a key that is not a leader.

View Source
const (
	DefaultModalDim     = 35 // about the scheme's muted colour, as the backdrop always was
	DefaultDimUnfocused = 20
	MaxDim              = 90
)

Dim defaults, in percent toward the background (the settings modal-dim and dim-unfocused, Model.Styles).

View Source
const (
	ModalDimSetting     = "modal-dim"
	DimUnfocusedSetting = "dim-unfocused"
	// ModalBackdropHighlightsSetting: keep (the page's reverse video and
	// underline beneath a modal stay, dimmed) or plain (the backdrop is
	// drawn without them).
	ModalBackdropHighlightsSetting = "modal-highlights"
)

The dim settings: rows of settings/ochazuke.json.

View Source
const (
	ToneWorking    = "state.working"
	ToneNeedsInput = "state.needs-input"
	ToneDone       = "state.done"
	ToneErrored    = "state.errored"
	ToneIdle       = "state.idle"
	ToneExited     = "state.exited"
	ToneStar       = "marker.star"
	ToneQueued     = "marker.queued"
	// ToneSession marks a setting's session value on the Settings page
	// (set this session, not written): bold in every theme, mono too.
	ToneSession = "marker.session"
	// ToneError marks a cell that is wrong (a duplicate key, a value that
	// does not parse): bold on an error background in every built-in
	// theme, bold alone in mono.
	ToneError = "error"
	// ToneChip draws a chip (a query term, a tag) on a dim background;
	// ToneChipFocused is the chip the focus is on, bright: the scheme's
	// surface on its accent, bold. mono draws the focused chip bold.
	ToneChip        = "chip"
	ToneChipFocused = "chip.focused"
)

The tones every built-in theme draws (defaultTones); applications and themes.json add their own names.

View Source
const (
	SelectedBackgroundDrop = "drop"
	SelectedBackgroundKeep = "keep"
)

The values of SelectedBackgroundSetting.

View Source
const (
	TreeAdd    = "add"
	TreeRename = "rename"
	TreeMove   = "move"
	TreeDelete = "delete"
)

Tree change operations.

View Source
const (
	// TreeZoomSetting is how a tree zooms: TreeZoomManual (the default)
	// only through the zoom verbs, TreeZoomAuto also when the selected
	// row's indent takes more than half the tree's width, TreeZoomOff
	// never (the verbs are unavailable and a zoom in place is dropped).
	TreeZoomSetting = "tree.zoom"
	// TreeZoomRootSetting is where the zoomed-on node goes:
	// TreeZoomRootCrumb (the default) ends the breadcrumb and its children
	// are the top rows; TreeZoomRootRow keeps it as the top row.
	TreeZoomRootSetting = "tree.zoom.root"
	// TreeBreadcrumbSetting is where a zoomed tree draws its breadcrumb:
	// TreeBreadcrumbLine (the default) a dimmed line above the rows,
	// TreeBreadcrumbTitle the header beside the mode (after the focus
	// display) while the tree holds the focus, TreeBreadcrumbOff nowhere.
	TreeBreadcrumbSetting = "tree.breadcrumb"
	// TreeBreadcrumbAncestorsSetting is how many of the nearest hidden
	// ancestors the breadcrumb names (default 2); farther ones fold into
	// "…". 0 names them all.
	TreeBreadcrumbAncestorsSetting = "tree.breadcrumb.ancestors"
)

The tree zoom settings, rows of settings/ochazuke.json.

View Source
const (
	TreeZoomManual      = "manual"
	TreeZoomAuto        = "auto"
	TreeZoomOff         = "off"
	TreeZoomRootCrumb   = "crumb"
	TreeZoomRootRow     = "row"
	TreeBreadcrumbLine  = "line"
	TreeBreadcrumbTitle = "title"
	TreeBreadcrumbOff   = "off"
)

The tree zoom setting values.

View Source
const (
	UINotice      = "notice"
	UIClearNotice = "clear"
	UIError       = "status"
	UIInfo        = "info"
)

UI message kinds. The status line is one line with two tones: UIError is the error tone (Ctx.Error; the TUI draws "Error: TEXT" in the error style, the CLI prints "error: TEXT") and UIInfo the neutral one (Ctx.Info: plain text before the hints, "status: TEXT" on the CLI). Either replaces the other. The kind strings are wire values (Response.Messages), so UIError keeps its old wire value "status".

View Source
const ActionsFile = "actions.json"

ActionsFile is the user actions file in the config directory, beside bindings.json.

View Source
const AliasShadowSetting = "aliases.shadow"

AliasShadowSetting says whether a bare alias may take the name of a verb (a typed word): refuse (the default: such an alias row is skipped and reported) or allow (the alias loads and, typed alone, wins over the verb of that name; the verb stays reachable as noun verb).

View Source
const AnyParameterType = "any"

AnyParameterType is the Parameter.Type of a value of any type: a word from the CLI or the palette arrives as text, an API request's value as it was sent, and the handler types it (a standard verb's prop value, propValue).

View Source
const AppNoun = "app"

AppNoun is the noun of the application as a whole (app.quit). It is never namespaced.

View Source
const ArgsFormID = "args-form"

ArgsFormID is the args form's modal instance (one at a time).

View Source
const BindingsHeader = `` /* 199-byte string literal not displayed */

BindingsHeader is the one comment line FormatBindings starts a file with.

View Source
const CancelKey = "esc"

CancelKey is the key every key-sequence prefix answers with mode.leave: a default row "<prefix> esc" is kept in each table that binds a sequence, so Escape cancels a pending prefix without running anything and the resolver never names a key.

View Source
const ChoicesCursorParameter = "cursor"

ChoicesCursorParameter is the parameter a rest parameter's choices source declares to see where the cursor is in the text (a rune offset into the query); without it the cursor is at the end.

View Source
const ChoicesQueryParameter = "query"

ChoicesQueryParameter is the parameter a choices source declares to see the typed text: a source verb with a parameter of this name is called with what the user has typed so far (the word in the palette, the query in a form's suggestions chooser, the value being checked), so it can complete as you type; one without it is called with no arguments.

View Source
const ChooserPreviewMin = 60

ChooserPreviewMin is the width from which a chooser with a Preview draws it beside the rows.

View Source
const ChooserStableHeightSetting = "chooser.stable-height"

ChooserStableHeightSetting keeps an open chooser at the height it reached (settings/ochazuke.json).

View Source
const ClipboardSetting = "clipboard"

ClipboardSetting says which yanks also go to the system clipboard (Registers.Copy): none (only the clipboard register "+), yanks (every yank, not a delete: the default) or unnamed (every yank and delete, as Vim's clipboard=unnamed).

View Source
const ColumnWidthStep = 2

ColumnWidthStep is the cells z > and z < add to or take from a column.

View Source
const CompletionNoun = "ochazuke.completion"

CompletionNoun is the noun whose rows answer while suggestions are open.

View Source
const DefaultArchiveConfirm = "Archive {{noun}} {{label}}? (delete it again to delete it for good)"

DefaultArchiveConfirm is what a standard delete asks instead when it will only archive the thing (delete.archive): the confirm says what happens. delete.archive-confirm off archives without asking.

View Source
const DefaultBindingTimeout = 1000 * time.Millisecond

DefaultBindingTimeout was the key-sequence timeout before the sequence-timeout setting, whose default (0, wait until a key comes) is in settings/ochazuke.json. Nothing in ochazuke reads it.

Deprecated: read or set the sequence-timeout setting (SequenceTimeoutSetting), or set Runtime.BindingTimeout in code.

View Source
const DefaultCompletionDebounce = 150 * time.Millisecond

DefaultCompletionDebounce is the pause after the last edit before an input's search is asked.

View Source
const DefaultDeleteConfirm = "Delete {{noun}} {{label}}?"

DefaultDeleteConfirm is the prompt a standard delete asks before it runs unless the store names its own (Store.Confirm["delete"]; "" asks nothing): a delete is never silent.

View Source
const DefaultRecordDebounce = DefaultTreeDebounce

DefaultRecordDebounce is how long typing in a field pauses before the record is written.

View Source
const DefaultTreeDebounce = 400 * time.Millisecond

DefaultTreeDebounce is how long typing in an outline line pauses before the line is written.

View Source
const (
	// DocsShowConfigSetting adds the user's "yours:" lines to the docs
	// viewer's pages (default on); off, a page reads as the committed
	// file below its header.
	DocsShowConfigSetting = "docs.show-config"
)

The docs noun's setting and the viewer.

View Source
const FitFollowsCursorSetting = "table.fit-follows-cursor"

FitFollowsCursorSetting is the setting that makes a cell-mode table's current column fit its content as the cursor moves (default off).

View Source
const FocusDisplaySetting = "focus-display"

FocusDisplaySetting is the framework setting that shows where the focus is left of the mode badge in the header: off (the default) leaves the chrome as it was, noun shows the focused instance's noun (pane NORMAL), stack the focus path from the outermost level to the innermost, open modals included (panes › pane-list › pane NORMAL). A row of settings/ochazuke.json, declared when the runtime is made; read at every frame, so a change (settings set, the Settings page, the focus.display verb, another process's write) shows on the next one.

View Source
const FocusLabelMax = 16

FocusLabelMax is the widest label (in cells) the stack shows for a level; a level with a longer label, or none, shows its noun.

View Source
const FormsOutsideWriteSetting = "forms.outside-write"

FormsOutsideWriteSetting says what an open record editor does when its record is written from outside it (RecordSpec.Watch, Reload): reload (the default) takes the new values and stays open, focus, field and mode kept, a field with unsaved typing keeping the typing; close leaves the editor (e edits again), as before.

View Source
const FrameworkBindingsSource = "ochazuke/"

FrameworkBindingsSource is the source prefix of the framework's embedded files in bindings defaults ("ochazuke/bindings/list.json").

View Source
const FrameworkNamespace = "ochazuke"

FrameworkNamespace is the namespace of the framework's own nouns: every noun the framework registers (inside Runtime.Builtin) is named ochazuke.<noun> (ochazuke.settings, ochazuke.list, ochazuke.page), with the short name (settings) as an alias. The app noun itself keeps its name (AppNoun), so its verbs (app.quit, an application's app.state) never collide with a framework noun.

View Source
const HelpInsertKey = "ctrl+\\"

HelpInsertKey opens the bindings help in insert mode, where ? types itself: an app row NewModel adds beside ? in normal mode. ctrl+\ is bound by no Readline default, no editor, palette, chooser, completion, filter, form or outline row, and the terminal is in raw mode, so it sends no SIGQUIT.

View Source
const HintsShowHiddenSetting = "help.hints-hidden"

HintsShowHiddenSetting puts the rows marked hidden (the editor's insert keys, the palette key, counts, registers) on the hint lines too; off by default, they are left to ? help and bindings list.

View Source
const HistoryFetchLimit = 100

HistoryFetchLimit bounds the fetches the ring keeps apart from the user's actions and changes, so a host polling a state verb never pushes those out.

View Source
const HistoryFetchesSetting = "history-fetches"

HistoryFetchesSetting is the declared boolean setting that lets the history file keep fetches (entries of kind fetch the user did not type into the palette). Off by default: a host polling a state verb would fill the file and push the user's own entries out of it, and nothing reads a fetch back after a restart.

View Source
const HistoryFile = "history.jsonl"

HistoryFile is the action history file in the state directory.

View Source
const HistoryLimit = 500

HistoryLimit bounds the action history ring.

View Source
const HistorySetting = "history-limit"

HistorySetting is the declared setting that bounds the history file (and the ring while it is persisted): the last N entries are kept; 0 writes and reads no file.

View Source
const ImplicitGuard = "input"

ImplicitGuard is the guard the framework puts on every editor noun row that runs an input operation (input.cancel aside): such a row answers only while the focus is an input itself, not a non-input instance an application parented under one. It is the framework's, not the user's: it is not part of a row's identity, so a row without when replaces or unbinds the default it shadows, and a user row that runs an input operation on the editor noun gets it too, as the default it replaces had.

View Source
const InputWritableGuard = "input-writable"

InputWritableGuard is the verb guard of the editor's editing verbs (insert, replace, delete, kill, paste, begin, undo, redo): false while the focus is a read-only input.

View Source
const JobLinger = 4 * time.Second

JobLinger is how long a finished job stays on the ticker after the frame that first saw it finished. The Model schedules one JobLingerMsg for the earliest remembered finish (Model.lingerCommand), so the row goes on an idle screen; any earlier frame past the deadline drops it too, and a newer job can push it off sooner.

View Source
const JobTickerRows = 2

JobTickerRows is the most entries the jobs ticker shows; they ride the rule line above the footer (Layout.TickerRule), so the ticker takes no row of its own.

View Source
const ListFilterMode = "list_filter"

ListFilterMode is the mode the filter line is typed in.

View Source
const MissingOpensFormSetting = "palette.missing-opens-form"

MissingOpensFormSetting says whether a request missing a required argument, run from the palette's enter or from a key, opens the args form (on, the default) instead of naming the first missing word.

View Source
const ModalAnchorSetting = "modal.anchor"

ModalAnchorSetting turns anchored modals on (the default) or off. A modal opened for something drawn on the page (Payload.Anchor: a form field's chooser) is drawn beside it, sized to its content, so the thing it is for and the lines around it stay visible; off, or when the screen leaves no room, it is centered as every other modal.

View Source
const ModeBadgeKeyCaseSetting = "mode-badge.key-case"

ModeBadgeKeyCaseSetting is the framework setting that sets the case of the keys a pending mode holds in the mode badge (R2.10): upper (the default, NORMAL G for both g and G) or as-typed (NORMAL g, NORMAL G, LEADER PENDING ctrl+a). The mode's name is upper case either way. A row of settings/ochazuke.json, read at every frame.

View Source
const ModeBadgeWidthSetting = "mode-badge.width"

ModeBadgeWidthSetting is the framework setting that sets the cells the mode badge reserves (R2.10): widest (the default) pads every label to the widest base mode's name, so the badge keeps both edges as the mode changes; fit draws each label in its own cells, so only its right edge stays. Either way the badge is the right end of the title row. A row of settings/ochazuke.json, read at every frame.

View Source
const MovementSection = "movement"

MovementSection is the help section that holds every motion, after the app's rows.

View Source
const NoopAction = "ochazuke.key.ignore"

NoopAction is the always-available action that does nothing: a row bound to it consumes its key (KeyConsumed), which is how a container clamps a key its children leave unhandled at an edge.

View Source
const NounPlaceLimit = 2000

NounPlaceLimit bounds the placements kept, in memory and in the file: past it the least recently seen one is dropped.

View Source
const NounPlaceWriteEvery = 2 * time.Second

NounPlaceWriteEvery is the least time between two writes of the placements file while the Model runs; Config.Flush (on quit) writes what is left.

View Source
const NounPlacesFile = "noun-places.json"

NounPlacesFile is the record of where each noun was seen, in the state directory: a JSON array of NounPlace, most recently seen first.

View Source
const NounsDisplaySetting = "nouns.display"

NounsDisplaySetting says which name DisplayNoun draws a noun by.

View Source
const OperatorWritableGuard = "input-operator-writable"

OperatorWritableGuard is input.operator's: false while the focus is a read-only input and the request applies an operator that changes the text to the visual selection (a visual mode's d, c, x: no motion), so those rows stand aside and leave the hints. An operator over a motion (d w, d d) stays available, and the handler leaves it a no-op; the editor's normal c and d rows carry input-writable as their row guard, so a read-only input never enters operator pending for them and the hint line does not offer them (y still does).

View Source
const PagesHiddenSetting = "pages.hidden"

PagesHiddenSetting is the framework setting that hides pages from the tab row and the page-cycling keys (page.next, page.previous, ctrl+j/k): a list of page ids. A hidden page stays registered and reachable: page.open, the page picker (marked hidden), the palette, the CLI and an application's own OpenPage still open it, and while it is current its tab shows so the chrome says where the focus is. Its default is the ids of the pages declared hidden by default (Page.DefaultHidden, the DefaultHidden option, a catalog page's defaultHidden), so an application's opt-in pages start hidden. Once settings.json holds a value it is the whole list; settings reset pages.hidden goes back to the application's defaults. It is read at every frame and every page motion, so settings set, page.hide, page.show, config.reload and another process's write apply on the next one.

View Source
const PaletteChoiceWordsSetting = "palette.choice-words"

PaletteChoiceWordsSetting says whether the palette offers a choice's own word (Choice.Word, a page's title) or its id.

View Source
const PaletteNamespaceWordsSetting = "palette.namespace-words"

PaletteNamespaceWordsSetting turns the namespace words (json doc for json.doc) on.

View Source
const PaletteNounTailsSetting = "palette.noun-tails"

PaletteNounTailsSetting turns the tail reading (doc for json.doc) on.

View Source
const PaletteTextResultsSetting = "palette.text-results"

PaletteTextResultsSetting says how the palette shows a text result: editor, all or plain (settings/ochazuke.json).

View Source
const PanesFile = "panes.json"

PanesFile is the remembered pane dividers in the state directory: an object of page id to Layout.Shift.

View Source
const PathChooserKind = "path-chooser"

PathChooserKind is the path chooser's modal kind; the source last used is remembered under it.

View Source
const PathParameterType = "path"

PathParameterType is the Parameter.Type of a path.

View Source
const PropObject = "object"

PropObject is the prop type of a JSON object (map[string]any). The other prop types are the setting types (SettingString, SettingInteger, SettingNumber, SettingBoolean, SettingDuration, SettingList), parsed the same way: a word such as "3", "true" or "400ms", a JSON array or object.

View Source
const ReferenceDir = "reference"

ReferenceDir is the directory config.export writes to by default, inside the config directory.

View Source
const ResultText = "text"

ResultText is the Operation.Result of a verb whose answer is text to read and copy (a jq program, a JSON mapping), set by NounBuilder.TextResult. The palette shows such an answer in the text view (palette.text-results); the CLI and the API return the value as they return any other.

View Source
const SearchCaseSetting = "search.case"

SearchCaseSetting is how searches treat case: SearchCaseSmart (the default), SearchCaseIgnore or SearchCaseSensitive. A row of settings/ochazuke.json.

View Source
const SelectedBackgroundSetting = "tones.selected-background"

SelectedBackgroundSetting says how the selected row draws a run with a tone background: drop (the default: the row stays one reverse bar, the background left out as the colour is) or keep (the run keeps its background and colour, bold, out of the reverse bar, so an error cell still reads as one on the selected row).

View Source
const SettingsPoll = time.Second

SettingsPoll is how often a Model checks settings.json for a change another process made (the CLI's settings set).

View Source
const SinglePathSetting = "forms.single-path"

SinglePathSetting says what a request whose only missing required argument is a path opens (R7.8): SinglePathChooser (the default) the path chooser at once, its pick running the request, optional parameters left out; SinglePathAlone the same only when the path is the form's one field (with optional parameters, the form); SinglePathForm always the args form. A form that opens on a missing path field of the picker kind opens its chooser over it, so typing reaches the path.

View Source
const TablesFile = "tables.json"

TablesFile is the remembered table views in the state directory: an object of table id (a list's, a grid's) to TableState.

View Source
const TerminalLeaderTimeoutSetting = "terminal-leader-timeout"

TerminalLeaderTimeoutSetting is the old name of sequence-timeout, which now governs the terminal leader as every other pending sequence: settings.get/set/reset, a declaration and a settings.json key under this name read and write sequence-timeout, warning once.

Deprecated: use SequenceTimeoutSetting.

View Source
const TextViewID = "text-view"

TextViewID is the text view's modal: the instance id and, canonical as ochazuke.text-view, its noun.

View Source
const TextViewNoun = "ochazuke.text-view"

TextViewNoun is the text view modal's noun (q closes it).

View Source
const ThemeSetting = "theme"

ThemeSetting is the declared setting that selects the colour scheme.

View Source
const ThemesFile = "themes.json"

ThemesFile is the user colour schemes file in the config directory.

View Source
const TimelineBodyNoun = "ochazuke.timeline-body"

TimelineBodyNoun is the noun of a timeline's body: the place inside the selected card while the focus walks its steps.

View Source
const TimelineCardNoun = "ochazuke.timeline-card"

TimelineCardNoun is the noun of a card that names none.

View Source
const TreeRowNoun = "ochazuke.outline-row"

TreeRowNoun is the noun of a node that names none: enter toggles it.

View Source
const UIStatus = UIError

UIStatus is the error tone's message kind.

Deprecated: use UIError (the same wire value, "status").

View Source
const UndoGuard = "history-undoable"

UndoGuard is the guard history.undo is available under: the newest entry holding changes can be undone (undoable), or, with none, some noun's store declares Undo.

View Source
const YankReportSetting = "yank.report"

YankReportSetting names the setting that has an editor's yank say what it copied on the status line (yankReport).

Variables

View Source
var BuiltinThemes = []string{"adaptive", "dark", "light", "mono"}

BuiltinThemes are the schemes every application has: adaptive follows the terminal's background, dark and light fix it, mono draws no colour.

ChromeLevels are chrome.color's values.

FocusDisplayModes are focus-display's values, in cycle order.

View Source
var KeyEchoPlacements = []string{KeyEchoOff, KeyEchoFooter, KeyEchoBadge}

KeyEchoPlacements are keys.echo's values, in cycle order.

ModeBadgeKeyCases are mode-badge.key-case's values.

ModeBadgeWidths are mode-badge.width's values.

Functions

func BindingHints

func BindingHints(r *Runtime, focus string) string

BindingHints renders the rows a focus answers to in its current mode as a hint line, from the innermost level outward (the focused instance's rows, its noun's, then its parents' up to the page and app): "enter demo.open · : palette.open · ? bindings.help". Motions (Operation.Motion) and hidden rows (counts, registers, macros, ctrl+c) are left to ? help, except a motion row with its own Hint (J reads "J/K detail"; a hint that starts with the row's key and a slash is shown alone), and of rows that run the same request only the first (innermost) key is shown. It is the data bindings.list prints, so a hint never names a key that is not bound; the descriptions are in BindingHelp (the ? modal).

func Call

func Call(ctx context.Context, path string, q Request) (any, error)

Call runs q in the application listening on the socket at path and returns its result (CallResponse keeps the messages too).

func ComposeModal

func ComposeModal(background, title, body, footer string, width, height int, styles Styles) string

ComposeModal centers a content-sized panel over the existing page, not a blank screen. Body and backdrop may contain trusted ANSI; title and footer are raw labels.

func CutKey added in v0.16.0

func CutKey(key string) (noun, verb string, ok bool)

CutKey is SplitKey with ok reporting whether the key held a dot.

func DecodeJSONC added in v0.33.0

func DecodeJSONC(data []byte, v any) error

DecodeJSONC decodes a JSONC document into v. A syntax error or a value of the wrong type names its line and column in data.

func DefaultTones added in v0.26.0

func DefaultTones() map[string]ToneStyle

DefaultTones are the built-in tones and how the built-in themes draw them, a copy.

func FitFocusPath added in v0.20.0

func FitFocusPath(levels []string, width int) string

FitFocusPath joins levels with " › " in at most width cells. When they do not fit, it cuts from the left a whole level at a time behind "… › ", keeping the innermost level; with less room the innermost level alone follows "…", cut from its left when it is wider still. A cut path always starts with "…". Width under 1 is "".

func FormatBindings added in v0.33.0

func FormatBindings(doc BindingsDoc) ([]byte, error)

FormatBindings writes doc in the grouped format: the BindingsHeader line, then "modes" (names sorted, one per line) when there are any, then "bindings" with one group per table in doc order, its rows one per line in table order (a key repeats where the table repeats it). A row is an object with its fields in the order key, action, args, hint, when, from, hidden, help, replay, capture, target, confirmed, unbind.

func FormatRows added in v0.33.0

func FormatRows(rows any) ([]byte, error)

FormatRows writes any JSON array of rows (a slice of structs or objects) one row per line, as FormatBindingRows does, each row's fields in their marshalled order (a struct's declaration order).

func FormatRowsJSON added in v0.33.0

func FormatRowsJSON(data []byte) ([]byte, error)

FormatRowsJSON rewrites a JSON array one element per line, keeping each element's key order; an error when data is not a JSON array.

func InputView

func InputView(in *Input, width, height int) string

InputView renders an input's visible text without a cursor, for inputs that are not focused. See InputBlock.

func IntArg

func IntArg(a Arguments, name string, fallback int) int

func JSONPointer

func JSONPointer(value any, path string) (any, error)

func JobsTicker

func JobsTicker(jobs []JobInfo, width int) []string

JobsTicker renders the ticker's entries: one message per job, "noun.verb state" ("noun.verb label state" when the job has a Label), with ": error" on a failure, each truncated to width (Layout.TickerRule joins them into the rule line).

func JoinHints added in v0.59.0

func JoinHints(cells []HintCell) string

JoinHints is the hint line of cells as plain text, BindingHints' form.

func ListHash added in v0.53.0

func ListHash(records []string) string

ListHash is a list's content hash: SHA-256 (128 bits, hex) of its record hashes in order, one per line. An empty list hashes too.

func MatchModes added in v0.59.0

func MatchModes() []string

MatchModes lists the match modes in cycle order.

func MatchTag added in v0.59.0

func MatchTag(mode string) string

MatchTag is the short tag the search line shows for mode.

func ModalSize

func ModalSize(width, height int) (contentWidth, contentHeight int)

ModalSize returns safe body bounds, reserving the same chrome as ComposeModal. Modal chrome uses one horizontal padding cell regardless of page density.

func MotionScroll added in v0.32.0

func MotionScroll(want, page int) int

MotionScroll is the scroll a motion makes in a view page lines tall when reaching its target would scroll want lines (down when positive): want itself when it is at most half the page, else half the page (at least one line) toward it.

func Namespaced added in v0.16.0

func Namespaced(namespace, name string) string

Namespaced is name under namespace: "ai" and "skills" give "ai.skills"; an empty namespace is name unchanged.

func NextMatch added in v0.59.0

func NextMatch(mode string, step int) string

NextMatch is the mode step places after mode in the cycle (negative steps go back), wrapping; an unknown mode counts as substring.

func On added in v0.36.0

func On(b bool) *bool

On returns a pointer to b, for Segment.Enabled.

func PanelContentSize

func PanelContentSize(width, height int) (int, int)

PanelContentSize returns the body cells available inside a Panel, excluding its border and horizontal padding. Tiny panels omit their chrome.

func ParseSchemes added in v0.2.0

func ParseSchemes(data []byte) (map[string]Scheme, []string)

ParseSchemes reads colour schemes in the themes.json shape, an object of schemes by name:

{"kombu": {"background": "dark", "accent": "#C9A227",
           "error": {"light": "#B3261E", "dark": "#FF8A80"},
           "tones": {"state.working": {"fg": "#5FAFD7", "bold": true}}},
 "dark":  {"tones": {"build.cached": "muted"}}}

A role left out takes the built-in palette's; "tones" (ToneStyle by tone name) are laid over the built-in tones. An entry named after a built-in theme holds only "tones": they override and add to that theme's (adaptive's reach dark and light too). A scheme that does not validate (an unknown role, a bad colour, background or tone, a built-in's name with anything but tones, an error colour equal to the accent or muted one) is skipped and reported; a file that is not a JSON object yields no schemes.

func RecordHash added in v0.53.0

func RecordHash(line []byte) string

RecordHash is a record's hash: SHA-256 (128 bits, hex) of its encoded line, surrounding space trimmed. The state delta protocol hashes row lines with it (cli.RecordHash) and watch hashes things.

func RegisterInputOperations

func RegisterInputOperations(r *Runtime)

func SegmentSetting added in v0.36.0

func SegmentSetting(id string) string

SegmentSetting is the setting that shows or hides one segment.

func SortBindings added in v0.15.0

func SortBindings(rows []Binding)

SortBindings orders rows the way the full export (bindings.list --all, bindings.reference.json) prints them: by mode (the any-mode rows, mode "", first), then by noun, a noun's rows before an instance's of the same name, then by the request's verb (a row with no verb, an unbind, after every verb), then by keys, a pattern row after the key rows; stable, so rows equal on all of these keep their stored order.

func SpanInView added in v0.32.0

func SpanInView(from, to, page int) bool

SpanInView reports whether any of lines from through to (relative to the view's first line) is inside a view page lines tall.

func SplitKey added in v0.16.0

func SplitKey(key string) (noun, verb string)

SplitKey splits an operation key on its last dot: the noun before it (a noun may be dotted: ochazuke.settings, ai.skills) and the verb after it. It is the reading of a name nothing is registered under; a registered name splits where it was declared (a verb may hold a dot: dirs.base.add), which Runtime.CanonicalKey and the request lookup read from the table. A key with no dot is all noun and no verb.

func SplitKeys added in v0.27.0

func SplitKeys(keys string) (prefix, final string)

SplitKeys splits a key sequence into its prefix and its final key: "z l" is "z" and "l", "ctrl+a v" is "ctrl+a" and "v", "g c x" is "g c" and "x"; a single key (or a pattern, "<digit>") has no prefix.

func StandardVerbs added in v0.52.0

func StandardVerbs() []string

StandardVerbs lists the verbs of the standard verb table, in order.

func StandardizeJSONC added in v0.33.0

func StandardizeJSONC(data []byte) ([]byte, error)

StandardizeJSONC is data as standard JSON: each comment and trailing comma becomes spaces, so every byte offset (and so every line and column) is the original file's. Plain JSON is returned as is, without a copy. A file that is not JSONC is an error naming its line and column.

func StringArg

func StringArg(a Arguments, name, fallback string) string

func TableText added in v0.2.0

func TableText(cols []Column, rows [][]string, width int) []string

TableText lays a table out as plain text lines, the header line first, with the layout a list with columns draws (List.View) and no styling, gutter or highlight: a printer outside the TUI (the command line's --format table) reads the same column declarations. At width > 0 the columns that do not fit drop by Priority and cells cut with "…" at their width; at width <= 0 nothing drops or cuts, every column is as wide as its widest cell or title (Width and Min are ignored). A row with fewer cells than columns has empty ones; control characters in a cell become spaces; trailing spaces are trimmed. No columns is no lines.

func TextBody added in v0.17.0

func TextBody(text string) func(int) string

TextBody is a Body that is always text (wrapped by the timeline).

Types

type Action added in v0.2.0

type Action struct {
	Noun        string               `json:"noun"`
	Verb        string               `json:"verb"`
	Description string               `json:"description,omitempty"`
	Command     Argv                 `json:"command,omitempty"`
	Base        Argv                 `json:"base,omitempty"`
	Call        string               `json:"call,omitempty"`
	Target      string               `json:"target,omitempty"`
	JSON        bool                 `json:"json,omitempty"`
	Label       string               `json:"label,omitempty"`
	Confirm     string               `json:"confirm,omitempty"`
	Parameters  map[string]Parameter `json:"parameters,omitempty"`
	Positional  []string             `json:"positional,omitempty"`
	Dir         string               `json:"dir,omitempty"`
	Timeout     string               `json:"timeout,omitempty"`
	Quiet       bool                 `json:"quiet,omitempty"`
	History     string               `json:"history,omitempty"`
	// Foreground gives the command the terminal (Foreground, foreground.go):
	// the TUI suspends while it runs (o-csv FILE, an editor) and its exit
	// status is told the user; no timeout, no captured output.
	Foreground bool `json:"foreground,omitempty"`
	// contains filtered or unexported fields
}

Action is one entry of actions.json: a verb on an existing noun that runs an external command. It becomes an application operation (noun.verb) like any other, so binding rows, the palette, the CLI, ? help and the catalog see it; its work runs off the loop as a job labelled Label, and the command's standard output is the job's result (JSON when it parses, a JSON value per line when every line does, else the text).

The command is either Command, an argv template run directly (never through a shell), or Base, the convention for a CLI with a JSON form: BASE NOUN VERB --json ARGS [--target TARGET], where NOUN VERB is Call ("noun verb", default this action's noun and verb), ARGS the action's arguments as one JSON object and TARGET the Target template when it is not empty. JSON appends --json ARGS to a Command too.

Templates ({{name}}) in Command, Base, Label, Dir and Target expand to: target or id (the instance the verb runs on), label (its label, else its id), noun and verb (the action's), data (the instance's Data: a string as is, else JSON), data.KEY (one field of Data as a JSON object), args (the arguments as JSON) or a declared parameter's value. An argv element that is exactly one placeholder and expands to nothing is left out, so an optional parameter disappears instead of passing "". Confirm is a confirm prompt template, as NounBuilder.Confirm takes. History is the kind of history entry it records (Operation.HistoryKind): "fetch" for a command that only reads; empty is a change, as for any application verb.

Actions are read only from the user's own actions.json (Config.Path): never from a catalog, a binding row, a socket call or an application's data, so nothing but the user's file decides what runs.

An entry with an "alias" field is an alias row instead (AliasRow): one more name for an existing action, which runs nothing of its own.

func (Action) Key added in v0.2.0

func (a Action) Key() string

Key is the action's operation key, noun.verb.

type ActionAlias added in v0.28.0

type ActionAlias struct {
	Alias        string       `json:"alias"`
	Action       string       `json:"action"`
	Noun         string       `json:"noun,omitempty"`
	Verb         string       `json:"verb,omitempty"`
	Since        string       `json:"since,omitempty"`
	RemoveAfter  string       `json:"removeAfter,omitempty"`
	Note         string       `json:"note,omitempty"`
	Source       string       `json:"source,omitempty"`
	Args         Arguments    `json:"args,omitempty"`
	Bare         bool         `json:"bare,omitempty"`
	Shadows      bool         `json:"shadows,omitempty"`
	Palette      bool         `json:"palette,omitempty"`
	ParamAliases []ParamAlias `json:"paramAliases,omitempty"`
}

ActionAlias is one extra name of a registered action. Alias is the name (noun.verb, its noun canonical), Action the canonical key it runs. Noun and Verb are the alias's own noun and verb: the subject side the handler is told (Invocation). Since and RemoveAfter mark a deprecated alias, an old name kept for one release after a rename (Keep actions): its first use in a runtime posts a one-time notice naming the new name. Note is free text shown beside it. Args are preset arguments the alias runs its action with ({"force": true} for w!): a typed or bound argument of the same name wins. Presets may leave a required parameter out: it is asked for when the alias runs (the args form for a key or the palette, NAME is required for the CLI and the API). Bare marks an alias declared without a noun (w!, q): its noun is its action's, and the bare name alone reaches it in the palette, the CLI and the API (Request{Verb: "w!"}); a binding row names it by its full name (restructure.w!). Shadows marks a bare alias that may take the name of a verb and yields to it by what follows (set for settings.apply beside mode set): typed alone, or followed by words its action's rest parameter reads, it is the alias; followed by a noun that has the verb of its name, the line is that noun's verb (set mode normal is mode set normal). Its name is the bare word (set), since NOUN.VERB may be the verb it shadows. Palette keeps a bare alias to the command line inside the app: the CLI leaves the word to the shell's own commands, so bin help stays the shell's help while :help opens the docs viewer, which needs the TUI. ParamAliases are old names of its action's parameters the alias still takes (ParamAlias): --starred for --value on star.

func (ActionAlias) Deprecated added in v0.28.0

func (a ActionAlias) Deprecated() bool

Deprecated reports whether the alias is an old name on its way out.

func (ActionAlias) Name added in v0.43.0

func (a ActionAlias) Name() string

Name is how the alias is typed: its bare name, else noun.verb.

func (ActionAlias) ParamAlias added in v0.58.0

func (a ActionAlias) ParamAlias(name string) (ParamAlias, bool)

ParamAlias is the old parameter name the alias takes as name, false when name is none.

type AliasRow added in v0.28.0

type AliasRow struct {
	Alias   string    `json:"alias"`
	Action  string    `json:"action"`
	Note    string    `json:"note,omitempty"`
	Args    Arguments `json:"args,omitempty"`
	Shadows bool      `json:"shadows,omitempty"`
	Palette bool      `json:"palette,omitempty"`
	// ParamAliases are old names of the action's parameters the alias
	// takes (ActionAlias.ParamAliases): "paramAliases": [{"alias":
	// "starred", "param": "value"}].
	ParamAliases []ParamAlias `json:"paramAliases,omitempty"`
}

AliasRow is an alias entry of actions.json: {"alias": "pane.k", "action": "pane.kill"} makes pane.k another name of pane.kill, for keys (bindings.json rows), the palette, the CLI and the API. Alias is noun.verb on a registered noun (a short noun name such as list works); Action is a registered action or alias. An alias may not take the name of an action or of another alias; such a row is skipped and reported, as bindings check reports a bad row. Note is free text listed with it. Shadows lets a bare alias take a verb's name and yield to it by what follows (ActionAlias.Shadows); Palette keeps a bare alias out of the CLI (ActionAlias.Palette).

type Align

type Align string

Align is a column's alignment: AlignLeft (the zero value) or AlignRight.

const (
	AlignLeft  Align = ""
	AlignRight Align = "right"
)

Alignments.

type AppHandler

type AppHandler func(Ctx) Result

AppHandler is the signature of an application verb: it reads the Ctx and returns Done, Failed or Pending work. Pending work runs off the loop; its completion is delivered to the owning instance through the contract, so a handler never blocks key handling.

type Appearance

type Appearance struct {
	Theme   string      `json:"theme"`
	Density string      `json:"density"`
	Dark    bool        `json:"dark"`
	Accent  color.Color `json:"-"`
	// Schemes are the colour schemes beyond the built-in themes, by name:
	// the user's themes.json (Model.Init, themes.reload and config.reload set it) or an
	// application's own (NewSchemeSet). A pointer keeps Appearance
	// comparable.
	Schemes *SchemeSet `json:"-"`
}

Appearance is event-loop-owned configuration. Operation results are value snapshots. Dark is the terminal background reported by tea.BackgroundColorMsg; the adaptive theme assumes a dark background until that message arrives.

Accent replaces the theme's accent colour when it is not nil: the title, panel and modal borders, the active tab, the badge and every highlight drawn in the accent take it, so an application can say "you are looking at everything" by colour alone (a pin state). Semantic colours (errors) and the muted text keep their meaning. The mono theme and NO_COLOR stay colourless. Applications set it in code; the appearance verbs leave it.

func NewAppearance

func NewAppearance(r *Runtime) *Appearance

NewAppearance registers appearance operations once per runtime.

func (Appearance) Background added in v0.4.0

func (a Appearance) Background() (background string, plain bool)

Background is the background the appearance draws on, "light" or "dark" (an adaptive scheme follows Dark), and whether it draws no colour at all (the mono theme or NO_COLOR). A renderer with its own palette, such as the markdown package's Glamour styles, picks from it.

func (Appearance) ThemeNames added in v0.2.0

func (a Appearance) ThemeNames() []string

ThemeNames are the schemes Theme can name: the built-in themes, then the application's or user's (Schemes) by name.

type ArgumentError added in v0.1.1

type ArgumentError struct{ Err error }

ArgumentError is a request refused for its arguments (a missing required one, a wrong type, a value outside the enum or the source's choices) before any instance was chosen, so a caller never blames the target for it (the CLI adds no "pass --target" hint).

func (*ArgumentError) Error added in v0.1.1

func (e *ArgumentError) Error() string

func (*ArgumentError) Unwrap added in v0.1.1

func (e *ArgumentError) Unwrap() error

type Arguments

type Arguments map[string]any

Arguments are a request's named arguments, keyed by parameter name.

func ParseArguments

func ParseArguments(raw string) (Arguments, error)

ParseArguments parses the same JSON object used by the wire API.

type Argv added in v0.2.0

type Argv []string

Argv is a command line: a JSON array of words, or a string split on spaces (use the array for a word holding a space).

func (*Argv) UnmarshalJSON added in v0.2.0

func (v *Argv) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an array of strings or one string split on spaces.

type BareReading added in v0.50.0

type BareReading struct {
	Alias ActionAlias
	Args  Arguments
	Skip  int
	Noun  string
}

BareReading is how a command line that starts with a bare alias reads (ReadBareAlias): the alias and its presets, with the presets of any further bare aliases of the same action right after it (verbose set is settings.apply {verbose: true}), Skip the words they took; or, for an alias that shadows a verb, Noun: the line is that noun's verb of the alias's name (set mode normal is mode set normal).

type Binding

type Binding struct {
	// The field order is the bindings file's (BindingFieldOrder): mode,
	// the noun or instance, the keys or pattern, the request, then the
	// rest. FormatBindingRows writes a file in that order (and the
	// request noun before verb); plain json.Marshal follows the
	// declarations below.
	Mode     string            `json:"mode,omitempty"`
	Noun     string            `json:"noun,omitempty"`
	Instance string            `json:"instance,omitempty"`
	Keys     string            `json:"keys,omitempty"`
	Pattern  string            `json:"pattern,omitempty"`
	Request  Request           `json:"request"`
	When     string            `json:"when,omitempty"`
	Unbind   bool              `json:"unbind,omitempty"`
	From     map[string]string `json:"from,omitempty"`
	Replay   bool              `json:"replay,omitempty"`
	Capture  bool              `json:"capture,omitempty"`
	// Hint replaces "noun.verb: description" in the footer and the help
	// for a row whose operation says nothing useful on its own (the
	// terminal leader's mode.enter); bindings list carries it too.
	Hint string `json:"hint,omitempty"`
	// Hidden keeps the row off the footer's hint line (counts, registers,
	// macros, ctrl+c); ? help and bindings list still show it.
	Hidden bool `json:"hidden,omitempty"`
	// Help replaces the operation's description in ? help and bindings
	// list for a row whose operation is generic (mode.enter into a
	// register, macro or count mode).
	Help string `json:"help,omitempty"`
	// Aliases are the other names of the row's operation, which bindings
	// list adds so a row names its canonical operation and its aliases
	// once; a stored row never holds them (a file's value is dropped).
	Aliases []string `json:"aliases,omitempty"`
	// contains filtered or unexported fields
}

Binding is one row of a mode table, identical in code and config: {noun | instance, mode, keys | pattern, request | null, from, when}. Keys is an exact key or a space-separated sequence ("g g"); Pattern is a key class: digit, alpha, printable, paste, any, a class minus keys ("alpha-q"), or a set ("one-of:h j k l"); upper is one uppercase letter and ctrl+alpha one ctrl+letter (ctrl+a to ctrl+z). From fills request arguments from the key or the mode payload (see Sources). When names a registered guard. A row's identity is its table (noun or instance), mode, keys or pattern and guard: a row replaces only the row with the same identity, so a row with When and the unguarded row on the same keys coexist, and Unbind removes only the row with the same identity (an unbind row without When removes the unguarded row, never a guarded one). The editor noun's implicit "input" guard is not part of the identity (see withImplicitGuard). Replay dispatches the key again, fresh, after the row ran (a pending mode that hands an unknown key back to the stack). Capture rows are consulted outer-first (app first) before the inner-first walk (see resolve.go).

A row is atomic: a Request (one registered operation, its arguments from the row, the key or the payload), a mode transition (Enter, Leave) or an unbind. There is no row that runs Go code with the key. Composite behaviour is an operation whose handler calls other operations through Execute (macro.record, terminal.paste under the leader); a condition is a named guard. TestBindingRowsAreAtomic pins this for every table.

func Do

func Do(operation string, args ...Arguments) Binding

Do builds a row that runs "noun.verb" with optional arguments.

func Enter

func Enter(mode string, payload ...Payload) Binding

Enter builds a row that enters a pending mode with a typed payload: the operator fields (Op, Count, OpCount) and, for a leader, Prefix (the key sequence the mode holds, which arms the sequence timer) and Request (what the timer runs when no second key arrives).

func HintBindings added in v0.16.0

func HintBindings(r *Runtime, focus string) []Binding

HintBindings is the rows BindingHints shows, in its order: what a check of the footer presses to prove every hint answers.

func Leave

func Leave() Binding

Leave builds a row that returns from a pending mode to the mode it shadowed.

func SetProp added in v0.53.0

func SetProp(noun, prop string, value any) Binding

SetProp builds a row that writes value to noun's prop (the file's {"key": KEY, "request": {"noun": NOUN, "prop": PROP, "value": VALUE}}).

func ToggleProp added in v0.53.0

func ToggleProp(noun, prop string) Binding

ToggleProp builds a row that flips noun's boolean prop ({"request": {"noun": NOUN, "prop": PROP, "toggle": true}}).

func (Binding) Captured

func (b Binding) Captured() Binding

Captured marks a row as a capture row: consulted outer-first before the inner-first walk (config field "capture").

func (Binding) FromKey

func (b Binding) FromKey(arg string) Binding

FromKey fills an argument from the pressed key name.

func (Binding) FromPayload

func (b Binding) FromPayload(arg, source string) Binding

FromPayload fills an argument from the mode payload (a Source name).

func (Binding) FromRow added in v0.3.0

func (b Binding) FromRow(arg, field string) Binding

FromRow fills an argument from the Data of the row the key acted on: the innermost instance carrying Data from the focus out to the level the row answered at (a list row's ListItem.Data, also when the row is bound on the list). field names a key of that value (a map's key, a struct's JSON field name; dots walk nested values, "repo.path"); "" passes the whole value. A struct is read through its JSON encoding, so the value is what the CLI would send (numbers float64, the whole row an object). A row without Data, or without the field, leaves the argument out. The source is "row:<field>" (or "row") in a binding file.

func (Binding) Guard

func (b Binding) Guard(name string) Binding

Guard names the registered guard the row requires.

func (Binding) Hide

func (b Binding) Hide() Binding

Hide keeps the row off the footer (config field "hidden"); ? help and bindings list still show it.

func (Binding) Hinted

func (b Binding) Hinted(text string) Binding

Hinted sets the row's hint (config field "hint"): the text shown after its key in place of the operation and its description.

func (Binding) Join

func (b Binding) Join(arg string, sources ...string) Binding

Join fills an argument from several sources joined with a space: the leader's any row sends Join("keys", SourcePrefix, SourceKey).

type BindingGroup added in v0.33.0

type BindingGroup struct {
	Noun     string
	Instance string
	Mode     string
	Extends  string
	// Fallback ("fallback": true) keeps a default file's group to the keys
	// its table did not bind before the file loaded (LoadDefaultBindings):
	// an application's row bound earlier keeps its key.
	Fallback bool
	// Source ("source") is where the group's rows are declared, as
	// bindings defaults writes it; a reader keeps it and nothing acts on it.
	Source string
	Rows   []Binding
}

BindingGroup is one table of a grouped bindings file: a noun's or an instance's mode table and its rows in table order. Every row carries the group's Noun or Instance and Mode.

func GroupBindings added in v0.33.0

func GroupBindings(rows []Binding) []BindingGroup

GroupBindings groups rows into tables: nouns by name, then each noun's modes by name ("" first), then instances by ID and mode, each group's rows in their given order.

func (BindingGroup) Context added in v0.33.0

func (g BindingGroup) Context() string

Context is the group's "context" spelling, "noun/mode" or a bare noun; "" for an instance group.

type BindingTimeoutMsg

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

BindingTimeoutMsg resolves a pending key sequence on the owning event loop. Messages from an older sequence or another runtime are ignored.

type BindingsDoc added in v0.33.0

type BindingsDoc struct {
	Modes  map[string]ModeSpec
	Groups []BindingGroup
}

BindingsDoc is a parsed bindings file: its modes and its groups, in file order. A rows-format file is one group per row run of the same table.

func ParseBindings added in v0.33.0

func ParseBindings(data []byte) (BindingsDoc, string, error)

ParseBindings reads a bindings file in either format (JSONC), with the format it found. A malformed file is an error with its line and column; a bad group or value is an error naming the group and key.

func (BindingsDoc) Rows added in v0.33.0

func (d BindingsDoc) Rows() []Binding

Rows are the doc's rows, group by group in file order.

type Block

type Block struct {
	Text   string
	Cursor *Pos
}

Block is the result of rendering. Text is trusted ANSI. Cursor is where the focused input's cursor sits inside Text, or nil when the block holds no focused input. Only the innermost focused component supplies a cursor; composers move it by where they placed the child and never invent one.

func ComposeModalBlock

func ComposeModalBlock(background, title string, body Block, footer string, width, height int, styles Styles) Block

ComposeModalBlock is ComposeModal for a body that may carry a cursor. The result's cursor is the body's, moved to where the panel placed it; the backdrop never contributes one because a modal covers whatever it held.

func InputBlock

func InputBlock(in *Input, width, height int) Block

InputBlock renders width x height cells of an input around its cursor and reports where the cursor sits, without changing text or editing state. Visual selections and an open select range are painted in reverse video (the visual-selection style); the cursor itself is left to the terminal, so compose this block only for the focused input.

func Text

func Text(s string) Block

Text wraps rendered text that carries no cursor.

func (Block) Clip

func (b Block) Clip(width, height int) Block

Clip drops a cursor that fell outside a width x height cell area whose top-left corner is the block's origin, as when a composer clipped the child.

func (Block) Offset

func (b Block) Offset(dx, dy int) Block

Offset returns the block with its cursor moved by dx, dy. Text is unchanged.

func (Block) WithText

func (b Block) WithText(text string) Block

WithText replaces the text and keeps the cursor, for composers that rewrite the child's cells without moving them.

type CallMsg

type CallMsg struct {
	Request Request
	Reply   chan Response
	// Stream asks for a watch (the watch verb's *Watch) live, as the
	// result, for a caller that reads its events on the loop (the CLI
	// shell); without it the result is the events so far and the watch
	// ends.
	Stream bool
}

CallMsg is delivered to the UI loop; only that loop may call Runtime.Execute.

type Card added in v0.17.0

type Card struct {
	ID       string                 `json:"id"`
	Noun     string                 `json:"noun,omitempty"`
	Label    string                 `json:"label,omitempty"`
	Data     any                    `json:"data,omitempty"`
	Header   string                 `json:"header"`
	Meta     string                 `json:"meta,omitempty"`
	Body     func(width int) string `json:"-"`
	Sections []CardSection          `json:"sections,omitempty"`
	Steps    []CardStep             `json:"steps,omitempty"`
	Open     bool                   `json:"open,omitempty"`
	Active   bool                   `json:"active,omitempty"`
	Muted    bool                   `json:"muted,omitempty"`
	Group    string                 `json:"group,omitempty"`
	Revision uint64                 `json:"revision,omitempty"`
	// Event draws the card as something that happened rather than
	// something said: indented one level (eventIndent cells), its border
	// dashed and muted until it is selected. A task's notification is one.
	Event bool `json:"event,omitempty"`
	// MetaTones tone runs of Meta (a status word, its glyph) as a list
	// row's ToneSpan tones a cell: From and To are rune offsets into Meta
	// (To 0: its end), Cell is not read, a later span wins where two
	// overlap. A toned run draws in its tone's style instead of the muted
	// meta style; the text never changes, so widths and copies are the
	// same as without tones. An unknown tone draws muted, as the rest.
	MetaTones []ToneSpan `json:"metaTones,omitempty"`
	// Tone is a tone whose style draws the card's border (and the Active
	// "●" in it) in place of the border role: a card whose state should
	// be seen from across the timeline (a running turn, a failed one).
	// The chrome row border.<tone> of the chrome.color level draws it when
	// the level has one (chrome.rich.border.state.working), else the tone.
	// The focused timeline's selected card keeps the accent, so the
	// focus always reads; an unknown tone, or "", draws the usual border.
	Tone string `json:"tone,omitempty"`
}

Card is one entry of a timeline: a box with a header that always shows (wrapped onto as many lines as it needs) and a meta line under it, and a body shown only while the card is open. Like a ListItem, a card is an instance of its noun (Noun, default TimelineCardNoun) under the timeline's list, so the app's verbs and rows on that noun answer on it and Data is what a verb reads as Ctx.Instance.Data. Label is the instance's label (palette, {{label}}, the / filter), default the header on one line.

Body and every section's Body are asked lazily, with the inner width, only while the card is open and drawn (or scrolled across); the result is kept until the width, the folds or Revision change, so an app bumps Revision whenever a body's text changes (a streaming answer). Open is the card's state the first time the timeline sees its id; after that the user's open and close follow the id. Active draws the card brighter (its header bold, a "●" in its top border, which reads in mono too); Muted draws its header and meta in the muted style (an older card). A card whose Group differs from the card above it is preceded by a full-width rule with the group as its label (a session boundary).

Steps are the places inside an open card that l steps onto and j/k walk (timeline_steps.go). A card with Steps draws its body from them, and Body and Sections are not drawn; a card without them steps through its Body's paragraphs (blank-line separated, a fenced code block one paragraph) and then each section, title and text, as one step.

type CardRole added in v0.17.0

type CardRole string

CardRole is the style a section's text draws in.

const (
	CardRoleText   CardRole = ""
	CardRoleMuted  CardRole = "muted"
	CardRoleAccent CardRole = "accent"
	CardRoleError  CardRole = "error"
)

Card roles: the theme's text, muted (thinking), accent, error.

type CardSection added in v0.17.0

type CardSection struct {
	Name    string                 `json:"name,omitempty"`
	Title   string                 `json:"title"`
	Summary string                 `json:"summary,omitempty"`
	Role    CardRole               `json:"role,omitempty"`
	Folded  bool                   `json:"folded,omitempty"`
	Body    func(width int) string `json:"-"`
}

CardSection is one foldable part of an open card's body, drawn after Body: a title line ("▾ 2 thinking · Summary") and, unfolded, its text indented in its Role's style. Name keys its fold state (default the title, else its number); Folded is its state until the user folds it.

type CardStep added in v0.30.0

type CardStep struct {
	ID         string                 `json:"id,omitempty"`
	Title      string                 `json:"title,omitempty"`
	Summary    string                 `json:"summary,omitempty"`
	Role       CardRole               `json:"role,omitempty"`
	Folded     bool                   `json:"folded,omitempty"`
	Header     bool                   `json:"header,omitempty"`
	Paragraphs bool                   `json:"paragraphs,omitempty"`
	Body       func(width int) string `json:"-"`
}

CardStep is one place inside an open card (Card.Steps), in order.

  • Header: the step is the card's header (a prompt): it draws nothing of its own, its lines are the header's and its text is Header.
  • A Title draws a bold title line; with a Body the step folds like a section ("▾ 2 tool Bash · summary", z 2, timeline.fold {section} by ID, title or number), Folded its first state, and its body is indented under the title. Folded, the title is the whole step; l inside opens it.
  • Paragraphs splits the Body into steps of its own, one per paragraph (blank-line separated, a fenced code block one paragraph); under a Title the title line belongs to the first.
  • Without a Title the Body draws at the full width in Role.

Steps follow each other with a blank line between them, except two titled steps in a row (they stack as sections do). ID keys the fold.

type CaseMatch added in v0.55.0

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

CaseMatch is how one query compares with text: folded (case ignored) or exact. Build it with CaseFor or Runtime.CaseFor; the zero value matches exactly.

func CaseFor added in v0.55.0

func CaseFor(mode, query string) CaseMatch

CaseFor is the CaseMatch search.case value mode gives query: smart folds unless query holds an upper-case letter (unicode.IsUpper, so É counts and a separator or digit never does); ignore always folds; sensitive never does. An unknown mode reads as smart.

func (CaseMatch) Contains added in v0.55.0

func (m CaseMatch) Contains(text, query string) bool

Contains reports whether text holds query.

func (CaseMatch) Fold added in v0.55.0

func (m CaseMatch) Fold() bool

Fold reports whether the match ignores case.

func (CaseMatch) HasPrefix added in v0.55.0

func (m CaseMatch) HasPrefix(text, query string) bool

HasPrefix reports whether text starts with query.

func (CaseMatch) Rune added in v0.55.0

func (m CaseMatch) Rune(r rune) rune

Rune is r as the match compares it.

func (CaseMatch) String added in v0.55.0

func (m CaseMatch) String(s string) string

String is s as the match compares it: lower-cased when folding, else unchanged. Apply it to both the query and the text.

type Choice

type Choice struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Word is what the palette offers and takes for the choice when it is
	// not the id ("" the id): a page's title for page open. Typed whole,
	// the id still names it (palette.choice-words).
	Word string `json:"word,omitempty"`
}

Choice is one value a parameter accepts: ID is the argument value, Label what a pick list shows.

func ParseChoices

func ParseChoices(result any) ([]Choice, error)

ParseChoices reads a source operation's result: []string, []Choice, []PaletteInstance, []Operation (the id is noun.verb), []map whose id is "id", else "key", else "name" and whose label is "label", else "title" (and word "word", Choice.Word), or []any of strings or such maps (the JSON-decoded form).

type Chooser added in v0.2.0

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

Chooser is one open chooser, the Component of its modal instance.

func (*Chooser) Close added in v0.2.0

func (c *Chooser) Close()

func (*Chooser) HandleMessage added in v0.2.0

func (c *Chooser) HandleMessage(tea.Msg) bool

The delivery contract: a chooser runs no jobs of its own (Choose and Create return their own results). Pending work they return belongs to the focus the chooser opened over (runApplication), since the chooser and its input are closed before the callback runs.

func (*Chooser) Highlighted added in v0.2.0

func (c *Chooser) Highlighted() (ChooserRow, bool)

Highlighted is the row Enter takes: the moved-to row, else the top match; none means Enter creates.

func (*Chooser) Kind added in v0.2.0

func (c *Chooser) Kind() string

Kind is the chooser's modal kind.

func (*Chooser) Loading added in v0.44.0

func (c *Chooser) Loading() bool

Loading reports whether the current source's load is in flight.

func (*Chooser) MatchMode added in v0.59.0

func (c *Chooser) MatchMode() string

MatchMode is the chooser's match mode: the one search.cycle-match or search.set-match chose while it is open, else the chooser.match setting. It decides the default filter only (not a Filter of the application's own, not a Live source's own ranking).

func (*Chooser) Matches added in v0.2.0

func (c *Chooser) Matches() []ChooserRow

Matches are the rows the query keeps: matches first, then trailing rows, then the create row, then the fixed rows.

func (*Chooser) ModalBlock added in v0.2.0

func (c *Chooser) ModalBlock(_ Styles, width, height int) Block

func (*Chooser) ModalTitle added in v0.2.0

func (c *Chooser) ModalTitle() string

ModalTitle and ModalBlock make a chooser a self-drawing modal body (ModalBody), drawn like a record editor and its chooser.

func (*Chooser) Moved added in v0.2.0

func (c *Chooser) Moved() bool

Moved reports whether the user moved the highlight since the last edit.

func (*Chooser) PendingCommand added in v0.2.0

func (c *Chooser) PendingCommand() tea.Cmd

PendingCommand follows the query after every event: a Live source loads again for the edited query, and the work it queues is handed over here (the runtime's queue was drained before the components were asked).

func (*Chooser) Query added in v0.2.0

func (c *Chooser) Query() string

Query is the search input's text.

func (*Chooser) SetQuery added in v0.44.0

func (c *Chooser) SetQuery(query string)

SetQuery replaces the search text (cursor at its end), as typing would.

func (*Chooser) SetRows added in v0.2.0

func (c *Chooser) SetRows(rows []ChooserRow)

SetRows replaces the rows (a background load landing); the highlight stays on the same row id when the user had moved it.

func (*Chooser) Source added in v0.44.0

func (c *Chooser) Source() string

Source is the current source's name, "" for a chooser without sources.

func (*Chooser) Sources added in v0.44.0

func (c *Chooser) Sources() []string

Sources are the names of the chooser's sources, in order.

func (*Chooser) Title added in v0.2.0

func (c *Chooser) Title() string

Title is the chooser modal's title; with sources, the current source in brackets and the others after it.

func (*Chooser) View added in v0.2.0

func (c *Chooser) View(width, height int) Block

View draws the search line, then the rows with the highlighted one in reverse video, with what Enter would create when nothing is highlighted after the matches (before the fixed rows); with a Preview and the width for it, the highlighted row's preview on the right. Its cursor is the search input's.

type ChooserRow added in v0.2.0

type ChooserRow struct {
	ID       string
	Label    string
	Data     any
	Trailing bool
	Fixed    bool
	// Cells, when set, draw the row as aligned columns (each column as
	// wide as its widest cell among the rows); Label stays what the
	// filter reads.
	Cells []string
	// Opens marks a row its source can open (ChooserSource.Open: a
	// folder to browse into): chooser.open opens it, and so does enter
	// unless the setting chooser.enter is "pick". NoPick marks a row that
	// only opens (a folder in a file chooser): picking it opens it.
	Opens  bool
	NoPick bool
	// Refuse marks a row that cannot be picked and says why: picking it
	// fails with Refuse and the chooser stays open (a typed path whose
	// folder is missing, R7.8).
	Refuse string
}

ChooserRow is one choice. Trailing rows (a "browse…" entry) follow the matches. Enter takes one without moving onto it only when the query is not empty and no ordinary row matches, so their filter should be strict (a substring of the label); an empty query with no ordinary rows creates. Fixed rows (a "no pin" entry) sit at the bottom whatever the query: the filter never sees them and Enter takes one only once the highlight is moved onto it, or when the query spells it.

type ChooserSource added in v0.44.0

type ChooserSource struct {
	// Name is what the title calls the source ("browse", "recent").
	Name string
	// Label, when set, is what the title shows for the current source in
	// place of Name ("browse ~/proj").
	Label func() string
	// Load lists the source's rows for the query: Done([]ChooserRow),
	// Failed (the error is the empty line), or Pending work whose value is
	// a []ChooserRow, run off the loop as a job of the chooser (a newer
	// load replaces it; closing the chooser cancels it).
	Load func(query string) Result
	// Live sources match the query themselves: Load runs again on every
	// edit and its rows are shown as they come, in their order. Other
	// sources load once when they become current (and after Open or Up)
	// and the chooser's Filter narrows their rows.
	Live bool
	// Empty is the line shown while the source has no rows ("no recent
	// paths"); the spec's Empty (or "loading…" while a load runs) else.
	Empty string
	// Open navigates into a row marked Opens (browse into a folder) and
	// returns the query to show next; false leaves everything as it is.
	// The source then loads again.
	Open func(row ChooserRow) (query string, ok bool)
	// Up navigates back out (the parent folder) given the query and
	// returns the query to show next; false when there is nowhere to go.
	Up func(query string) (string, bool)
	// Create and CreateLabel, when set, stand in for the spec's while the
	// source is current (a browse source creates in its folder).
	Create      func(query string) Result
	CreateLabel func(query string) string
	// Keep, when set, stands in for the spec's Keep while the source is
	// current: the cell columns cut last (a known-folder source's path,
	// its branch and project columns narrowing first).
	Keep []int
}

ChooserSource is one source of a chooser's rows.

type ChooserSpec added in v0.2.0

type ChooserSpec struct {
	Kind        string
	Title       string
	Rows        []ChooserRow
	Filter      func(query string, row ChooserRow) bool
	Choose      func(ChooserRow) Result
	Create      func(query string) Result
	CreateLabel func(query string) string
	CreateRow   bool
	Empty       string
	// Keep names the columns (indexes into ChooserRow.Cells) cut last when
	// the cells do not fit (a directory chooser's path): the others narrow
	// to their minimum first, then the kept ones, widest first.
	Keep []int
	// Preview, when set, draws the highlighted row's text beside the rows
	// (wrapped, cut at the bottom) once the chooser is ChooserPreviewMin
	// cells wide; narrower, the rows take the whole width.
	Preview func(ChooserRow) string
	// Sources, when set, supply the rows one source at a time (see
	// ChooserSource; Rows is then the current source's). Source names
	// the one to open on; else (or when this open has no source of that
	// name) the one last used for the kind (chooser.remember-source),
	// else the first.
	Sources []ChooserSource
	Source  string
}

ChooserSpec opens a chooser. Kind is the modal's kind (one open chooser per kind). Title is the modal's title. Filter defaults to a fuzzy match on Label, case as the search.case setting says (CaseFor; a Filter of the application's own can read Runtime.CaseFor too); matches whose label holds the query whole come first, otherwise in Rows order. Create is optional; without it Enter on no match fails. CreateLabel names what Enter would create from the query. CreateRow shows that as a "+ <label>" row while the query is not empty, after the matches and trailing rows and before the fixed rows; typing never matches or ranks it, it is the default only when nothing else matches, and Enter on it creates. Empty is the line shown while there are no rows at all ("loading…"). Keep names the cell columns cut last. Preview draws a preview of the highlighted row beside the rows when there is room.

type Column

type Column struct {
	Title    string `json:"title"`
	Width    int    `json:"width,omitempty"`
	Min      int    `json:"min,omitempty"`
	Max      int    `json:"max,omitempty"`
	Align    Align  `json:"align,omitempty"`
	Priority int    `json:"priority,omitempty"`
	Wrap     bool   `json:"wrap,omitempty"`
	Pinned   bool   `json:"pinned,omitempty"`
	Group    bool   `json:"group,omitempty"`
}

Column is one column of a table. Width fixes the column's cells (0: a flexible column, as wide as its widest cell or title when there is room); Min is a flexible column's least width before columns drop (default: 10 cells or its title's width when wider, at most its widest cell or title). Priority orders dropping when the width is short: the column with the largest Priority drops first, ties the rightmost first; 0, the default, is the most important, and the last column left never drops (it is cut instead). Max caps a flexible column's growth (0: up to its widest cell). Wrap makes List.View wrap a cell longer than its column onto further lines of the row instead of cutting it: the row is as tall as its tallest wrapped cell, the other cells sit on its first line (TableText still cuts). Group makes List.View draw a cell blank when it repeats the cell above it in the same section (and every Group column left of it does too), so a run of rows sharing a value (the help's key prefix) shows it once; the first row a frame draws always shows its cells, and the rows' Cells keep the value (TableText does not blank).

type Completer added in v0.5.0

type Completer struct {

	// Debounce is the pause before a search is asked
	// (DefaultCompletionDebounce when 0).
	Debounce time.Duration
	// contains filtered or unexported fields
}

Completer is the inline completion component: which input it follows, the token whose suggestions are wanted and the answer on screen.

func (*Completer) Close added in v0.5.0

func (c *Completer) Close()

Close hides the list and cancels its searches.

func (*Completer) DebounceCurrent added in v0.5.0

func (c *Completer) DebounceCurrent(msg CompletionDebounceMsg) bool

DebounceCurrent reports whether a pause timer is for the latest request, whose search has not started yet.

func (*Completer) DebounceTick added in v0.5.0

func (c *Completer) DebounceTick() (CompletionDebounceMsg, bool)

DebounceTick is the pause timer in flight, for a host that delivers it at once (tests, o-story): false when no search is waiting on one.

func (*Completer) Err added in v0.5.0

func (c *Completer) Err() error

Err is the search error on screen, nil for none.

func (*Completer) HandleMessage added in v0.5.0

func (c *Completer) HandleMessage(msg tea.Msg) bool

HandleMessage starts a search when its pause ends and takes a search's answer.

func (*Completer) Highlighted added in v0.5.0

func (c *Completer) Highlighted() int

Highlighted is the highlighted suggestion's index, -1 for none.

func (*Completer) Input added in v0.5.0

func (c *Completer) Input() string

Input is the input the list belongs to, "" when none is followed.

func (*Completer) Open added in v0.5.0

func (c *Completer) Open() bool

Open reports whether the suggestion list is shown (its rows answer).

func (*Completer) PendingCommand added in v0.5.0

func (c *Completer) PendingCommand() tea.Cmd

PendingCommand looks at the focused input and schedules the pause timer of a new request.

func (*Completer) Searching added in v0.5.0

func (c *Completer) Searching() bool

Searching reports whether a search newer than the answer on screen runs.

func (*Completer) State added in v0.5.0

func (c *Completer) State() map[string]any

State is what the completion verbs return.

func (*Completer) Suggestions added in v0.5.0

func (c *Completer) Suggestions() []Suggestion

Suggestions are the answer on screen.

func (*Completer) Token added in v0.5.0

func (c *Completer) Token() (CompletionToken, bool)

Token is the token whose suggestions are wanted, and whether there is one.

type Completion

type Completion struct {
	Ticket
	Value any
	Err   error
}

Completion is the message off-loop work sends back. It is delivered to the owning instance only while its ticket is current.

type CompletionDebounceMsg added in v0.5.0

type CompletionDebounceMsg struct {
	Seq uint64
}

CompletionDebounceMsg is the pause timer of one request: when it is the latest (Completer.DebounceCurrent) the search is started.

type CompletionQuery added in v0.44.0

type CompletionQuery struct {
	Query  string          `json:"query"`
	Text   string          `json:"text"`
	Cursor int             `json:"cursor"`
	Token  CompletionToken `json:"token"`
}

CompletionQuery is what a SearchAt search is asked: the query (the token after its trigger), the input's whole text, the cursor (a rune offset) and the token.

type CompletionSearch added in v0.5.0

type CompletionSearch func(ctx context.Context, query string) ([]Suggestion, error)

CompletionSearch answers a query, the token after its trigger, with suggestions. It runs off the loop, as a job; its context is cancelled when the answer can no longer be shown (the suggestions were dismissed, or a newer answer is already on screen). An error is shown in the list.

func SearchStrings added in v0.5.0

func SearchStrings(search func(ctx context.Context, query string) ([]string, error)) CompletionSearch

SearchStrings adapts a search that answers plain strings, for the usual case where what the list shows is what is inserted.

type CompletionToken added in v0.5.0

type CompletionToken struct {
	Start   int    `json:"start"`
	End     int    `json:"end"`
	Trigger string `json:"trigger"`
	Query   string `json:"query"`
}

CompletionToken is the trigger token under an input's cursor: the rune range [Start, End) it covers, its trigger and its query (the token after the trigger).

func FindCompletionToken added in v0.5.0

func FindCompletionToken(text []rune, cursor int, triggers []string) (CompletionToken, int, bool)

FindCompletionToken finds the token holding the cursor in text and the index of the trigger it starts with. A token is a run of non-whitespace; it counts only when it starts with a trigger (the longest one, when triggers overlap) and the cursor is past that trigger, at the token's end or anywhere inside it.

func FindCompletionTokenIn added in v0.44.0

func FindCompletionTokenIn(text []rune, cursor int, triggers []CompletionTrigger) (CompletionToken, int, bool)

FindCompletionTokenIn is FindCompletionToken over full triggers: each trigger's token also ends at its Boundaries.

type CompletionTrigger added in v0.5.0

type CompletionTrigger struct {
	Trigger string
	Search  CompletionSearch
	// SearchAt, when set in place of Search, answers with the whole text
	// and cursor as well as the query (CompletionQuery).
	SearchAt func(ctx context.Context, q CompletionQuery) ([]Suggestion, error)
	// DropTrigger makes accepting replace the trigger too: the
	// suggestion's Text is all that stays (a "\" that only asks for a
	// symbol). Off, the default, keeps it.
	DropTrigger bool
	// Boundaries are the characters besides whitespace that end a token
	// (both ways), so the trigger can follow one directly: "|(,"
	// lets a jq "." start after a pipe or an open paren. "" is
	// whitespace only. They may not hold the trigger's characters.
	Boundaries string
}

CompletionTrigger is one trigger of an input: the characters that start a completion token and the search that answers its query.

type Component

type Component interface {
	HandleMessage(tea.Msg) bool
	PendingCommand() tea.Cmd
	Close()
}

Component is the delivery contract every instance that works off the loop implements through Instance.Component. HandleMessage applies a result on the loop and reports whether the message was for this component; PendingCommand hands the Bubble Tea adapter the work scheduled since the last drain; Close cancels outstanding work and releases anything held. The picker and the registers component are the framework's own; an application adds its own by setting Instance.Component.

type Config added in v0.2.0

type Config struct {
	App string
	Dir string
	// Report, when set, receives every problem as it is found: a bindings
	// row that was skipped, a file that does not parse, an unknown or
	// invalid setting. NewModel sets it to Model.Notify, so problems are
	// persistent footer notices.
	Report func(problem string)
	// Withdraw, when set, takes back a problem Report sent once it no
	// longer holds (bindings.reload of a fixed file); NewModel sets it to
	// drop the notice.
	Withdraw func(problem string)
	// StateDir, when set, is the state directory (the history file);
	// else $XDG_STATE_HOME/<App>, else ~/.local/state/<App>.
	StateDir string
	// NoHistoryFile keeps the action history in memory only: an
	// application opts out of history.jsonl.
	NoHistoryFile bool
	// contains filtered or unexported fields
}

Config is the application's per-user configuration directory and what the framework loaded from it: the user bindings file (bindings.json, rows in the bindings.load shape that replace or unbind the defaults by noun, mode and keys) and the declared settings (settings.json). It is one instance under app, reached through Runtime.Config(), never a Runtime field.

The directory is Dir when set, else $XDG_CONFIG_HOME/<App>, else ~/.config/<App>. App defaults to the binary's name (a test binary, NAME.test, has none), so every application gets the files without code; an application whose directory is named otherwise sets App before the Model starts (mtm sets "matomeru"). With App and Dir both empty there is no directory: nothing is read or written.

func (*Config) ActionProblems added in v0.2.0

func (c *Config) ActionProblems() []string

ActionProblems are the problems the last read of actions.json found.

func (*Config) BindingProblems added in v0.2.0

func (c *Config) BindingProblems() []string

BindingProblems are the problems the last load of the user bindings found (rows skipped, a file that does not parse).

func (*Config) BindingsFormat added in v0.33.0

func (c *Config) BindingsFormat() string

BindingsFormat is the format the last read of bindings.json found: BindingsGrouped, BindingsRows, or "" when there was no file.

func (*Config) Close added in v0.2.0

func (c *Config) Close()

Close keeps everything: the config lives as long as the runtime.

func (*Config) Directory added in v0.2.0

func (c *Config) Directory() string

Directory is the config directory, "" when there is none.

func (*Config) Disable added in v0.2.0

func (c *Config) Disable()

Disable gives the runtime no config directory (App and Dir empty): a sandbox such as an o-story session reads and writes no user files, and keeps no history file.

func (*Config) Flush added in v0.2.0

func (c *Config) Flush() error

Flush stops the history writer once every line sent to it is written, and writes the placements record (NounPlacesFile) and stops its writer. The Model calls it on quit; later requests are not persisted.

func (*Config) FrameworkTheme added in v0.2.0

func (c *Config) FrameworkTheme() bool

FrameworkTheme reports whether the theme setting is the framework's (the Model applies it to Appearance.Theme) rather than the application's own.

func (*Config) HandleMessage added in v0.2.0

func (c *Config) HandleMessage(tea.Msg) bool

HandleMessage: the config does no off-loop work.

func (*Config) HistoryPath added in v0.2.0

func (c *Config) HistoryPath() string

HistoryPath is the history file, "" when the history is not persisted (no state directory, or the application set NoHistoryFile).

func (*Config) NounPlacesPath added in v0.15.0

func (c *Config) NounPlacesPath() string

NounPlacesPath is the placements file, "" when placements are not persisted (no state directory: Config.Disable, a test binary).

func (*Config) PanesPath added in v0.4.0

func (c *Config) PanesPath() string

PanesPath is the panes file, "" when dividers are not persisted (no state directory: Config.Disable, a test binary).

func (*Config) Path added in v0.2.0

func (c *Config) Path(name string) string

Path is a file in the config directory, "" when there is none.

func (*Config) Paths added in v0.6.0

func (c *Config) Paths() ConfigPaths

Paths are the config, state and default reference directories.

func (*Config) PendingCommand added in v0.2.0

func (c *Config) PendingCommand() tea.Cmd

PendingCommand: nothing is ever scheduled.

func (*Config) Schemes added in v0.2.0

func (c *Config) Schemes() map[string]Scheme

Schemes are the user's colour schemes from themes.json, by name, as the last read found them (EnsureConfigSettings, themes.reload).

func (*Config) StateDirectory added in v0.2.0

func (c *Config) StateDirectory() string

StateDirectory is the application's state directory, "" when there is none: StateDir when set, else $XDG_STATE_HOME/<App>, else ~/.local/state/<App>. Disable leaves none.

func (*Config) TablesPath added in v0.12.0

func (c *Config) TablesPath() string

TablesPath is the tables file, "" when table views are not persisted (no state directory: Config.Disable, a test binary).

type ConfigExport added in v0.6.0

type ConfigExport struct {
	Dir    string   `json:"dir"`
	Files  []string `json:"files"`
	Config string   `json:"config"`
	State  string   `json:"state"`
}

ConfigExport is what config.export wrote: the directory, the files in it (absolute paths, in the order written) and where the live files are.

type ConfigPaths added in v0.6.0

type ConfigPaths struct {
	Config    string `json:"config"`
	State     string `json:"state"`
	Reference string `json:"reference"`
}

ConfigPaths are where the application's user files live: Config is the config directory (bindings.json, settings.json, actions.json, themes.json), State the state directory (history.jsonl, panes.json) and Reference the directory config.export writes to by default. A directory the application has none of is "".

type Context

type Context struct {
	Path    []string `json:"path"`
	InputID string   `json:"inputId,omitempty"`
}

Context is the derived view of a focus: the instance ids from app down to the focused instance (Path), and the focused input when there is one.

func (Context) Clone

func (c Context) Clone() Context

Clone returns a copy whose Path does not share the original's backing array.

type Ctx

type Ctx struct {
	Runtime  *Runtime
	Context  Context
	Args     Arguments
	Instance *Instance
	// Subjects are the instances the request acts on: Instance alone,
	// or, for a verb that takes many (Operation.Many) run over a visual
	// selection, every selected row in display order (Instance among them).
	Subjects []*Instance
	// Invoked is the name the request ran the verb by: its own key, or an
	// alias (an old name, a user's actions.json alias, the other noun of
	// an operation reachable under two nouns), with that name's noun as
	// the subject side.
	Invoked Invocation
}

Ctx is what an application handler receives: the runtime, the context the request runs in, its arguments and the instance it addresses (id, noun, payload).

func (Ctx) ClearNotice added in v0.4.0

func (c Ctx) ClearNotice(id NoticeID)

ClearNotice takes back a notice Notify posted.

func (Ctx) Each added in v0.36.0

func (ctx Ctx) Each(one AppHandler) Result

Each is how a verb that takes many subjects (Operation.Many) makes its change once it knows what to do (an argument given, a chooser answered): one runs for every subject in order, each with a Ctx narrowed to that subject (Instance, Context and Subjects), so the one-subject body stays as it was. A run over several posts the notice a per-row run would (subjectsNotice): one info, or one error counting the done and the failed. A body must answer synchronously (Done or Failed); pending work counts as a failure. On one subject Each is that subject's Result.

func (Ctx) Error added in v0.31.0

func (c Ctx) Error(text string)

Error sets the status line to an error through the runtime's UI (the TUI's "Error: TEXT" until the next key, an error: line on the CLI); "" clears it. A verb that fails returns Failed instead; Error is for what fails beside the result (a job's Then, a refresh).

func (Ctx) Info added in v0.31.0

func (c Ctx) Info(text string)

Info sets the status line to a plain message through the runtime's UI (before the hints until the next key, a status: line on the CLI); "" clears it. Notify is the notice that stays.

func (Ctx) Notify added in v0.4.0

func (c Ctx) Notify(text string) NoticeID

Notify posts a persistent notice through the runtime's UI (the footer in the TUI, a notice: line on the CLI) and returns its id.

func (Ctx) Status deprecated added in v0.4.0

func (c Ctx) Status(text string)

Status is Error: the status line in its error tone.

Deprecated: use Error for what failed, Info for a plain message.

func (Ctx) SubjectIDs added in v0.36.0

func (ctx Ctx) SubjectIDs() []string

SubjectIDs are the ids of ctx's subjects, for a handler that hands them on (Request.Subjects of the request it runs next: a confirm, a chooser's choice).

type DefaultBinding added in v0.34.0

type DefaultBinding struct {
	Binding
	Source string `json:"source"`
}

DefaultBinding is one row of the default layer and where it is declared: a file's source, SourceGo or SourceGenerated.

type Detail added in v0.2.0

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

Detail is the component a detail instance fronts: a page's read-only detail region (the text beside or below a list about its selected row) that scrolls while the focus stays in the list. The application names the item the detail is about with the func it gives AddDetail (the selected row's id) and draws the text through Window; the framework keeps the offset. A new item starts at the top, checked on every Window and every scroll, so a scroll typed before the next frame lands on the new item; the same item keeps its offset while its text refreshes (clamped to the new length). J and K on the app noun (detail.scroll, counts work: 10J) scroll the current page's detail while it overflows and the focus is on the page outside it; a focused noun that binds J or K (the outline) keeps them, as inner rows answer first. A detail is not a focus stop.

func (*Detail) ID added in v0.2.0

func (d *Detail) ID() string

ID is the detail's instance id.

func (*Detail) Item added in v0.2.0

func (d *Detail) Item() string

Item is the item the offset belongs to.

func (*Detail) Marker added in v0.2.0

func (d *Detail) Marker() string

Marker is the position marker of the last Window: first and last visible lines and the total, "12–40 / 300", or "" when the text fits.

func (*Detail) Offset added in v0.2.0

func (d *Detail) Offset() int

Offset is the first visible line, from 0.

func (*Detail) Overflows added in v0.2.0

func (d *Detail) Overflows() bool

Overflows reports whether the last Window had more lines than it showed.

func (*Detail) Scroll added in v0.2.0

func (d *Detail) Scroll(lines int) int

Scroll moves the window by lines (down when positive), clamped to the text the last Window measured, and returns the new offset. A new item starts at the top first.

func (*Detail) Width added in v0.52.0

func (d *Detail) Width() int

Width is the widest line of the whole text the last Window measured (wrapped, so at most its width), not only of the lines in view: a panel sized from it keeps one width while the text scrolls.

func (*Detail) Window added in v0.2.0

func (d *Detail) Window(text string, width, height int) (body, marker string)

Window returns the lines of text the detail shows in a width by height window (text wrapped to width first when width > 0, so a line is a row on screen) and the position marker, "12–40 / 300", when the text overflows the window ("" when it fits).

type EditNode

type EditNode struct {
	Text     string `json:"text"`
	Cursor   int    `json:"cursor"`
	Parent   int    `json:"parent"`
	Children []int  `json:"children"`
}

EditNode is one state in an input's undo tree: its text, cursor, parent and children.

type FocusTargeter

type FocusTargeter interface {
	FocusTarget() string
}

FocusTargeter is a component that knows where focus lands inside it: a list on its selected row, a grid on its cursor cell.

type Footer struct {
	Text  string
	Error bool
	// Hints are the binding hints Text ends with (HintCells), so the
	// chrome can colour their keys (the hint.key, hint.text and hint.sep
	// roles); without them, or when Text does not end with them, the
	// whole line draws as one muted label.
	Hints []HintCell
	Jobs  []string
	// Keys is the key echo when keys.echo puts it in the footer: drawn at
	// the right end in the cells it reserves, the text cut before them.
	Keys *KeyEchoCell
}

Footer is the bottom row of the page chrome: a raw label, styled as an error when Error is set. Jobs are the jobs ticker's entries (Model.JobsTicker), drawn in the rule line above the footer (TickerRule); the body keeps its size, and no jobs means the plain rule.

type ForegroundExit added in v0.43.0

type ForegroundExit struct {
	Program string `json:"program"`
	Code    int    `json:"code"`
}

ForegroundExit is a foreground program's completion value: the program (its base name) and its exit status.

type ForegroundMsg added in v0.43.0

type ForegroundMsg struct {
	Ticket Ticket
	Cmd    *exec.Cmd
}

ForegroundMsg asks the host to give the terminal to Cmd. The Model runs it through tea.ExecProcess (Model.Foreground replaces that, for a story or a test); Runtime.Deliver runs it in place. Done turns the program's exit into the job's completion.

func (ForegroundMsg) Done added in v0.43.0

func (m ForegroundMsg) Done(err error) tea.Msg

Done is the completion a foreground program's exit (Cmd.Run's error) delivers.

func (ForegroundMsg) Run added in v0.43.0

func (m ForegroundMsg) Run() tea.Msg

Run runs the program in place on the process's standard streams (those the command leaves nil) and returns its completion: the headless path.

type Guard

type Guard func(*Runtime, KeyEvent) bool

Guard is a named condition: an action's availability (Available, the verb guard) or, the older use kept while areas move, a condition a row requires (Binding.When; bindings check lists such rows as debts). The built-in guards are "input" and "no-input" (the focus is or is not an input), "multiline", "count" and "no-count" (the pending count is present or absent), "self" (the focus is the instance whose level the row sits on, not a descendant), "shadow-idle" (the mode a shadow mode such as macro_recording re-dispatches in is normal with an empty payload) and "op:<key>" (the pending operator). Applications add their own with DefineGuard.

type Handler

type Handler func(*Runtime, Context, Arguments) (any, error)

Handler runs an interaction operation on the UI loop and returns its result.

type Header struct {
	Title    string
	Badge    string
	Focus    []string
	Subtitle string
	Tabs     []string
	Active   int
	Segments []SegmentCell
	// Keys is the key echo when keys.echo puts it beside the badge.
	Keys *KeyEchoCell
	// BadgeWidth is the fewest cells the badge's label takes: a shorter
	// label is padded inside the badge, so the badge keeps its left edge
	// as the mode changes (the shell passes Runtime.ModeBadgeWidth).
	BadgeWidth int
}

Header is the top of the page chrome: the title row with an optional right-aligned badge (the shell shows the mode there) and the subtitle row, which is a label or, when Tabs is set, the page tabs with Active marked. The badge is always the right end of the title row. Focus is the focus left of it (the focus-display setting): its levels, outermost first, drawn dim and cut from the left (FitFocusPath) so the innermost level stays. Segments are the status segments (Runtime.SegmentCells), drawn right-aligned in the rule under the header (HeaderRule); they take no row. Every field is a raw label.

type HelpCell added in v0.15.0

type HelpCell struct {
	Mode string    `json:"mode"`
	Rows []HelpRow `json:"rows"`
}

HelpCell is one mode's rows for a key in the help's table view: the first answers, the ones after answer when its guard is false.

type HelpKey added in v0.15.0

type HelpKey struct {
	Key   string     `json:"key"`
	Modes []HelpCell `json:"modes"`
}

HelpKey is one row of the help's table view: a key (or key class) and its rows per mode, in column order; a mode where nothing answers has no cell.

type HelpRow

type HelpRow struct {
	Key         string    `json:"key"`
	Prefix      string    `json:"prefix,omitempty"`
	Final       string    `json:"final,omitempty"`
	Operation   string    `json:"operation"`
	Request     string    `json:"request,omitempty"`
	Hint        string    `json:"hint,omitempty"`
	Args        Arguments `json:"args,omitempty"`
	Description string    `json:"description,omitempty"`
	Noun        string    `json:"noun"`
	Section     string    `json:"section,omitempty"`
	// Guard is the guard a hypothetical row (the help's pick and table
	// views) answers under; the live help judges guards and leaves it out.
	Guard string `json:"when,omitempty"`
	// Aliases are the other names of the row's operation (ActionAlias),
	// listed once on the row and after its description ("also: …"); the
	// row itself always names the canonical operation.
	Aliases []string `json:"aliases,omitempty"`
	// Enters is the pending mode the row's key enters when the help lists
	// that mode's rows after it (the terminal leader: leader_pending).
	Enters string `json:"enters,omitempty"`
	// Group marks a prefix row: its key starts longer sequences (g of
	// g c, the leader ctrl+a), which are listed Under it. A prefix bound
	// to nothing alone is a row helpGroups makes, with no Operation.
	Group bool `json:"group,omitempty"`
	// Under is the prefix row this row is listed under (its longest
	// prefix that is a Group row: "ctrl+a" for "ctrl+a v", "g c" for
	// "g c x"); "" at the top of its section. Key is the whole sequence.
	Under string `json:"under,omitempty"`
	// Steps are a sequence's keys one by one, each with what it does at
	// that point: entering a mode, waiting for the next key, then the
	// final operation. A single key has none.
	Steps []HelpStep `json:"steps,omitempty"`
	// contains filtered or unexported fields
}

HelpRow is one binding as the help shows it: the key, the operation it runs (noun.verb, or the row's Hint when it has one), arguments resolved when help opens, its description, the answering noun, and the help's section: that noun, or "movement" for a motion (Operation.Motion). Prefix and Final are Key split by SplitKeys (the help's prefix and key columns); Request is the operation the row runs (noun.verb, the noun by its shortest name, also when Operation shows the Hint; "" for a mode transition) and Hint the row's own Hint.

func BindingHelp

func BindingHelp(r *Runtime, focus string) []HelpRow

BindingHelp lists the rows a focus answers to in its current mode with their descriptions, grouped by the noun of the level that answers, from the innermost instance outward (the focused instance's rows, its noun's, its parents' up to the page, then app; a capture row sits with its own level, so app's ctrl+c comes after the focused row's verbs), and the motions of every level last, under "movement". A row whose key enters a pending mode (the terminal leader) is followed by that mode's rows as whole sequences (helpEnters, R6.10).

func NounHelp added in v0.15.0

func NounHelp(r *Runtime, noun string, mode ModeState) []HelpRow

NounHelp is BindingHelp for a hypothetical focus on noun in mode, with no instance (nounRows: the noun's tables, app, the editor fallback for an input noun): a guarded row is listed with its Guard, its operation marked "?", and the rows answering when that guard is false follow it; arguments a row takes from the key, the payload or the row read as "$source".

func PlaceHelp added in v0.15.0

func PlaceHelp(r *Runtime, place NounPlace, mode ModeState) []HelpRow

PlaceHelp is NounHelp with a parent chain: the hypothetical focus on place's noun has the levels the place recorded between it and app (its list, its page; the modal noun inside a modal), each answering with its noun's tables, so a list row's keys from its list and page are there.

type HelpStep added in v0.29.0

type HelpStep struct {
	Key         string `json:"key"`
	Operation   string `json:"operation,omitempty"`
	Mode        string `json:"mode,omitempty"`
	Description string `json:"description"`
}

HelpStep is one key of a sequence as the help's steps show it: the key, and what it does at that point in the sequence: the pending mode it enters (Mode), waiting for the next key, or the final operation.

type HintCell added in v0.59.0

type HintCell struct {
	Key  string `json:"key"`
	Text string `json:"text,omitempty"`
}

HintCell is one hint of a hint line: the row's key (or "J/K" for a row whose own hint names its keys) and what it does, "" for a key alone. The chrome draws them in the hint.key and hint.text roles.

func HintCells added in v0.59.0

func HintCells(r *Runtime, focus string) []HintCell

HintCells is BindingHints as cells, a key and its text each, for a hint line that colours its keys.

func (HintCell) String added in v0.59.0

func (c HintCell) String() string

String is the hint as BindingHints writes it: "key text".

type HistoryContext

type HistoryContext struct {
	Focus  string `json:"focus"`
	Page   string `json:"page,omitempty"`
	Mode   string `json:"mode"`
	Source string `json:"source"`
}

HistoryContext is the interaction state a request ran in. Source is "key:<keys>", "macro:<register>", "palette", "cli" or "api".

type HistoryEntry

type HistoryEntry struct {
	Seq     uint64         `json:"seq"`
	At      time.Time      `json:"at"`
	Kind    string         `json:"kind,omitempty"`
	Request Request        `json:"request"`
	Context HistoryContext `json:"context"`
	Result  HistoryResult  `json:"result"`
	Moved   *HistoryMove   `json:"moved,omitempty"`
	Job     uint64         `json:"job,omitempty"`
	// Depth is how many requests enclose this one: a request an operation
	// runs while it runs (a choices source, a macro's keys) is one deeper.
	Depth int `json:"depth,omitempty"`
	// Restored marks an entry read from the history file at start
	// (EnsureHistory): an earlier session ran it. Dot-repeat skips it.
	Restored bool `json:"restored,omitempty"`
	// Changes are what a standard write did to each thing, before and
	// after (standard_undo.go): what history.undo reverts.
	Changes []ThingChange `json:"changes,omitempty"`
}

HistoryEntry is one user action: what ran, where, from which source, how it ended and, when it moved the interaction, from where to where (Moved). It holds ids and the request, never the data the operation returned, so an entry costs the same over a list of ten rows or ten thousand. Kind is the operation's HistoryKind. Job is the job id an application verb launched.

type HistoryMove added in v0.7.0

type HistoryMove struct {
	From HistoryPlace `json:"from"`
	To   HistoryPlace `json:"to"`
}

HistoryMove is how a request moved the interaction: j on a list moves the focus from row A to row B, page.next from one page to the next, a modal's open into the modal and its close back out.

type HistoryPlace added in v0.7.0

type HistoryPlace struct {
	Focus string `json:"focus"`
	Page  string `json:"page,omitempty"`
	Mode  string `json:"mode"`
}

HistoryPlace is where the interaction stands: the focused instance (a list's focus is its selected row), the page and the mode.

type HistoryResult

type HistoryResult struct {
	OK    bool   `json:"ok"`
	Error string `json:"error,omitempty"`
}

HistoryResult is the outcome: ok, or the error. The value the operation returned is the caller's (the CLI prints it), not the history's; a reference to it (a hash into a content-addressed store) would go here, beside ok.

type InfoSink deprecated added in v0.31.0

type InfoSink interface {
	Info(text string)
}

InfoSink was the optional interface for the status line's plain tone. Every UISink now has Info.

Deprecated: Info is part of UISink.

type Input

type Input struct {
	ID         string
	Text       []rune
	Cursor     int
	Mode       string // the editing mode: normal, insert or a visual mode; pending modes live on the instance
	Multiline  bool
	Kind       string
	PathFilter string
	// Secret marks an input whose text is never shown outside it: the key
	// echo (keys.echo) shows nothing at all while it has the focus, not
	// even how much was typed. A record editor field over a Secret prop
	// sets it (RecordField.Secret).
	Secret bool
	// Completions are the input's completion triggers (Completions, the
	// AddInput option); none falls back to its noun's.
	Completions []CompletionTrigger
	// ReadOnly makes the input a viewer: the cursor, motions, visual
	// selections and yanks work, every edit is a silent no-op (Replace
	// leaves the text, insert mode is not entered, a delete or change
	// operator neither deletes nor yanks), and the editing verbs are
	// unavailable at it (guard input-writable), so their rows stand aside
	// and leave the hints. Like Vim's 'nomodifiable', without E21: nothing
	// is reported. Set it before or after AddInput (or the ReadOnly option).
	ReadOnly bool
	Anchor   int
	History  []EditNode
	Head     int
	// contains filtered or unexported fields
}

Input is a single- or multi-line modal text field with an undo tree.

func NewInput

func NewInput(id, text string, multiline bool) *Input

NewInput returns an input in normal mode holding text, with text as its undo root.

func (*Input) Count

func (in *Input) Count() int

Count is the pending Vim count, read from the global mode payload while the input is focused.

func (*Input) Pending

func (in *Input) Pending() string

Pending describes the pending editor mode the way the old grammar did: "d" for an operator, "g" for a g prefix, "dg" for both, "register" while a register name is awaited, "" otherwise.

func (*Input) Redo

func (in *Input) Redo(steps, branch int) error

func (*Input) Replace

func (in *Input) Replace(start, end int, text string) error

func (*Input) SelectAll added in v0.38.0

func (in *Input) SelectAll() error

SelectAll opens a select range over the whole text (SelectText).

func (*Input) SelectText added in v0.38.0

func (in *Input) SelectText(start, end int) error

SelectText opens a select range over the runes [start, end) in insert mode, as Vim's select mode does over a new name: the first text typed (input.insert, a paste) replaces the range and typing continues in insert; backspace or delete removes it; a motion, a mode change (esc), an undo or any other edit closes it and keeps the text. The range is drawn in the visual-selection style. It is a state of the input, not a mode: the person is inserting, and the mode stays insert. An empty range selects nothing and only enters insert at end.

func (*Input) SelectedText added in v0.38.0

func (in *Input) SelectedText() (start, end int, ok bool)

SelectedText is the open select range (SelectText), if any.

func (*Input) Selection added in v0.43.0

func (in *Input) Selection() (start, end int, ok bool)

Selection is the visual selection's rune range [start, end) while the input is in a character or line visual mode (v, V): the runes under the anchor and the cursor are both in it, a line selection covers whole lines and its last newline. ok is false outside a visual mode and in a block selection (visual-block), which is not one range (its snapshot names the rows and columns). Hosts read it instead of recomputing it from Anchor and Cursor.

func (*Input) SetMode

func (in *Input) SetMode(mode string)

SetMode is the mode-transition hook for both editor operations and set.mode. Direct assignment to Mode cannot delimit insert sessions.

func (*Input) SetText added in v0.56.0

func (in *Input) SetText(text string)

SetText puts text in the input from the program, read-only or not: a viewer refreshed with what it shows (a jq panel following the query). The text becomes the undo tree's root (nothing to undo back to); the cursor and a visual selection's anchor keep their offsets, clamped into the new text as a motion would leave them (in normal mode not past the line's last character); an open select range and an insert session end. A single-line input keeps the text up to its first line break. The same text again changes nothing, so the undo history stays.

func (*Input) Snapshot

func (in *Input) Snapshot() map[string]any

func (*Input) Undo

func (in *Input) Undo(steps int) error

type Instance

type Instance struct {
	ID          string    `json:"id"`
	Noun        string    `json:"noun"`
	Parent      string    `json:"parent,omitempty"`
	Payload     Payload   `json:"payload"`
	Bindings    []Binding `json:"bindings,omitempty"`
	Unfocusable bool      `json:"unfocusable,omitempty"`
	Label       string    `json:"label,omitempty"` // a display name (a list row's label, a header name); {{label}} in a confirm prompt
	Data        any       `json:"data,omitempty"`  // an opaque application value (a list row's ListItem.Data)
	Component   any       `json:"-"`
	// contains filtered or unexported fields
}

Instance is one addressable thing on screen: a page, a list, a list row, a modal body, or an input. Parent links form the focus stack; walking them from the focused instance outward is the path Context.Path spells out. An instance holds no mode: the mode is global (Runtime.Mode). Payload is the data a modal body carries (a confirm's prompt and request). Bindings are this instance's own rows, resolved above its noun's table at the same stack level. Component holds the typed component the instance fronts. Unfocusable opts the instance out of being a focus stop although its noun is Focusable (a disabled panel). Label is an optional display name a confirm prompt reads as {{label}}. Data is an opaque application value (a list row's ListItem.Data); the framework never reads it.

type InstanceOption

type InstanceOption func(*instanceSpec)

InstanceOption configures the instance constructors: Instance, AddPage, AddList, AddInput, AddTerminal and RegisterPage.

func CellSelect added in v0.13.0

func CellSelect() InstanceOption

CellSelect makes a table (AddList with Columns) cell-based: a current column beside the selected row, moved with h/l, 0/$, N| and g c, and the cell keys y and z >/z </z =. For a table one reads cell by cell (a JSON or CSV view). AddTree ignores it: a tree's rows answer h and l.

func ClearFilterOnEnter added in v0.10.0

func ClearFilterOnEnter() InstanceOption

ClearFilterOnEnter makes enter in a list's (or a tree's list's) filter line choose the selected match: list.filter-choose clears the filter with the selection staying on that row, every row shows again, the mode is normal and the page keeps the row on screen. For a list one picks a row from, such as a pane list. With no match enter keeps the filter, as on every other list (list.filter-keep; its verb guard, list-chooses, is false there and off this option).

func CloseOnDetach

func CloseOnDetach() InstanceOption

CloseOnDetach makes terminal.detach remove the terminal instance after returning focus, so the stream is released (see TerminalReleaser) instead of kept for a later attach. Only AddTerminal reads it.

func Columns

func Columns(cols ...Column) InstanceOption

Columns makes AddList's list a table with these columns (List.SetColumns changes them later). A list without columns draws its labels.

func Completions added in v0.5.0

func Completions(triggers ...CompletionTrigger) InstanceOption

Completions gives an input its completion triggers (AddInput reads it). They replace the triggers its noun declares (NounBuilder.Completions).

func DefaultHidden added in v0.41.0

func DefaultHidden() InstanceOption

DefaultHidden declares a page hidden by default (Page.DefaultHidden): it starts out of the tabs until page.show (or the pages.hidden setting) brings it in. AddPage and RegisterPage read it; other constructors ignore it.

func Focus

func Focus(id string) InstanceOption

Focus names the instance a page starts focused on (default: the page itself). Other constructors ignore it.

func FocusOnClose

func FocusOnClose(id string) InstanceOption

FocusOnClose names the instance the focus moves to when this instance is removed while the focus is on it or inside it: a CloseOnDetach detach, Pop of a modal body, a list row dropped by SetItems, RemoveInstance. A target that is gone (or removed with it) falls back to the default (the parent, or the return Pop restores). Every constructor reads it.

func FollowTail added in v0.17.0

func FollowTail() InstanceOption

FollowTail makes a timeline follow its end: the window sticks to the bottom while the last card is selected and the bottom is in view; a card appended then is selected and a growing last card keeps its bottom in view. Moving or scrolling up stops it; G or reaching the bottom again resumes it.

func HeaderLines added in v0.17.0

func HeaderLines(n int) InstanceOption

HeaderLines caps a closed card's header at n lines, the rest read "… N more lines"; an open card shows its whole header. 0 shows every line.

func Kind

func Kind(noun string) InstanceOption

Kind names the noun the instance answers to (default: the instance id for plain instances, "editor" for inputs, "list" for lists, "page" for pages, "terminal" for terminals).

func NoMarks added in v0.2.0

func NoMarks() InstanceOption

NoMarks makes a list (or a tree's list) a read-only view: its rows take no marks, so space does not answer with list.mark there (the verb's guard, list-marks, is false; the footer and ? help leave it out) and list.mark refuses. list.apply still runs on the selected row.

func NoSpill

func NoSpill() InstanceOption

NoSpill makes a list trap its motions: list.move past its last (first) row stays on that row instead of moving the focus to the next (previous) stop on the page. For a list that must keep the focus, such as a picker.

func Parent

func Parent(id string) InstanceOption

Parent places the instance under another instance (default app).

func ParentStop added in v0.30.0

func ParentStop(id string) InstanceOption

ParentStop names where h on a closed card of the timeline goes (an instance; a stop lands on its remembered or selected child). Without it h on a closed card stays.

func ReadOnly added in v0.55.0

func ReadOnly() InstanceOption

ReadOnly makes AddInput's input read-only (Input.ReadOnly).

func RowSelect deprecated added in v0.12.0

func RowSelect() InstanceOption

RowSelect is a no-op kept for code written against v0.12.0, where every table was cell-based unless added with it.

Deprecated: tables select rows unless added with CellSelect; drop it.

func SpillToSelection added in v0.55.0

func SpillToSelection() InstanceOption

SpillToSelection makes a spill into a list (j or k past the edge of the stop beside it, R3.4) land on the list's selected row instead of its first or last: for a list that chooses what is drawn beside it (the Settings page's section list), so moving back into it keeps the choice.

type Invocation added in v0.28.0

type Invocation struct {
	Name  string `json:"name"`
	Noun  string `json:"noun"`
	Verb  string `json:"verb"`
	Alias bool   `json:"alias,omitempty"`
}

Invocation is the name a request ran an action by: the action's own key or one of its aliases. Noun is that name's noun (the subject side: for project.associate, an alias of pane.associate, it is project), Verb its verb. Handlers read it from Ctx.Invoked (application verbs) or Runtime.Invoked (interaction handlers).

type JobInfo

type JobInfo struct {
	Job     uint64    `json:"job"`
	Owner   string    `json:"owner"`
	Verb    string    `json:"verb"`
	Label   string    `json:"label,omitempty"`
	Slot    string    `json:"slot,omitempty"`
	Scope   string    `json:"scope,omitempty"`
	Started time.Time `json:"started"`
	State   string    `json:"state"`
	Error   string    `json:"error,omitempty"`
}

JobInfo is one row of the jobs list: what jobs.list returns and what the snapshot's /jobs holds for running jobs.

type JobLingerMsg

type JobLingerMsg struct{ At time.Time }

JobLingerMsg is the ticker's one-shot timer: it fires when the oldest remembered finished job passes JobLinger, so the frame it causes drops the row with no key pressed. At is the deadline it was scheduled for; only the message for the timer in flight clears it.

type KeyEchoCell added in v0.55.0

type KeyEchoCell struct {
	Labels []string
	Width  int
}

KeyEchoCell is the key echo as the shell draws it (Header.Keys, Footer.Keys): the entries, oldest first, and the cells it reserves (keys.echo-width), which the shell holds to at most half the line.

type KeyEvent

type KeyEvent struct {
	Key   MacroKey
	Mode  ModeState
	Focus string
	Level string // the instance whose level is answering, "" for a noun-only level
	// Args are the arguments of the request whose availability is judged
	// (Available): a row's own, or a call's; nil for a row's own guard.
	Args Arguments
}

KeyEvent is what a row receives: the key, the mode it was resolved in and the focused instance.

type KeyOutcome added in v0.36.0

type KeyOutcome int

KeyOutcome is what resolving one key came to (DispatchOutcome).

const (
	// KeyUnhandled: no level had a row on the key whose action is
	// available, so it went past app.
	KeyUnhandled KeyOutcome = iota
	// KeyHandled: a row ran, or the key started or continued a sequence.
	KeyHandled
	// KeyConsumed: the row that answered runs the noop (NoopAction), the
	// always-available action a clamping container binds a key to so it
	// goes no further out: handled, and nothing happened.
	KeyConsumed
)

type Layout

type Layout struct {
	Width, Height int
	Styles        Styles
	// Shift moves the divider of every split this layout draws, in percent
	// points of the split's length: positive grows the first (left or top)
	// panel, negative the second, 0 is the split's default. It is the
	// page's remembered divider (Runtime.PaneLayout sets it; pane.grow,
	// pane.shrink and pane.reset change it). Divide applies it.
	Shift int
	// contains filtered or unexported fields
}

Layout renders page chrome, bounded panels and panel pairs for a viewport. It is a plain value: every method only renders and keeps no state.

Example
layout := Layout{
	Width: 80, Height: 24,
	Styles: NewStyles(Appearance{Theme: "adaptive"}),
}
body := layout.Split("Files", "main.go\nlayout.go", "Preview", "Selected file contents")
page := layout.Page("Workspace", "Browse files", body, "Enter open · Esc back")
fmt.Print(page)

func (Layout) BodySize

func (l Layout) BodySize() (width, height int)

BodySize returns the exact cells available to Page's body. Viewports that cannot hold any body report 0, 0. Small viewports drop the header and keep only a footer row.

func (Layout) BodySizeWith

func (l Layout) BodySizeWith(f Footer) (width, height int)

BodySizeWith is the body's size with the footer f: BodySize, since the jobs ticker rides the rule line above the footer and takes no body row, so a job starting or lingering out never moves or hides the body (UX review 2 F13).

func (Layout) Divide added in v0.4.0

func (l Layout) Divide(first, total, least int) int

Divide is where a split of total cells puts its divider: first is the split's default size of its first (left or top) panel, moved by Shift percent points of total and clamped so each panel keeps least cells. A split with no shift, or too small for two panels of least cells, keeps first. A layout of its own (a page body split by hand) calls it with its default; Split and its kin call it for theirs.

func (Layout) HeaderRule added in v0.36.0

func (l Layout) HeaderRule(cells []SegmentCell, width int) string

HeaderRule is the rule line under the header, width cells: the plain rule with no segments; with segments, rule characters, then the segments right-aligned, joined by " · ", then " ──". Segments are dropped from the last while they do not fit, and when the first alone does not, it is cut with "…"; at least "── " of rule stays on the left. Each segment draws in its tone (muted without one), the rule and separators muted, so the chrome still reads as a rule.

func (Layout) Page

func (l Layout) Page(title, subtitle, body, footer string) string

Page renders title, subtitle, body and footer into exactly Width x Height cells. Body is trusted ANSI; title, subtitle and footer are raw labels. Overlong bodies are clipped; use Panel for a visible overflow marker.

func (Layout) PageBlock

func (l Layout) PageBlock(title, subtitle string, body Block, footer string) Block

PageBlock is Page for a body that may carry a cursor; the cursor is moved by the page chrome around the body.

func (Layout) Panel

func (l Layout) Panel(title, body string, width, height int, focused bool) string

Panel renders a rounded, titled box of exactly width x height outer cells. Focused panels use the heavy accent border. Body is trusted ANSI; title is a raw label. Content that does not fit is clipped and marked with "…" (columns) or a "… N more" last row (lines). Below 3x3 cells the border is dropped.

func (Layout) PanelBlock

func (l Layout) PanelBlock(title string, body Block, width, height int, focused bool) Block

PanelBlock is Panel for a body that may carry a cursor; the cursor is moved inside the border and padding.

func (Layout) Shell

func (l Layout) Shell(h Header, body Block, f Footer) Block

Shell is the one page chrome: title row, subtitle row, a rule, the body, a rule, the footer and a bottom margin, inside a gutter, into exactly Width x Height cells. Viewports too small for the chrome keep the body and, from three rows up, the footer. The shell and PageBlock both render through it, so a page and the application around it reserve the same rows. The body's cursor is moved by the chrome around it.

func (Layout) Sidebar

func (l Layout) Sidebar(title string, items []string, selected int, mainTitle, mainBody string) string

Sidebar renders a 28-cell navigation rail beside the main panel. Below 72 columns it stacks above the main panel. Items are raw labels; mainBody is trusted ANSI. Selection is zero-based and clamped for rendering. The caller owns selection and key handling; this method keeps the selected item visible.

Example
layout := Layout{Width: 80, Height: 24, Styles: NewStyles(Appearance{Theme: "adaptive"})}
body := layout.Sidebar("Workspace", []string{"Files", "Search", "Settings"}, 1, "Search", "Search results")
fmt.Print(layout.Page("Project", "Workspace navigation", body, "↑↓ select · Enter open"))

func (Layout) SidebarBlock

func (l Layout) SidebarBlock(title string, items []string, selected int, mainTitle string, mainBody Block) Block

SidebarBlock is Sidebar for a main body that may carry a cursor.

func (Layout) Split

func (l Layout) Split(leftTitle, leftBody, rightTitle, rightBody string) string

Split renders two panels filling BodySize: side by side (left ~40%) when the viewport is at least 72 cells wide, otherwise stacked (top ~40%), the divider moved by Shift (Divide). The left or top panel is the focused one; SplitFocusBlock takes which.

func (Layout) SplitBlock

func (l Layout) SplitBlock(leftTitle string, leftBody Block, rightTitle string, rightBody Block) Block

SplitBlock is Split for bodies that may carry a cursor. One body should carry it; when both do, the left or top panel wins.

func (Layout) SplitFocusBlock added in v0.2.0

func (l Layout) SplitFocusBlock(focused SplitSide, leftTitle string, leftBody Block, rightTitle string, rightBody Block) Block

SplitFocusBlock is SplitBlock with the focused panel named: the one holding the focus draws in the focused style (accent title and border), the other plain, so a view whose focus moves between its panes (o-json's tree and detail) shows where it is. When both bodies carry a cursor, the focused panel's wins.

func (Layout) TickerRule added in v0.2.0

func (l Layout) TickerRule(jobs []string, width int) string

TickerRule is the rule line above the footer, width cells: the plain rule with no jobs; with jobs, "── " then the ticker entries (Footer.Jobs, at most JobTickerRows) joined by " · ", cut with "…" so at least " ─" of rule is left, and the rest of the row filled with rule characters, all muted, so the chrome still reads as a rule.

func (Layout) WithPanelTone added in v0.59.0

func (l Layout) WithPanelTone(tone string) Layout

WithPanelTone is the layout whose panels (Panel, PanelBlock) carry tone, a tone name such as state.working, on their border, as a timeline card carries Card.Tone: the border draws in the chrome row border.<tone> of the chrome.color level (chrome.rich.border.state.working), bold when the panel is focused, and keeps its heavy lines when focused. A level with no such row, or "", draws the panel's usual border. An application passes the state of the thing a panel shows (a terminal pane's agent state):

layout.WithPanelTone(stateTone(pane)).PanelBlock(title, body, w, h, focused)

type LineScroller added in v0.50.0

type LineScroller interface {
	// CanScrollLines reports whether the last frame windowed the lines (more
	// lines than the window shows), so a scroll would move it.
	CanScrollLines() bool
	// ScrollLines moves the window by lines, down when positive, clamped to
	// the first and last line.
	ScrollLines(lines int)
}

LineScroller is a component that windows its own lines and scrolls that window without a motion of the cursor (Vim's ctrl+e and ctrl+y, :help CTRL-E): the window moves, and the cursor stays where it is unless it would leave the window (with the page's scrolloff), when it moves to the nearest line still shown. A list (tables and trees through their list), a timeline and a markdown document implement it; view.scroll scrolls the innermost one on the focus path that can.

type Lines

type Lines []any

Lines is a result printed as JSON Lines (one compact value per line, no outer array) by a CLI, so a reader can decode it as it arrives; over JSON it is an array. HandleCall keeps the type through its copy.

type List

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

List owns flat selection, marks and scrolling on the runtime's event loop. Focus sits on the selected row when there is one, else on the list.

func NewList

func NewList(r *Runtime, id string, items []ListItem, opts ...InstanceOption) (*List, error)

NewList is AddList for callers that hold the runtime as a value.

func (*List) CanScrollLines added in v0.50.0

func (l *List) CanScrollLines() bool

CanScrollLines reports whether the list windowed its rows in the last frame (more rows than its window).

func (*List) Column added in v0.12.0

func (l *List) Column() int

Column is a cell-mode table's current column (an index into Columns); 0 for any other list.

func (*List) ColumnOffset added in v0.9.0

func (l *List) ColumnOffset() int

ColumnOffset is the table's column offset: 0 unscrolled, else k for the view that starts the scrolling columns at the k-th.

func (*List) ColumnWidths added in v0.12.0

func (l *List) ColumnWidths() map[int]int

ColumnWidths is the widths given to columns with z > and z < (column index to cells); a column left out is laid out automatically.

func (*List) Columns

func (l *List) Columns() []Column

Columns returns a copy of the list's columns (nil for a plain list).

func (*List) EndVisual added in v0.12.0

func (l *List) EndVisual()

EndVisual ends a visual selection: the marks go back to the ones it started over.

func (*List) Filter added in v0.8.0

func (l *List) Filter() string

Filter is the list's filter query ("" when every row is shown).

func (*List) Filtering added in v0.8.0

func (l *List) Filtering() bool

Filtering reports whether the filter line shows: a filter is set, or its query is being typed on this list.

func (*List) Focus

func (l *List) Focus() error

Focus points the active frame at the list's selected row, or the list.

func (*List) FocusTarget

func (l *List) FocusTarget() string

FocusTarget is where a focus jump to the list lands: its selected row.

func (*List) Focused

func (l *List) Focused() bool

Focused derives focus from the active frame instead of retaining a stale flag.

func (*List) Height added in v0.8.0

func (l *List) Height() int

Height is the lines the list needs to draw every row without windowing (a table's header aside): Len, plus the filter line while it shows. A host that sizes a list to its rows sizes it with Height, so opening the filter line neither windows the rows nor moves what is drawn below the list as the filter narrows it.

func (*List) Items

func (l *List) Items() []ListItem

Items returns a copy of every row in display order, the ones a filter hides included. Cells and Tones are copies too, so editing a returned row in place changes nothing until SetItems, which re-measures it; Data is the application's value, shared as given.

func (*List) Len

func (l *List) Len() int

Len is the number of rows, the ones a filter hides included (Shown counts the rest).

func (*List) Marked

func (l *List) Marked() []ListItem

Marked lists the marked rows in list order, the ones a filter hides included (a mark survives the filter).

func (*List) MatchMode added in v0.59.0

func (l *List) MatchMode() string

MatchMode is the filter's match mode: the one search.cycle-match or search.set-match chose for this list, else the search.match setting.

func (*List) ModeChanged added in v0.43.0

func (l *List) ModeChanged(from, to string)

ModeChanged follows the global mode (ModeObserver): a line-shaped selection mode entered with the focus on one of the list's rows starts the selection there; leaving it with the focus on the list ends it. A mode left for a modal opened over the selection holds it: the mode the modal restores on close resumes it, anchor and marks as they were.

func (*List) Move

func (l *List) Move(delta int)

Move clamps at either end and does not take focus from another component.

func (*List) Patch added in v0.8.0

func (l *List) Patch(p ListPatch) error

Patch applies a record-level change (ListPatch) without the caller rebuilding the rows: it is SetItems over the patched rows, so a row that stays keeps its instance (and the bindings and pending jobs on it), the selection and the marks follow their ids, and only a removed row's instance is closed. An empty patch does nothing; an invalid one (an index out of order or out of range, a repeated id) leaves the list unchanged. The patch applies to every row, the ones a filter hides included, and SetItems filters the result again.

func (*List) PinColumn added in v0.25.0

func (l *List) PinColumn(i int)

PinColumn pins column i; UnpinColumn unpins it.

func (*List) PinnedColumns added in v0.25.0

func (l *List) PinnedColumns() []int

PinnedColumns is the table's pinned columns (indexes into Columns) in declared order.

func (*List) ResetColumnWidths added in v0.12.0

func (l *List) ResetColumnWidths()

ResetColumnWidths makes every column automatic again and remembers it.

func (*List) ResetPins added in v0.25.0

func (l *List) ResetPins()

ResetPins puts the default pins back (Column.Pinned, else the first).

func (*List) ScrollLines added in v0.50.0

func (l *List) ScrollLines(lines int)

ScrollLines moves the list's window by lines rows, clamped, keeping the selection unless it would leave the window's scrolloff margin; then it moves to the nearest row inside (relaxed at the first and last row, as windowOffset is). It never spills.

func (*List) Select

func (l *List) Select(id string) error

Select changes the selected row by stable ID without taking focus. A row the filter hides is shown by clearing the filter.

func (*List) Selected

func (l *List) Selected() (ListItem, bool)

Selected returns a value copy; empty lists have no selected item.

func (*List) SetColumn added in v0.12.0

func (l *List) SetColumn(i int)

SetColumn makes column i (clamped) the current column of a cell-mode table and remembers it; on any other list it does nothing.

func (*List) SetColumnWidth added in v0.12.0

func (l *List) SetColumnWidth(i, width int)

SetColumnWidth fixes column i at width cells (0 or less: automatic again) and remembers it.

func (*List) SetColumns

func (l *List) SetColumns(cols ...Column)

SetColumns replaces the list's columns; none makes it a plain list again.

func (*List) SetFilter added in v0.8.0

func (l *List) SetFilter(query string)

SetFilter sets the filter query and shows the rows that match it; "" shows every row. The selection stays on its row when that row still shows, else it moves to the first match (none when nothing matches); the focus follows it.

func (*List) SetItems

func (l *List) SetItems(items []ListItem) error

SetItems copies rows, preserves selection by ID, and falls back to the nearest remaining index if that ID disappears. Invalid updates leave the list unchanged. A filter (SetFilter) stays and applies to the new rows. It creates one instance per new row under the list and removes the instances of rows that disappear; a retained row keeps its instance and any bindings the application put on it. Rows whose cells are unchanged keep a table's measured widths. A record-level change is Patch.

func (*List) SetPinnedColumns added in v0.25.0

func (l *List) SetPinnedColumns(pins []int)

SetPinnedColumns makes these columns (indexes into Columns) the table's pins and remembers them; the default pins are remembered as no choice.

func (*List) Shown added in v0.8.0

func (l *List) Shown() int

Shown is the number of rows the filter lets through (Len without one).

func (*List) Snapshot

func (l *List) Snapshot() map[string]any

Snapshot is the list's state with a copy of its rows (the snapshot's /lists entry); changing it never reaches the list.

func (*List) StartVisual added in v0.12.0

func (l *List) StartVisual() error

StartVisual starts a visual row selection at the selected row; a list without rows or one added with NoMarks refuses.

func (*List) ToggleMark

func (l *List) ToggleMark(id string) error

ToggleMark marks or unmarks a row for fan-out verbs; a list added with NoMarks refuses.

func (*List) UnpinColumn added in v0.25.0

func (l *List) UnpinColumn(i int)

UnpinColumn unpins column i.

func (*List) UnpinColumns added in v0.25.0

func (l *List) UnpinColumns()

UnpinColumns leaves no column pinned.

func (*List) View

func (l *List) View(width, height int) string

View fits the viewport and updates its scroll offset to keep selection visible; a list with columns draws as a table (tableView). Calling it places the list in its page's drawing order (Placed), even at zero height, and reports its selected row's line (PlacedAt) so the page scrolls to keep that row on screen.

func (*List) Visual added in v0.12.0

func (l *List) Visual() bool

Visual reports whether a V selection is active on the list.

type ListItem

type ListItem struct {
	ID      string     `json:"id"`
	Label   string     `json:"label"`
	Noun    string     `json:"noun"`
	Data    any        `json:"data,omitempty"`
	Cells   []string   `json:"cells,omitempty"`
	Section string     `json:"section,omitempty"`
	Tones   []ToneSpan `json:"tones,omitempty"`
}

ListItem is application-owned identity, display text, and the registered noun the row answers to. Each row is an Instance whose ID is the item ID and whose Parent is the list; its bindings and actions come from its noun. Data is an opaque value the application keeps on the row (a host's record of the row, an extension's own id); SetItems copies it to the row instance's Data, where a verb reads it as Ctx.Instance.Data. The framework never reads it. Cells are the row's text per column when the list has columns (a table, Columns); Label stays the row's name for the palette, search and {{label}}, and is the first cell of a row without cells. Section groups a table's rows: List.View draws the section as a label line above the first row of each run of rows with the same Section (a list without columns ignores it). Tones give cells, or runs inside them, a named tone the theme colours (ToneSpan, tone.go; in a list without columns cell 0 is the label); they never change the text.

func PatchItems added in v0.8.0

func PatchItems(rows []ListItem, p ListPatch) ([]ListItem, error)

PatchItems is rows with p applied (ListPatch); rows is not modified.

type ListPatch added in v0.8.0

type ListPatch struct {
	Upsert []ListItem
	At     []int
	Remove []string
}

ListPatch is a record-level change to a list's rows: the rows that changed or were added, whole (Upsert), and the ids of the rows that went away (Remove). Every other row stays as it is, in its order.

At, when given, is each upserted row's index in the patched list, one per Upsert and ascending: the rows neither upserted nor removed keep their relative order and fill the indexes the upserts leave free. Without At a row whose id the list has replaces it in place and a new row is appended, in Upsert order.

func (ListPatch) Empty added in v0.8.0

func (p ListPatch) Empty() bool

Empty reports whether the patch changes nothing.

type ListQuery added in v0.52.0

type ListQuery struct {
	Where map[string]any
	Limit int
	Args  Arguments
}

ListQuery is what list hands its store: the where pairs (prop to typed value, equality, all of them), the limit (0 for none) and the store's own ListParams the request gave. A store may use them to read less; the runtime applies where and limit to the answer either way, so a store that ignores them is still right.

type MacroKey

type MacroKey struct {
	Key   string `json:"key"`
	Paste bool   `json:"paste,omitempty"`
}

MacroKey is one recorded key of a macro; Paste marks pasted text.

type MacroState

type MacroState struct {
	Recording string     `json:"recording,omitempty"`
	Last      string     `json:"last,omitempty"`
	Keys      []MacroKey `json:"keys,omitempty"`
	Depth     int        `json:"depth"`
	Steps     int        `json:"steps"`
}

MacroState is the application-wide recording and replay state. Awaiting a register name is the macro_pending or replay_pending mode of the focused instance, not a field here.

type Matcher added in v0.59.0

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

Matcher is one query compiled in one match mode, case as search.case says. Build it with NewMatcher or Runtime.Matcher; the zero value matches everything as a substring search.

func NewMatcher added in v0.59.0

func NewMatcher(mode, caseMode, query string) Matcher

NewMatcher compiles query in mode (substring for an unknown mode) with case as the search.case value caseMode gives it. A blank query matches every text. For regex, smart case folds unless the pattern holds an upper-case letter outside an escape (\S, \W and \p{Lu} do not count, as in Vim), and folding is the (?i) flag.

func (Matcher) Err added in v0.59.0

func (m Matcher) Err() error

Err is why the query matches nothing (an invalid regex), else nil.

func (Matcher) Fold added in v0.59.0

func (m Matcher) Fold() bool

Fold reports whether Prepare folds case (a regex folds through (?i) instead, so its texts are prepared unchanged).

func (Matcher) Match added in v0.59.0

func (m Matcher) Match(text string) bool

Match reports whether text matches the query.

func (Matcher) MatchPrepared added in v0.59.0

func (m Matcher) MatchPrepared(hay string) bool

MatchPrepared reports whether hay, a text from Prepare, matches.

func (Matcher) Mode added in v0.59.0

func (m Matcher) Mode() string

Mode is the matcher's match mode.

func (Matcher) Prepare added in v0.59.0

func (m Matcher) Prepare(text string) string

Prepare is text as the matcher compares it; a caller that matches the same texts often can keep the prepared texts while Fold is unchanged.

func (Matcher) Scattered added in v0.59.0

func (m Matcher) Scattered() bool

Scattered reports whether the mode's matches may be strewn across the text (fuzzy), rather than spelled in it.

func (Matcher) ScorePrepared added in v0.59.0

func (m Matcher) ScorePrepared(hay string) (int, bool)

ScorePrepared reports whether hay (from Prepare) matches and how well: fuzzyScore for fuzzy (compact runs and word starts score higher), the sum of each word's fuzzyScore for substring, 0 for regex. Higher is better; the blank query scores 0 everywhere.

type ModalBody added in v0.2.0

type ModalBody interface {
	ModalTitle() string
	ModalBlock(s Styles, width, height int) Block
}

ModalBody is a modal body component that draws itself: a modal whose instance's Component implements it needs no ModalView (a record editor opened as a modal, its chooser, a Chooser). A ModalView for the id still wins.

type ModalOption

type ModalOption func(*modalSpec)

ModalOption configures OpenModal.

func ReplaceOpen added in v0.52.0

func ReplaceOpen() ModalOption

ReplaceOpen makes an open of a kind that is already the top modal close that modal first and open the new one in its place, over the focus and mode the old one opened over: a viewer asked to show something else (docs.open TOPIC inside the docs viewer) shows it instead of failing "already open" or stacking a second copy. Without it a second open of an open kind is refused, so a modal holding a question (a confirm, a prompt, a chooser) keeps it. A kind open beneath another modal is still refused.

func WithInput

func WithInput(in *Input, opts ...InstanceOption) ModalOption

WithInput places an input inside the modal body and focuses it, so a one-field prompt is one call. The input is registered under the body (a Kind option names its noun; Parent is ignored) and is removed with the body on Pop; the *Input keeps its text and undo history and may be passed again to the next OpenModal.

type ModalView

type ModalView struct {
	Title  string
	Render func(*Runtime, *Instance, int, int) Block
}

ModalView renders one modal without replacing or inspecting its parent page. Render receives the modal instance (its Payload carries what OpenModal gave it) and returns the body as a Block; its cursor, when the modal holds the focused input, is relative to the body's top-left cell.

type ModeBuilder

type ModeBuilder struct {
	*NounBuilder
	// contains filtered or unexported fields
}

ModeBuilder binds rows into one mode table of a noun.

func (*ModeBuilder) Bind

func (m *ModeBuilder) Bind(keys string, row Binding) *ModeBuilder

Bind adds an exact-key (or key-sequence) row, replacing the row with the same keys and guard (Binding.Guard, or When after Bind).

func (*ModeBuilder) Extends

func (m *ModeBuilder) Extends(parent string) *ModeBuilder

Extends makes the selected mode's table read parent's rows after its own, as the editor spec's "extends" does: three motion tables become one table and two that extend it. A mode extends one parent; Extends("") removes the link.

func (*ModeBuilder) Pattern

func (m *ModeBuilder) Pattern(pattern string, row Binding) *ModeBuilder

Pattern adds a key-class row.

func (*ModeBuilder) Unbind

func (m *ModeBuilder) Unbind(keysOrPattern string) *ModeBuilder

Unbind removes the unguarded row with these keys or this pattern; a guarded row on them stays (UnbindGuarded removes that one).

func (*ModeBuilder) UnbindGuarded added in v0.6.0

func (m *ModeBuilder) UnbindGuarded(keysOrPattern, guard string) *ModeBuilder

UnbindGuarded removes the row with these keys or this pattern and this guard ("" is the unguarded row).

func (*ModeBuilder) When

func (m *ModeBuilder) When(guard string) *ModeBuilder

When guards the last bound row with a registered guard name. The guard is part of the row's identity, so the row is placed again under it: a row it replaced as an unguarded row comes back, and it replaces the row with the same keys and this guard instead.

type ModeObserver

type ModeObserver interface {
	ModeChanged(from, to string)
}

ModeObserver is implemented by a component that follows the base mode while the focus sits on it or beneath it: the grid starts and ends its selection when a visual shape is entered or left.

type ModeOption added in v0.43.0

type ModeOption func(*ModeSpec)

ModeOption is a property DefineMode gives a mode, as a bindings file's "modes" entry does.

func ModeExtends added in v0.43.0

func ModeExtends(parent string) ModeOption

ModeExtends makes a mode fall back to parent's rows for every noun with no table of its own in the mode (no rows and no extends there): a mode that is "normal plus a few keys" (o-json's query, visual-line) binds only its own keys, and the nouns it does not mention keep their normal rows. A noun's own table (even an empty one, or one with its own extends) replaces the fallback for that noun.

type ModeSpec added in v0.33.0

type ModeSpec struct {
	Pending     bool `json:"pending,omitempty"`
	Passthrough bool `json:"passthrough,omitempty"`
	// Selection is the selection shape the mode holds (char, line, block;
	// DefineSelection), "" for a mode that selects nothing.
	Selection string `json:"selection,omitempty"`
	// Extends is the mode whose rows the mode falls back to for a noun
	// with no table of its own in it (ModeExtends).
	Extends string `json:"extends,omitempty"`
}

ModeSpec is one mode's entry in a bindings file's "modes".

type ModeState

type ModeState struct {
	Name    string  `json:"name"`
	Payload Payload `json:"payload"`
}

ModeState is a mode name with the payload the mode carries.

type Model

type Model struct {
	// Foreground answers a ForegroundMsg (a verb's Foreground program);
	// nil runs it through tea.ExecProcess, suspending the TUI. o-story
	// and tests replace it to run the program headless.
	Foreground func(ForegroundMsg) tea.Cmd
	Runtime    *Runtime
	Palette    *Palette
	Appearance *Appearance
	ModalViews map[string]ModalView
	Title      string
	Width      int
	Height     int
	// Status is the status line in its error tone: the last key's error,
	// or what a handler set with ctx.Error (ctx.Status); the footer reads
	// "Error: TEXT" in the error style in place of the hints. Info is the
	// line in its neutral tone (ctx.Info), drawn plain before the hints.
	// Setting one clears the other, and the next key clears both.
	Status string
	Info   string
	// Notices are persistent lines (a host's mount warnings), kept across
	// keys and errors until notice.clear (or the application) clears them.
	// The footer shows the newest before the hints, cut to half the width,
	// with "(+N more)" for the rest (notice.list has them all), so notices
	// never hide the hints. A notice does not go with the next key. The
	// Model is the runtime's UI sink (Runtime.UI), so ctx.Notify,
	// ctx.Error and ctx.Info land here.
	Notices []string

	// Sidebar replaces page tabs with a navigation rail. Existing page operations
	// remain the only navigation state; input focus and modal routing are unchanged.
	Sidebar bool

	// Now is the Model's clock: the ticker's memory of finished jobs and
	// the linger timer read it (time.Now by default, time.Now when nil). A
	// headless host fakes it, advances it to JobLingerTick's deadline and
	// delivers that message instead of waiting JobLinger.
	Now func() time.Time
	// contains filtered or unexported fields
}

Model is the Bubble Tea adapter. Pages and modal instances retain their state in Runtime; components (picker, registers, application components) are instances the runtime drives through the delivery contract, so the adapter holds no component list of its own.

func NewModel

func NewModel(r *Runtime) *Model

NewModel returns the Bubble Tea model that renders and drives r.

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init installs the user actions file (Runtime.EnsureUserActions) and applies the user bindings file (Runtime.EnsureUserBindings), after the application defined its own nouns and rows, declares the framework's settings (EnsureConfigSettings), reads settings.json (its problems are notices), draws themes.json's schemes and the theme setting's (applyThemeSetting), restores and persists the action history (EnsureHistory), leaves a start page the pages.hidden setting hides for the first page in the tabs (OpenVisibleStart), starts the settings.json poll (SettingsPoll) when the application declared settings, and asks for the background colour.

func (*Model) JobLingerTick

func (m *Model) JobLingerTick() (JobLingerMsg, bool)

JobLingerTick is the linger timer in flight, the message its tea.Tick will deliver at its deadline (At), and false when none is scheduled. A host with a fake Now advances the clock to At and delivers the message itself rather than waiting JobLinger.

It is the Model's one linger timer: the key echo's entries (keys.echo- linger) ride it too, so the earlier of the two deadlines in flight is the one returned, and its message clears whichever timer it was for.

func (*Model) JobsTicker

func (m *Model) JobsTicker(width int) []string

JobsTicker is the ticker the shell draws in the rule line above the footer for the current frame, as plain entries at most width cells each: none when no job shows.

func (*Model) KeyEchoLabels added in v0.55.0

func (m *Model) KeyEchoLabels() []string

KeyEchoLabels are the entries the key echo shows now, oldest first: none while keys.echo is off.

func (*Model) Notify

func (m *Model) Notify(text string) NoticeID

Notify adds a persistent notice to the footer (Notices) through the runtime's UI, as ctx.Notify does, and returns its id; notice.clear removes them.

func (*Model) SegmentTick added in v0.36.0

func (m *Model) SegmentTick() (SegmentTickMsg, bool)

SegmentTick is the segment timer in flight, the message its tea.Tick will deliver at its deadline (At), and false when none is scheduled. A host with a fake Now advances the clock to At and delivers the message itself rather than waiting.

func (*Model) SegmentsInFlight added in v0.36.0

func (m *Model) SegmentsInFlight() int

SegmentsInFlight counts the refreshes started and not yet answered.

func (*Model) StatusSegments added in v0.36.0

func (m *Model) StatusSegments() []string

StatusSegments are the segment texts the header rule draws this frame, first to last, before fitting (Layout.HeaderRule cuts what does not fit).

func (*Model) Styles added in v0.10.0

func (m *Model) Styles() Styles

Styles is the Model's appearance with the dim settings applied (modal-dim, dim-unfocused, modal-highlights) and the chrome level (chrome.color) in the current mode; the shell, modals and page lists draw in it.

func (*Model) Update

func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

func (*Model) View

func (m *Model) View() tea.View

View renders the shell as a full-screen tea.View; View().Content is the string. The terminal cursor follows the rendered block through the page or modal that holds it: a bar in insert mode, a block in normal mode and an underline in visual modes. It is hidden when the block reports no cursor.

type NoticeID added in v0.4.0

type NoticeID uint64

NoticeID names one notice so the code that posted it can clear it. The UI assigns it, whatever sink shows the notice (or none), so a handler can always clear what it posted.

type Noun

type Noun struct {
	Name      string               `json:"name"`
	Verbs     []string             `json:"verbs,omitempty"`
	Pin       string               `json:"pin,omitempty"`
	Focusable bool                 `json:"focusable,omitempty"`
	Region    bool                 `json:"region,omitempty"`
	Bindings  map[string][]Binding `json:"bindings"`
	Extends   map[string]string    `json:"extends,omitempty"`
	Guards    map[string]string    `json:"guards,omitempty"`
	// Availability are the guards added to a verb beside its own
	// (Runtime.AddVerbAvailability), by verb: every one must hold too.
	Availability map[string][]string `json:"availability,omitempty"`
	Actions      map[string]Handler  `json:"-"`
	// Columns are the table columns a list of the noun's rows draws
	// (NounBuilder.Columns, the catalog's columns): declared data a host
	// passes to Columns when it builds the list, never applied on its own.
	Columns []Column `json:"columns,omitempty"`
	// Completions are the completion triggers of the noun's inputs that
	// declare none of their own (NounBuilder.Completions).
	Completions []CompletionTrigger `json:"-"`
	// Props are the fields of the noun's things (NounBuilder.Props,
	// props.go), in declaration order; Store is its store row
	// (NounBuilder.Store), nil when it declares none.
	Props []PropSpec `json:"props,omitempty"`
	Store *Store     `json:"-"`
}

Noun is the behaviour shared by every instance of one kind: the verbs it answers to, its key bindings per mode, the action handlers that override an operation's default while the noun is on the focus stack, and an optional pinned mode (the prompt noun pins insert). Focusable marks every instance of the noun as a focus stop (focus.next and the mode rule read it); Region marks a grouping that focus.next {scope: "region"} jumps between.

Bindings is keyed by mode name. "" holds rows that apply in every base mode; a pending mode (operator_pending, a key-sequence prefix, ...) is exclusive and reads only its own table.

func (*Noun) StoreKind added in v0.52.0

func (n *Noun) StoreKind() string

StoreKind is the kind of the noun's store (Collection, Singleton, Instances), "" when it declares none.

type NounAlias added in v0.16.0

type NounAlias struct {
	Alias       string `json:"alias"`
	Noun        string `json:"noun"`
	Shadowed    bool   `json:"shadowed,omitempty"`
	Since       string `json:"since,omitempty"`
	RemoveAfter string `json:"removeAfter,omitempty"`
	Note        string `json:"note,omitempty"`
}

NounAlias is one alias: the short name, the noun it names, and whether an application noun of that name shadows it (the short name then reaches the application's noun and the framework's stays reachable by Noun). Since and RemoveAfter mark a deprecated alias (an old name kept for a release after a rename, Keep actions); Note is free text its notice adds.

func (NounAlias) Deprecated added in v0.57.0

func (a NounAlias) Deprecated() bool

Deprecated reports whether the alias is an old name on its way out.

type NounBuilder

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

NounBuilder is the declaration surface of one noun.

func (*NounBuilder) Action

func (b *NounBuilder) Action(key string, h Handler) *NounBuilder

Action overrides any operation ("noun.verb") while this noun is on the stack.

func (*NounBuilder) Alias added in v0.28.0

func (b *NounBuilder) Alias(verbs ...string) *NounBuilder

Alias makes each name another verb of this noun for the last declared verb (show for get, forget for kill): a permanent alias. A name may hold a dot (base.add). It panics on a clash (AddActionAlias), as Verb does on a duplicate.

func (*NounBuilder) AliasOn added in v0.28.0

func (b *NounBuilder) AliasOn(noun, verb string) *NounBuilder

AliasOn makes noun.verb another name of the last declared verb: one operation reachable under both nouns' names (project.associate for pane.associate). The handler reads which side named it from Ctx.Invoked.

func (*NounBuilder) Columns

func (b *NounBuilder) Columns(cols ...Column) *NounBuilder

Columns declares the table columns a list of the noun's rows draws, in order, each row's ListItem.Cells the same order (Noun.Columns). The catalog carries them, so a host mounting the noun's rows draws a table; an application passes r.Noun(noun).Columns to the Columns list option.

func (*NounBuilder) Completions added in v0.5.0

func (b *NounBuilder) Completions(triggers ...CompletionTrigger) *NounBuilder

Completions declares the completion triggers of every input of the noun that has none of its own (Input.Completions).

func (*NounBuilder) Confirm

func (b *NounBuilder) Confirm(prompt string) *NounBuilder

Confirm asks before the last declared verb runs: the prompt template ({{id}}, {{noun}}, {{<arg>}}) opens a confirm modal whose y runs the stored request and n or esc pops it. An empty prompt removes the confirm.

func (*NounBuilder) Fetch added in v0.7.0

func (b *NounBuilder) Fetch() *NounBuilder

Fetch marks the last declared verb as a data request (Operation.HistoryKind HistoryFetch): a state, list or show verb. Its calls are history entries of kind fetch, which history.list leaves out by default and the ring bounds apart from the user's actions and changes.

func (*NounBuilder) Focusable

func (b *NounBuilder) Focusable() *NounBuilder

Focusable makes every instance of the noun a focus stop.

func (*NounBuilder) Many added in v0.36.0

func (b *NounBuilder) Many() *NounBuilder

Many marks the last declared verb as taking many subjects at once (Operation.Many): run over a visual selection, its handler is called once with every selected row in Ctx.Subjects instead of once per row. Use it for a verb that asks something (a chooser, a confirm naming what it affects) or that should make one change and one notice for all.

func (*NounBuilder) Mode

func (b *NounBuilder) Mode(mode string) *ModeBuilder

Mode selects the table rows are bound into; "" is the any-mode table.

func (*NounBuilder) Motion

func (b *NounBuilder) Motion() *NounBuilder

Motion marks the last declared verb as a motion (Operation.Motion): the footer leaves its rows to ? help, as it does for list.move.

func (*NounBuilder) Noun

func (b *NounBuilder) Noun() *Noun

func (*NounBuilder) PersistArgs added in v0.2.0

func (b *NounBuilder) PersistArgs() *NounBuilder

PersistArgs marks the last declared verb's text-like arguments as safe to keep in the history file (Operation.PersistArgs).

func (*NounBuilder) Pin

func (b *NounBuilder) Pin(mode string) *NounBuilder

Pin keeps every instance of the noun in one base mode.

func (*NounBuilder) Positional

func (b *NounBuilder) Positional(names ...string) *NounBuilder

Positional names the parameters of the last declared verb that bare words fill first, in order (Operation.Positional): Positional("name") makes BIN project link foo set name even though the boolean all sorts first. The CLI gives a boolean a bare word only when it is named here.

func (*NounBuilder) Props added in v0.52.0

func (b *NounBuilder) Props(props ...PropSpec) *NounBuilder

Props declares props of the noun (see PropSpec), in order. It panics on a bad declaration: a name that is not one word, a standard verb's name, a name the noun's verbs or a nested noun already take, a second prop of that name, an unknown type, or a bad role. Declared after Store, the standard verbs follow the new props.

func (*NounBuilder) Quiet

func (b *NounBuilder) Quiet() *NounBuilder

Quiet marks the last declared verb as bookkeeping (Operation.Quiet): its jobs stay off the jobs ticker. The framework names no quiet verb.

func (*NounBuilder) Region

func (b *NounBuilder) Region() *NounBuilder

Region makes every instance of the noun a focus region: a grouping (a panel) that focus.next {scope: "region"} jumps between, never a stop.

func (*NounBuilder) Renamed added in v0.28.0

func (b *NounBuilder) Renamed(old, since, removeAfter string) *NounBuilder

Renamed keeps old, the verb's name before a rename, as a deprecated alias of the last declared verb: since is the release that renamed it and removeAfter the last release that keeps the old name (one release, per Keep actions; record it in the CHANGELOG). Its first use posts a one-time notice naming the new name.

func (*NounBuilder) Rows

func (b *NounBuilder) Rows(noun string) *NounBuilder

Rows declares that the last declared verb's result lists rows of noun (Operation.Rows): a host reading the catalog knows which noun a list verb's rows answer to. An empty noun removes the declaration.

func (*NounBuilder) State

func (b *NounBuilder) State() *NounBuilder

State marks the last declared verb as the runtime's state source (Operation.State): one call answers every list's rows as JSON Lines, each line tagged with the list noun (see cli.CatalogDoc). A host reading the catalog's state runs it once instead of one row source per list. The framework names no state verb.

func (*NounBuilder) Store added in v0.52.0

func (b *NounBuilder) Store(s Store) *NounBuilder

Store declares the noun's store row and registers the standard verbs it supports (standard_verbs.go). Props come first. It panics when the noun has no props, the kind is unknown, the key props do not fit the kind (one Key prop for a collection or instances, none for a singleton), or a role, fallback or list parameter is wrong.

func (*NounBuilder) TextResult added in v0.55.0

func (b *NounBuilder) TextResult() *NounBuilder

TextResult marks the last declared verb's result as text (Operation.Result ResultText): the palette opens what it answers in the text view, a read-only editor. A string is shown as it is; any other value as indented JSON.

func (*NounBuilder) Verb

func (b *NounBuilder) Verb(verb string, h any, description ...string) *NounBuilder

Verb registers noun.verb as an operation when it is new, else installs the handler as this noun's override of the existing operation. The handler is a Handler (an interaction verb, run on the loop) or an AppHandler (func(Ctx) Result: an application verb whose pending work runs off the loop). An override of an existing operation must be a Handler.

func (*NounBuilder) Verbs

func (b *NounBuilder) Verbs(verbs ...string) *NounBuilder

Verbs records the verbs the noun answers to, for help and the palette.

func (*NounBuilder) When

func (b *NounBuilder) When(guard string) *NounBuilder

When guards the last declared verb with a registered guard name: while the guard is false at the focus and mode the verb would run in, the palette does not offer it. The guard reads a KeyEvent whose Focus and Level are that focus and whose Mode is that mode. A palette noun's default verb is never guarded (RegisterNoun refuses one). An empty name removes the guard.

type NounPlace added in v0.15.0

type NounPlace struct {
	Noun      string    `json:"noun"`
	Ancestors []string  `json:"ancestors"`
	Page      string    `json:"page,omitempty"`
	PageTitle string    `json:"pageTitle,omitempty"`
	Modal     string    `json:"modal,omitempty"`
	Count     int       `json:"count"`
	First     time.Time `json:"first"`
	Last      time.Time `json:"last"`
}

NounPlace is one place a noun was seen: an instance of Noun registered under instances of the Ancestors nouns (outermost first, app left out), on Page, or inside the open modal Modal. Inside a modal the ancestors start at the modal instance, where the stack walk stops; Page is then the page the modal opened over. Instance ids are never part of a placement (rows and generated instances differ per run), only nouns and the page id (page ids are stable). A list row counts once per SetItems for each noun its rows answer to, not once per row.

func (NounPlace) Chain added in v0.15.0

func (p NounPlace) Chain() []string

Chain is the stack walk of the placement from outside in: the ancestors, then the noun itself.

type NounWord added in v0.53.0

type NounWord struct {
	Kind       string
	Value      string
	Candidates []string
}

NounWord is how the word after a noun reads (ReadNounWord): Kind is NounWordVerb or NounWordProp with Value the whole word, or "" when it is neither (a key or an instance: the caller's own reading), with Candidates when it is a prefix of several verbs or several props.

type Operation

type Operation struct {
	Verb        string               `json:"verb"`
	Noun        string               `json:"noun"`
	Description string               `json:"description"`
	Parameters  map[string]Parameter `json:"parameters"`
	Result      string               `json:"result"`
	Kind        string               `json:"kind"`
	Confirm     string               `json:"confirm,omitempty"`
	Repeatable  bool                 `json:"repeatable,omitempty"`
	// Rows names the noun whose rows the verb's result lists (a list
	// verb's JSON array of rows of that noun); "" when the result is not
	// rows. It is data for hosts (the catalog's rows); the runtime does
	// not read it.
	Rows string `json:"rows,omitempty"`
	// State marks the verb whose answer is the rows of every one of a
	// host's lists in one call (NounBuilder.State), as JSON Lines of
	// cli.Row tagged by list noun ({"noun":"agent","id":..,"label":..}).
	// Data for hosts (the catalog's state); the runtime does not read it.
	State bool `json:"state,omitempty"`
	// Quiet marks bookkeeping (a list reload) the jobs ticker does not
	// show; set by NounBuilder.Quiet. The catalog's quiet.
	Quiet bool `json:"quiet,omitempty"`
	// Builtin marks an operation the framework registered itself: every
	// one NewRuntime and NewModel register, and those a framework
	// constructor registers later (NewPicker, NewPalette, grid.Register,
	// markdown.Register, cli.AddCommands), each inside Runtime.Builtin. An
	// application's verb is never builtin, even on a framework noun
	// (history.capture-hook). Data for hosts (the catalog's builtin): a
	// host mounting another tool's verbs skips these, which every
	// ochazuke tool has; the runtime does not read it.
	Builtin bool `json:"builtin,omitempty"`
	// PersistArgs lets the history file keep this operation's arguments
	// named like text (text, value, keys, args, password, secret, token), which
	// it otherwise leaves out; set by NounBuilder.PersistArgs. Only for an
	// operation whose arguments are never typed secrets (settings.set).
	PersistArgs bool `json:"persistArgs,omitempty"`
	// Motion marks movement (list.move, focus.next, surface.scroll,
	// page.next): the footer's hint line leaves its rows out, since motions
	// are standard and the footer is for the verbs the focus offers; ?
	// help and bindings list keep them. Set by NounBuilder.Motion; the
	// framework's own motions are marked as they register (motionOps).
	Motion bool `json:"motion,omitempty"`
	// Typing marks an operation that passes the key that ran it on as
	// content rather than acting on it as a command: typing into an input
	// (input.insert), keys forwarded to a pane (terminal.send,
	// terminal.paste). The key echo (keys.echo) collapses a run of them
	// into the text typed, and hides the ones a passthrough mode forwards
	// unless keys.echo-terminal is on. The framework's own are marked as
	// they register (typingOps).
	Typing bool `json:"typing,omitempty"`
	// HistoryKind is the kind of entry the operation records
	// (HistoryAction, HistoryChange, HistoryFetch); empty derives it
	// (HistoryKindOf). Set it to HistoryFetch on a verb that only asks for
	// data (NounBuilder.Fetch, the catalog's history), so history.list's
	// default view and the bounded ring leave its calls to the fetches.
	HistoryKind string `json:"historyKind,omitempty"`
	// Positional names the parameters bare words fill first, in this
	// order (NounBuilder.Positional), ahead of ParameterOrder's
	// required-then-by-name rest. The CLI gives a boolean a bare word only
	// when it is named here. The catalog's positional.
	Positional []string `json:"positional,omitempty"`
	// Many marks a verb whose handler takes every subject of a request at
	// once (Ctx.Subjects: a visual selection's rows), so it asks one
	// question, makes one change and posts one notice for all of them; set
	// by NounBuilder.Many. A verb without it that is asked to act on
	// several subjects runs once per subject. The catalog's many.
	Many bool `json:"many,omitempty"`
	// Aliases are the action's other names (ActionAlias), display
	// spelling, sorted. Catalog and operations.list fill it; an entry of
	// Runtime.Operations does not hold it (the alias table does).
	Aliases []string `json:"aliases,omitempty"`
	// Standard is the standard verb (standard_verbs.go: get, list) the
	// runtime generated this operation from for a noun with a store, ""
	// for every verb written by hand. An application verb of the same key
	// replaces a standard one, registered before or after. The catalog's
	// standard.
	Standard string `json:"standard,omitempty"`
	// Checks run before the verb from every path (AddVerbCheck,
	// BeforeQuit, verb_checks.go): each allows, asks first or refuses.
	Checks []VerbCheck `json:"-"`
	// ConfirmFor, when set, is the prompt template one request asks in
	// place of Confirm (given as prompt), read when the request would ask:
	// a verb whose confirm depends on what it will do to the thing (the
	// standard delete under delete.archive). "" asks nothing.
	ConfirmFor func(r *Runtime, c Context, q Request, prompt string) string `json:"-"`
	Run        Handler                                                      `json:"-"`
	App        AppHandler                                                   `json:"-"`
}

Operation is one registered noun.verb. Kind is "interaction" (the default: Run executes synchronously on the loop) or "application" (App is an AppHandler whose pending work runs off the loop and reports through the delivery contract). Confirm, when set, is a prompt template ({{id}}, {{noun}}, {{label}}, {{<arg>}}) shown in a confirm modal before the operation runs. Repeatable marks a change (not a motion or navigation) that dot-repeat (history.repeat, bound to . on app in normal mode) may run again; set it on the Operation passed to Register.

func (Operation) HistoryKindOf added in v0.7.0

func (o Operation) HistoryKindOf() string

HistoryKindOf is the kind of history entry the operation records: its HistoryKind when set; else a fetch for a verb that answers rows (Rows, State), a change for a Repeatable one, an action for a Motion, a change for any other application verb (work that may change something outside the runtime: the safe reading of an extension verb that declares nothing), and an action for any other interaction verb.

func (Operation) Key

func (o Operation) Key() string

func (Operation) ParameterOrder

func (o Operation) ParameterOrder() []string

ParameterOrder lists the operation's parameters in positional order: the Positional names first, in their order, then the rest required first, then by name. Parameters is a map, so this is the declared order the palette's words and the CLI's bare arguments fill.

func (Operation) RestParameter added in v0.50.0

func (o Operation) RestParameter() string

RestParameter is the name of the operation's rest-of-line parameter (Parameter.Rest), "" when it has none.

func (Operation) SubjectOmitted added in v0.53.0

func (o Operation) SubjectOmitted(open []string, word string) bool

SubjectOmitted reports whether word, met where the first of open (the parameters still unfilled, in line order) is a subject filled from the focus (Parameter.Focus), is the next parameter's word instead: one of its Enum values, or NAME=VALUE with NAME one of them when it takes Pairs. The subject then comes from the focus, a target or --KEY (the flag named after the key prop). A thing whose key equals a prop name is reached with --KEY.

func (Operation) WithPresets added in v0.55.0

func (op Operation) WithPresets(args, presets Arguments) Arguments

WithPresets is args with presets (an action alias's arguments) filling what args leaves out: a caller's argument wins over a preset of the same name, and over a preset it excludes or that excludes it (Parameter.Excludes: star, task.set {toggle: true}, given value: false writes false). args is not changed.

type Origin added in v0.50.0

type Origin struct {
	Layer  string    `json:"layer"`
	Path   string    `json:"path,omitempty"`
	Line   int       `json:"line,omitempty"`
	By     string    `json:"by,omitempty"`
	Source string    `json:"source,omitempty"`
	Via    string    `json:"via,omitempty"`
	At     time.Time `json:"at,omitzero"`
	Disk   time.Time `json:"disk,omitzero"`
}

Origin is where a setting's value comes from, as :verbose names it. Layer is OriginDefault, OriginFile or OriginSession. For a default, Path is the embedded settings file (settings/ochazuke.json) or the application's file:line that declared it, and By is "ochazuke" or "app". For the file, Path is settings.json and Line the line of its key (0 when not found). For a session value, Source is the history source of the request that set it ("palette", "key:<keys>", "cli", "api", "macro:<r>"), Via the name it ran by (an alias such as setting.save, or the action's key) and At the time. Disk, when set, is when the poll (or settings.reload) read another value for the setting from settings.json: another process changed it under this runtime.

func (Origin) String added in v0.50.0

func (o Origin) String() string

String is the origin as one line: "default, settings/ochazuke.json (ochazuke)", "set in PATH line N", "set this session by NAME (palette, 14:02)", each followed by "; settings.json changed on disk at 14:05" when the file moved under the runtime.

type OverlayMark added in v0.14.0

type OverlayMark struct {
	Row   int            `json:"row"`
	Col   int            `json:"col"`
	Text  string         `json:"text"`
	Style lipgloss.Style `json:"-"`
}

OverlayMark is plain text drawn from one cell of the frame (Row and Col, 0-based, in the pane's cells) to the right, cut at the frame's edge; a wide rune it half covers becomes a space. Style draws the text; the empty style draws it reverse and bold, so a mark stands out in mono too. Marks are drawn in order, a later one over an earlier one.

type Page

type Page struct {
	ID         string                         `json:"id"`
	Title      string                         `json:"title"`
	Focus      string                         `json:"focus"`
	Remembered string                         `json:"remembered"`
	Render     func(*Runtime, int, int) Block `json:"-"`
	// OnOpen, when set, runs on the loop each time OpenPage makes this page
	// current from another page (or from none: the first page opened), after
	// the focus and mode are restored; from is the page left, "" for none.
	// Reopening the current page does not run it. An application refreshes
	// what the page shows here (SetItems, or Launch a reload job owned by
	// one of its instances) instead of polling. Every way a page opens goes
	// through OpenPage: page.open, page.next/previous, ctrl+j/k, the page
	// picker.
	OnOpen func(r *Runtime, from string) `json:"-"`
	// Scrolloff is how many lines the page keeps visible above and below
	// the focused element when it scrolls to follow the focus: 0 means the
	// default, 2; a negative value keeps no margin.
	Scrolloff int `json:"scrolloff,omitempty"`
	// DefaultHidden declares the page hidden by default: an opt-in page,
	// out of the tabs and ctrl+j/k until page.show brings it in. It is
	// data for the pages.hidden setting's default (PagesHiddenSetting);
	// the setting, once the user sets it, decides. Set it before
	// RegisterPage, or pass the DefaultHidden option.
	DefaultHidden bool `json:"defaultHidden,omitempty"`
	// contains filtered or unexported fields
}

Page is the component a page instance fronts: a title, the instance it starts focused on (Focus), the focus it remembers while another page is open (Remembered, restored with its mode by OpenPage), and a renderer. Render returns the page body for the given cell bounds as a Block; its cursor, when the page holds the focused input, is relative to the body's top-left cell. Pages without inputs return Text(body).

type Palette

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

Palette is the ex-mode command line: one prompt input whose text is the source of truth, parsed by the grammar in palette_parse.go, with a completion list for the next word beneath it. It never edits the originating input. Create one palette per runtime: operation keys are globally unique.

func NewPalette

func NewPalette(r *Runtime) *Palette

NewPalette returns the command palette for r.

func (*Palette) Close

func (p *Palette) Close()

func (*Palette) HandleKey

func (p *Palette) HandleKey(key string) (bool, error)

HandleKey dispatches one key while the palette is the active modal.

func (*Palette) IsActive

func (p *Palette) IsActive() bool

IsActive reports whether the palette is the top modal.

func (*Palette) IsOpen

func (p *Palette) IsOpen() bool

func (*Palette) Open

func (p *Palette) Open() error

func (*Palette) RegisterNoun

func (p *Palette) RegisterNoun(noun string, config PaletteNoun) error

RegisterNoun adds or replaces a live instance source without changing operation forms.

func (*Palette) Text

func (p *Palette) Text() string

Text is the command line.

func (*Palette) View

func (p *Palette) View() string

func (*Palette) ViewSized

func (p *Palette) ViewSized(width, height int) string

type PaletteEntry

type PaletteEntry struct {
	Value string `json:"value"`
	Kind  string `json:"kind"`
	Label string `json:"label"`
	ID    string `json:"id,omitempty"`
	Verb  string `json:"verb,omitempty"`
	// Aliases are the other verb words that name this entry's action
	// (ActionAlias): typing one narrows to this entry, which is listed
	// once under its canonical name.
	Aliases []string `json:"aliases,omitempty"`
	// Splice marks a rest parameter's completion (Parameter.Rest): taking
	// it puts Value in place of the line from From (a rune offset) to the
	// cursor, adding no space, instead of replacing the word being typed.
	Splice bool `json:"splice,omitempty"`
	From   int  `json:"from,omitempty"`
}

PaletteEntry is one completion: Value is the word it appends, Kind is verb, noun or choice, Label what the list shows.

type PaletteInstance

type PaletteInstance struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Word is the word the palette offers and takes for it ("" the id):
	// a page's title (Choice.Word).
	Word string `json:"word,omitempty"`
}

PaletteInstance is a labeled object whose ID becomes the default action argument.

func PagesPaletteSource

func PagesPaletteSource(r *Runtime, _ Context) []PaletteInstance

PagesPaletteSource reads the runtime registry on every listing, not at startup.

type PaletteNoun

type PaletteNoun struct {
	Source      PaletteSource
	DefaultVerb string
	Argument    string
}

PaletteNoun explicitly chooses the action and string argument used for an instance.

type PaletteSource

type PaletteSource func(*Runtime, Context) []PaletteInstance

PaletteSource reads current instances in the context captured when the palette opened.

type PaletteWord

type PaletteWord struct {
	Text       string   `json:"text"`
	Kind       string   `json:"kind,omitempty"`
	Value      string   `json:"value,omitempty"`
	Param      string   `json:"param,omitempty"`
	Candidates []string `json:"candidates,omitempty"`
}

PaletteWord is one word of the line and what it resolved to: Kind is verb, noun, instance or argument; Value is the full word ("" while it is unresolved); Candidates are the words an ambiguous prefix could be.

type ParamAlias added in v0.58.0

type ParamAlias struct {
	Alias       string `json:"alias"`
	Param       string `json:"param"`
	Since       string `json:"since,omitempty"`
	RemoveAfter string `json:"removeAfter,omitempty"`
	Note        string `json:"note,omitempty"`
}

ParamAlias is an old name of a parameter, taken by the action alias that declares it (Keep actions, for a parameter: a renamed flag works for one release). Alias is the old name, Param the parameter of the alias's action it fills. Since and RemoveAfter date a deprecated one: its first use in a runtime posts a one-time notice naming the new name. An old name is read from the CLI (--starred), the palette (--starred), binding rows' args and the API alike; it is never completed and help never lists it. The parameter's own name wins when both are given.

func (ParamAlias) Deprecated added in v0.58.0

func (p ParamAlias) Deprecated() bool

Deprecated reports whether the old name is on its way out.

type Parameter

type Parameter struct {
	Type        string `json:"type"`
	Required    bool   `json:"required,omitempty"`
	Description string `json:"description,omitempty"`
	// Enum lists the static choices of a string parameter; Source names an
	// operation (noun.verb) whose result lists more. Free also accepts a
	// value outside them.
	Enum   []string `json:"enum,omitempty"`
	Source string   `json:"source,omitempty"`
	Free   bool     `json:"free,omitempty"`
	// Noun says the value names one of that noun's things: a row of its
	// list verb (NOUN.list, when it is a read with no required parameter,
	// stands in for an empty Source), else the id of a live instance of
	// the noun. A Source still wins; Enum values come first.
	Noun string `json:"noun,omitempty"`
	// A path parameter (Type "path") names a file, or a folder when Path
	// is "dir"; its form field opens the path chooser (path_chooser.go),
	// whose browse starts at Base (~ and relative to the working
	// directory) when the field is empty. New allows a path that does not
	// exist yet (a file to write).
	Path string `json:"path,omitempty"`
	Base string `json:"base,omitempty"`
	New  bool   `json:"new,omitempty"`
	// Rest marks a string parameter that takes the rest of the line,
	// verbatim: the palette hands it the text from its first word to the
	// end, quotes and spaces as typed, and the CLI joins the remaining
	// words with spaces. A verb has at most one, the last its words fill
	// (settings.apply's line: :set scrolloff=5 nowrap). Its Source is asked
	// with the text as the query and, when it declares
	// ChoicesCursorParameter, the cursor in it; each choice's id is the
	// text up to the cursor with the completion in place.
	Rest bool `json:"rest,omitempty"`
	// Focus declares that an omitted value is filled from the focus: the
	// instance the request acts for once ExecuteAt has applied its target
	// and the focus path (Ctx.Instance, or the nearest instance of Noun
	// above it). A standard verb's subject parameter (standard_verbs.go)
	// declares it, and so does a create parameter of a FromFocus prop;
	// values never come from the focus unless their parameter says so,
	// and a fill is always shown (the palette slot, the args form). The
	// catalog's focus.
	Focus bool `json:"focus,omitempty"`
	// Edits names the prop of the subject this parameter writes (rename's
	// name writes the label prop): the args form opens holding the prop's
	// current value, selected as a rename is (rename.select), or, when it
	// is empty, empty with the prop's Fallback value as its placeholder.
	Edits string `json:"edits,omitempty"`
	// ValueOf names the parameter whose argument is a prop of the
	// operation's noun: this parameter holds a value of that prop, so its
	// choices (and the palette's check of a typed word) are the prop's own
	// (its Enum, Source or Noun; true and false for a boolean). A standard
	// set's value declares ValueOf "prop". The catalog's valueOf.
	ValueOf string `json:"valueOf,omitempty"`
	// Pairs marks a parameter that takes NAME=VALUE words of the noun's
	// props (where, set's several-prop form): a word holding = completes
	// the values of prop NAME; one without completes the Enum when there
	// is one, else NAME= for each prop. The catalog's pairs.
	Pairs bool `json:"pairs,omitempty"`
	// Excludes names the parameters a request cannot give with this one
	// (set's toggle and value). A preset (an action alias's args) that a
	// caller's argument excludes, or that excludes it, yields to the
	// caller's (Operation.WithPresets). The catalog's excludes.
	Excludes []string `json:"excludes,omitempty"`
}

Parameter describes one argument of an operation: its type, whether it is required, and its choices.

type PathChooserSpec added in v0.44.0

type PathChooserSpec struct {
	Kind  string // default PathChooserKind
	Title string // default "Choose <name>"
	Pick  PathPick
	// Source names the source to open on (PathSourceBrowse, an
	// application's AddPathSource name); "" (or a source this pick leaves
	// out) opens on the one chooser.remember-source gives, else browse.
	Source string
	// Choose takes the path; nil returns it as the result.
	Choose func(path string) Result
}

PathChooserSpec opens a path chooser. Choose takes the chosen path (absolute, cleaned).

type PathPick added in v0.44.0

type PathPick struct {
	// Name is the parameter (or field) name; Parameter its description
	// (Path, Base, New).
	Name      string
	Parameter Parameter
	// Value is the field's value when the chooser opened.
	Value string
	// Start is the folder browse starts in (PathStart), filled in by
	// OpenPathChooser.
	Start string
}

PathPick describes what a path chooser is open for.

func (PathPick) Dir added in v0.44.0

func (p PathPick) Dir() bool

Dir reports whether the pick wants a folder.

type Payload

type Payload struct {
	Return  string     `json:"return,omitempty"`
	Count   int        `json:"count,omitempty"`
	OpCount int        `json:"opCount,omitempty"`
	Op      string     `json:"op,omitempty"`
	Prefix  string     `json:"prefix,omitempty"`
	Prompt  string     `json:"prompt,omitempty"`
	Request *Request   `json:"request,omitempty"`
	Shadow  *ModeState `json:"shadow,omitempty"`
	// Anchor is the instance a modal is opened for (a form field, for its
	// chooser): the modal is drawn beside it (modal.anchor).
	Anchor string `json:"anchor,omitempty"`
}

Payload is the small typed state a mode carries (Runtime.Mode.Payload). For a pending mode Return is the mode it returns to on leave. Count and OpCount are the Vim counts before and after an operator; Op is the pending operator; Prefix is the key sequence typed so far; Request is a stored request (the completed match a sequence prefix falls back to, or a confirm's deferred action); Prompt is the text a confirm modal shows; Shadow is the mode the macro_recording shadow mode re-dispatches in.

type Picker

type Picker struct {
	Runtime   *Runtime
	Origin    Context
	Directory string
	Filter    string
	Entries   []PickerEntry
	Selected  int
	Error     string
	Loading   bool
	// contains filtered or unexported fields
}

Picker owns one modal and one ordinary editor. Background commands only read immutable snapshots; HandleMessage is the sole result-application boundary. Its work runs as four replacing jobs on the picker instance (the "index", "search", "preview" and "stat" slots), so the runtime's jobs list decides which result is current: a newer job in a slot drops the older, and Close cancels them all.

func NewPicker

func NewPicker(r *Runtime) *Picker

NewPicker returns the picker for r.

func (*Picker) Close

func (p *Picker) Close()

Close cancels indexing, searching and previews; the picker instance stays registered for the next open.

func (*Picker) HandleMessage

func (p *Picker) HandleMessage(msg tea.Msg) bool

HandleMessage applies only the current job of each slot (index, search, preview) on the UI loop; the runtime's jobs list says which that is.

func (*Picker) IsOpen

func (p *Picker) IsOpen() bool

func (*Picker) MatchMode added in v0.59.0

func (p *Picker) MatchMode() string

MatchMode is the picker's match mode: the one search.cycle-match or search.set-match chose while it is open, else the chooser.match setting. It decides how the query (the path after its directory) picks entries.

func (*Picker) PendingCommand

func (p *Picker) PendingCommand() tea.Cmd

PendingCommand is drained by Runtime.PendingCommands after every event, including CallMsg. It schedules work, never waits on filesystem or search.

func (*Picker) View

func (p *Picker) View(width, height int) string

func (*Picker) ViewBlock

func (p *Picker) ViewBlock(width, height int) Block

ViewBlock renders the picker and reports the cursor of its path editor on the first row, after the label.

type PickerEntry

type PickerEntry struct {
	Path string `json:"path"`
	Dir  bool   `json:"dir"`
}

PickerEntry is relative to the indexed root. Symlinks are selectable files, never traversal edges.

type Placement

type Placement struct {
	ID string `json:"id"`
	// Line is the body line the view's first line landed on, -1 when the
	// view reported no text or the page did not draw it; Height is its line
	// count.
	Line   int `json:"line"`
	Height int `json:"height"`
	// Focus and FocusHeight are the focused lines, relative to Line.
	Focus       int `json:"focus"`
	FocusHeight int `json:"focusHeight"`
}

Placement is one Placed call of a frame: the instance drawn and, when its view reported them (PlacedAt), the lines it covers in the page body and the lines inside it that hold the focus (a list's selected row, a grid's cursor row, an input's whole box, a terminal's top line).

type Pos

type Pos struct {
	X, Y int
}

Pos is a cell position inside a rendered block: zero-based, counted from the block's top-left corner.

type Predicate

type Predicate struct {
	Name string      `json:"name"`
	Arg  string      `json:"arg,omitempty"`
	Of   []Predicate `json:"of,omitempty"`
}

Predicate is one named test over an instance: a value, never a string selector. A query is a list of predicates, ANDed. Name is a registered predicate (noun, id, kind, within, child-of, focusable, region, state or one an application adds) and Arg its argument; the combinators any, all and not take nested predicate lists in Of instead. The wire form is a JSON array: ["noun","row"], ["any",[["noun","a"],["noun","b"]]].

func AllOf

func AllOf(of ...Predicate) Predicate

func AnyOf

func AnyOf(of ...Predicate) Predicate

func ByID

func ByID(id string) Predicate

func ByKind

func ByKind(kind string) Predicate

func ByNoun

func ByNoun(noun string) Predicate

Go spellings of the framework predicates and combinators.

func ChildOf

func ChildOf(id string) Predicate

func InState

func InState(mode string) Predicate

func IsFocusable

func IsFocusable() Predicate

func IsRegion

func IsRegion() Predicate

func Not

func Not(of ...Predicate) Predicate

func ParsePredicates

func ParsePredicates(v any) ([]Predicate, error)

ParsePredicates reads the wire form: a list of [name, arg] pairs, or [combinator, [nested pairs]] for any, all and not. A []Predicate from Go passes through.

func Where

func Where(name, arg string) Predicate

Where builds a predicate by name.

func Within

func Within(id string) Predicate

type PredicateFunc

type PredicateFunc func(inst *Instance, r *Runtime, arg string) bool

PredicateFunc tests one instance; arg is the predicate's argument.

type PropSpec added in v0.52.0

type PropSpec struct {
	Name string `json:"name"`
	Parameter
	ReadOnly   bool   `json:"readOnly,omitempty"`
	CreateOnly bool   `json:"createOnly,omitempty"`
	Key        bool   `json:"key,omitempty"`
	Role       string `json:"role,omitempty"`
	Fallback   string `json:"fallback,omitempty"`
	FromFocus  bool   `json:"fromFocus,omitempty"`
	Default    any    `json:"default,omitempty"`
	Secret     bool   `json:"secret,omitempty"`
	Multiline  bool   `json:"multiline,omitempty"`
	When       string `json:"availability,omitempty"`
}

PropSpec is one field of a noun's things. Parameter carries the type, Required, Enum, Source, Noun and Description, as a verb parameter does, so the palette, CLI help and forms read it unchanged; Type is a setting type or PropObject ("" is string). A prop whose Parameter.Noun is set is a reference: its value is the key of one of that noun's things.

ReadOnly props are never written by set (a Key prop always is); CreateOnly ones are written by create only. Role gives the prop a part (RoleLabel, RoleOwner). Fallback names another prop of the noun shown in this prop's place when this one is empty: display only (list rows, {{label}}, choosers); get still reads the prop itself. Default is what create writes when the value is omitted. A Secret prop is left out of get's and list's records unless asked for by name, and its writes are never repeated or persisted. Multiline asks a form for a text area. FromFocus, on a reference prop, lets create fill it from the focused thing of its noun when the request omits it (the create.from-focus setting, on by default; the fill is always shown: the palette slot and the args form hold it, and create's notice names it). Values are never read from the focus unless their prop says so. When names a guard: where it is false (read where the request acts) the prop is not offered, read or written (the catalog's availability); the guard is the prop's own, apart from the noun's verb guards.

type QueryMatch

type QueryMatch struct {
	ID     string `json:"id"`
	Noun   string `json:"noun"`
	Parent string `json:"parent,omitempty"`
}

QueryMatch is one instances.query result row.

type Record added in v0.2.0

type Record map[string]string

Record is one record's values by field name, as an editor loads and writes them.

type RecordDebounceMsg added in v0.2.0

type RecordDebounceMsg struct {
	Editor string
	Seq    uint64
}

RecordDebounceMsg is the timer a pause in typing sets off: when Seq is still the editor's latest change, the record is written.

type RecordEditor added in v0.2.0

type RecordEditor struct {

	// Styles colour the labels (the zero value draws them plain); a modal
	// editor uses the Model's.
	Styles Styles
	// contains filtered or unexported fields
}

RecordEditor is a form over one record: a field per schema entry, each a focus stop, and every change written as it is made. Typing in a text field is written after a pause (Debounce) and at once when the field is left or insert mode ends; a choice, an edit in normal mode, an undo or a redo is written at once. A value that is not valid (Required, the type, the choices, Validate) is not written, and its label says why. u and ctrl+r undo and redo the record's written changes, each written like any other; q and esc leave, and nothing is ever discarded. There is no save key.

The editor is an instance of the form noun (id) with a child per field (id/name): text fields are inputs of form-field (form-text when multiline), choice fields instances of form-choice, whose enter opens the chooser (a modal list of form-option rows).

func (*RecordEditor) Block added in v0.2.0

func (e *RecordEditor) Block(width, height int) Block

Block draws the form: per field its label (with why a value is not written) and its value, a text field as its input, a choice field as its value with the one highlight while focused; a failed write is the last line. Each field is placed in drawing order, so motions follow it.

func (*RecordEditor) Close added in v0.2.0

func (e *RecordEditor) Close()

Close writes what is pending (the editor is being removed). It is the delivery contract's Close: to close an editor, an application calls Leave, which also removes it (a closed editor's id is free again either way).

func (*RecordEditor) Closed added in v0.2.0

func (e *RecordEditor) Closed() bool

Closed reports whether the editor was left (form.leave) or removed.

func (*RecordEditor) DebounceCurrent added in v0.2.0

func (e *RecordEditor) DebounceCurrent(tick RecordDebounceMsg) bool

DebounceCurrent reports whether a pause timer is for the latest change.

func (*RecordEditor) DebounceTick added in v0.16.0

func (e *RecordEditor) DebounceTick() (RecordDebounceMsg, bool)

DebounceTick is the pause timer in flight, for a host that delivers it at once (explore): false when no change waits on one.

func (*RecordEditor) Failure added in v0.2.0

func (e *RecordEditor) Failure() error

Failure is the last background failure, cleared when read.

func (*RecordEditor) Flush added in v0.2.0

func (e *RecordEditor) Flush() error

Flush writes what is pending now (on quit).

func (*RecordEditor) Focus added in v0.2.0

func (e *RecordEditor) Focus() error

Focus focuses the first field (the spec's Start; in insert mode when the spec says so).

func (*RecordEditor) FocusTarget added in v0.2.0

func (e *RecordEditor) FocusTarget() string

FocusTarget is where a jump to the editor lands: its first field (the spec's Start).

func (*RecordEditor) HandleMessage added in v0.2.0

func (e *RecordEditor) HandleMessage(msg tea.Msg) bool

HandleMessage writes the record when its pause timer is the latest.

func (*RecordEditor) ID added in v0.2.0

func (e *RecordEditor) ID() string

ID is the editor's instance id.

func (*RecordEditor) Leave added in v0.54.0

func (e *RecordEditor) Leave() error

Leave writes what is pending and closes the editor, as form.leave does: a modal editor's modal closes, the editor's instance is removed (the focus goes where FocusOnClose says) and OnLeave runs.

func (*RecordEditor) ModalBlock added in v0.2.0

func (e *RecordEditor) ModalBlock(s Styles, width, height int) Block

func (*RecordEditor) ModalTitle added in v0.2.0

func (e *RecordEditor) ModalTitle() string

ModalTitle and ModalBlock draw a modal editor (ModalBody).

func (*RecordEditor) PendingCommand added in v0.2.0

func (e *RecordEditor) PendingCommand() tea.Cmd

PendingCommand notices changes: typing in a text field sets the pause timer; leaving a field, ending insert mode or any other change writes at once and closes the field's undo step.

func (*RecordEditor) Problem added in v0.2.0

func (e *RecordEditor) Problem(name string) string

Problem says why a field's value is not written, "" when it is.

func (*RecordEditor) Ran added in v0.36.0

func (e *RecordEditor) Ran() bool

Ran reports whether form.run handed the values to Submit.

func (*RecordEditor) Reload added in v0.54.0

func (e *RecordEditor) Reload() error

Reload loads the record again (Spec.Load) and takes in what changed outside the editor; what it does then follows forms.outside-write, as a RecordSpec.Watch event does.

func (*RecordEditor) Runnable added in v0.36.0

func (e *RecordEditor) Runnable() bool

Runnable reports whether form.run would run the form now: it has a Submit, is open, and every field is valid.

func (*RecordEditor) Values added in v0.2.0

func (e *RecordEditor) Values() Record

Values is every field's value as shown, valid or not.

func (*RecordEditor) WriteError added in v0.2.0

func (e *RecordEditor) WriteError() string

WriteError is the last write's failure, "" once a write succeeds.

func (*RecordEditor) Written added in v0.2.0

func (e *RecordEditor) Written() Record

Written is the record as written (or queued to be): the last valid value of every field.

type RecordField added in v0.2.0

type RecordField struct {
	Name  string `json:"name"`
	Label string `json:"label,omitempty"` // shown above the value (default Name)
	Parameter
	Multiline bool `json:"multiline,omitempty"`
	// Secret makes the field's input secret (Input.Secret): what is typed
	// into it is never echoed. PropField sets it from a Secret prop.
	Secret bool `json:"secret,omitempty"`
	// Placeholder is shown, muted, in the field while its text is empty
	// (a rename's Fallback: what the thing shows with no name).
	Placeholder string `json:"placeholder,omitempty"`
	// Validate checks a value the type, Required and the choices allow;
	// its error is why the value is not written.
	Validate func(value string) error `json:"-"`
}

RecordField is one editable field of a record schema. Its Parameter is the same description a verb's parameter carries (Type, Required, Enum, Source, Noun, Free, Description), so a form can come from a verb's catalog parameters (RecordFields). A field with choices (Enum, Source or Noun: Runtime.Choices) and not Free, or of Type boolean, is edited through a chooser, never as free text. A Free field with choices is a text field with suggestions (form-suggest): typing stays free text, enter in normal mode or ctrl+space opens the framework chooser over the suggestions (the Enum, then the Source's result, loaded off the loop when the Source verb is Pending), a pick fills the field and is written at once, and a value outside the suggestions is written as typed; it is one line high (Multiline is ignored). The rest are text inputs, Multiline ones several lines high.

func ArgsFields added in v0.36.0

func ArgsFields(op Operation) ([]RecordField, error)

ArgsFields is the args form's schema for a verb: its form-held parameters (RecordFields), the required ones first, an optional one's label marked "(optional)", a description after the name. It fails when a required parameter cannot be held by a field.

func PropField added in v0.53.0

func PropField(p PropSpec) RecordField

PropField is a prop as a form field (RecordField): its name, its parameter and whether it is multiline, so a record editor or an args form over a noun's things reads its props.

func RecordFields added in v0.2.0

func RecordFields(op Operation) []RecordField

RecordFields is a form's schema from a verb's parameters, in the order bare CLI words fill them (Operation.ParameterOrder): a mounted tool's edit verb gets a form from its catalog alone.

type RecordSpec added in v0.2.0

type RecordSpec struct {
	Title  string // the modal's title; a placed editor's heading is the application's
	Fields []RecordField
	// Load reads the record when the editor opens (nil: every field empty).
	Load func() (Record, error)
	// Save writes one change: Done, Failed, or Pending work that runs off
	// the loop. At most one write is in flight; changes made meanwhile go
	// in the next write. A failed write keeps the values on screen, says
	// so, and is retried with the next change.
	Save func(RecordWrite) Result
	// Debounce is the pause in typing before a text field is written
	// (DefaultRecordDebounce when zero).
	Debounce time.Duration
	// Insert opens the editor with the first field in insert mode when it
	// is a text field.
	Insert bool
	// Rename says the editor renames a thing: it opens in insert like
	// Insert, and with the start field's text selected (Input.SelectAll)
	// while the rename.select setting is on, so typing replaces the name
	// and a motion keeps it.
	Rename bool
	// OnLeave runs after the editor closed (form.leave, or form.run's
	// Submit): every change is written or queued by then; a placed editor
	// stops being drawn.
	OnLeave func()
	// Submit, when set, makes the editor a form that runs once instead of
	// writing each change: Save is never called, changes stay on screen,
	// and form.run (available once every field is valid) closes a modal
	// editor and hands Submit every value as shown. A failed Submit
	// reopens the modal with the values and the error (`! not run:`);
	// leaving (form.leave, esc) runs nothing.
	Submit func(Record) Result
	// Start names the field focused first ("" the first field).
	Start string
	// Watch names the noun whose store holds the record: when its things
	// change other than through this editor (a verb such as set, another
	// client, Runtime.Changed), the open editor loads the record again
	// (forms.outside-write: reload keeps it open, close leaves it). ""
	// watches nothing; Reload does the same on the application's call.
	Watch string
}

RecordSpec is what an application gives a record editor: the schema, how to load the record and how to write it.

type RecordWrite added in v0.2.0

type RecordWrite struct {
	Values  Record
	Changed []string
}

RecordWrite is one write an editor hands Save: the record as it is to be stored (every field's last valid value) and the fields this write changes, in schema order.

func (RecordWrite) String added in v0.2.0

func (w RecordWrite) String() string

String reads a write in one line: "write title=milk status=doing", the changed fields in order (a value with spaces or empty is quoted).

type RecordingSink added in v0.4.0

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

RecordingSink is a UISink that keeps every message, for tests. Attach it with r.UI().Attach(&ochazuke.RecordingSink{}).

func (*RecordingSink) ClearNotice added in v0.4.0

func (s *RecordingSink) ClearNotice(id NoticeID)

ClearNotice records a clear.

func (*RecordingSink) Info added in v0.31.0

func (s *RecordingSink) Info(text string)

Info records a plain status.

func (*RecordingSink) LastError added in v0.36.0

func (s *RecordingSink) LastError() string

LastError is the last error status recorded (Error), "" for none.

func (*RecordingSink) LastInfo added in v0.31.0

func (s *RecordingSink) LastInfo() string

LastInfo is the last plain status recorded (Info), "" for none.

func (*RecordingSink) LastStatus deprecated added in v0.4.0

func (s *RecordingSink) LastStatus() string

LastStatus is the last error status recorded.

Deprecated: use LastError.

func (*RecordingSink) Messages added in v0.4.0

func (s *RecordingSink) Messages() []UIMessage

Messages is a copy of what the sink recorded, in order.

func (*RecordingSink) Notices added in v0.4.0

func (s *RecordingSink) Notices() []string

Notices is the text of the notices still standing (posted and not cleared), oldest first.

func (*RecordingSink) Notify added in v0.4.0

func (s *RecordingSink) Notify(id NoticeID, text string)

Notify records a notice.

func (*RecordingSink) Status added in v0.4.0

func (s *RecordingSink) Status(text string)

Status records an error status (UIError).

type Register

type Register struct {
	Yank Yank       `json:"yank"`
	Keys []MacroKey `json:"keys,omitempty"`
}

Register holds a yank and, when a macro was recorded into it, its keys.

type Registers

type Registers struct {
	Named   map[string]Register
	History []Yank
	Active  string
	Macro   MacroState
	// Copy puts a yank's text on the system clipboard (the clipboard
	// register + and the clipboard setting); nil sends it through the
	// terminal as OSC 52 (tea.SetClipboard), which TUIOS and ssh pass on.
	// An app with a clipboard program of its own (pbcopy) sets it.
	Copy func(text string) tea.Cmd
	// contains filtered or unexported fields
}

Registers is the component that owns the shared yanks, named registers, yank history, the register selected for the next operation and the macro state. It is one instance under app, reached through the register, macro and yank-history operations and Runtime.Registers(), never through Runtime fields. Its key rows (q, @, " and the pending modes they enter) sit on the app noun so a page or list focus can record and replay too.

func (*Registers) Close

func (g *Registers) Close()

Close abandons a recording in progress; the registers themselves stay.

func (*Registers) HandleMessage

func (g *Registers) HandleMessage(tea.Msg) bool

HandleMessage: the registers do no off-loop work.

func (*Registers) PendingCommand

func (g *Registers) PendingCommand() tea.Cmd

PendingCommand copies the last yank bound for the system clipboard.

type Request

type Request struct {
	Verb      string    `json:"verb"`
	Noun      string    `json:"noun"`
	Target    string    `json:"target,omitempty"`
	Args      Arguments `json:"args,omitempty"`
	Confirmed bool      `json:"confirmed,omitempty"`
	// Via is the alias the request was spelled by (an old verb name, a
	// user's actions.json alias): the request is rewritten to the action it
	// names (Noun, Verb) and Via keeps the spelling, so the handler is told
	// which name ran it (Ctx.Invoked) and history shows it. "" for a
	// request that named its action directly.
	Via string `json:"via,omitempty"`
	// Subjects are the instances a request acts on when it acts on
	// several (the rows of a visual selection), in display order; Target
	// is one of them, the one a confirm or a chooser names. Empty means
	// Target alone. A verb that takes many subjects (Operation.Many) runs
	// once with all of them in Ctx.Subjects; any other runs once per
	// subject (Runtime.eachSubject).
	Subjects []string `json:"subjects,omitempty"`
	// Prop, Value and Toggle make the request prop-shaped (props.go):
	// {noun, prop} reads the prop of the thing the request acts for,
	// {noun, prop, value} writes it and {noun, prop, toggle} flips a
	// boolean prop. A prop-shaped request names no verb; it runs as the
	// noun's standard get or set (propVerbRequest), and history keeps it
	// as it was sent. Args then holds at most the subject's key.
	Prop   string `json:"prop,omitempty"`
	Value  any    `json:"value,omitempty"`
	Toggle bool   `json:"toggle,omitempty"`
}

Request names an operation and, optionally, the instance it addresses. Confirmed skips the operation's Confirm prompt: the confirm modal's y sets it on the stored request, and a script may set it to run unattended.

func PropShorthand added in v0.53.0

func PropShorthand(noun, prop string, value any, toggle bool, args Arguments) Request

PropShorthand is the request NOUN PROP [VALUE] runs (plan 2.6): a prop-shaped request, so it reads (no value), writes (a value) or flips a boolean (toggle) the thing it acts for, as the noun's standard get or set; args hold at most the subject's key (--KEY).

func (Request) Empty added in v0.53.0

func (q Request) Empty() bool

Empty reports whether the request names nothing: no verb and no prop (a binding row's null request, an unbind).

func (Request) IsProp added in v0.53.0

func (q Request) IsProp() bool

IsProp reports whether the request is prop-shaped: it reads or writes a prop instead of naming a verb.

func (Request) Key

func (q Request) Key() string

Key returns the request's operation as noun.verb, or for a prop-shaped request its prop as noun.prop (what hints, history and errors print).

func (Request) Writes added in v0.53.0

func (q Request) Writes() bool

Writes reports whether a prop-shaped request writes its prop (a Value or a Toggle) rather than reading it.

type Response

type Response struct {
	// Result is the operation's result. From HandleCall it is detached
	// from application state: Lines stays Lines (each line encoded), any
	// other value is its JSON encoding as a json.RawMessage, so object
	// keys keep the order the handler's value marshals in (a struct's
	// field order); a nil or null result is nil.
	Result any    `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
	// Argument is true when Error is an ArgumentError: the request was
	// refused for its arguments, before any instance was chosen.
	Argument bool `json:"argument,omitempty"`
	// Messages are what the call told the user while it ran (ctx.Notify,
	// ctx.ClearNotice, ctx.Status), in order; the runtime's sink got them
	// too. Messages posted later, by a job's Then, reach only the sink.
	Messages []UIMessage `json:"messages,omitempty"`
}

Response is the reply to a socket call: a result or an error message.

func CallResponse added in v0.4.0

func CallResponse(ctx context.Context, path string, q Request) (Response, error)

CallResponse is Call returning the whole Response: the result and the Messages the call told the user. A failed call is an error.

type Result

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

Result is what an application handler returns.

func Done

func Done(value any) Result

Done reports a synchronous result.

func Failed

func Failed(err error) Result

Failed reports a synchronous failure.

func Foreground added in v0.43.0

func Foreground(cmd *exec.Cmd) Result

Foreground is the Result that runs cmd in the foreground (see above). Its stdio left nil is the terminal's; Then and Label work as on Pending. The completion's value is a ForegroundExit.

func Pending

func Pending(work func(context.Context) (any, error)) Result

Pending schedules work off the loop as a job that accumulates: it runs beside the owner's other jobs and its completion is delivered whenever it finishes. The context is cancelled when the owning instance closes.

func (Result) Label added in v0.2.0

func (res Result) Label(label string) Result

Label names this job for people reading the jobs list: the ticker shows it after the verb ("agent.launch claude running") and jobs.list carries it. It says which of a verb's jobs this is (the program a launch starts, the file a build writes); "" leaves the verb alone.

func (Result) Replacing

func (res Result) Replacing(slot string) Result

Replacing puts the pending work in a slot on its owner: starting it cancels the owner's running job in the same slot, and a newer job in the slot cancels this one. Use it for replaceable work such as a preview or a search, never for independent work.

func (Result) ReplacingAt

func (res Result) ReplacingAt(scope, slot string) Result

ReplacingAt is Replacing with the slot scoped to scope, the owner or one of its ancestors: the newest job in (scope, slot) cancels the older one whichever descendant of scope asked, so previews launched from the rows of one list replace each other while another list keeps its own. The job still belongs to the row that asked (its completion and Then land there and closing it cancels the job); Replacing(slot) is ReplacingAt(owner, slot). A scope off the owner's ancestry fails the launch.

func (Result) Then

func (res Result) Then(fn func(Ctx, any, error)) Result

Then runs on the loop when the pending work's completion is delivered and still current; it never runs for a stale or cancelled ticket.

type Runtime

type Runtime struct {
	Nouns      map[string]*Noun
	Instances  map[string]*Instance
	Focus      string    // the focused instance; Context() is derived from it
	Mode       ModeState // the one interaction mode; mode.set writes it, a focus change to another stop resets it
	Page       string    // the current page instance; always an ancestor of BaseFocus()
	Modes      map[string]bool
	Operations map[string]Operation
	Quit       bool
	Pending    string
	// BindingTimeout, when positive, is how long every pending key
	// sequence waits on this runtime in place of the sequence-timeout
	// setting (a host or test that fixes it in code); 0, the default,
	// reads the setting.
	BindingTimeout time.Duration
	// ResolveTarget, when set, maps a request target that is not an
	// instance (a foreign id: an extension's row id, a database key) to
	// the instance that stands for it; ExecuteAt consults it (TargetInstance)
	// before refusing an unknown target, so keys, the palette, the CLI and
	// the API all accept the foreign id. An error refuses the request with
	// it; "" and no error leaves the target unknown.
	ResolveTarget func(target string) (string, error)
	// contains filtered or unexported fields
}

Runtime is owned by one event loop. Transport callers submit messages to that loop. It holds the operation registry (Operations, Modes and their guards), the instance registry (Nouns, Instances and their parent links, including list rows), the three plain interaction fields Focus, Mode and Page with the chain of open modals, the pending key-sequence state (Pending, prefix, BindingTimeout) and the hook that hands off-loop work to the adapter (commands). Components such as inputs, lists, the picker and the registers are instances, never fields; TestRuntimeHoldsNoComponentFields pins this list.

func NewRuntime

func NewRuntime() *Runtime

NewRuntime returns a runtime with the framework nouns registered and focus on the app instance.

func (*Runtime) Accepts

func (r *Runtime) Accepts(t Ticket) bool

Accepts reports whether a ticket names a running job.

func (*Runtime) ActionAlias added in v0.28.0

func (r *Runtime) ActionAlias(name string) (ActionAlias, bool)

ActionAlias is the alias a name is, its noun resolved, or the bare alias a word without a dot is (false when the name is no alias).

func (*Runtime) ActionAliasProblems added in v0.28.0

func (r *Runtime) ActionAliasProblems() []string

ActionAliasProblems are the aliases dropped because an action registered under their name after them.

func (*Runtime) ActionAliases added in v0.28.0

func (r *Runtime) ActionAliases() []ActionAlias

ActionAliases lists every alias, sorted by name.

func (*Runtime) ActionFor

func (r *Runtime) ActionFor(focus, key string) Handler

ActionFor returns the innermost noun handler for an operation key on the focus stack, or nil when the operation's own Run applies.

func (*Runtime) AddActionAlias added in v0.28.0

func (r *Runtime) AddActionAlias(a ActionAlias) error

AddActionAlias registers an alias. The alias names a registered noun and a verb (dirs.base.add: the longest registered noun prefix is the noun, the rest the verb); action names a registered action, by its key or by another alias (which resolves to its action). An alias may not be the name of a registered action, nor of another alias for a different action; registering the same alias for the same action again is a no-op. Source defaults to app, or framework inside Builtin.

func (*Runtime) AddDetail added in v0.2.0

func (r *Runtime) AddDetail(id string, item func() string, opts ...InstanceOption) (*Detail, error)

AddDetail registers a detail instance under its parent (Parent(page) or an instance beneath the page) and returns its component. item names what the detail shows now (the selected row's id); a different answer than the last one starts the detail at the top. A nil item never resets.

func (*Runtime) AddInput

func (r *Runtime) AddInput(in *Input, opts ...InstanceOption) error

AddInput registers an editor instance. Options: Parent(id) (default app), Kind(noun) (default "editor"; "prompt" pins insert mode) and Completions(triggers...).

func (*Runtime) AddList

func (r *Runtime) AddList(id string, items []ListItem, opts ...InstanceOption) (*List, error)

AddList registers a list instance of the list noun with its rows. Options: Parent(id) (default app), Kind(noun) for a list that answers to its own noun as well, NoSpill() for a list whose motions stay inside it, SpillToSelection() for one a spill lands in on its selected row, NoMarks() for a read-only view, ClearFilterOnEnter() for a list whose filter enter chooses a row and clears, Columns(...) for a table, and CellSelect() for a table with a current column (table_cells.go).

func (*Runtime) AddNounAlias added in v0.57.0

func (r *Runtime) AddNounAlias(a NounAlias) error

AddNounAlias registers a noun alias with its fields: Since and RemoveAfter (either) make it a deprecated name, accepted for now with a one-time notice naming the noun (and a bindings check note for a row spelled by it), but never completed, listed in the CLI's help or drawn (DisplayNoun). Note is free text added to the notice. Shadowed is ignored. Registering the same alias again replaces its fields.

func (*Runtime) AddPage

func (r *Runtime) AddPage(id, title string, render func(*Runtime, int, int) Block, opts ...InstanceOption) (*Page, error)

AddPage registers a page instance of kind page under app with a title and a renderer. Options: Focus(id) names where the page starts (the page itself or an instance beneath it, registered first) and Kind(noun) a noun of the application's own. Registration does not activate the page; see OpenPage. It is RegisterPage for callers that do not hold a *Page.

func (*Runtime) AddPathSource added in v0.44.0

func (r *Runtime) AddPathSource(name string, fn func(PathPick) (ChooserSource, bool))

AddPathSource adds a source to every path chooser, after browse, recent and typed, in the order added; adding a name again replaces it. fn builds the source for one open (false leaves it out of that one). A row's Data is the path a pick takes (a string).

func (*Runtime) AddRecordEditor added in v0.2.0

func (r *Runtime) AddRecordEditor(id string, spec RecordSpec, opts ...InstanceOption) (*RecordEditor, error)

AddRecordEditor places a record editor under Parent (default app); the application draws it with Block in its page. FocusOnClose names where the focus goes when it leaves. Call Focus to start editing.

func (*Runtime) AddSegment added in v0.36.0

func (r *Runtime) AddSegment(rows ...Segment) error

AddSegment adds status segments. A row whose id is already registered changes that segment: its non-zero fields replace the old ones, and a row naming a source replaces the old source, so an application turns a library row on with AddSegment(Segment{ID: "cpu", Enabled: On(true)}). Each segment's setting (SegmentSetting) is declared with the row's Enabled as its default.

func (*Runtime) AddSettingsPage added in v0.7.0

func (r *Runtime) AddSettingsPage() (*Page, error)

AddSettingsPage registers the Settings page as a permanent page, a tab in registration order like the application's own; settings.edit then switches to it and settings.close goes back without removing it. Without it, settings.edit registers the page when it opens and settings.close removes it.

func (*Runtime) AddTerminal

func (r *Runtime) AddTerminal(id string, stream TerminalStream, opts ...InstanceOption) (*Terminal, error)

AddTerminal registers a terminal instance of the terminal noun fed by stream, in terminal mode: every key forwards to the pane except the leader. Options: Parent(id) (default app), Kind(noun) for a noun that supplies its own tables and CloseOnDetach to remove the instance (and release the stream) on detach. The first frame read is scheduled at once.

func (*Runtime) AddTimeline added in v0.17.0

func (r *Runtime) AddTimeline(id string, cards []Card, opts ...InstanceOption) (*Timeline, error)

AddTimeline registers a timeline under Parent (default app) with its cards. Options: FollowTail, HeaderLines(n), NoSpill (motions stay in it), ParentStop(id) (where h on a closed card goes).

func (*Runtime) AddTree

func (r *Runtime) AddTree(id string, nodes []TreeNode, opts ...InstanceOption) (*Tree, error)

AddTree registers a tree under Parent (default app) with its nodes. Columns(...) makes its rows a table; NoSpill keeps motions inside it; NoMarks makes it a read-only view whose rows take no marks; ClearFilterOnEnter makes enter in its filter line choose the match and clear the filter.

func (*Runtime) AddVerbAvailability added in v0.55.0

func (r *Runtime) AddVerbAvailability(key, guard string) error

AddVerbAvailability adds a guard to a registered verb (aliases resolve) beside the availability it already has (its own guard, NounBuilder.When or SetAvailability, and guards added before): the verb is available only while every one holds, so the resolver, the palette, the hints, the help and Execute all leave it out where the added guard is false. It is how an application narrows a framework verb it uses (ochazuke.list.choose-column where its own pane draws no columns) without replacing the framework's guard or guarding each binding row. The guard need not be registered yet; one that is not registered when asked hides nothing, as a verb guard does. Adding a guard the verb already has is a no-op.

func (*Runtime) AddVerbCheck added in v0.43.0

func (r *Runtime) AddVerbCheck(key string, check VerbCheck) error

AddVerbCheck hangs a check on the verb key names (aliases resolve). A check of the same name on that verb is replaced in place.

func (*Runtime) Alias added in v0.16.0

func (r *Runtime) Alias(alias, noun string) error

Alias makes alias another name of noun: input naming alias (keys, binding files, actions.json, the palette, the CLI, Do) reaches noun unless the application registers a noun named alias, which then owns the name. The framework registers one per framework noun (settings for ochazuke.settings); a host mounting an extension's nouns under a namespace (json.doc) gives each its bare name (doc) the same way. An alias holding a dot is refused, as is one that already names another noun (Unalias it first). See AddNounAlias for a deprecated alias.

func (*Runtime) AliasAction added in v0.28.0

func (r *Runtime) AliasAction(alias, action string) error

AliasAction makes alias another name of the action registered as action (an application's permanent alias: show for get, forget for kill, or the same operation under another noun, project.associate for pane.associate). See AddActionAlias for the rules.

func (*Runtime) AliasOf added in v0.16.0

func (r *Runtime) AliasOf(noun string) string

AliasOf is the alias DisplayNoun draws noun by ("" when it draws the noun itself): under nouns.display shortest (the default) the shortest live alias that reaches noun now and is shorter than its name; under framework only a framework noun's short name (settings for ochazuke.settings); under canonical none.

func (*Runtime) AliasShadow added in v0.43.0

func (r *Runtime) AliasShadow() string

AliasShadow is the aliases.shadow setting's value (refuse unless set to allow).

func (*Runtime) Aliases added in v0.16.0

func (r *Runtime) Aliases() []NounAlias

Aliases lists the alias names, each with the noun it names, sorted by alias; a deprecated alias carries its Since, RemoveAfter and Note.

func (*Runtime) AliasesOf added in v0.28.0

func (r *Runtime) AliasesOf(name string) []ActionAlias

AliasesOf lists the aliases of an action (by its key or any of its names), sorted by name; nil when it has none.

func (*Runtime) Ancestry

func (r *Runtime) Ancestry(id string) []string

Ancestry walks the parent links from id outward: id first, app last. An unknown id yields nil.

func (*Runtime) Available added in v0.36.0

func (r *Runtime) Available(q Request, focus string, mode ModeState) bool

Available reports whether an action can run now: its availability (the verb guard, NounBuilder.When or SetAvailability) holds at the focus in the mode for the request's arguments, or it has none. The guard reads a KeyEvent whose Focus and Level are focus, Mode is mode and Args are the request's (a binding row's own arguments, or a CLI call's), so an action that acts on an argument (timeline.open {card}) judges that thing. The resolver runs, at each level, the first row on a key whose action is available (an unavailable one stands aside and the key goes on, out to the next level when none at this one is); the palette, the hints, the help and Execute ask the same question. A guard name that is not registered hides nothing. A standard verb also reads its props' guards (PropSpec.When, propsAvailable), and a prop-shaped request is asked as the get or set it runs as.

func (*Runtime) BaseFocus

func (r *Runtime) BaseFocus() string

BaseFocus is the focus beneath every open modal: the return of the outermost modal, else Focus. Runtime.Page is always an ancestor of it.

func (*Runtime) BaseMode

func (r *Runtime) BaseMode() string

BaseMode is the mode Runtime.Mode stands in: its name, or for a pending mode or a key-sequence prefix the base mode it returns to.

func (*Runtime) BeforeQuit added in v0.43.0

func (r *Runtime) BeforeQuit(name string, check func(r *Runtime, c Context) Verdict) error

BeforeQuit hangs a check named name on app.quit: return AskFirst(prompt) while there is something to lose (unsaved edits), Refuse(reason) when quitting must not happen now, else Allow(). app.quit {force: true} skips it.

func (*Runtime) Bind

func (r *Runtime) Bind(rows ...Binding) error

Bind installs rows from config or code onto their noun or instance tables by identity (mode, keys or pattern, and When): the row with the same identity is replaced in place, a new row is added (a guarded one before the unguarded row on its keys, so it answers first while its guard holds), and an unbind row removes only the row with its identity. A key sequence in progress (d of d d) is kept unless a row added or removed is on it: in its mode, with the keys typed so far, a sequence extending them or one they extend. Such a row cancels the sequence, so the next key starts fresh against the new tables.

The rows of one call are one batch (rowBatch): a key repeated with the same identity is not a replacement but an alternative after the first, so Bind(Do("timeline.open"), Do("timeline.enter")) on l keeps both, and the first whose action is available answers.

func (*Runtime) BindingDebts added in v0.36.0

func (r *Runtime) BindingDebts() []string

BindingDebts lists the stored rows that carry a guard of their own (Binding.When; the editor's implicit input guard aside): the older way to say when a key answers, kept working while areas move the condition onto the action's availability (Available), so the row needs none.

func (*Runtime) BindingTimeoutCommand

func (r *Runtime) BindingTimeoutCommand() tea.Cmd

BindingTimeoutCommand schedules the latest deadline once. Custom Tea models call it after dispatch and send BindingTimeoutMsg to HandleBindingTimeout. A prefix without a deadline (sequence-timeout 0, the default) schedules nothing.

func (*Runtime) BindingTimeoutTick added in v0.16.0

func (r *Runtime) BindingTimeoutTick() (BindingTimeoutMsg, bool)

BindingTimeoutTick is the sequence timer in flight as the message its command delivers at the deadline, already due: a host with a fake clock (explore) delivers it at once instead of waiting sequence-timeout, as Model.JobLingerTick does for the linger timer. False when no sequence waits on a deadline (none pending, or sequence-timeout 0).

func (*Runtime) BindingsDoc added in v0.33.0

func (r *Runtime) BindingsDoc() BindingsDoc

BindingsDoc is every stored table as a bindings file: the pending and passthrough modes, every noun's mode tables (with their extends) and every instance's, in GroupBindings order, rows in table order.

func (*Runtime) Builtin added in v0.8.0

func (r *Runtime) Builtin(register func())

Builtin runs register and marks every operation it registered as the framework's own (Operation.Builtin). NewRuntime and NewModel wrap their registrations in it, and so does every framework constructor that registers operations after them (NewPicker, NewPalette, NewAppearance, grid.Register, markdown.Register, cli.AddCommands), so an operation registered lazily is marked too. Operations registered before it, or by the application at any other time, keep Builtin false. Calls nest. It is for framework packages; an application's own verbs are not builtin.

func (*Runtime) CancelPendingBinding

func (r *Runtime) CancelPendingBinding()

CancelPendingBinding leaves a key-sequence prefix mode without running its completed match and invalidates its timer.

func (*Runtime) CanonicalKey added in v0.16.0

func (r *Runtime) CanonicalKey(key string) string

CanonicalKey is an operation key with its noun resolved (CanonicalNoun): settings.set is ochazuke.settings.set unless the application has a settings noun of its own. A name is looked up whole first: a registered action or action alias keeps its name, and a dotted verb (dirs.base.add) resolves where it was declared; otherwise each dot, last first, is tried as the noun/verb split, and an unknown name reads its last dot (SplitKey).

func (*Runtime) CanonicalNoun added in v0.16.0

func (r *Runtime) CanonicalNoun(name string) string

CanonicalNoun is the registered noun a noun name stands for. A noun the application registered under that exact name owns it (an app's own settings noun shadows the framework's alias); otherwise an alias (settings for ochazuke.settings) names its noun; otherwise the name is returned unchanged. While framework code registers (Runtime.Builtin) an alias wins over an application noun of the same name, so the framework's rows and tables always reach its own nouns. The v0.16.0 spelling app.<noun> of a framework noun is read as ochazuke.<noun> (deprecated, for one release) unless a noun of that exact name exists or the app noun has a verb of that name (app.state, an application verb, shadows the old spelling of ochazuke.state).

func (*Runtime) CanonicalRequest added in v0.28.0

func (r *Runtime) CanonicalRequest(q Request) Request

CanonicalRequest is q as the runtime runs it: its noun resolved and an alias rewritten to its action, Via keeping the alias (a host building a request from words, the CLI shell, calls it before reading the operation by q.Key()).

func (*Runtime) CaseFor added in v0.55.0

func (r *Runtime) CaseFor(query string) CaseMatch

CaseFor is the CaseMatch the search.case setting gives query.

func (*Runtime) Catalog

func (r *Runtime) Catalog() []Operation

func (*Runtime) Changed added in v0.53.0

func (r *Runtime) Changed(nouns ...string)

Changed tells the watches of nouns (every watch when none is named) that their things may have changed: each fallback watch lists again and emits the difference. An application calls it when its store changed other than through a verb of the change kind (an editor's write, a daemon's event delivered on the loop). Call it on the loop.

func (*Runtime) CheckDefaultBindings added in v0.34.0

func (r *Runtime) CheckDefaultBindings(source string, data []byte) []string

CheckDefaultBindings reports what is wrong with a default bindings file on this runtime, every problem at once: a file that does not parse, a table whose noun, instance or mode is unknown, an extends to an unknown mode, a row that does not validate (an unknown operation, argument, source or guard), a mode.enter into a mode that is not pending, and two rows that clash (the same key and guard in one table: the second would replace the first). It is the rule check for embedded defaults: an application runs it in a test on its built runtime, after its files loaded, for each file it embeds.

func (*Runtime) CheckUserActions added in v0.28.0

func (r *Runtime) CheckUserActions() []string

CheckUserActions reports what a load of actions.json would skip, without installing anything: entries that do not parse or validate, and alias rows that clash with an action or another alias. An entry the last load installed unchanged is not a problem.

func (*Runtime) CheckUserBindings added in v0.2.0

func (r *Runtime) CheckUserBindings() []string

CheckUserBindings reports what a load of the bindings file would skip, without installing anything, and any row of the merged tables that no longer validates; then warnings ("warning: " lines): each guard row of the file (a debt, BindingDebts) and each merged row that can never answer (UnreachableBindings). A row spelled by an action alias is accepted and gets a line saying what it resolves to (not "skipped"). The problems of actions.json (CheckUserActions) follow.

func (*Runtime) Children

func (r *Runtime) Children(id string) []*Instance

Children lists the instances parented at id in registration order.

func (*Runtime) Choices

func (r *Runtime) Choices(c Context, p Parameter) ([]Choice, error)

Choices lists a parameter's accepted values in context c: its Enum, then the result of its choices source (ChoicesSource), or, for a Noun with no list verb, the noun's live instances. A source that asks for confirmation is refused; it must be a read.

func (*Runtime) ChoicesFor added in v0.44.0

func (r *Runtime) ChoicesFor(c Context, p Parameter, query string) ([]Choice, error)

ChoicesFor is Choices for the text typed so far: a source that declares ChoicesQueryParameter receives query.

func (*Runtime) ChoicesSource added in v0.14.0

func (r *Runtime) ChoicesSource(p Parameter) string

ChoicesSource is the operation (noun.verb) a parameter's choices come from: its Source, else its Noun's list verb when that is registered, asks for no confirmation and needs no argument; empty when there is none (a Noun parameter then lists the noun's live instances).

func (*Runtime) ChoicesTakeQuery added in v0.44.0

func (r *Runtime) ChoicesTakeQuery(p Parameter) bool

ChoicesTakeQuery reports whether a parameter's choices source sees the typed text (it declares ChoicesQueryParameter).

func (*Runtime) Chooser added in v0.2.0

func (r *Runtime) Chooser(kind string) *Chooser

Chooser is the open chooser of kind, nil when none is open.

func (*Runtime) ChooserLastSource added in v0.44.0

func (r *Runtime) ChooserLastSource(kind string) string

ChooserLastSource is the source last used by a chooser of kind ("" when none was).

func (*Runtime) ChooserMatch added in v0.59.0

func (r *Runtime) ChooserMatch() string

ChooserMatch is the chooser.match setting (fuzzy for any other value and on a nil runtime).

func (*Runtime) ChromeLevel added in v0.59.0

func (r *Runtime) ChromeLevel() string

ChromeLevel is the chrome.color value, rich (its default) when it holds anything else.

func (*Runtime) Completer added in v0.5.0

func (r *Runtime) Completer() *Completer

Completer is the inline completion component.

func (*Runtime) CompletionTriggers added in v0.5.0

func (r *Runtime) CompletionTriggers(id string) []CompletionTrigger

CompletionTriggers are the triggers an input completes with: its own, else its noun's.

func (*Runtime) Config added in v0.2.0

func (r *Runtime) Config() *Config

Config returns the config component.

func (*Runtime) Context

func (r *Runtime) Context() Context

Context derives the path view of the focus.

func (*Runtime) DeclareSetting added in v0.2.0

func (r *Runtime) DeclareSetting(settings ...Setting) error

DeclareSetting declares settings; each must have a unique name, a known type and a default of that type (in the enum when there is one).

func (*Runtime) DeclareSettingOwner added in v0.55.0

func (r *Runtime) DeclareSettingOwner(owners ...SettingOwner) error

DeclareSettingOwner declares owners of settings (tabs of the Settings page). Declaring an ID again replaces its title, description and order where it stands.

func (*Runtime) DeclareSettingSection added in v0.55.0

func (r *Runtime) DeclareSettingSection(sections ...SettingSection) error

DeclareSettingSection declares sections of an owner's settings (rows of the Settings page's section list). Declaring an owner's section again replaces its title and description where it stands.

func (*Runtime) DefaultBindings added in v0.34.0

func (r *Runtime) DefaultBindings() []DefaultBinding

DefaultBindings are the rows of the default layer, every table as it stands without the user's bindings.json (the rows it replaced back in place, the rows it added left out), each with its source: nouns by name, each noun's modes by name, then instances by id, rows in table order.

func (*Runtime) DefaultBindingsDoc added in v0.51.0

func (r *Runtime) DefaultBindingsDoc() BindingsDoc

DefaultBindingsDoc is BindingsDoc without the user's bindings.json: every table as it stands with the rows the file replaced or unbound back in place and the rows it added left out (DefaultBindings, which replays the applied rows backwards on a copy). With no user file it equals BindingsDoc. The generated reference is drawn from it.

func (*Runtime) Define

func (r *Runtime) Define(name string) *NounBuilder

Define declares a noun, or returns the builder of an existing one. A name the framework's nouns answer to (settings for ochazuke.settings: CanonicalNoun) returns that noun's builder, so an application's verbs and rows extend it; DefineOwn claims the short name for a noun of the application's own instead. Inside Builtin a plain name is the framework noun ochazuke.<name>.

func (*Runtime) DefineGuard

func (r *Runtime) DefineGuard(name string, fn Guard)

DefineGuard registers a named row guard.

func (*Runtime) DefineMode

func (r *Runtime) DefineMode(name string, pending bool, opts ...ModeOption) error

DefineMode registers a mode name. A pending mode is exclusive: only rows in its own table answer, and a row that leaves the mode unchanged returns the instance to the mode it shadowed.

func (*Runtime) DefineOwn added in v0.16.0

func (r *Runtime) DefineOwn(name string) *NounBuilder

DefineOwn declares a noun of the application's own under exactly name, or returns its builder when it exists. When name is the alias of a framework noun (settings for ochazuke.settings) the application's noun owns the short name from then on: keys, binding files, actions.json, the palette and the CLI reach it by that name, and the framework's noun stays reachable by its canonical name (ochazuke.settings), its verbs and rows intact. An application with a settings, config or page noun of its own declares it with DefineOwn instead of removing the framework's.

func (*Runtime) DefinePassthrough

func (r *Runtime) DefinePassthrough(name string) error

DefinePassthrough marks a defined mode as a passthrough mode: while it is the base mode (a pending mode over it included) capture rows stand aside, so the focused level's rows answer every key. The terminal mode is one: ctrl+c reaches the pane instead of the app's captured quit.

func (*Runtime) DefineSelection added in v0.43.0

func (r *Runtime) DefineSelection(name, shape string) error

DefineSelection marks a defined base mode as a selection mode of shape (char, line, block, or a component's own shape such as the grid's row and column); "" makes it an ordinary mode again.

func (*Runtime) Deliver

func (r *Runtime) Deliver(msg tea.Msg) (bool, error)

Deliver routes a message on the loop: a Completion goes to its owner when its job is running and is dropped otherwise; any other message is offered to every component until one claims it. A Then callback that removes its own owner is safe: the job is already settled and the completion is not offered to the gone component. It reports whether a component consumed the message and the delivered completion's error, if any.

func (*Runtime) DeprecatedNounAlias added in v0.57.0

func (r *Runtime) DeprecatedNounAlias(name string) (NounAlias, bool)

DeprecatedNounAlias is the deprecated alias name stands for, if it is one that reaches its noun now.

func (*Runtime) Detail added in v0.2.0

func (r *Runtime) Detail(id string) *Detail

Detail returns the detail an instance fronts, or nil.

func (*Runtime) Dispatch

func (r *Runtime) Dispatch(key MacroKey) (bool, error)

Dispatch resolves one key through the stack walk and runs the first row that answers. It reports whether any row claimed the key. Live keys and macro playback both arrive here.

func (*Runtime) DispatchOutcome added in v0.36.0

func (r *Runtime) DispatchOutcome(key MacroKey) (KeyOutcome, error)

DispatchOutcome is Dispatch reporting which of the three outcomes the key had: handled, unhandled (no level had an available row on it), or consumed by a noop row.

func (*Runtime) DisplayKey added in v0.16.0

func (r *Runtime) DisplayKey(key string) string

DisplayKey is an operation key with its noun as DisplayNoun.

func (*Runtime) DisplayNoun added in v0.16.0

func (r *Runtime) DisplayNoun(noun string) string

DisplayNoun is the shortest name that reaches noun: its alias (AliasOf) while no application noun shadows it (list for ochazuke.list, doc for an extension's json.doc a host aliased doc), else noun itself. The footer's hints, the ? help, the palette and the jobs ticker draw it; history, bindings.list, operations.list and the catalog print canonical names.

func (*Runtime) DocsPage added in v0.51.0

func (r *Runtime) DocsPage(topic string) (header, text string, err error)

DocsPage is a topic's page rendered from the live runtime with the running binary's stamp, and the viewer's header line naming that build: "TOOL COMMIT[+dirty] · VERSION · catalog FINGERPRINT". The page's text is its body below the generated header (the header line stands for it); with docs.show-config off it equals the committed file's body for the same catalog.

func (*Runtime) DocsTool added in v0.51.0

func (r *Runtime) DocsTool() string

DocsTool is the tool name the docs viewer's header and pages name: the config's App, else the binary's name.

func (*Runtime) EnsureConfigSettings added in v0.2.0

func (r *Runtime) EnsureConfigSettings()

EnsureConfigSettings declares the framework settings whose rows depend on the application, unless the application declared one of the same name first: theme (the colour scheme; its choices are the built-in themes and themes.json's, read here and again when the config directory changed), pages.hidden (its default the pages declared hidden), the segments' settings and history-limit while the history is persisted. The fixed framework settings (settings/ochazuke.json) are declared when the runtime is made, so they need no call. It applies terminal-leader when an application declared it (EnsureTerminalLeader). Model.Init and the CLI shell call it, so settings set works in both; an application may call it earlier (after setting Config.App) to have them before the Model starts.

func (*Runtime) EnsureHistory added in v0.2.0

func (r *Runtime) EnsureHistory()

EnsureHistory persists the action history, once: it reads the history file (the last history-limit entries, marked Restored, before what this session already recorded), compacts it when it holds more or has lines that do not parse (each such file is one notice), and starts the writer every later entry is appended through. Nothing happens without a state directory (Config.Disable, a test binary) or with Config.NoHistoryFile. Model.Init calls it; the CLI shell does not (a one-shot call is not history worth keeping).

func (*Runtime) EnsureNounPlaces added in v0.15.0

func (r *Runtime) EnsureNounPlaces()

EnsureNounPlaces persists the placements record, once: it reads the placements file into the record (a file that does not parse is one notice and is replaced at the next write) and starts the writer the record is saved through, off the loop, at most every NounPlaceWriteEvery and on Config.Flush. Nothing is read or written without a state directory (Config.Disable, a test binary). Model.Init calls it.

func (*Runtime) EnsureSegments added in v0.36.0

func (r *Runtime) EnsureSegments() []string

EnsureSegments declares the segments area's settings and reads the user's segments.json, once. EnsureConfigSettings calls it (Model.Init and the CLI shell), so settings set reaches every segment.

func (*Runtime) EnsureTerminalLeader added in v0.2.0

func (r *Runtime) EnsureTerminalLeader()

EnsureTerminalLeader declares the terminal-leader setting unless the application declared it: an application with terminal panes calls it at setup (cli.AddCommands does), so settings.json, the Settings page and the CLI's settings set know the setting before the first pane opens. An application without terminals does not, and its settings list stays free of it. How long the leader waits is sequence-timeout, as for every other sequence.

func (*Runtime) EnsureUserActions added in v0.2.0

func (r *Runtime) EnsureUserActions() []string

EnsureUserActions installs the user's actions.json once; later calls do nothing. Model.Init, cli.Mount and the CLI shell call it before the user bindings, so a bindings.json row can name an action's verb.

func (*Runtime) EnsureUserBindings added in v0.2.0

func (r *Runtime) EnsureUserBindings() []string

EnsureUserBindings applies the user bindings file once; later calls do nothing. Model.Init and the CLI shell call it, after the application defined its own rows, so a file row replaces an application default.

func (*Runtime) Execute

func (r *Runtime) Execute(q Request) (any, error)

Execute runs an operation at the current focus context; see ExecuteAt.

func (*Runtime) ExecuteAt

func (r *Runtime) ExecuteAt(c Context, q Request) (any, error)

ExecuteAt runs an operation for a context. The innermost noun on the focus stack that overrides the operation handles it; otherwise its Run does. Every request is appended to the action history with its kind, the context it ran in, its outcome and where it moved the interaction.

func (*Runtime) ExportConfig added in v0.6.0

func (r *Runtime) ExportConfig(dir string, force bool) (ConfigExport, error)

ExportConfig writes a complete reference of the user configuration into dir ("" is <config dir>/reference): settings.json with every declared setting at its current value, settings.reference.json with each setting's type, default, choices, description and value, and bindings.reference.json with every stored table in the grouped bindings format (FormatBindings of BindingsDoc), settings.reference.json and actions.example.json one row per line (FormatRows). Each file is written atomically, a temp file renamed over it. A file that would land on one of the live config files (dir is the config directory) is refused unless force is set, and then nothing is written.

func (*Runtime) FocusDisplay added in v0.20.0

func (r *Runtime) FocusDisplay() string

FocusDisplay is the focus-display value, off when it is undeclared or holds anything else.

func (*Runtime) FocusInTopLevel added in v0.16.0

func (r *Runtime) FocusInTopLevel() bool

FocusInTopLevel reports the focus invariant: the focus is inside the top level, the top modal's subtree while a modal is open (else the current page, else app).

func (*Runtime) FocusNoun added in v0.20.0

func (r *Runtime) FocusNoun() string

FocusNoun is the focused instance's noun as DisplayNoun, "" without a focus.

func (*Runtime) FocusPath added in v0.20.0

func (r *Runtime) FocusPath() []string

FocusPath is the focus as the stack shows it, outermost level first and the focused instance last, app left out: each level's label when it has one no wider than FocusLabelMax (a page's is its title), else its noun as DisplayNoun. Open modals are levels in the chain: a modal's levels follow the focus it opened over.

func (*Runtime) GuardHolds added in v0.16.0

func (r *Runtime) GuardHolds(name, focus string) (holds, known bool)

GuardHolds evaluates the named guard at focus in the current mode, as the footer's hints and ? help judge a row's guard (KeyEvent{Mode, Focus}); known is false for a name no guard answers to.

func (*Runtime) GuardNames added in v0.16.0

func (r *Runtime) GuardNames() []string

GuardNames lists every registered row guard (the built-ins and those of DefineGuard), sorted. The "op:<key>" family is not listed: it is a pattern, not a name.

func (*Runtime) HandleBinding

func (r *Runtime) HandleBinding(key string) (bool, error)

HandleBinding dispatches a named key; kept for callers that only know keys.

func (*Runtime) HandleBindingTimeout

func (r *Runtime) HandleBindingTimeout(msg BindingTimeoutMsg) (bool, error)

HandleBindingTimeout executes the longest completed match, or clears an incomplete prefix. Its result is false for a stale or cancelled timer.

func (*Runtime) HandleCall

func (r *Runtime) HandleCall(msg CallMsg)

func (*Runtime) HelpModes added in v0.15.0

func (r *Runtime) HelpModes(place NounPlace, pending bool) []ModeState

HelpModes are the modes the help's pick view offers for place's noun: the registered modes, and with pending the pending modes and every key-sequence prefix the place's walk binds ("normal g" after g). NounPlace{Noun: noun} is the noun with no place.

func (*Runtime) HelpTable added in v0.15.0

func (r *Runtime) HelpTable(place NounPlace, pending bool) ([]string, []HelpKey)

HelpTable is the help's table view for place's noun (NounPlace{Noun: noun} for no place): the modes whose own tables hold a row on its walk (the registered modes, and with pending the pending ones; a key sequence is a row of its base mode, so prefixes add no column), and a row per key or key class with its rows per mode (nounRows; a generated prefix cancel left out). The keys the noun or a level of its place answers come first, then app's, each sorted with key classes last.

func (*Runtime) HiddenPages added in v0.41.0

func (r *Runtime) HiddenPages() []string

HiddenPages is the pages.hidden value: the ids left out of the tabs. Before the setting is declared (EnsureConfigSettings, Model.Init, or the first page.hide or page.show) it is the declared-hidden pages.

func (*Runtime) HidePage added in v0.41.0

func (r *Runtime) HidePage(id string) error

HidePage adds a page to pages.hidden. It refuses an unknown page and the last page not hidden, so the tabs always hold one; hiding the current page keeps it open, its tab shown until another page opens.

func (*Runtime) History

func (r *Runtime) History(n int) []HistoryEntry

History returns the last n entries of every kind, oldest first (all of them for n <= 0): the user's and the fetches, merged by Seq.

func (*Runtime) HistoryOf added in v0.7.0

func (r *Runtime) HistoryOf(n int, kinds ...string) []HistoryEntry

HistoryOf returns the last n entries of the given kinds (every kind when none is given), oldest first; n <= 0 returns all of them.

func (*Runtime) Input

func (r *Runtime) Input(id string) *Input

Input returns the input an instance fronts, or nil.

func (*Runtime) Inputs

func (r *Runtime) Inputs() []*Input

Inputs lists the registered inputs in registration order.

func (*Runtime) Instance

func (r *Runtime) Instance(id string, opts ...InstanceOption) *Instance

Instance registers a plain instance: a page body, a panel, a modal body. Its noun is defined when it does not exist yet; a framework alias names the framework's noun (Kind("prompt") is ochazuke.prompt). Registering an existing id returns it unchanged.

func (*Runtime) InstancePath

func (r *Runtime) InstancePath(id string) []string

InstancePath is Ancestry reversed: app first, id last.

func (*Runtime) Invoked added in v0.28.0

func (r *Runtime) Invoked() Invocation

Invoked is the name the running request named its action by (the action's own key unless an alias ran it); the zero Invocation outside a request.

func (*Runtime) IsPassthrough added in v0.16.0

func (r *Runtime) IsPassthrough(name string) bool

IsPassthrough reports whether name is a passthrough base mode (DefinePassthrough).

func (*Runtime) IsPendingMode added in v0.16.0

func (r *Runtime) IsPendingMode(name string) bool

IsPendingMode reports whether name is a registered pending mode.

func (*Runtime) Issue

func (r *Runtime) Issue(owner, verb, slot string, c Ctx) (Ticket, context.Context, error)

Issue admits a job for owner and returns its ticket and the context its work runs under; the caller runs the work and reports back with a message carrying the ticket, checked with Accepts and closed with Settle. A slot name cancels the owner's running job in that slot; "" accumulates. Launch and Start build on it for work the runtime runs as a tea.Cmd.

func (*Runtime) IssueAt

func (r *Runtime) IssueAt(owner, scope, verb, slot string, c Ctx) (Ticket, context.Context, error)

IssueAt is Issue with the slot scoped to scope, owner or one of its ancestors: the running job in (scope, slot) is cancelled whichever instance owns it. See Result.ReplacingAt.

func (*Runtime) Jobs

func (r *Runtime) Jobs() []JobInfo

Jobs lists every job the runtime knows in start order: the running ones and the finished ones retained since the last jobs.list read.

func (*Runtime) JumpFocus

func (r *Runtime) JumpFocus(steps int, scope string) error

JumpFocus moves the focus steps stops (scope "stop") or regions (scope "region") forward, or backward for negative steps, through the focus root in drawing order (units), wrapping. The current unit is the nearest stop (or region) on the focus path; the next one is the first after that unit's whole subtree. A stop is never descended into (a grid is one stop, its cells are not); the focus lands on the unit's remembered child.

func (*Runtime) KeyEcho added in v0.55.0

func (r *Runtime) KeyEcho() string

KeyEcho is the keys.echo value, off when it is undeclared or holds anything else.

func (*Runtime) Launch

func (r *Runtime) Launch(owner, verb string, res Result, c Ctx) (Ticket, error)

Launch starts a pending result as a job of owner under verb and queues its work for the adapter. The completion reaches the owner's Component.HandleMessage and the result's Then callback when the job is still current.

func (*Runtime) List

func (r *Runtime) List(id string) *List

List returns the list an instance fronts, or nil.

func (*Runtime) ListBindings

func (r *Runtime) ListBindings(focus string) []Binding

ListBindings prints the rows the focus answers to in its current mode, one per key or pattern, sorted by key with pattern rows last.

func (*Runtime) Lists

func (r *Runtime) Lists() []*List

Lists lists the registered lists in registration order.

func (*Runtime) LoadBindings

func (r *Runtime) LoadBindings(data []byte) ([]Binding, error)

LoadBindings installs rows from a JSON array in the binding row shape and returns the installed rows.

func (*Runtime) LoadDefaultBindings added in v0.34.0

func (r *Runtime) LoadDefaultBindings(source string, data []byte) error

LoadDefaultBindings installs a default bindings file (the grouped format, ParseBindings in bindings_file.go) into the default layer: the noun and instance tables, below the user's bindings.json, exactly where the same rows bound in Go would sit. Modes come first, then each group's rows in file order (a row replaces the row with its identity in place, a guarded row goes before the unguarded row on its keys, a sequence gets its prefix cancel), then the group's extends.

Unlike a user file, an embedded default is checked strictly: an unknown operation, argument, source, guard, mode or instance is an error naming source, the table and the key, and the rows after it are not installed. An application loads its files at setup, after it registered the verbs and guards they name and before Model.Init applies the user's file; MustLoadDefaultBindings panics instead, so a test that builds the app catches a bad row. source tags the rows in bindings defaults ("mtm/ bindings/app.json").

func (*Runtime) LoadDefaultBindingsFS added in v0.34.0

func (r *Runtime) LoadDefaultBindingsFS(fsys fs.FS, patterns ...string) error

LoadDefaultBindingsFS installs every file of fsys matching the patterns (fs.Glob), each pattern's files in name order, each tagged with its path. A pattern that matches nothing is an error.

func (*Runtime) Matcher added in v0.59.0

func (r *Runtime) Matcher(mode, query string) Matcher

Matcher compiles query in mode with case as search.case says.

func (*Runtime) ModalFocus

func (r *Runtime) ModalFocus(id string) string

ModalFocus is the instance an open modal points at: Focus for the top modal, else the return focus stored in the modal opened over it.

func (*Runtime) ModalReturn added in v0.16.0

func (r *Runtime) ModalReturn(id string) (focus string, mode ModeState)

ModalReturn is what closing an open modal restores: the focus and mode it opened over. Unknown or closed modals report "" and the zero mode.

func (*Runtime) Modals

func (r *Runtime) Modals() []*Instance

Modals lists the open modal instances, outermost first.

func (*Runtime) ModeBadgeKeyCase added in v0.53.0

func (r *Runtime) ModeBadgeKeyCase() string

ModeBadgeKeyCase is the mode-badge.key-case value, upper when it is undeclared or holds anything else.

func (*Runtime) ModeBadgeWidth added in v0.55.0

func (r *Runtime) ModeBadgeWidth() int

ModeBadgeWidth is the cells the mode badge's label reserves (Header.BadgeWidth): with mode-badge.width widest (the default, or any value it does not know), the widest label of a registered base mode (Runtime.Modes, as the badge names it); 0 with fit. Pending modes are left out: they show the keys they hold, so no width fits them, and a longer label grows the badge leftward from the same right edge.

func (*Runtime) ModeKnown added in v0.16.0

func (r *Runtime) ModeKnown() bool

ModeKnown reports whether the current mode is one the runtime defined: a base mode, a pending mode, or a key-sequence prefix over a base mode.

func (*Runtime) ModeParent added in v0.43.0

func (r *Runtime) ModeParent(name string) string

ModeParent is the mode name falls back to for a noun with no table of its own (ModeExtends), "" for none.

func (*Runtime) MustLoadDefaultBindings added in v0.34.0

func (r *Runtime) MustLoadDefaultBindings(source string, data []byte)

MustLoadDefaultBindings is LoadDefaultBindings that panics on an error: embedded defaults are code, and a bad row fails at startup.

func (*Runtime) NoteNounAlias added in v0.57.0

func (r *Runtime) NoteNounAlias(name string)

NoteNounAlias posts the one-time notice of a deprecated noun alias typed as name (a request's noun, a palette or CLI word); nothing for any other name.

func (*Runtime) Noun

func (r *Runtime) Noun(name string) *Noun

Noun returns the registered noun a name stands for (an alias resolved: CanonicalNoun), or nil.

func (*Runtime) NounAliasNotice added in v0.57.0

func (r *Runtime) NounAliasNotice(name string) (text string, ok bool)

NounAliasNotice is the one-time notice of name when it is a deprecated noun alias whose notice has not been given yet in this runtime, and records it as given; ok is false otherwise. NoteNounAlias posts it; a host printing its own warnings (cli.Mount) takes the text.

func (*Runtime) NounAliasesOf added in v0.57.0

func (r *Runtime) NounAliasesOf(noun string) []NounAlias

NounAliasesOf lists the aliases that reach noun now (not shadowed by an application noun of their name), the live ones shortest first, then the deprecated ones.

func (*Runtime) NounPlaces added in v0.15.0

func (r *Runtime) NounPlaces(noun string) []NounPlace

NounPlaces is where noun was seen (every noun when noun is ""): one entry per distinct place, most seen first, then most recently seen. It includes the placements file's when the Model read it (EnsureNounPlaces). A consumer resolving a key for a noun that is not on the focus path walks a placement's Chain (outermost first) from its Page, or from its Modal.

func (*Runtime) NounWords added in v0.16.0

func (r *Runtime) NounWords(words []string) (noun string, rest []string, ok bool)

NounWords reads the noun a command line's leading words name and returns it (canonical) with the words after it. The noun is the longest run of leading words that, joined with dots, names a noun or an alias of one: "ochazuke settings list" and "ochazuke.settings list" are ochazuke.settings, "settings list" is ochazuke.settings unless the application has a settings noun of its own, "app quit" is app. At least one word is left for the verb. ok is false when no leading run names a noun.

func (*Runtime) OnConfigReload added in v0.15.0

func (r *Runtime) OnConfigReload(name string, fn func() []string)

OnConfigReload adds an application's own configuration to config.reload: fn reads its file again and returns the problems it found (an entry skipped, a file that does not parse), never fatal. Hooks run in registration order after the framework's files. Each problem not already starting with "name: " gets that prefix, is reported through Config.Report like a framework file's and withdrawn at the next config.reload. fn runs on the update loop.

func (*Runtime) OpenArgsForm added in v0.36.0

func (r *Runtime) OpenArgsForm(q Request, run func(Request) error) (*RecordEditor, error)

OpenArgsForm opens the args form over the focus for a request whose verb lacks arguments: one field per parameter (ArgsFields), prefilled from q's arguments, the first missing required one focused (typing, when it is a text field). Every field is filled by the user: nothing is read from the focus or a guess (R12.5), except what a parameter declares and the form shows: a Focus parameter starts holding the focused thing (focusValue), and an Edits one the subject's current value of its prop, selected as a rename is, or empty with the prop's Fallback as its placeholder (argsFormStart). enter runs the form once every required field is valid (form.run) and otherwise goes to the field that still needs a value; esc in normal mode cancels and runs nothing. run executes the completed request after the form closed, at the focus it opened over; its error reopens the form with the values. When the only missing required parameter is a path and SinglePathSetting allows, no form opens: the path chooser does (the editor returned is nil), and its pick runs the request.

func (*Runtime) OpenChooser added in v0.2.0

func (r *Runtime) OpenChooser(spec ChooserSpec) (*Chooser, error)

OpenChooser opens a chooser modal with its search input focused in insert mode. Like OpenModal, it opens only from the top level.

func (*Runtime) OpenModal

func (r *Runtime) OpenModal(kind string, payload Payload, opts ...ModalOption) (*Instance, error)

OpenModal opens a modal whose body is a new instance of noun kind (its id is the kind), parented at the current focus and carrying payload, and focuses it (or the input WithInput places in it). The instance lives until Pop closes the modal. The kind's rows answer first, then the focus it opened over, then the modal noun.

func (*Runtime) OpenPage

func (r *Runtime) OpenPage(id string) error

OpenPage makes a page current and restores the focus and mode it was left in; an open modal blocks navigation. Runtime.Page is always an ancestor of the focus.

func (*Runtime) OpenPagePicker added in v0.2.0

func (r *Runtime) OpenPagePicker() (*Chooser, error)

OpenPagePicker opens the page chooser (page.pick): the pages visited before, most recent first, then the pages never visited in registration order, then the current page, marked "current" (a hidden page is listed too, marked "hidden"), so the highlighted first row is the page last left and enter goes back to it. Typing filters by title; enter opens the highlighted page, esc closes.

func (*Runtime) OpenPathChooser added in v0.44.0

func (r *Runtime) OpenPathChooser(spec PathChooserSpec) (*Chooser, error)

OpenPathChooser opens the path chooser (browse, recent, typed, then the application's sources) for spec.Pick.

func (*Runtime) OpenRecordEditor added in v0.2.0

func (r *Runtime) OpenRecordEditor(id string, spec RecordSpec) (*RecordEditor, error)

OpenRecordEditor opens a record editor as a modal over the focus, its first field focused; leaving closes the modal and restores the focus and mode it opened over.

func (*Runtime) OpenTextView added in v0.55.0

func (r *Runtime) OpenTextView(title, text string) (*Input, error)

OpenTextView opens text in the text view: a modal over the focus holding a read-only input (Input.ReadOnly), one line when the text is one line, else many, with the cursor at the start in normal mode. The editor's motions, visual modes and yanks work there; q or esc closes it back to the focus it opened over. title heads it (the palette's is the verb's name). Opened while the text view is the top modal, it shows the new text in its place, from the top, over the focus the first opened over (ReplaceOpen, R4.8).

func (*Runtime) OpenVisibleStart added in v0.41.0

func (r *Runtime) OpenVisibleStart() error

OpenVisibleStart leaves a hidden start page: when the current page is hidden and another page is not, it opens the first page not hidden. Model.Init calls it once the settings are read, so an application whose start page the user hid opens on the first page in the tabs instead; later, opening a hidden page (page.open, OpenPage) stays on it.

func (*Runtime) Operation added in v0.16.0

func (r *Runtime) Operation(key string) (Operation, bool)

Operation is the registered operation a key names, aliases resolved: noun aliases (settings.set) and action aliases (an old verb name) alike.

func (*Runtime) PageFocus

func (r *Runtime) PageFocus(id string) string

PageFocus is the focus a page shows: the live base focus while it is the current page, else the focus it remembers.

func (*Runtime) PageHidden added in v0.41.0

func (r *Runtime) PageHidden(id string) bool

PageHidden reports whether pages.hidden holds the page id.

func (*Runtime) PageList

func (r *Runtime) PageList() []*Page

PageList lists pages in registration order: app's children of kind page. It reads the app instance's page order (appPages), so a frame that asks several times costs the number of pages, not of instances; without one (an application gave app a component of its own) it scans the instances.

func (*Runtime) PageOf

func (r *Runtime) PageOf(id string) *Page

PageOf returns the page an instance fronts, or nil.

func (*Runtime) PaneLayout added in v0.4.0

func (r *Runtime) PaneLayout(id string, l Layout) Layout

PaneLayout is l with the divider of the page id is on (or is): a page renderer that draws a list/detail split passes its Layout through it, so Split, SplitBlock, SplitFocusBlock and Divide follow the page's pane keys. Called while the page renders, it also records that the page draws a split, which is when pane.grow, pane.shrink and pane.reset answer their keys and show in the hints.

func (*Runtime) PaneShift added in v0.4.0

func (r *Runtime) PaneShift(page string) int

PaneShift is the remembered divider of page (Layout.Shift), 0 for the split's default.

func (*Runtime) PathStart added in v0.44.0

func (r *Runtime) PathStart(pick PathPick) string

PathStart is the folder browse starts in for pick: the field's value's folder (the value itself for a folder; a relative value is under Base), else the parameter's Base, else what path.start names. It reads no file system.

func (*Runtime) PendingCommands

func (r *Runtime) PendingCommands() tea.Cmd

PendingCommands drains the work scheduled since the last call: the runtime's own queue and every component's PendingCommand.

func (*Runtime) PendingModes added in v0.16.0

func (r *Runtime) PendingModes() []string

PendingModes lists the registered pending modes (DefineMode with pending), sorted.

func (*Runtime) Placed

func (r *Runtime) Placed(id string)

Placed records that the instance id is being drawn now, during its page's render: the order of these calls in a frame is the page's drawing order, which focus jumps (focus.next, focus.previous) and list spills walk, so motions follow the screen as drawn and cannot drift from it. List, Input (InputBlock), Terminal and grid views call it; a component of the application's own calls it from its view. Outside a page render it does nothing. There is no other way to order stops: before the first frame the order is the tree's, and once a frame drew any stop, a stop the last frame did not draw is skipped (it is not on screen). A stop drawn by an application view that never calls Placed is therefore skipped too.

func (*Runtime) PlacedAt

func (r *Runtime) PlacedAt(id, text string, focus, height int) string

PlacedAt records where the view text of instance id holds the focus (lines focus to focus+height of text; a list's selected row, an input's whole box) and returns text marked so its page finds the body line it lands on, which is how the page scrolls to keep the focus visible. Call it with the view's final text after Placed; it amends that placement (or places id, if Placed was not called). Outside a page render it returns text unchanged. List, Input, Terminal and grid views call it.

func (*Runtime) Pop

func (r *Runtime) Pop() error

Pop closes the active modal and restores the focus and mode it opened over. A body the modal created is closed through the delivery contract and removed with what it holds.

func (*Runtime) PropGuard added in v0.53.0

func (r *Runtime) PropGuard(noun, prop string) string

PropGuard is the guard a noun's prop is available under (PropSpec.When), "" for none: the prop guards, apart from the verb guards (VerbGuard).

func (*Runtime) PropOf added in v0.52.0

func (r *Runtime) PropOf(noun, name string) (PropSpec, bool)

PropOf is noun's prop of that name.

func (*Runtime) Props added in v0.52.0

func (r *Runtime) Props(noun string) []PropSpec

Props lists a noun's props in declaration order (a copy), nil for an unknown noun or one without props.

func (*Runtime) Push

func (r *Runtime) Push(id, focus string) error

Push opens a modal with id focused on focus (app when empty). An id that is not already an instance becomes one of the modal noun for as long as it is open. The modal remembers the focus and mode it opened over.

func (*Runtime) Query

func (r *Runtime) Query(preds ...Predicate) []*Instance

Query returns the instances matching every predicate, in tree order: app first, then depth-first with siblings in the order they were added. An unknown predicate matches nothing; instances.query reports it instead.

func (*Runtime) ReadBareAlias added in v0.50.0

func (r *Runtime) ReadBareAlias(c Context, words []string, nouns []string) (BareReading, bool, error)

ReadBareAlias reads words (a palette line's or the CLI's) that start with a bare alias; false when the first word is none. nouns are the noun words that may follow a shadowing alias; nil reads every noun that has the verb. The CLI and the palette read a line with this one rule.

func (*Runtime) ReadNounWord added in v0.53.0

func (r *Runtime) ReadNounWord(noun, word string, verbs []string) NounWord

ReadNounWord reads the word after noun (owner decision 18): verbs are the noun's verb words where the line is read. An exact verb wins, then an exact prop, then a unique verb prefix, then a unique prop prefix.

func (*Runtime) ReadYank

func (r *Runtime) ReadYank(register string) (Yank, error)

ReadYank reads a register ("" is the active register, else the unnamed one).

func (*Runtime) RecentPaths added in v0.44.0

func (r *Runtime) RecentPaths() []string

RecentPaths are the paths picked through a path chooser this run, newest first.

func (*Runtime) RecordEditor added in v0.2.0

func (r *Runtime) RecordEditor(id string) *RecordEditor

RecordEditor is the record editor with this id, or nil.

func (*Runtime) ReferenceModel added in v0.51.0

func (r *Runtime) ReferenceModel() refdoc.Model

ReferenceModel is the runtime as the generated reference sees it: every declared setting (with the user's value where it differs from the default) and every default key row (DefaultBindingsDoc, with the user's bindings.json rows that change each table). refdoc.Render draws the pages from it; the committed docs/reference files are its render on the framework runtime, and docs.open renders it live.

func (*Runtime) Register

func (r *Runtime) Register(o Operation)

Register adds an operation. An operation with App set is of kind application and its Run is the framework's dispatcher for it. Its noun may be dotted (ai.skills) and so may its verb (base.add): the key is a name in a flat table, looked up whole. A noun named by a framework alias (settings) is the noun it names (ochazuke.settings), as Define reads it; inside Builtin a plain noun is ochazuke.<noun>. A verb y on noun x beside a noun x.y is refused (checkOverlap).

func (*Runtime) RegisterPage

func (r *Runtime) RegisterPage(page *Page, opts ...InstanceOption) error

RegisterPage registers a page as an instance of kind page under app (the instance may already exist, registered through Instance with the inputs and lists it holds). Focus names where the page starts: the page itself or an instance beneath it. Registration does not activate the page. A page declared hidden by default (Page.DefaultHidden, or the DefaultHidden option) joins the pages.hidden setting's default.

func (*Runtime) RegisterPredicate

func (r *Runtime) RegisterPredicate(name string, fn PredicateFunc)

RegisterPredicate adds a named predicate an application's queries (and the CLI's instances.query) can use, such as marked.

func (*Runtime) Registers

func (r *Runtime) Registers() *Registers

Registers returns the registers component.

func (*Runtime) ReloadConfig added in v0.15.0

func (r *Runtime) ReloadConfig() ([]string, error)

ReloadConfig reads every configuration file the application uses again, in dependency order: themes.json (when it was read: the theme setting's choices are then current), settings.json (when settings are declared; observers see every value that changed, the Model's theme among them), actions.json (when it was installed), bindings.json (when it was applied, once: a row can name an action's verb), segments.json (when it was read), then each OnConfigReload hook. Each file's last problems are withdrawn and its new ones reported, so no stale notice survives; a bad file is skipped, never fatal. It returns the problems in that order, each naming its file, and an error only when the application has no config directory.

func (*Runtime) ReloadThemes added in v0.2.0

func (r *Runtime) ReloadThemes() []string

ReloadThemes reads themes.json again: the schemes that validate replace the user's, every problem is reported (and the last read's withdrawn), and the theme setting's choices follow when the framework declared it. A missing file is no schemes and no problem.

func (*Runtime) ReloadUserActions added in v0.2.0

func (r *Runtime) ReloadUserActions() []string

ReloadUserActions removes the actions a previous load installed, then reads actions.json again and installs each valid entry as an application verb. An entry that does not validate (an unknown noun, a verb that exists, a bad template) is skipped and reported, never fatal; a file that does not parse installs nothing. A missing file is no actions and no problem. It returns the problems, each also sent to Config.Report.

func (*Runtime) ReloadUserBindings added in v0.2.0

func (r *Runtime) ReloadUserBindings() []string

ReloadUserBindings takes out the rows a previous load installed (the rows they replaced come back), then reads the bindings file again and installs its rows one by one: a row that does not validate is skipped and reported, never fatal, and a file that does not parse installs nothing. A missing file is no rows and no problem. It returns the problems, each also sent to Config.Report.

func (*Runtime) ReloadUserSegments added in v0.36.0

func (r *Runtime) ReloadUserSegments() []string

ReloadUserSegments reads segments.json again: the rows it held before are taken back (a user-only segment goes, a patched one keeps the application's row), then each valid row patches or adds its segment. A row that does not validate is skipped and reported; a missing file is no rows and no problem.

func (*Runtime) RemoveInstance

func (r *Runtime) RemoveInstance(id string) error

RemoveInstance closes an instance and its descendants (components closed, jobs cancelled) and drops them. Every focus reference into the removed subtree (Focus, a page's remembered focus, an open modal's return) moves to the nearest surviving ancestor (the Focus itself to a removed instance's FocusOnClose target when that survives); an open modal inside the subtree is kept and reparented there. app cannot be removed.

func (*Runtime) RemoveVerbAvailability added in v0.55.0

func (r *Runtime) RemoveVerbAvailability(key, guard string) bool

RemoveVerbAvailability takes a guard AddVerbAvailability added off a verb; false when the verb had no such added guard (its own guard stays: SetAvailability changes that one).

func (*Runtime) RemoveVerbCheck added in v0.43.0

func (r *Runtime) RemoveVerbCheck(key, name string) bool

RemoveVerbCheck takes the check named name off the verb; false when it had none of that name.

func (*Runtime) RenameSelect added in v0.42.0

func (r *Runtime) RenameSelect() bool

RenameSelect is the rename.select setting: whether a rename opens with its text selected. Read at the moment a rename opens.

func (*Runtime) ResolveAction added in v0.28.0

func (r *Runtime) ResolveAction(name string) (Operation, Invocation, bool)

ResolveAction is the action a name runs and how it was named: the action's own key (noun aliases resolved: settings.set is ochazuke.settings.set) or an alias of it.

func (*Runtime) RetargetFocus

func (r *Runtime) RetargetFocus(match func(id string) bool, to string)

RetargetFocus points every focus reference that match accepts (the focus, a page's remembered focus, an open modal's return) at to. A component that recreates its focused child (the grid's cell, the list's row) calls it after the move; staying inside one focus stop, it keeps the mode.

func (*Runtime) SearchCase added in v0.55.0

func (r *Runtime) SearchCase() string

SearchCase is the search.case setting: smart, ignore or sensitive (smart for any other value, and on a nil runtime).

func (*Runtime) SearchMatch added in v0.59.0

func (r *Runtime) SearchMatch() string

SearchMatch is the search.match setting (substring for any other value and on a nil runtime).

func (*Runtime) SegmentCells added in v0.36.0

func (r *Runtime) SegmentCells() []SegmentCell

SegmentCells are the segments the header rule draws now: the active rows that have answered, in order. A failed refresh keeps the last text and draws it in state.errored; one that never answered draws its label and "!" in state.errored.

func (*Runtime) SegmentProvider added in v0.36.0

func (r *Runtime) SegmentProvider(name string, fn SegmentProvider)

SegmentProvider registers a Go source under name; a segment names it in its Provider field. A later registration of the name replaces it.

func (*Runtime) Segments added in v0.36.0

func (r *Runtime) Segments() []SegmentState

Segments lists every segment in drawing order, with whether it shows and its last answer.

func (*Runtime) SegmentsShown added in v0.36.0

func (r *Runtime) SegmentsShown() bool

SegmentsShown reports whether the segments area is on (its setting undeclared reads on).

func (*Runtime) SelectedBackground added in v0.43.0

func (r *Runtime) SelectedBackground() string

SelectedBackground is the tones.selected-background setting's value (a row of settings/ochazuke.json, declared when the runtime is made, default drop).

func (*Runtime) SelectionMode added in v0.43.0

func (r *Runtime) SelectionMode(shape string) string

SelectionMode is the mode that selects shape ("" when none does); of several, the first by name.

func (*Runtime) SelectionShape added in v0.43.0

func (r *Runtime) SelectionShape(mode string) string

SelectionShape is the selection shape of mode, "" when the mode holds no selection.

func (*Runtime) SetAvailability added in v0.36.0

func (r *Runtime) SetAvailability(key, guard string)

SetAvailability makes a registered action available only while the named guard holds (Available): what NounBuilder.When does for the verb it follows, for an operation registered with Register (the framework's components). An empty guard makes the action always available.

func (*Runtime) SetConfirm

func (r *Runtime) SetConfirm(key, prompt string) error

SetConfirm sets or clears (empty prompt) the confirm prompt of noun.verb.

func (*Runtime) SetFocus

func (r *Runtime) SetFocus(id string) error

SetFocus points the focus at one instance: an input, a list, a row, a page or a modal body. Without a modal, the focus must sit inside the current page; a hidden page's instances are addressed with an explicit target.

func (*Runtime) SetMode

func (r *Runtime) SetMode(mode string) error

SetMode sets the global mode by name and clears its payload, as mode.set does: a focused input runs its own transition (insert sessions, visual anchor), and a pinned input stays in its pinned mode.

func (*Runtime) SetPaneShift added in v0.4.0

func (r *Runtime) SetPaneShift(page string, shift int) (int, error)

SetPaneShift remembers page's divider, clamped to PaneShiftLimit either way, and writes the panes file (the state directory's PanesFile) when there is one; a failed write is a notice and the divider still holds for the session. It returns the shift kept.

func (*Runtime) SetPathBase added in v0.44.0

func (r *Runtime) SetPathBase(fn func(PathPick) string)

SetPathBase gives the folder path.start=base starts in when the parameter names none (the open file's folder); "" falls back to the working directory.

func (*Runtime) SetRecentPaths added in v0.44.0

func (r *Runtime) SetRecentPaths(fn func(PathPick) []string)

SetRecentPaths gives the recent source's paths, newest first; the paths picked this run follow them.

func (*Runtime) SetTableState added in v0.12.0

func (r *Runtime) SetTableState(id string, s TableState)

SetTableState remembers the view of the table with this id and writes the tables file (the state directory's TablesFile) when it changed; a failed write is a notice and the view still holds for the session.

func (*Runtime) SetTerminalLeader added in v0.2.0

func (r *Runtime) SetTerminalLeader(key string) error

SetTerminalLeader sets the terminal-leader setting to key (declaring it first when the application has not), so every row naming the setting moves to key. A key that is not one ctrl+ or alt+ combination is refused.

func (*Runtime) SetWatchVersions added in v0.53.0

func (r *Runtime) SetWatchVersions(v WatchVersions) WatchVersions

SetWatchVersions sets where fallback watches keep their versions (nil: in memory, the default) and answers the previous keeper, to restore.

func (*Runtime) Settings added in v0.2.0

func (r *Runtime) Settings() *Settings

Settings returns the settings of the config component.

func (*Runtime) Settle

func (r *Runtime) Settle(t Ticket, err error) bool

Settle records the outcome of a running job and reports whether the ticket was current; a stale ticket leaves the list unchanged. Deliver settles the completions it routes; a component that runs its own commands settles the tickets it issued.

func (*Runtime) ShowMatch added in v0.59.0

func (r *Runtime) ShowMatch() bool

ShowMatch is the search.show-match setting (on for a nil runtime).

func (*Runtime) ShowPage added in v0.41.0

func (r *Runtime) ShowPage(id string) error

ShowPage takes a page out of pages.hidden, back into the tabs in its registration place.

func (*Runtime) Snapshot

func (r *Runtime) Snapshot() map[string]any

func (*Runtime) Sourced

func (r *Runtime) Sourced(source string) (restore func())

Sourced sets the source the requests executed until restore is called are recorded with, unless an outer caller already set one (a row run by a key inside a macro replay keeps "macro:q"). Callers: the resolver ("key:<keys>"), the transport ("cli"), the palette ("palette").

func (*Runtime) StandardShadows added in v0.53.0

func (r *Runtime) StandardShadows() []string

StandardShadows lists, as info lines, every verb the application registered under a standard verb's name on a noun whose store would generate it: the named verb wins, and the standard one is not offered.

func (*Runtime) StandardVerbsView added in v0.53.0

func (r *Runtime) StandardVerbsView() StandardVerbsView

StandardVerbsView reads palette.standard-verbs: the first ordering part it holds (mixed when none), and the tag and record parts. Unknown parts are ignored. Read each time the palette lists or shows a result.

func (*Runtime) Start

func (r *Runtime) Start(owner string, work func(context.Context) (any, error), then func(Ctx, any, error), c Ctx) (Ticket, error)

Start schedules accumulating work owned by an instance and returns its ticket; it is Launch with Pending(work).Then(then) under the verb "work".

func (*Runtime) StopBindings added in v0.2.0

func (r *Runtime) StopBindings() []StopBindings

StopBindings is the app-wide keyboard: the effective rows of every focus stop, as ListBindings gives them for the focus a jump to the stop lands on. The order is fixed: the pages in tab order (PageList), each page's stops in drawing order (the order focus.next walks, undrawn stops after in tree order), then the open modals bottom to top with theirs, then app in normal mode. The mode is the one the focus would have there: the current mode at the current focus, else the stop's pinned mode (a prompt is insert, a terminal terminal), else normal. Nothing moves: the focus and mode are back as they were on return.

It differs from bindings.list --all, which exports every stored row (each noun's and instance's tables, every mode, as configuration JSON), active or not: this answers "what does each key do where", after shadowing, guards and the modal boundary.

func (*Runtime) StoreYank

func (r *Runtime) StoreYank(y Yank, register string, deletion bool) error

StoreYank puts a yank into the shared registers with the bookkeeping the editor's yank operations use: the named or active register, the unnamed register, "0" for a yank or "1".."9" and "-" for a deletion, and the yank history. A component outside the package (a grid) yanks shapes the editor does not know ("column"), which register.set refuses, so it stores through this call and the editor still sees the text.

func (*Runtime) TabPages added in v0.41.0

func (r *Runtime) TabPages() []*Page

TabPages are the pages the tab row draws and page.next/previous cycle, in registration order: every page not hidden, and the current page even when it is (it leaves the tabs once another page opens).

func (*Runtime) TableState added in v0.12.0

func (r *Runtime) TableState(id string) TableState

TableState is the remembered view of the table with this id (a list's or a grid's instance id): the zero TableState when none was kept.

func (*Runtime) TargetInstance added in v0.2.0

func (r *Runtime) TargetInstance(target string) (string, error)

TargetInstance is the instance a request target names: the target when it is an instance, else what ResolveTarget maps it to. An unknown target is an error naming it.

func (*Runtime) Terminal

func (r *Runtime) Terminal(id string) *Terminal

Terminal returns the terminal an instance fronts, or nil.

func (*Runtime) TerminalLeader added in v0.2.0

func (r *Runtime) TerminalLeader() string

TerminalLeader is the key that enters leader_pending: the terminal-leader setting (its embedded default before it is declared), DefaultTerminalLeader when that is not one ctrl+ or alt+ key. The rows that bind it name the setting ({terminal-leader}), so they follow it (binding_settings.go).

func (*Runtime) Timeline added in v0.17.0

func (r *Runtime) Timeline(id string) *Timeline

Timeline is the timeline with this id, or nil.

func (*Runtime) TopModal

func (r *Runtime) TopModal() string

TopModal is the id of the innermost open modal, "" when none is open.

func (*Runtime) Tree

func (r *Runtime) Tree(id string) *Tree

Tree is the tree with this id, or nil.

func (*Runtime) TreeBreadcrumb added in v0.43.0

func (r *Runtime) TreeBreadcrumb() string

TreeBreadcrumb is the tree.breadcrumb setting: line, title or off.

func (*Runtime) TreeBreadcrumbAncestors added in v0.43.0

func (r *Runtime) TreeBreadcrumbAncestors() int

TreeBreadcrumbAncestors is the tree.breadcrumb.ancestors setting: the hidden ancestors the breadcrumb names, 0 all of them.

func (*Runtime) TreeZoomMode added in v0.43.0

func (r *Runtime) TreeZoomMode() string

TreeZoomMode is the tree.zoom setting: manual, auto or off.

func (*Runtime) TreeZoomRoot added in v0.43.0

func (r *Runtime) TreeZoomRoot() string

TreeZoomRoot is the tree.zoom.root setting: crumb or row.

func (*Runtime) UI added in v0.4.0

func (r *Runtime) UI() *UI

UI returns the UI component: Notify, ClearNotice, Error and Info for code without a Ctx (setup, daemon events), Attach for a host.

func (*Runtime) Unalias added in v0.57.0

func (r *Runtime) Unalias(alias string) error

Unalias removes a noun alias, so a host can rename a noun's short name while it runs (Unalias the old, Alias the new, or AddNounAlias it as deprecated). It is an error when alias names no noun.

func (*Runtime) UnreachableBindings added in v0.36.0

func (r *Runtime) UnreachableBindings() []string

UnreachableBindings reports every stored row that can never answer (unreachableRows), table by table.

func (*Runtime) UseParamAliases added in v0.58.0

func (r *Runtime) UseParamAliases(q Request) (Request, []string)

UseParamAliases is q with the old parameter names its alias takes moved to their parameters (ParamAlias), and the one-time notices of the deprecated ones it used, each returned once per runtime. Requests run through it (ExecuteAt posts the notices); a host reading words into a request before it runs (the CLI shell, which applies an alias's presets itself) calls it and shows the notices its own way.

func (*Runtime) UserActions added in v0.2.0

func (r *Runtime) UserActions() []Action

UserActions are the actions installed from actions.json, in file order.

func (*Runtime) UserAliases added in v0.28.0

func (r *Runtime) UserAliases() []ActionAlias

UserAliases are the alias rows installed from actions.json, in file order.

func (*Runtime) ValidateBindings

func (r *Runtime) ValidateBindings() ([]string, error)

ValidateBindings checks every row of every noun and instance table the way Bind checks a row it installs: keys or a pattern, a registered mode and guard, and a Request to a registered operation with known arguments and sources, or an unbind. Every row is therefore atomic. It is the check behind TestBindingRowsAreAtomic and is for an application to run after it loads its own rows.

func (*Runtime) VerbAvailability added in v0.55.0

func (r *Runtime) VerbAvailability(key string) []string

VerbAvailability names every guard noun.verb is available under: its own (VerbGuard) first, then those AddVerbAvailability added, in order; nil when it has none.

func (*Runtime) VerbChecks added in v0.43.0

func (r *Runtime) VerbChecks(key string) []string

VerbChecks names the checks on a verb, in the order they run.

func (*Runtime) VerbGuard

func (r *Runtime) VerbGuard(key string) string

VerbGuard names the guard on noun.verb, "" when the verb is unguarded.

func (*Runtime) VerbShown

func (r *Runtime) VerbShown(key, focus string, mode ModeState) bool

VerbShown reports whether noun.verb is offered at a focus in a mode: true for an unguarded verb or one whose guard holds there. A guard name that is not registered hides nothing. It is Available for a request with no arguments.

func (*Runtime) Watch added in v0.53.0

func (r *Runtime) Watch(noun string, args Arguments, fn func(WatchEvent)) (*Watch, error)

Watch subscribes to noun's things: args are the watch verb's (the key prop for one thing, where, since). fn receives each event on the loop; nil queues them for Take. A store without a Watch handler is answered at once with the events since (every thing as added when since is empty). Stop ends it.

type Scheme added in v0.2.0

type Scheme struct {
	Background string               `json:"background,omitempty"`
	Text       SchemeColor          `json:"text"`
	Muted      SchemeColor          `json:"muted"`
	Accent     SchemeColor          `json:"accent"`
	Border     SchemeColor          `json:"border"`
	Surface    SchemeColor          `json:"surface"`
	Error      SchemeColor          `json:"error"`
	Tones      map[string]ToneStyle `json:"tones,omitempty"`
	// contains filtered or unexported fields
}

Scheme is a named colour scheme: the palette roles NewStyles draws pages, panels, inputs and modals with. Background is which side of each role it draws: "adaptive" (the terminal's, the default), "light" or "dark". Text is body text and the title; Muted hints and inactive tabs; Accent the active tab, badge, subtitle and focused borders; Border unfocused panel borders; Surface the active tab's and badge's background; Error errors, kept apart from Accent and Muted. Selection stays reverse video in every scheme, so the selected row reads without colour.

type SchemeColor added in v0.2.0

type SchemeColor struct {
	Light string `json:"light"`
	Dark  string `json:"dark"`
}

SchemeColor is one palette role: Light is drawn on a light background, Dark on a dark one. Each is "#RRGGBB", "#RGB" or an ANSI index "0" to "255". In themes.json a role is one colour for both, or {"light": "...", "dark": "..."}.

func (*SchemeColor) UnmarshalJSON added in v0.2.0

func (c *SchemeColor) UnmarshalJSON(data []byte) error

UnmarshalJSON reads "#hex" (both sides) or {"light", "dark"} (a missing side takes the other).

type SchemeSet added in v0.2.0

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

SchemeSet is a read-only set of named schemes; a nil set is empty.

func NewSchemeSet added in v0.2.0

func NewSchemeSet(schemes map[string]Scheme) *SchemeSet

NewSchemeSet holds a copy of schemes.

func (*SchemeSet) Get added in v0.2.0

func (s *SchemeSet) Get(name string) (Scheme, bool)

Get is the scheme of that name.

func (*SchemeSet) Names added in v0.2.0

func (s *SchemeSet) Names() []string

Names are the scheme names, sorted; an entry that only adds tones to a built-in theme is not a scheme of its own and is left out.

type Segment added in v0.36.0

type Segment struct {
	ID       string        `json:"id"`
	Label    string        `json:"label,omitempty"`
	Format   string        `json:"format,omitempty"`
	Provider string        `json:"provider,omitempty"`
	Command  Argv          `json:"command,omitempty"`
	Verb     string        `json:"verb,omitempty"`
	Args     Arguments     `json:"args,omitempty"`
	Every    time.Duration `json:"-"`
	Timeout  time.Duration `json:"-"`
	Tone     string        `json:"tone,omitempty"`
	Order    int           `json:"order,omitempty"`
	Enabled  *bool         `json:"enabled,omitempty"`
	Path     string        `json:"path,omitempty"`
	// Description is the line segment list and the segment's setting show.
	Description string `json:"description,omitempty"`
	// Owner is the settings owner of the segment's setting (a tab of the
	// Settings page, Setting.Owner): an extension's segment names the
	// extension's owner; "" is the declaring application's.
	Owner string `json:"owner,omitempty"`
}

Segment is one status segment row. Format is a template over {{label}} and {{value}} (default "{{label}} {{value}}", or "{{value}}" without a label). Exactly one of Provider, Command and Verb is the source; Args are the verb's arguments. Every is the refresh interval (default DefaultSegmentEvery, at least MinSegmentEvery) and Timeout the most one refresh may take (default DefaultSegmentTimeout, at most Every). Tone is a named tone (tone.go) the text draws in, unless the answer brings its own (SegmentValue.Tone); none draws muted like the rule. Order sorts the rows (lower first, then the order they were added) before status.segment-order. Enabled is the default of the segment's setting (nil: on). Path is the provider's path (disk free reads it).

In segments.json the durations are strings ("2s"), as settings.json writes them.

func (Segment) MarshalJSON added in v0.36.0

func (s Segment) MarshalJSON() ([]byte, error)

MarshalJSON writes the durations as strings ("2s").

func (*Segment) UnmarshalJSON added in v0.36.0

func (s *Segment) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the durations as strings ("2s", "500ms"); an unknown field is an error.

type SegmentCell added in v0.36.0

type SegmentCell struct {
	ID   string
	Text string
	Tone string
}

SegmentCell is one drawn segment: its text and tone ("" muted).

type SegmentMsg added in v0.36.0

type SegmentMsg struct {
	ID    string
	Value SegmentValue
	Err   error
}

SegmentMsg is a refresh's answer, delivered on the loop.

type SegmentProvider added in v0.36.0

type SegmentProvider func(ctx context.Context, s Segment) (SegmentValue, error)

SegmentProvider is a Go source: it returns the segment's value, off the loop, within ctx's deadline (the segment's Timeout).

type SegmentState added in v0.36.0

type SegmentState struct {
	Segment
	Source   string    `json:"source"` // provider, command or verb
	From     string    `json:"from"`   // app, or segments.json
	Shown    bool      `json:"shown"`  // its setting is on (and the area is)
	Position int       `json:"position"`
	Text     string    `json:"text,omitempty"`
	Error    string    `json:"error,omitempty"`
	At       time.Time `json:"at,omitzero"`
}

SegmentState is a segment as segment.list and segment.show answer: the row as merged, where it came from, whether it shows, its position and its last answer.

type SegmentTickMsg added in v0.36.0

type SegmentTickMsg struct{ At time.Time }

SegmentTickMsg is the segments' one-shot timer: it fires at the earliest next refresh of a shown segment (Model.segmentCommand), so a reading changes on an idle screen. At is the deadline it was scheduled for; only the message for the timer in flight clears it. Nothing shown, nothing is scheduled.

type SegmentValue added in v0.36.0

type SegmentValue struct {
	Text string `json:"text"`
	Tone string `json:"tone,omitempty"`
}

SegmentValue is one answer of a source: the text and, optionally, the tone it draws in (a disk nearly full answers state.errored).

type Server

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

Server serves runtime requests over a Unix socket; see Listen.

func Listen

func Listen(path string, send func(CallMsg)) (*Server, error)

Listen requires a private, current-user-owned socket directory. A socket file left by an application that is gone (nothing answers a connect) is removed and listened on again; a live one is never removed.

func (*Server) Close

func (s *Server) Close() error

type Setting added in v0.2.0

type Setting struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Default     any      `json:"default"`
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	// Owner says which owner (a tab of the Settings page) the setting
	// belongs to: "" is the declaring application (OwnerApp), unless the
	// framework declares it (its embedded rows, a feature's declaration
	// inside Runtime.Builtin: OwnerFramework). An application that
	// declares a framework row's name to change its default keeps the
	// framework's owner unless it sets Owner itself. Settings.OwnerOf
	// resolves it.
	Owner string `json:"owner,omitempty"`
	// Section files the setting under a section of its owner; "" takes
	// the name before its first dot ("tree.zoom.root" is in "tree"), and
	// a name without a dot is in SettingsGeneralSection (SectionName).
	// DeclareSettingSection gives a section its title, order and line.
	Section string `json:"section,omitempty"`
	// Group, when set, puts the setting under a heading row of that name
	// inside its section (the schedules of an application, each with its
	// own settings).
	Group string `json:"group,omitempty"`
	// Validate, when set, checks a value of the right type further: Set
	// refuses a value it rejects and a file value it rejects reads the
	// default, as a value of the wrong type does.
	Validate func(value any) error `json:"-"`
	// Deprecated are older names of the setting, kept for one release:
	// settings.get, set and reset, Value and settings.json read them as
	// this setting, each warning once, and a write moves the file's value
	// to this name. A declaration under an old name declares this one.
	Deprecated []string `json:"deprecated,omitempty"`
}

Setting is one declared user preference: its name, type, default, the line the settings list shows and, for a string, the allowed values. Settings are not for secrets: the file is plain JSON in the config directory.

func (Setting) SectionName added in v0.7.0

func (s Setting) SectionName() string

SectionName is the section the Settings page files the setting under: Section when declared, else the name before its first dot ("tree.zoom.root" is in "tree"), else SettingsGeneralSection.

type SettingDiff added in v0.50.0

type SettingDiff struct {
	Name    string `json:"name"`
	Type    string `json:"type"`
	Saved   any    `json:"saved"`
	SavedIn string `json:"savedIn"`
	Session any    `json:"session"`
	Origin  Origin `json:"origin"`
}

SettingDiff is one setting whose session value differs from its persisted one, as settings.diff answers: the name, the persisted value (settings.json's, else the default: SavedIn says which, "file" or "default"), the session value, both in their file form, and the session value's origin.

type SettingOwner added in v0.55.0

type SettingOwner struct {
	ID          string `json:"id"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Order       int    `json:"order,omitempty"`
}

SettingOwner declares an owner of settings: a tab of the Settings page. Owners are drawn by Order (lowest first), then in the order they were declared, then the owners nobody declared in the order of their first setting. The framework declares the application (OwnerApp, order 0) and itself (OwnerFramework, order 100), so an application's owners (one for its extensions) fall between them unless they give an Order.

type SettingOwnerInfo added in v0.55.0

type SettingOwnerInfo struct {
	SettingOwner
	Sections int `json:"sections"`
	Settings int `json:"settings"`
	Session  int `json:"session,omitempty"`
}

SettingOwnerInfo is an owner as settings.owners answers: the declaration filled in (the title resolved), with its section and setting counts and how many of its settings hold a session value.

type SettingSection added in v0.55.0

type SettingSection struct {
	Owner       string `json:"owner,omitempty"`
	ID          string `json:"id"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
}

SettingSection declares a section of an owner's settings: its title, the line the page shows while the section list has the focus, and its place: declared sections come first, in declaration order, then the rest in the order of their first setting. Owner "" declares the section for every owner (the framework's General); an owner's own declaration wins.

type SettingSectionInfo added in v0.55.0

type SettingSectionInfo struct {
	SettingSection
	Settings []string `json:"settings"`
	Session  int      `json:"session,omitempty"`
}

SettingSectionInfo is a section as settings.sections answers: the declaration filled in (owner and title resolved) with its settings' names in page order (by group, each group in declaration order) and how many hold a session value that differs from the saved one.

type SettingShown added in v0.50.0

type SettingShown struct {
	SettingValue
	Line   string  `json:"line"`
	Origin *Origin `json:"origin,omitempty"`
}

SettingShown is setting.show's answer: the setting, its value and the line the status line shows (name=value, name or noname), with the origin when verbose.

type SettingValue added in v0.2.0

type SettingValue struct {
	Setting
	Value   any  `json:"value"`
	Set     bool `json:"set"`
	Session bool `json:"session,omitempty"`
	Saved   any  `json:"saved,omitempty"`
}

SettingValue is a setting with its current value, as settings.list and settings.get answer: Value and Default in their file form (a duration as "400ms"), Set when settings.json holds a value for it. Session is set when the value is a session value (settings_session.go), and Saved is then the persisted value beneath it (settings.json's, else the default).

type SettingWritten added in v0.50.0

type SettingWritten struct {
	SettingValue
	Written string `json:"written"`
}

SettingWritten is a value verb's answer: the setting with its value after the write and the layer written, session or file (a runtime with no session writes the file: "saved: no running session").

type Settings added in v0.2.0

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

Settings holds the declared settings and their values from settings.json in the config directory. It is part of the config component, reached through Runtime.Settings(). The file is read on first use (and again when the config directory changes), written atomically (a temp file renamed over it) on every Set and Reset, and keeps every key it holds: an unknown or invalid key is reported and written back unchanged, never dropped. Without a config directory the values last for the session. Model polls the file (SettingsPoll) so a value another process set (the CLI) reaches a running TUI.

func (*Settings) Autosave added in v0.50.0

func (s *Settings) Autosave() bool

Autosave is the settings.autosave setting: session writes go to the file.

func (*Settings) Bool added in v0.2.0

func (s *Settings) Bool(name string) bool

Bool is a boolean setting's value.

func (*Settings) Declared added in v0.2.0

func (s *Settings) Declared() []Setting

Declared lists the declared settings in declaration order.

func (*Settings) Diff added in v0.50.0

func (s *Settings) Diff() []SettingDiff

Diff lists the settings whose session value differs from the persisted one, in declaration order: what settings.write would write and the review screen shows.

func (*Settings) Duration added in v0.2.0

func (s *Settings) Duration(name string) time.Duration

Duration is a duration setting's value.

func (*Settings) Float added in v0.2.0

func (s *Settings) Float(name string) float64

Float is a number setting's value.

func (*Settings) FrameworkSetting added in v0.51.0

func (s *Settings) FrameworkSetting(name string) bool

FrameworkSetting reports whether the framework declared the setting (its fixed rows, or a feature's), not the application.

func (*Settings) Get added in v0.2.0

func (s *Settings) Get(name string) (SettingValue, error)

Get is one setting with its value.

func (*Settings) HasSession added in v0.50.0

func (s *Settings) HasSession() bool

HasSession reports whether the runtime has a session (StartSession).

func (*Settings) Int added in v0.2.0

func (s *Settings) Int(name string) int

Int is an integer setting's value.

func (*Settings) List added in v0.2.0

func (s *Settings) List() []SettingValue

List is every declared setting with its value, in declaration order.

func (*Settings) Observe added in v0.2.0

func (s *Settings) Observe(name string, fn func(name string, value any))

Observe calls fn with a setting's new value whenever it changes (Set, Reset, or a reload that read another value); name "" observes every setting. Observers run on the caller's goroutine, the update loop.

func (*Settings) Origin added in v0.50.0

func (s *Settings) Origin(name string) (Origin, error)

Origin is where a setting's effective value comes from.

func (*Settings) OwnerOf added in v0.55.0

func (s *Settings) OwnerOf(name string) string

OwnerOf is the owner the named setting files under ("" for an unknown name).

func (*Settings) Owners added in v0.55.0

func (s *Settings) Owners() []SettingOwnerInfo

Owners is every owner holding a setting, in the Settings page's order.

func (*Settings) Problems added in v0.2.0

func (s *Settings) Problems() []string

Problems are the problems the last read of settings.json found.

func (*Settings) Reload added in v0.2.0

func (s *Settings) Reload() []string

Reload reads settings.json again and tells the observers of every value that changed. It returns the problems the file has. A session value stays on top of what the file now holds; a setting whose file value changed is marked changed on disk (Origin.Disk).

func (*Settings) ReloadIfChanged added in v0.2.0

func (s *Settings) ReloadIfChanged() bool

ReloadIfChanged reloads when the file changed on disk since it was last read or written (another process set a value); it reports whether it did.

func (*Settings) Reset added in v0.2.0

func (s *Settings) Reset(name string) error

Reset removes a setting's value from settings.json, so it reads its default again; its session value is dropped too.

func (*Settings) ResetAll added in v0.50.0

func (s *Settings) ResetAll() (string, []string, error)

ResetAll sets every setting back to its default by the writes-through rule: with a session (and autosave off) each setting not at its default gets the default as a session value (Write removes the file's keys, RevertAll takes it back); otherwise every declared setting's key is removed from settings.json in one write (unknown keys stay) and the session values are dropped. It returns the layer written and the names it reset.

func (*Settings) ResetSession added in v0.50.0

func (s *Settings) ResetSession(name string) (string, error)

ResetSession sets a setting back to its default for this session (the file keeps its value until Write, which then removes it), or resets the file (Reset) when the runtime has no session or autosave is on. It returns the layer written.

func (*Settings) Revert added in v0.50.0

func (s *Settings) Revert(name string) error

Revert drops a setting's session value, so settings.json's value (or the default) shows again. A setting without one is left alone.

func (*Settings) RevertAll added in v0.50.0

func (s *Settings) RevertAll() []string

RevertAll drops every session value; it returns the names reverted.

func (*Settings) Sections added in v0.55.0

func (s *Settings) Sections(owner string) ([]SettingSectionInfo, error)

Sections is an owner's sections in the Settings page's order; owner "" is every owner's, owner by owner.

func (*Settings) Session added in v0.50.0

func (s *Settings) Session(name string) (any, bool)

Session is a setting's session value, typed, false when it has none.

func (*Settings) Set added in v0.2.0

func (s *Settings) Set(name string, value any) error

Set validates value against the setting's type and enum (a string is parsed: "3", "true", "400ms"), writes settings.json and tells the observers. A value that does not validate changes nothing. Writing the file drops the setting's session value, so what was written shows.

func (*Settings) SetSession added in v0.50.0

func (s *Settings) SetSession(name string, value any) (string, error)

SetSession sets a setting for this session: value is checked as Set checks it and lives above settings.json, unwritten. It writes the file instead (Set) when the runtime has no session or settings.autosave is on. It returns the layer written, OriginSession or OriginFile.

func (*Settings) StartSession added in v0.50.0

func (s *Settings) StartSession()

StartSession marks the runtime as having a session: a running UI whose session values last until it exits. Model.Init calls it. A runtime without one (a one-shot CLI process, a script) writes every session write to settings.json.

func (*Settings) String added in v0.2.0

func (s *Settings) String(name string) string

String is a string setting's value ("" when undeclared or another type).

func (*Settings) Strings added in v0.8.0

func (s *Settings) Strings(name string) []string

Strings is a list setting's value, a copy (nil when undeclared or another type).

func (*Settings) Value added in v0.2.0

func (s *Settings) Value(name string) (any, bool)

Value is a setting's current value (the session's when it holds one, else the file's when it holds a valid one, else the default), typed as its getter returns it.

func (*Settings) Write added in v0.50.0

func (s *Settings) Write(name string) (bool, error)

Write moves a setting's session value into settings.json (a value a reset put there removes the file's key). A setting without one is left alone; false reports that nothing was written.

func (*Settings) WriteAll added in v0.50.0

func (s *Settings) WriteAll() ([]string, error)

WriteAll moves every session value into settings.json; it returns the names written. The first failure stops it, the ones before staying written.

type SettingsApplied added in v0.50.0

type SettingsApplied struct {
	Shown   []string       `json:"shown,omitempty"`
	Changed []SettingValue `json:"changed,omitempty"`
}

SettingsApplied is settings.apply's answer for a line that is not a list form: what it showed and the settings it changed, with their values after.

type SettingsPollMsg added in v0.2.0

type SettingsPollMsg struct{}

SettingsPollMsg is the Model's settings.json check.

type SplitSide added in v0.2.0

type SplitSide int

SplitSide names the panel of a split that draws focused.

const (
	SplitLeft  SplitSide = iota // the left (or top) panel, Split's default
	SplitRight                  // the right (or bottom) panel
	SplitNone                   // neither: the focus is elsewhere
)

type StandardVerbsView added in v0.53.0

type StandardVerbsView struct {
	Order  string
	Tag    bool
	Record bool
}

StandardVerbsView is what palette.standard-verbs asks of the palette: the ordering of the verb column and whether the std tag and get's record rows show.

type StopBindings added in v0.2.0

type StopBindings struct {
	Page     string    `json:"page,omitempty"`
	Stop     string    `json:"stop"`
	Focus    string    `json:"focus"`
	Mode     string    `json:"mode"`
	Bindings []Binding `json:"bindings"`
}

StopBindings is one entry of bindings.stops: the rows a focus stop answers to (ListBindings at Focus in Mode), with the page it sits on. Stop is the stop instance, Focus where a jump to it lands (its remembered child, a list's selected row), Mode the mode the focus has there. The last entry is app itself (Stop and Focus "app").

type Store added in v0.52.0

type Store struct {
	Kind       string
	Get        func(Ctx, string) (Thing, error)
	List       func(Ctx, ListQuery) ([]Thing, error)
	Create     func(Ctx, Thing) (Thing, error)
	Patch      func(Ctx, string, Thing) (Thing, error)
	Delete     func(Ctx, string) error
	ListParams map[string]Parameter
	Watch      func(c Ctx, q WatchQuery, emit func(WatchEvent)) (stop func(), err error)
	Confirm    map[string]string
	// ConfirmFor builds the prompt a standard verb that asks (delete, or
	// one Confirm gives a prompt) asks for one request: it gets the
	// request's context and arguments, the verb, the keys of the things
	// it acts on (one, or a visual selection's) and the prompt it would
	// ask (Confirm's, the default, or the archive prompt), and answers
	// the template to ask ({{noun}}, {{label}} and the rest still
	// expand); "" asks nothing. It is how a store says what a delete
	// costs (a task's subtasks and notes left without it) without
	// replacing the standard verb. nil asks the prompt as it is.
	ConfirmFor func(c Ctx, verb string, keys []string, prompt string) string
	When       map[string]string
	// Undo lets history.undo revert this store's standard changes
	// (standard_undo.go); AcceptsKey says Create keeps a key the values
	// give, so a delete can be undone under its old key.
	Undo       bool
	AcceptsKey bool
	// Live, on an instances store, answers the ids of the live instances
	// that are its things, in order; nil is every instance of the noun in
	// registration order. (Pages are ochazuke.page's things whatever noun
	// their instances have.)
	Live func(r *Runtime) []string
}

Store is a noun's row in the handler table: its kind and the handlers that read and write its things, each optional. A standard verb exists on the noun exactly when its handler is set (standardVerbs' Needs). Get answers the thing with that key ("" for a singleton); List answers the things. ListParams are list's parameters beside where, props and limit.

Create stores a new thing from the props given (typed, each prop's Default filling an omitted one) and answers it, its key filled. Patch writes the changed props of the thing with that key and answers the thing after the write (nil: the runtime reads it back with Get). Delete removes the thing with that key.

Confirm is a standard verb's confirm prompt by verb ({{label}} is the thing's label prop, else its Fallback); delete asks DefaultDeleteConfirm unless the store names its own ("" asks nothing). When is a standard verb's availability by verb: a guard name, set on the generated verb as SetAvailability does.

Watch, when set, answers watch itself (standard_watch.go): it pushes each event to emit, from any goroutine, until stop; without it watch lists again (List, a singleton's Get) whenever things may have changed.

type Styles

type Styles struct {
	Title        lipgloss.Style
	Subtitle     lipgloss.Style
	Muted        lipgloss.Style
	Accent       lipgloss.Style
	Error        lipgloss.Style
	Panel        lipgloss.Style
	FocusedPanel lipgloss.Style
	Tab          lipgloss.Style
	ActiveTab    lipgloss.Style
	Badge        lipgloss.Style
	Padding      int
	// Backdrop draws what a modal covers (modal-dim); Unfocused draws a page
	// list without the focus (dim-unfocused). Either is the empty style when
	// its dim is 0. WithDims sets both from percents.
	Backdrop  lipgloss.Style
	Unfocused lipgloss.Style
	// contains filtered or unexported fields
}

Styles is a render-time value; it does not retain mutable appearance state.

func NewStyles

func NewStyles(a Appearance) Styles

NewStyles keeps layout and focus cues usable without terminal color support. Theme names the scheme (a built-in theme or one of Schemes; an unknown name draws adaptive); mono and NO_COLOR draw no colour at all.

func (Styles) CardBorders added in v0.23.0

func (s Styles) CardBorders() (focused, selected, other lipgloss.Style)

CardBorders are the border styles of a card timeline's three states (the selection is the border, never reverse video): selected while the timeline has the focus, the accent in bold; selected without the focus, halfway from the accent to the border role; every other card, the border role faded toward the surface by dim-unfocused. With no colour (mono, NO_COLOR) they are bold, plain and faint; the timeline also draws the two selected states in heavy lines, so they read without any attribute.

func (Styles) Chrome added in v0.59.0

func (s Styles) Chrome(role string, fallback lipgloss.Style) lipgloss.Style

Chrome is the style of a chrome role at the current level: fallback with the colours the row chrome.<level>.<role> names laid over it and the row's attributes (bold, dim), or fallback itself when the scheme has no such row. fallback keeps everything a row does not set (padding, borders, a colour the row leaves empty).

func (Styles) ChromeLevel added in v0.59.0

func (s Styles) ChromeLevel() string

ChromeLevel is the level WithChrome set ("" before it).

func (Styles) Fade added in v0.10.0

func (s Styles) Fade(percent int) lipgloss.Style

Fade is a style that carries text percent of the way from the scheme's text colour toward its surface, blended in CIELAB (fadeRamp, lipgloss.Blend1D); with no colour (mono, NO_COLOR) any percent above 0 is the faint attribute. 0 is the empty style.

func (Styles) HasChrome added in v0.59.0

func (s Styles) HasChrome(roles ...string) bool

HasChrome reports whether any of the roles has a row at the current level.

func (Styles) Tone added in v0.26.0

func (s Styles) Tone(name string) lipgloss.Style

Tone is the style a tone draws in outside a list (an application's own line, a footer): its colour and attributes, the empty style for an unknown tone; mono and NO_COLOR keep the attributes alone.

func (Styles) WithBackdropHighlights added in v0.55.0

func (s Styles) WithBackdropHighlights(keep bool) Styles

WithBackdropHighlights says whether a modal's backdrop keeps the page's reverse video and underline (true, the default) or drops them (modal-highlights plain).

func (Styles) WithChrome added in v0.59.0

func (s Styles) WithChrome(level string, modeRoles []string) Styles

WithChrome sets the chrome level (chrome.color) and the current mode's badge role chain (Runtime.modeRoles): the badge takes the first row of the chain that exists, the mode role its colour, and the panel styles their level's border rows. Level off, or a level with no rows, leaves every style as it was.

func (Styles) WithDims added in v0.10.0

func (s Styles) WithDims(modal, unfocused int) Styles

WithDims sets Backdrop and Unfocused from percents: the backdrop is the fade plus the faint attribute (the look it always had at the default), an unfocused list the fade alone.

type Suggestion added in v0.5.0

type Suggestion struct {
	Text   string `json:"text"`
	Label  string `json:"label,omitempty"`
	Detail string `json:"detail,omitempty"`
}

Suggestion is one completion a search offers. Text replaces the token after its trigger; Label is what the list shows ("" shows Text); Detail is drawn muted after the label.

type TableState added in v0.12.0

type TableState struct {
	Column  int         `json:"column,omitempty"`
	Widths  map[int]int `json:"widths,omitempty"`
	Pins    *[]int      `json:"pins,omitempty"`
	Version int         `json:"version,omitempty"`
}

TableState is what a table remembers across a restart: its current column (a cell-mode table's), the widths its columns were given with z > and z < (column index to cells; a column left out is automatic) and the pinned columns the user chose (any table's; nil keeps the default pins, an empty list pins none).

Version is the format the widths were written in: tableStateVersion (1) since a row-select table remembers the widths z F gives it; a row-select table ignores widths without it (left by v0.12.0, when every table was cell-based).

type Terminal

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

Terminal is the component of a terminal instance: it holds the last frame the stream delivered, renders it into the area a page gives it and reports the pane's cursor. Frames arrive through the delivery contract as Completions owned by the instance in the "read" slot, one read at a time, so a frame that arrives after Close, or after a newer read started, is stale and dropped before it reaches the component.

func (*Terminal) Close

func (t *Terminal) Close()

Close stops reading and releases a TerminalReleaser stream, once; the runtime has already cancelled the read in flight.

func (*Terminal) Err

func (t *Terminal) Err() string

Err is the stream's last error, "" when it is healthy.

func (*Terminal) Focused

func (t *Terminal) Focused() bool

Focused reports whether keys go to this pane.

func (*Terminal) Frame

func (t *Terminal) Frame() TerminalFrame

Frame is the last frame the stream delivered.

func (*Terminal) HandleMessage

func (t *Terminal) HandleMessage(msg tea.Msg) bool

HandleMessage stores a frame delivered to this terminal and schedules the next read. A stream error ends reading; a cancelled read is silent.

func (*Terminal) ID

func (t *Terminal) ID() string

ID is the terminal's instance id.

func (*Terminal) Overlay added in v0.14.0

func (t *Terminal) Overlay() *TerminalOverlay

Overlay is the overlay SetOverlay set, nil for none.

func (*Terminal) PendingCommand

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

PendingCommand is nil: reads are scheduled through Runtime.Start.

func (*Terminal) SetOverlay added in v0.14.0

func (t *Terminal) SetOverlay(o *TerminalOverlay)

SetOverlay draws o over the pane from the next frame on; nil clears it. The overlay stays until the application clears or replaces it: a new frame from the stream does not clear it, and neither do a focus change, a mode change or a detach, so an application that pairs it with a mode clears it where it leaves the mode (and in its own focus or close handling). It changes only what ViewBlock draws: Frame, the stream and every other reader of the pane see the pane's own cells.

func (*Terminal) Size

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

Size is the area the pane was last told to fill.

func (*Terminal) View

func (t *Terminal) View(width, height int) string

View renders the pane without a cursor; see ViewBlock.

func (*Terminal) ViewBlock

func (t *Terminal) ViewBlock(width, height int) Block

ViewBlock renders the pane's cells into exactly width x height cells and reports the pane's cursor only while focused. The stream is told the area the first time it is seen and whenever it changes, so the pane is sized to the detail area it fills.

type TerminalFrame

type TerminalFrame struct {
	Lines  []string `json:"lines"`
	Cursor Pos      `json:"cursor"`
	Shape  string   `json:"shape,omitempty"`
	Hidden bool     `json:"hidden,omitempty"`
}

TerminalFrame is one rendering of a pane: its rows of trusted ANSI, the cursor cell, the cursor shape the pane reports ("block", "bar", "underline"; "" for the default block) and whether the cursor is hidden.

type TerminalOverlay added in v0.14.0

type TerminalOverlay struct {
	Dim   bool          `json:"dim,omitempty"`
	Marks []OverlayMark `json:"marks,omitempty"`
}

TerminalOverlay is what an application draws over a terminal's frame without touching the frame: Dim fades the pane's cells (the modal-dim backdrop style; faint in mono and NO_COLOR) and each mark replaces the cells it covers. Hints over a live pane (labels on its URLs and paths) are an overlay plus an application mode; see SetOverlay.

type TerminalReleaser

type TerminalReleaser interface {
	Release() error
}

TerminalReleaser is a TerminalStream that holds something to give back when its terminal closes: a daemon size lease, a connection. Terminal.Close calls Release once, so Pop, SetItems, RemoveInstance and a CloseOnDetach detach all release the stream; its error is kept as the terminal's Err.

type TerminalStream

type TerminalStream interface {
	Next(ctx context.Context) (TerminalFrame, error)
	Send(keys ...string) error
	Paste(text string) error
	Resize(cols, rows int) error
}

TerminalStream is the application's connection to one pane: a daemon client, never a PTY the framework owns. The framework reads frames from it, forwards keys and pasted text to it and tells it the pane's size. Next blocks until the pane changes and returns its next frame; it returns ctx's error when the terminal instance closes or newer work supersedes the read. Keys are named as bindings spell them ("ctrl+a", "d", "esc").

type Thing added in v0.52.0

type Thing map[string]any

Thing is one thing of a noun: its props by name.

func ThingOf added in v0.52.0

func ThingOf(v any) (Thing, error)

ThingOf reads a value as a Thing: a map as it is (a copy), a Record's strings, or a struct through its JSON encoding (its json tags name the props).

type ThingChange added in v0.53.0

type ThingChange struct {
	Noun   string         `json:"noun"`
	Key    string         `json:"key,omitempty"`
	Before map[string]any `json:"before,omitempty"`
	After  map[string]any `json:"after,omitempty"`
	Undone bool           `json:"undone,omitempty"`
}

ThingChange is what one standard write did to one thing: its noun and key, and the props it changed with their values before and after, in their file form. Before is nil for a create, After nil for a delete. Undone marks a change history.undo reverted.

type Ticket

type Ticket struct {
	Owner string `json:"owner"`
	Job   uint64 `json:"job"`
	Slot  string `json:"slot,omitempty"`
}

Ticket names one job: the instance that owns it, its runtime-wide id and the slot it was started in. Slot is "" for a job that accumulates (every completion is delivered, in finish order) and a name for a job that replaces: a newer job in the same slot on the same owner (or, with ReplacingAt, on the same scope) drops the older. A completion is stale, and dropped, only when its job was cancelled by a newer job in its slot or by its owner closing.

type Timeline added in v0.17.0

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

Timeline is a scrolling column of cards of varying height, each a box (Card). The selection, motions, counts, spills, the / filter and the card instances are those of a list child (id+"/list") whose rows are the cards, so j/k, g g, ctrl+d/ctrl+u and 3j behave as on any page list; the timeline draws the cards itself, in a window of its own measured in lines (top, the first card drawn and how many of its lines are above the window), and reports the selected card's lines with PlacedAt so the page keeps it on screen.

Selection rule (the cards' exception to a page list's reverse video): the selection is the border, and no text on a card is ever reversed. The selected card of a focused timeline has a heavy border with heavy corners in the accent, bold; the selected card of a timeline without the focus a heavy border with rounded corners halfway from the accent to the border role; every other card a light rounded border in the border role faded by dim-unfocused (Styles.CardBorders). Header, meta and body text keep their own styles whether selected or not. A timeline without the focus is also faded as a whole (dim-unfocused), as a page list is.

func (*Timeline) BodyID added in v0.30.0

func (t *Timeline) BodyID() string

BodyID is the id of the instance that holds the focus inside a card.

func (*Timeline) CanScrollLines added in v0.50.0

func (t *Timeline) CanScrollLines() bool

scroll moves the window by lines (down when positive) without moving the selection unless it would leave the window (it then lands on the nearest card on screen). Scrolling up stops following the end. CanScrollLines reports whether the last frame did not show every line (LineScroller, view.scroll).

func (*Timeline) Cards added in v0.17.0

func (t *Timeline) Cards() []Card

Cards is a copy of the cards in order.

func (*Timeline) Focus added in v0.17.0

func (t *Timeline) Focus() error

Focus focuses the selected card.

func (*Timeline) FocusTarget added in v0.17.0

func (t *Timeline) FocusTarget() string

FocusTarget is where a jump to the timeline lands: its selected card.

func (*Timeline) Folded added in v0.17.0

func (t *Timeline) Folded(id, section string) bool

Folded reports whether section (its Name, Title or number from 1) of the card with id is folded.

func (*Timeline) Following added in v0.17.0

func (t *Timeline) Following() bool

Following reports whether the timeline follows its end (FollowTail).

func (*Timeline) ID added in v0.17.0

func (t *Timeline) ID() string

ID is the timeline's instance id.

func (*Timeline) InBody added in v0.30.0

func (t *Timeline) InBody() bool

InBody reports whether the focus is inside the selected card.

func (*Timeline) IsOpen added in v0.17.0

func (t *Timeline) IsOpen(id string) bool

IsOpen reports whether the card with id is open.

func (*Timeline) List added in v0.17.0

func (t *Timeline) List() *List

List is the list whose rows are the cards (selection, motions, filter).

func (*Timeline) Patch added in v0.17.0

func (t *Timeline) Patch(cards ...Card) error

Patch updates the cards with these ids in place and appends the others at the end, in order: the cheap path for a streaming last card (bump its Revision) or a new one. The list's rows are rebuilt only when a card is added or its noun, label or data changed.

func (*Timeline) ScrollLines added in v0.50.0

func (t *Timeline) ScrollLines(lines int)

ScrollLines is timeline.scroll by lines (LineScroller).

func (*Timeline) Select added in v0.17.0

func (t *Timeline) Select(id string) error

Select selects the card with id without taking the focus.

func (*Timeline) Selected added in v0.17.0

func (t *Timeline) Selected() (Card, bool)

Selected is the selected card; an empty timeline has none.

func (*Timeline) SelectedID added in v0.17.0

func (t *Timeline) SelectedID() string

SelectedID is the selected card's id, or "".

func (*Timeline) SetAllOpen added in v0.17.0

func (t *Timeline) SetAllOpen(open bool)

SetAllOpen opens or closes every card.

func (*Timeline) SetCards added in v0.17.0

func (t *Timeline) SetCards(cards []Card) error

SetCards replaces the cards, keyed by id: the selection, open cards and section folds follow their ids (as List.SetItems keeps the selection), a new card starts as its Open says. While the timeline follows its end (FollowTail) and the last card is selected, the new last card is selected. Invalid cards leave the timeline unchanged.

func (*Timeline) SetFolded added in v0.17.0

func (t *Timeline) SetFolded(id, section string, folded bool) error

SetFolded folds or unfolds a section of the card with id (section is its Name, Title or number from 1).

func (*Timeline) SetOpen added in v0.17.0

func (t *Timeline) SetOpen(id string, open bool) error

SetOpen opens or closes the card with id.

func (*Timeline) SetParentStop added in v0.30.0

func (t *Timeline) SetParentStop(id string)

SetParentStop changes where h on a closed card goes ("" stays).

func (*Timeline) Step added in v0.30.0

func (t *Timeline) Step() (card string, step int, ok bool)

Step is the card the focus is inside and its current step (from 0); false outside a card.

func (*Timeline) StepText added in v0.30.0

func (t *Timeline) StepText() (string, bool)

StepText is the current step's text (what y yanks); false outside a card.

func (*Timeline) View added in v0.17.0

func (t *Timeline) View(width, height int) string

View draws the cards in a width by height window and records the timeline in its page's drawing order (Placed) with the selected card's lines (PlacedAt). When the cards overflow, the last line reads which cards are on screen, "3–5 / 40". A filter line (/) takes the first line.

type ToneSpan added in v0.26.0

type ToneSpan struct {
	Cell int    `json:"cell"`
	Tone string `json:"tone,omitempty"`
	Bg   string `json:"bg,omitempty"`
	From int    `json:"from,omitempty"`
	To   int    `json:"to,omitempty"`
}

ToneSpan gives a run of one cell a tone. Cell is the column index (in a list without columns, and a tree without them, 0 is the label); From and To are rune offsets into the cell's text as drawn (escape sequences, which a cell never draws, do not count), To 0 meaning the cell's end, so {Cell, Tone} alone tones the whole cell. A later span wins where two overlap; a span outside the text draws nothing. Bg names a tone (a theme token) whose background goes under the span while Tone keeps the foreground and attributes; Bg alone, with no Tone, only fills. Where spans overlap, the foreground comes from the last span with a Tone and the background from the last span that has one.

func CellTone added in v0.26.0

func CellTone(cell int, tone string) ToneSpan

CellTone tones a whole cell.

func SpanTone added in v0.26.0

func SpanTone(cell, from, to int, tone string) ToneSpan

SpanTone tones the runes [from, to) of a cell (to 0: to its end).

type ToneStyle added in v0.26.0

type ToneStyle struct {
	Fg   SchemeColor `json:"fg"`
	Bg   SchemeColor `json:"bg,omitzero"`
	Bold bool        `json:"bold,omitempty"`
	Dim  bool        `json:"dim,omitempty"`
}

ToneStyle is how a scheme draws one tone: Fg is a colour as a scheme role takes it ("#RRGGBB", "#RGB", an ANSI index, {"light", "dark"}) or the name of a palette role (text, muted, accent, border, surface, error) so the tone follows the scheme; empty keeps the text's colour. Bg is the background, a colour or role the same way; empty draws none. Bold and Dim (faint) are the attributes, the only part mono draws. In themes.json a tone is {"fg": ..., "bg": ..., "bold": true, "dim": true}, or a colour or role alone ("#5FAFD7", "error").

func (*ToneStyle) UnmarshalJSON added in v0.26.0

func (t *ToneStyle) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a colour or role alone, or {"fg", "bg", "bold", "dim"}.

type Tree

type Tree struct {

	// OnChange makes the tree editable and receives each change as it is
	// made; an error keeps the change on screen, marks the row and retries
	// it before the next change.
	OnChange func(TreeChange) error
	// NewID names a new node (default "<tree>-n<seq>").
	NewID func() string
	// RowNoun is the noun of nodes the tree adds (default TreeRowNoun).
	RowNoun string
	// Refuse is the application's check on a change before it is made
	// (rename, move, delete and add; for add the node is the parent, the
	// zero node at the top): a non-nil error refuses it with that reason,
	// from every path. It runs after the nodes' Fixed. Undo and redo are
	// not checked: they take back changes that were allowed.
	Refuse func(node TreeNode, change TreeChange) error
	// Debounce is the pause in typing before a line is written.
	Debounce time.Duration
	// contains filtered or unexported fields
}

Tree is a list whose rows are nested nodes: expand and collapse, the same motions as a list (it is one: rows spill to the neighbouring stops in drawing order), the one highlighted row, columns like a table. Given OnChange it is an outline editor: every structural edit is written at once, typing within a line is written after a pause (Debounce) and when the line is left, undo and redo are changes too, and esc never discards.

The tree is an instance of the outline noun with a list child (id+"/list") holding the visible rows; editing adds an input (id+"/line", noun outline-line) under the tree while a line is edited. (The nouns are "outline", not "tree", so palette prefixes such as "tr" stay unique in apps.)

func (*Tree) Block

func (t *Tree) Block(width, height int) Block

Block renders the rows as the list does; while a line is open its row is the input, with the terminal cursor in it. A zoomed tree draws its breadcrumb line above the rows (tree.breadcrumb line) when there is room for a row under it; the frame first applies tree.zoom (frameZoom).

func (*Tree) Breadcrumb added in v0.43.0

func (t *Tree) Breadcrumb() []string

Breadcrumb is the zoom's path as the breadcrumb shows it, outermost first: the hidden ancestors (the nearest tree.breadcrumb.ancestors of them named, farther ones folded into one "…"), then the zoomed node when it is not a row (tree.zoom.root crumb). Nil when not zoomed.

func (*Tree) Close

func (t *Tree) Close()

Close writes an open line.

func (*Tree) CollapseAll

func (t *Tree) CollapseAll() error

CollapseAll collapses every node that has children.

func (*Tree) Collapsed

func (t *Tree) Collapsed(id string) bool

Collapsed reports whether a node is collapsed.

func (*Tree) DebounceCurrent

func (t *Tree) DebounceCurrent(tick TreeDebounceMsg) bool

DebounceCurrent reports whether a pause timer is for the line's latest change (an older timer writes nothing).

func (*Tree) DebounceTick added in v0.16.0

func (t *Tree) DebounceTick() (TreeDebounceMsg, bool)

DebounceTick is the pause timer in flight, for a host that delivers it at once (explore): false when no typing waits on one.

func (*Tree) Edit added in v0.38.0

func (t *Tree) Edit(id string, selected bool) error

Edit opens a node's line as outline.edit does; selected opens it with its text selected, so typing replaces it (Input.SelectText).

func (*Tree) Editable

func (t *Tree) Editable() bool

Editable reports whether the tree takes edits (OnChange is set).

func (*Tree) Editing

func (t *Tree) Editing() string

Editing is the node whose line is open, or "".

func (*Tree) Failure

func (t *Tree) Failure() error

Failure is the last background failure, cleared when read: Deliver returns it for the message the tree handled, so it reaches the status.

func (*Tree) Flush

func (t *Tree) Flush() error

Flush writes the open line now (on quit, and when the line is left).

func (*Tree) Focus

func (t *Tree) Focus() error

Focus focuses the tree's selected row.

func (*Tree) FocusTarget

func (t *Tree) FocusTarget() string

FocusTarget is where a jump to the tree lands: its selected row.

func (*Tree) HandleMessage

func (t *Tree) HandleMessage(msg tea.Msg) bool

HandleMessage writes the open line when its pause timer is the latest.

func (*Tree) Height added in v0.43.0

func (t *Tree) Height() int

Height is the lines the tree needs to draw every visible row without windowing (a table's header aside): its list's Height, plus the breadcrumb line while a zoom draws one. A host that sizes a tree to its rows sizes it with Height.

func (*Tree) ID

func (t *Tree) ID() string

ID is the tree's instance id.

func (*Tree) List

func (t *Tree) List() *List

List is the list that holds the visible rows.

func (*Tree) Nodes

func (t *Tree) Nodes() []TreeNode

Nodes is a copy of every node in display order, collapsed ones included.

func (*Tree) PendingCommand

func (t *Tree) PendingCommand() tea.Cmd

PendingCommand notices typing in the open line and sets the pause timer; a line whose input lost the focus is closed (and written).

func (*Tree) Record added in v0.1.1

func (t *Tree) Record(a TreeAction) error

Record puts an application change on the undo stack: an open line is sealed first (so its typing undoes after the action, not before), and the redo stack is cleared, as for any new change.

func (*Tree) Select

func (t *Tree) Select(id string) error

Select selects a node, expanding its ancestors, without taking focus.

func (*Tree) Selected

func (t *Tree) Selected() (TreeNode, bool)

Selected is the node of the selected row.

func (*Tree) SetCollapsed

func (t *Tree) SetCollapsed(id string, collapsed bool) error

SetCollapsed collapses or expands one node.

func (*Tree) SetNodes

func (t *Tree) SetNodes(nodes []TreeNode) error

SetNodes replaces the nodes, keeping collapse state and the selection by id. Nodes must list each parent before its children.

func (*Tree) View

func (t *Tree) View(width, height int) string

View renders the visible rows (see Block).

func (*Tree) Zoom added in v0.43.0

func (t *Tree) Zoom(id string) error

Zoom draws only id's subtree (tree.zoom.root says whether id is the top row or ends the breadcrumb); "" shows every level again. The selection stays when it is inside the zoom, else moves to the first row in it. Zoom works whatever tree.zoom says; off only drops it at the next frame.

func (*Tree) ZoomOut added in v0.43.0

func (t *Tree) ZoomOut() error

ZoomOut steps the zoom out one level, onto the zoomed node's parent (or shows every level when it is a root); the selection stays.

func (*Tree) Zoomed added in v0.43.0

func (t *Tree) Zoomed() string

Zoomed is the node the tree is zoomed on, "" when it shows every level.

type TreeAction added in v0.1.1

type TreeAction struct {
	ID    string
	Label string // what the change is ("done n1"), for logs
	Undo  func() error
	Redo  func() error
}

TreeAction is an application change that goes on an outline's undo stack in order with the tree's own edits: a change the application keeps outside the tree's nodes, such as a task's status. u runs Undo and ctrl+r runs Redo; each is written by the application like any change. ID is the node selected after either runs ("" keeps the selection).

type TreeChange

type TreeChange struct {
	Op     string `json:"op"`
	ID     string `json:"id"`
	Parent string `json:"parent,omitempty"`
	Index  int    `json:"index"`
	Text   string `json:"text,omitempty"`
}

TreeChange is one committed edit of an outline: add, rename, move or delete. Index is the node's position among its parent's children after the change. The application writes each one to its store as it comes (Tree.OnChange); undo is a further change, never a discard.

func (TreeChange) String

func (c TreeChange) String() string

String reads a change in one line: "add n1 under root at 1: text", "rename n1: text", "move n1 under a at 0", "delete n1".

type TreeDebounceMsg

type TreeDebounceMsg struct {
	Tree string
	Seq  uint64
}

TreeDebounceMsg is the timer a pause in typing sets off: when Seq is still the line's latest change, the line is written.

type TreeNode

type TreeNode struct {
	ID     string     `json:"id"`
	Parent string     `json:"parent,omitempty"`
	Label  string     `json:"label"`
	Noun   string     `json:"noun,omitempty"`
	Data   any        `json:"data,omitempty"`
	Cells  []string   `json:"cells,omitempty"`
	Tones  []ToneSpan `json:"tones,omitempty"`
	// Section is the label line drawn above a run of rows in one section
	// (ListItem.Section); "" none.
	Section string `json:"section,omitempty"`
	// Fixed names the changes the node refuses: TreeRename, TreeMove
	// (move, indent, outdent) and TreeDelete (deleting it or any
	// ancestor). An outline's document root is Fixed all three; an array
	// item, whose key is its index, refuses rename alone. The refusal holds
	// from every path (keys, the palette, the CLI, Tree methods); the verb
	// is not available on the node (outline-renamable, outline-movable,
	// outline-deletable), so its hints and help rows drop out.
	Fixed []string `json:"fixed,omitempty"`
}

TreeNode is one node of a tree. Nodes are flat and in display order: a node's children follow it, and Parent "" is a root. Noun is the row's noun (default TreeRowNoun); Data, Cells and Tones are as on ListItem (cell 0 is the label: its tones stay on it, after the indent and fold marker).

func (TreeNode) Refuses added in v0.43.0

func (n TreeNode) Refuses(op string) bool

Refuses reports whether the node refuses the change op (TreeRename, TreeMove, TreeDelete).

type UI added in v0.4.0

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

UI is the component that routes handler messages to the host's sink. It is one instance under app (Runtime.UI), never a Runtime field. With no sink it discards, except that until the first sink attaches it keeps the last 32 messages (the startup ring) and replays them, in order, into that sink; after the first attach nothing is kept, so memory stays bounded whether or not a sink ever attaches.

Like the rest of Runtime it is called from the update loop; work off the loop posts from its Then (which gets a Ctx).

func (*UI) Attach added in v0.4.0

func (u *UI) Attach(s UISink) UISink

Attach makes s the sink every later message goes to and returns the one it replaces (nil for none). The first attach of the runtime's life replays the startup ring into s and drops it. Attach(nil) detaches: messages are discarded from then on.

func (*UI) ClearNotice added in v0.4.0

func (u *UI) ClearNotice(id NoticeID)

ClearNotice takes back the notice Notify returned id for.

func (*UI) Close added in v0.4.0

func (u *UI) Close()

Close keeps everything: the UI lives as long as the runtime.

func (*UI) Error added in v0.31.0

func (u *UI) Error(text string)

Error sets the status line to an error, drawn "Error: TEXT" in the error style until the next key; "" clears it. Use it for what failed and was not returned as a Failed result (a background refresh, a daemon event).

func (*UI) HandleMessage added in v0.4.0

func (u *UI) HandleMessage(tea.Msg) bool

HandleMessage: the UI does no off-loop work.

func (*UI) Info added in v0.31.0

func (u *UI) Info(text string)

Info sets the status line to a plain message ("copied 3 rows", "queued"), drawn without the error style before the hints until the next key; "" clears it.

func (*UI) Notify added in v0.4.0

func (u *UI) Notify(text string) NoticeID

Notify posts a persistent notice and returns its id for ClearNotice.

func (*UI) PendingCommand added in v0.4.0

func (u *UI) PendingCommand() tea.Cmd

PendingCommand: nothing is ever scheduled.

func (*UI) Sink added in v0.4.0

func (u *UI) Sink() UISink

Sink is the attached sink, nil when messages are discarded.

func (*UI) Status deprecated added in v0.4.0

func (u *UI) Status(text string)

Status is Error: the status line in its error tone. The name read as "any status", so plain messages posted through it were drawn as errors.

Deprecated: use Error for what failed, Info for a plain message.

type UIMessage added in v0.4.0

type UIMessage struct {
	Kind string   `json:"kind"`
	ID   NoticeID `json:"id,omitempty"`
	Text string   `json:"text,omitempty"`
}

UIMessage is one thing a handler told the user: a notice (Kind notice, ID and Text), the clearing of one (Kind clear, ID), or the status line in its error tone (Kind status, Text) or its neutral tone (Kind info, Text); "" clears the line. The startup ring, a call's Response.Messages and RecordingSink hold these.

func (UIMessage) Apply added in v0.4.0

func (msg UIMessage) Apply(s UISink)

Apply hands the message to s.

func (UIMessage) Line added in v0.31.0

func (msg UIMessage) Line() string

Line is the message as a host prints it on a line of its own (the CLI's stderr): "notice: TEXT", "error: TEXT" for the error line, "status: TEXT" for the neutral one; "" for a clear or an empty status.

type UISink added in v0.4.0

type UISink interface {
	// Notify shows a persistent notice until ClearNotice(id) or the host
	// clears it.
	Notify(id NoticeID, text string)
	// ClearNotice takes back a notice; an unknown id is ignored.
	ClearNotice(id NoticeID)
	// Status replaces the one-line status with an error ("" clears it):
	// what Ctx.Error posts (UIError). Only the error tone reaches it.
	Status(text string)
	// Info replaces the one-line status with plain text ("" clears it):
	// what Ctx.Info posts (UIInfo).
	Info(text string)
}

UISink is how a host shows what handlers tell the user: the Model puts notices in the footer and the status in the status line, the CLI shell prints them on stderr, a test records them. Handlers never reach the sink: they post through Ctx (ctx.Notify, ctx.ClearNotice, ctx.Error, ctx.Info) or Runtime.UI, and the host decides how it looks. Every sink shows both tones of the status line, so a plain message is never drawn as an error for want of a method. A sink that wraps another forwards every message (UIMessage.Apply does it).

type VerbCheck added in v0.43.0

type VerbCheck struct {
	Name  string
	Check func(r *Runtime, c Context, args Arguments) Verdict
}

VerbCheck is one check on a verb. Name identifies it (a second check of the same name replaces the first); Check reads the request's context and arguments and returns a Verdict. Checks run in the order they were added; the first that does not allow decides.

type Verbatim added in v0.34.0

type Verbatim string

Verbatim is a result a CLI prints as its text, unquoted (a file the verb writes: bindings defaults); over JSON it is a string.

type Verdict added in v0.43.0

type Verdict struct {
	Ask    string
	Refuse string
}

Verdict is a check's answer: the zero Verdict allows; Ask holds the question the confirm modal asks before the verb runs; Refuse holds the reason the request fails with.

func Allow added in v0.43.0

func Allow() Verdict

Allow is the Verdict that lets the verb run.

func AskFirst added in v0.43.0

func AskFirst(prompt string) Verdict

AskFirst is the Verdict that asks prompt in the confirm modal first; y runs the verb (its checks skipped), n and esc leave it unrun.

func Refuse added in v0.43.0

func Refuse(reason string) Verdict

Refuse is the Verdict that fails the request with reason.

type Watch added in v0.53.0

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

Watch is one watch of a noun's things (Runtime.Watch, the watch verb). Its methods run on the runtime's loop, like the runtime's own.

func (*Watch) Err added in v0.53.0

func (w *Watch) Err() error

Err is why the watch ended on its own, nil after Stop.

func (*Watch) Hash added in v0.53.0

func (w *Watch) Hash() string

Hash is a fallback watch's list hash now (the since that resumes from here), "" for a store's Watch.

func (*Watch) MarshalJSON added in v0.53.0

func (w *Watch) MarshalJSON() ([]byte, error)

MarshalJSON is the watch as one value, for a caller that cannot stream: the events so far as an array; the watch ends.

func (*Watch) Noun added in v0.53.0

func (w *Watch) Noun() string

Noun is the watched noun.

func (*Watch) Stop added in v0.53.0

func (w *Watch) Stop()

Stop ends the watch (a store Watch's stop runs once); events after it are dropped.

func (*Watch) Stopped added in v0.53.0

func (w *Watch) Stopped() bool

Stopped reports whether the watch ended (Stop, or a failing list).

func (*Watch) Take added in v0.53.0

func (w *Watch) Take() []WatchEvent

Take answers the queued events (a watch without a callback) and empties the queue.

type WatchEvent added in v0.53.0

type WatchEvent struct {
	Type  string         `json:"type"`
	ID    string         `json:"id"`
	Thing map[string]any `json:"thing,omitempty"`
	Hash  string         `json:"hash,omitempty"`
}

WatchEvent is one change to a watched thing: its type, its key (id, "" for a singleton) and the thing as get answers it (every prop but the secret ones). A deleted thing carries its last record when the watch saw it, else none. Hash is the since a later watch resumes from: a fallback watch's list hash after the change, or what a store's Watch sets.

type WatchQuery added in v0.53.0

type WatchQuery struct {
	Key   string
	Where map[string]any
	Since string
}

WatchQuery is what a store's Watch handler is asked for: one thing (Key) or the things whose props equal Where (typed by their props; empty for every thing), from Since ("" for now: the store chooses whether to send the current things first).

type WatchVersions added in v0.53.0

type WatchVersions interface {
	ReadVersion(scope, hash string) (ids, hashes []string, ok bool)
	WriteVersion(scope, hash string, ids, hashes []string) error
}

WatchVersions keeps the versions a fallback watch resumes from (since): per scope (a noun and its query), a version's sorted ids and their record hashes under the list hash. A version that is gone answers ok false.

type Yank

type Yank struct {
	Text  string `json:"text"`
	Shape string `json:"shape"`
	Width int    `json:"width,omitempty"`
}

Yank retains the geometry needed to paste independently of the source field.

Source Files

Directories

Path Synopsis
cli
Package cli is the generic command line of an ochazuke application: the NOUN VERB shell over a runtime (Shell), the oden mount that makes every noun a command of the bin (Mount) and the catalog answer that describes the runtime as JSON (Catalog).
Package cli is the generic command line of an ochazuke application: the NOUN VERB shell over a runtime (Shell), the oden mount that makes every noun a command of the bin (Mount) and the catalog answer that describes the runtime as JSON (Catalog).
inspect
Package inspect merges ochazuke tool catalogs (the JSON BIN catalog prints) into one model and writes it as a self-contained HTML page for browsing nouns, verbs, key rows, user actions, relations and, when annotations are given, the verbs someone suggested adding (the Gaps view).
Package inspect merges ochazuke tool catalogs (the JSON BIN catalog prints) into one model and writes it as a self-contained HTML page for browsing nouns, verbs, key rows, user actions, relations and, when annotations are given, the verbs someone suggested adding (the Gaps view).
cmd
charmrefs command
Command charmrefs writes docs/CHARM-INVENTORY.md: for every project listed in docs/charm-refs.txt, the Charm (charm.land, charmbracelet) modules it depends on, how many files import each package, its entry points, and its agent docs.
Command charmrefs writes docs/CHARM-INVENTORY.md: for every project listed in docs/charm-refs.txt, the Charm (charm.land, charmbracelet) modules it depends on, how many files import each package, its entry points, and its agent docs.
codemap command
Command codemap writes docs/CODEMAP.md: one entry per Go file in the root package and in each importable subpackage (cli/, grid/), listing what each file declares and which sibling files it leans on.
Command codemap writes docs/CODEMAP.md: one entry per Go file in the root package and in each importable subpackage (cli/, grid/), listing what each file declares and which sibling files it leans on.
docgen command
Command docgen generates the offline reference linked from the architecture guide: docs/{actions,bindings,api,transport}.html, and with -ref DIR the Markdown reference of the framework runtime (refdoc: README.md, settings.md, bindings.md) that TestReference holds to the catalog.
Command docgen generates the offline reference linked from the architecture guide: docs/{actions,bindings,api,transport}.html, and with -ref DIR the Markdown reference of the framework runtime (refdoc: README.md, settings.md, bindings.md) that TestReference holds to the catalog.
ochazuke command
renamekeys command
Command renamekeys rewrites operation keys from one spelling to the other across the repository's .go, .json, .md and .html files.
Command renamekeys rewrites operation keys from one spelling to the other across the repository's .go, .json, .md and .html files.
Package explore explores an ochazuke application's interaction states by pressing keys, checks properties in every state it reaches, and reports bad and impossible states and actions with the shortest key path to each.
Package explore explores an ochazuke application's interaction states by pressing keys, checks properties in every state it reaches, and reports bad and impossible states and actions with the shortest key path to each.
Package grid is a two-dimensional cursor component for ochazuke: a header and rows the application owns, a cursor and viewport in two axes, a visual selection in three shapes plus marks, and one instance per focused cell, parented to a row instance, parented to a column instance, parented to the grid, so the cell, row and column nouns all sit on the focus stack.
Package grid is a two-dimensional cursor component for ochazuke: a header and rows the application owns, a cursor and viewport in two axes, a visual selection in three shapes plus marks, and one instance per focused cell, parented to a row instance, parented to a column instance, parented to the grid, so the cell, row and column nouns all sit on the focus stack.
internal
demo
Package demo is the runnable example behind `ochazuke run`: seven pages, nested draft modals, the picker and the keyboard guide, built only from the public API.
Package demo is the runnable example behind `ochazuke run`: seven pages, nested draft modals, the picker and the keyboard guide, built only from the public API.
Package keytest drives Bubble Tea models from tests using the key names that bindings use ("ctrl+c", "esc", "enter", "shift+tab", "alt+b", "space", "x").
Package keytest drives Bubble Tea models from tests using the key names that bindings use ("ctrl+c", "esc", "enter", "shift+tab", "alt+b", "space", "x").
Package markdown renders Markdown with Charm's Glamour and edits its task lists in place.
Package markdown renders Markdown with Charm's Glamour and edits its task lists in place.
cliview
Package cliview is the "markdown" detail kind of a mounted data page (cli.CatalogDetail.Kind): an editable markdown.Doc over the file the selected row's PathField names.
Package cliview is the "markdown" detail kind of a mounted data page (cli.CatalogDetail.Kind): an editable markdown.Doc over the file the selected row's PathField names.
Package refdoc builds the generated reference of an ochazuke application: a Model of its settings and default key rows, a catalog Fingerprint over it, the Markdown pages Render writes from it (each with a header naming the build it came from), and Check, which compares those pages with the committed ones.
Package refdoc builds the generated reference of an ochazuke application: a Model of its settings and default key rows, a catalog Fingerprint over it, the Markdown pages Render writes from it (each with a header naming the build it came from), and Check, which compares those pages with the committed ones.
Package story is o-story's engine: a story is data (a synthetic page, a script of events, an expectation), Build turns it into a live runtime and model, a Driver plays events against it headless, and a Recorder turns the messages of a live session into the same events.
Package story is o-story's engine: a story is data (a synthetic page, a script of events, an expectation), Build turns it into a live runtime and model, a Driver plays events against it headless, and a Recorder turns the messages of a live session into the same events.
Package strictcheck fails an application's tests when its code uses a name ochazuke has deprecated.
Package strictcheck fails an application's tests when its code uses a name ochazuke has deprecated.
Package sysstat samples the machine for status segments: CPU busy percent, memory used and total, and free disk space at a path, on macOS and Linux, without cgo.
Package sysstat samples the machine for status segments: CPU busy percent, memory used and total, and free disk space at a path, on macOS and Linux, without cgo.

Jump to

Keyboard shortcuts

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