pick

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 15 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pick draws keyboard-driven prompts on a terminal: the interactive counterpart of a flag the user did not pass.

There are three shapes of prompt:

  • A list (Select, SelectOrType, SelectManyOrType, SelectRange, SelectView) picks one row, several rows or a range of rows from many. Rows are aligned columns; typing filters them, views narrow them, and rows can carry an action, a flag, details and their own colors.
  • A text field (Input) takes a value, optionally without echoing it.
  • Switches (Toggles, Checklist) set several yes/no values at once.

Every prompt switches its input to raw mode, draws itself in place below the cursor, and erases itself before returning, restoring the terminal whatever happened. A prompt needs both its input and its output to be a terminal; otherwise it returns ErrNotATerminal and the caller falls back to its non-interactive behavior. Colors come from the active theme (see package theme) and are used only where term.Colored allows them.

Keys

In a list:

↑ ↓, Ctrl-P Ctrl-N    move the cursor
PgUp PgDn             move a page
Home End, Ctrl-A Ctrl-E
                      move to the first or last row
typing                filters the rows; every word typed has to match
Backspace, Ctrl-U     delete from the filter, or clear it
Tab Shift-Tab, → ←    switch to the next or previous view
Space                 mark a row, in a list that takes several
Enter                 choose the row, or anchor and end a range
Esc                   go back (an open range is dropped first)
Ctrl-C, Ctrl-D        interrupt

In a text field the arrows, Home and End move the caret, Ctrl-W deletes a word, Ctrl-U deletes to the start and Ctrl-K to the end. In a set of switches Space or Tab throws the switch under the cursor, "a" turns all on and "n" all off.

Errors

A prompt that is left without an answer returns an error matching ErrAborted. Two more specific errors tell why:

  • ErrBack: the user pressed Esc and wants the previous question again.
  • ErrInterrupted: the user pressed Ctrl-C or Ctrl-D, or the input was closed, and wants out of the whole run.

A caller that does not distinguish the two checks errors.Is(err, ErrAborted). A list with nothing to show returns ErrNoItems.

Example
package main

import (
	"errors"
	"fmt"
	"os"

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

func main() {
	index, err := pick.Select(os.Stdin, os.Stderr, pick.Options{
		Title:   "Which version of %s?",
		Subject: "tool",
		Items: []pick.Item{
			{Cells: []string{"1.4.2", "latest"}, Action: "install"},
			{Cells: []string{"1.3.9", "installed ✓"}, Disabled: true},
			{Cells: []string{"1.2.0 (legacy)"}, Action: "install", Muted: true},
		},
	})
	switch {
	case errors.Is(err, pick.ErrNotATerminal):
		fmt.Println("pass --version instead")
	case errors.Is(err, pick.ErrAborted):
		fmt.Println("nothing selected")
	case err == nil:
		fmt.Println("chose row", index)
	}
}

Index

Examples

Constants

View Source
const (
	// PriorityLow suits a column whose full value is available elsewhere,
	// such as in the title line through Item.Detail.
	PriorityLow = iota
	// PriorityNormal is the priority of every column not ranked otherwise.
	PriorityNormal
	// PriorityHigh suits the column a reader actually scans.
	PriorityHigh
)

Column priorities for Options.ColumnPriority. When a row does not fit the terminal, the lowest-ranked column is shortened first.

Variables

View Source
var ErrAborted = errors.New("prompt aborted")

ErrAborted reports that a prompt was left without an answer. Every way out of a prompt other than answering it matches ErrAborted, so a caller that only needs to know "nothing was chosen" checks for it alone.

View Source
var ErrBack = fmt.Errorf("%w: went back", ErrAborted)

ErrBack reports that a prompt was left with Esc, or with Backspace on an empty filter where Options.DismissOnBackspace allows it: the user wants to return to the question asked before this one. It matches ErrAborted.

View Source
var ErrInterrupted = fmt.Errorf("%w: interrupted", ErrAborted)

ErrInterrupted reports that a prompt was left with Ctrl-C or Ctrl-D, or that its input was closed: the user wants out of the whole run, not just this question. It matches ErrAborted.

View Source
var ErrNoItems = errors.New("pick: nothing to select")

ErrNoItems reports that there was nothing to choose from. The caller knows what an empty list means in its context and says so itself.

View Source
var ErrNotATerminal = errors.New("pick: not a terminal")

ErrNotATerminal reports that the input or the output of a prompt is not a terminal, so nothing can be drawn. Callers fall back to their non-interactive behavior, such as requiring a flag.

Functions

func Checklist

func Checklist(in, out *os.File, opts ChecklistOptions) ([]bool, error)

Checklist draws a list of boxes and returns which were left ticked, in the order given. It takes the same keys as Toggles, but draws the box in front of each label, with the label's note beside it, the way a form does.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	ticked, err := pick.Checklist(os.Stdin, os.Stderr, pick.ChecklistOptions{
		Title: "Which tokens should be created?",
		Boxes: []pick.Box{
			{Label: "feed", Note: "calendar feed", Checked: true},
			{Label: "smtp", Note: "send mail"},
		},
	})
	if err == nil {
		fmt.Println(ticked)
	}
}

func Input

func Input(in, out *os.File, opts InputOptions) (string, error)

Input draws a one-line text field and returns what was typed. The field supports the usual line-editing keys: the arrows, Home and End (or Ctrl-A and Ctrl-E), Backspace and Delete, Ctrl-W to delete a word, Ctrl-U to delete to the start, and Ctrl-K to delete to the end. Enter answers, Esc returns ErrBack, and Ctrl-C or Ctrl-D returns ErrInterrupted. A cleared field answers with the empty string.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	password, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{
		Prompt:  "Password for %s: ",
		Subject: "alice@example.com",
		Secret:  true,
	})
	if err == nil && password != "" {
		fmt.Println("got a password")
	}
}

func Name

func Name(w io.Writer, text string) string

Name renders a value the way a list draws a row's name: in the subject style, with whatever it says in parentheses receding. Use it for lines written beside the prompts, so a value reads the same whether it is being chosen or reported. Where w takes no color it returns text unchanged.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	fmt.Println("Installing", pick.Name(os.Stdout, "tool (stable)"))
}
Output:
Installing tool (stable)

func Prompt

func Prompt(w io.Writer, prompt, subject string) string

Prompt renders a question the way Input draws it: the subject styled where the question holds %s for it, and the answers it spells out, such as y/N, receding. Use it for the line that keeps an answered prompt on screen once the field has erased itself. Where w takes no color it returns the question with the subject filled in.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	// Off a terminal the prompt is plain text with the subject filled in.
	fmt.Println(pick.Prompt(os.Stdout, "Recreate %s? [y/N]: ", "tool-1.2") + "y")
}
Output:
Recreate tool-1.2? [y/N]: y

func Select

func Select(in, out *os.File, opts Options) (int, error)

Select draws the list on out, reads keys from in, and returns the index of the item chosen: an index into opts.Items, or, with views that hold their own rows, into the Items of the view the list ended on (see SelectView). in is switched to raw mode for the duration and restored before returning, and the drawn block is erased so the caller's output starts on a clean line. With Options.Range, Select returns the first row of the range.

func SelectManyOrType

func SelectManyOrType(in, out *os.File, opts Options) ([]int, []string, error)

SelectManyOrType is SelectOrType for a list that takes several rows at once: Space marks the row under the cursor or unmarks it, and Enter answers with every row marked. It returns the indexes of the items marked, in the order of opts.Items, and the texts typed and marked, in the order they were marked. With nothing marked, Enter answers with the row under the cursor. Space marks rather than filters, so the filter is a single term.

func SelectOrType

func SelectOrType(in, out *os.File, opts Options) (int, string, error)

SelectOrType is Select for a list that also takes an answer it does not hold (see Options.Typed). It returns the index of the item chosen and "", or -1 and the text typed. A list without items is drawn all the same as long as it takes typed answers. It cannot be combined with views that hold their own rows.

Example
package main

import (
	"fmt"
	"os"
	"strings"

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

func main() {
	versions := []pick.Item{{Cells: []string{"1.4.2"}}, {Cells: []string{"1.4.1"}}}
	index, typed, err := pick.SelectOrType(os.Stdin, os.Stderr, pick.Options{
		Title:     "Release which version?",
		Items:     versions,
		Typed:     func(text string) bool { return strings.Count(text, ".") == 2 },
		TypedNote: "new version",
	})
	if err != nil {
		return
	}
	if index < 0 {
		fmt.Println("new version", typed)
	}
}

func SelectRange

func SelectRange(in, out *os.File, opts Options) (first, last int, err error)

SelectRange is Select for a list with Options.Range: it returns the two ends of the chosen range in the order the rows are drawn, first above last. Without Options.Range both are the row chosen.

Example
package main

import (
	"fmt"
	"os"

	"github.com/mittwald/cli-kit/pick"
	"github.com/mittwald/cli-kit/theme"
)

func main() {
	first, last, err := pick.SelectRange(os.Stdin, os.Stderr, pick.Options{
		Title: "Which changes?",
		Items: []pick.Item{
			{Cells: []string{"c3", "newest"}, Detail: "c3"},
			{Cells: []string{"b2", "middle"}, Detail: "b2"},
			{Cells: []string{"a1", "oldest"}, Detail: "a1"},
		},
		Range:      true,
		RangeUnit:  "change",
		CellStyles: []theme.Style{theme.Fg256(71)},
	})
	if err == nil {
		fmt.Println(first, last)
	}
}

func SelectView

func SelectView(in, out *os.File, opts Options) (view, index int, err error)

SelectView is Select for a list of views: it returns the index of the view the list ended on and the index of the item chosen. For views that hold their own rows the item index refers to that view's Items, otherwise to opts.Items.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	view, index, err := pick.SelectView(os.Stdin, os.Stderr, pick.Options{
		Title: "Pick a branch",
		Views: []pick.View{
			{Name: "local", Items: []pick.Item{{Cells: []string{"main"}, Key: "main"}}},
			{Name: "remote", Loading: "fetching remote branches…", Load: func() ([]pick.Item, error) {
				return []pick.Item{{Cells: []string{"origin/main"}, Key: "main"}}, nil
			}},
		},
		ColumnPriority:   []int{pick.PriorityHigh},
		ColumnTruncation: []pick.Truncation{pick.TruncateMiddle},
	})
	if err == nil {
		fmt.Println(view, index)
	}
}

func Status

func Status(w io.Writer, text string) func()

Status writes text as a line of its own (or several, where it has newlines) and returns a function that erases it again. Use it for what is only of interest while it lasts, such as "Fetching releases...". On a terminal the text is muted and the returned function takes it back off the screen; anywhere else the line stays, since a log is read after the fact.

The returned function erases by counting screen rows up from the cursor, so it must be called before anything else is written.

Example
package main

import (
	"os"

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

func main() {
	done := pick.Status(os.Stdout, "Fetching releases...")
	// ... fetch ...
	done() // erases the line on a terminal; keeps it anywhere else
}
Output:
Fetching releases...

func Toggles

func Toggles(in, out *os.File, opts ToggleOptions) ([]bool, error)

Toggles draws a set of switches and returns the position each was left in, in the order given. The arrows move the cursor, Space or Tab throws the switch under it, "a" turns all on and "n" all off, and Enter answers. A thrown switch shows what it was before. Esc returns ErrBack and Ctrl-C or Ctrl-D returns ErrInterrupted, without values.

Example
package main

import (
	"fmt"
	"os"

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

func main() {
	values, err := pick.Toggles(os.Stdin, os.Stderr, pick.ToggleOptions{
		Title:   "Settings for %s",
		Subject: "service-a",
		Toggles: []pick.Toggle{
			{Label: "Enabled", On: "enabled", Off: "disabled", Value: true},
			{Label: "Public", On: "public", Off: "private"},
		},
	})
	if err == nil {
		fmt.Println(values)
	}
}

Types

type Box

type Box struct {
	Label   string
	Note    string
	Checked bool
}

Box is one row of a checklist: what it is called, an optional note on what ticking it means, and whether it starts ticked.

type ChecklistOptions

type ChecklistOptions struct {
	// Title is the question, with one %s where Subject goes.
	Title string
	// Subject is the thing the checklist is about.
	Subject string
	// Note is an optional line under the title.
	Note  string
	Boxes []Box
	// Initial is the box the cursor starts on.
	Initial int
	// Nested names Esc "back" instead of "cancel" in the key line.
	Nested bool
}

ChecklistOptions configures one checklist.

type Field

type Field struct {
	Text  string
	Style theme.Style
}

Field is one part of an item's Details.

type InputOptions

type InputOptions struct {
	// Prompt is written in front of the value, with one %s where Subject
	// goes, such as "Name for %s: ". Anything more to say belongs on a line
	// the caller prints before the prompt, which stays on screen when the
	// prompt is erased.
	Prompt string
	// Subject is the thing the prompt is about, drawn in the theme's subject
	// style inside the prompt.
	Subject string
	// Value is what the field starts out holding, with the cursor at its end.
	Value string
	// Secret draws nothing for what is typed, the way a password prompt does.
	Secret bool
}

InputOptions configures one text prompt. The prompt is a single line with the terminal's own cursor in the text, so it reads like any other prompt a terminal puts up.

type Item

type Item struct {
	// Cells are the row's columns. The first names the row and carries the
	// weight; text in parentheses inside it recedes. Later cells qualify the
	// row and recede as a whole.
	Cells []string
	// Action is what choosing the row does, such as "install" or "merge #31".
	// It is drawn after every cell, in a lane and a color of its own, so the
	// thing a row is decided on sits in the same place on every row.
	Action string
	// Disabled marks a row there is nothing to do with: it is drawn receded
	// and Enter on it does nothing.
	Disabled bool
	// Muted recedes a row the way Disabled does, but it can still be chosen:
	// something that can be done, but that nobody is waiting on.
	Muted bool
	// Flag is a mark drawn right after the first cell in the theme's flag
	// color, on every row alike: something about the name worth stopping at.
	Flag string
	// Match overrides what type-to-filter searches. By default it searches
	// every cell and the action.
	Match string
	// MatchFields splits what the filter searches into parts, each of which
	// may demand a minimum term length: a field a short term must not reach,
	// such as an opaque identifier where any two characters hit some row, sets
	// MinTerm. It replaces Match when set.
	MatchFields []MatchField
	// Groups are the kinds of row this is, which views narrow the list by. A
	// row may be of several kinds and then shows in the view of each.
	Groups []string
	// Key identifies the row across views that hold their own rows: when the
	// view changes, the cursor stays on the row with the same key. Rows
	// without a key match nothing, and the cursor starts at the top.
	Key string
	// CellStyles overrides Options.CellStyles for this row, indexed like
	// Cells. An empty style falls back to the column's style.
	CellStyles []theme.Style
	// Detail is the row's full value, shown after the title while the row is
	// under the cursor. What a narrow column had to shorten stays readable
	// there.
	Detail string
	// Details is Detail in several parts, each in its own style, joined by
	// the separator the list uses elsewhere. It replaces Detail when set.
	Details []Field
}

Item is one selectable row. Cells are drawn as aligned columns, the first of them naming what the row is.

type Lens

type Lens struct {
	Filter string
	View   string
}

Lens is how a list was narrowed: what was typed into its filter and the name of the view it was left on.

type MatchField

type MatchField struct {
	Text    string
	MinTerm int
}

MatchField is one searchable part of a row. MinTerm is the shortest filter term that may search it; 0 lets every term through.

type Options

type Options struct {
	// Title is the question, drawn above the rows. It may hold one %s where
	// Subject goes.
	Title string
	// Subject is the thing the question is about, drawn in the theme's
	// subject style inside the title.
	Subject string
	// Note is an optional line under the title for what has to be said about
	// the offer as a whole.
	Note string
	// Items are the rows.
	Items []Item
	// Views are the ways of looking at the list that Tab switches between.
	// Views that narrow Items need at least two to be shown at all.
	Views []View
	// View is the index of the view the list opens on.
	View int
	// Initial is the index of the item the cursor starts on. An item the
	// filter or view hides, or an index out of range, starts at the first row.
	Initial int
	// MaxVisible caps how many rows are drawn at once; 0 derives the cap from
	// the terminal height.
	MaxVisible int
	// Hint replaces the key line under the list.
	Hint string
	// Nested says the list was opened from another prompt, so the key line
	// names Esc "back" instead of "cancel". Esc returns ErrBack either way.
	Nested bool
	// DismissOnBackspace lets Backspace on an empty filter leave the list the
	// way Esc does. It suits a nested prompt, where Backspace reads as back.
	DismissOnBackspace bool
	// Typed lets the list take an answer it does not hold: the filter is
	// offered as a row of its own, after the rows it matches, as long as
	// Typed accepts it and no row's first cell is exactly that text. Only
	// SelectOrType and SelectManyOrType honor it.
	Typed func(string) bool
	// TypedNote is what the typed row says about itself, in its second
	// column.
	TypedNote string
	// Lens, when set, is the filter and view the list opens on, and is left
	// holding the ones the list was closed on, so the next list about the
	// same rows opens narrowed the same way.
	Lens *Lens
	// CellStyles colors the columns, indexed like Item.Cells. Columns without
	// a style are drawn the default way: the first bold, the rest receding.
	CellStyles []theme.Style
	// PaintCell paints inside a cell, for columns whose parts deserve colors
	// of their own. It gets the column, the cell text already cut to its
	// column, and whether the row is under the cursor, and returns the
	// painted text and true, or false to leave the cell to the default
	// styles. It is called only when color is on and the row is not receded.
	PaintCell func(column int, text string, selected bool) (string, bool)
	// DetailStyle is the style of Item.Detail in the title line; the theme's
	// info style when empty.
	DetailStyle theme.Style
	// ColumnPriority ranks the columns, indexed like Item.Cells, by how long
	// they keep their width when a row does not fit: the lowest-ranked column
	// is shortened first. Unranked columns are PriorityNormal.
	ColumnPriority []int
	// ColumnTruncation says how each column's cells are shortened, indexed
	// like Item.Cells. Unlisted columns are TruncateEnd.
	ColumnTruncation []Truncation
	// Range turns the list into a range selection: the first Enter anchors
	// the range on the row under the cursor, moving extends it, and the
	// second Enter ends the list. Esc drops an open range before it leaves
	// the list. Read the range back with SelectRange.
	Range bool
	// RangeUnit names what the range covers, in the singular ("commit"), for
	// the summary in the title line; an "s" is appended for any count but
	// one.
	RangeUnit string
	// contains filtered or unexported fields
}

Options configures one list.

type Toggle

type Toggle struct {
	Label string
	On    string
	Off   string
	Value bool
}

Toggle is one switch: what it is called, the two words its positions stand for, and where it starts. On and Off are the caller's vocabulary, such as "enabled" and "disabled"; they default to "yes" and "no".

type ToggleOptions

type ToggleOptions struct {
	// Title is the question, with one %s where Subject goes.
	Title string
	// Subject is the thing the switches belong to.
	Subject string
	// Note is an optional line under the title.
	Note    string
	Toggles []Toggle
	// Initial is the switch the cursor starts on.
	Initial int
	// Nested names Esc "back" instead of "cancel" in the key line.
	Nested bool
}

ToggleOptions configures one set of switches.

type Truncation

type Truncation int

Truncation is how a cell too wide for its column is shortened.

const (
	// TruncateEnd cuts the end of the cell. It is the default.
	TruncateEnd Truncation = iota
	// TruncateMiddle cuts the middle of the cell, keeping both ends: right for
	// values told apart by their ends, such as long identifiers or paths.
	TruncateMiddle
)

type View

type View struct {
	// Name labels the view in the status line. An empty name is shown as the
	// view's position.
	Name string
	// Groups narrows Options.Items to the rows of these groups.
	Groups []string
	// Title replaces Options.Title while the view is shown.
	Title string
	// Items are the view's own rows.
	Items []Item
	// Load supplies the view's rows the first time it is shown, for rows that
	// are expensive to produce. The list shows Loading in their place, runs
	// Load once, and keeps what it returns. A failure is shown where the rows
	// would be, together with whatever rows Load did return.
	Load func() ([]Item, error)
	// Loading is the line shown while Load runs; "" uses a default.
	Loading string
	// Empty is the line shown in place of rows when the view has none; ""
	// uses a default.
	Empty string
}

View is one way of looking at a list. Tab and the right arrow switch to the next view, Shift-Tab and the left arrow to the previous one, and the filter carries over.

A view either narrows Options.Items to the rows with a group among Groups (every row when Groups is empty), or holds rows of its own in Items or Load. When any view holds its own rows, all of them do: a view with neither Items nor Load is then empty, and row indexes refer to the items of the view the list ended on.

Jump to

Keyboard shortcuts

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