textinput

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 14 Imported by: 54

Documentation

Overview

Package textinput implements prompts for string input. It provides a single-line text input that can also be used for secret strings such as passwords, and a multi-line text area for longer form input. Both offer customizable appearance as well as optional support for input validation and a customizable key map.

Index

Constants

View Source
const (
	// DefaultAreaTemplate defines the default appearance of the text area and
	// can be copied as a starting point for a custom template.
	DefaultAreaTemplate = `` /* 355-byte string literal not displayed */

	// DefaultAreaResultTemplate defines the default appearance with which the
	// final result of the prompt is presented.
	DefaultAreaResultTemplate = `{{- print .Prompt "\n" (Foreground "32" .FinalValue) "\n" -}}`
)
View Source
const (
	// DefaultTemplate defines the default appearance of the text input and can
	// be copied as a starting point for a custom template.
	DefaultTemplate = `
	{{- Bold .Prompt }} {{ .Input -}}
	{{- if .ValidationError }} {{ Foreground "1" (Bold "✘") }}
	{{- else }} {{ Foreground "2" (Bold "✔") }}
	{{- end -}}` +
		`{{- if .AutoCompleteIndecisive }}` +
		`{{ range AutoCompleteSuggestions }}` +
		`{{ "\n" }}{{ Repeat " " $.CursorOffset }}{{ Faint (TrimPrefix . $.InputValue) }}` +
		`{{ end }}{{ end -}}`

	// DefaultResultTemplate defines the default appearance with which the
	// finale result of the prompt is presented.
	DefaultResultTemplate = `
	{{- print .Prompt " " (Foreground "32"  (Mask .FinalValue)) "\n" -}}
	`

	// DefaultMask specified the character with which the input is masked by
	// default if Hidden is true.
	DefaultMask = '●'
)

Variables

View Source
var ErrInputValidation = fmt.Errorf("validation error")

ErrInputValidation is a generic input validation error. For more detailed diagnosis, feel free to return any custom error instead.

Functions

func AutoCompleteFromSlice added in v0.7.0

func AutoCompleteFromSlice(choices []string) func(string) []string

AutoCompleteFromSlice creates a case-insensitive auto-complete function from a slice of choices.

func AutoCompleteFromSliceWithDefault added in v0.7.0

func AutoCompleteFromSliceWithDefault(
	choices []string, defaultValue string,
) func(string) []string

AutoCompleteFromSliceWithDefault creates a case-insensitive auto-complete function from a slice of choices with a default completion value that is inserted if the function is called on an empty input.

func CaseSensitiveAutoCompleteFromSlice added in v0.7.0

func CaseSensitiveAutoCompleteFromSlice(choices []string) func(string) []string

CaseSensitiveAutoCompleteFromSlice creates a case-sensitive auto-complete function from a slice of choices.

func CaseSensitiveAutoCompleteFromSliceWithDefault added in v0.7.0

func CaseSensitiveAutoCompleteFromSliceWithDefault(
	choices []string, defaultValue string,
) func(string) []string

CaseSensitiveAutoCompleteFromSliceWithDefault creates a case-sensitive auto-complete function from a slice of choices with a default completion value that is inserted if the function is called on an empty input.

func ValidateNotEmpty added in v0.7.0

func ValidateNotEmpty(s string) error

ValidateNotEmpty is a validation function that ensures that the input is not empty.

Types

type AreaKeyMap added in v0.12.0

type AreaKeyMap struct {
	MoveBackward           []string
	MoveForward            []string
	MoveWordBackward       []string
	MoveWordForward        []string
	MoveUp                 []string
	MoveDown               []string
	JumpToLineBeginning    []string
	JumpToLineEnd          []string
	JumpToBeginning        []string
	JumpToEnd              []string
	DeleteBeforeCursor     []string
	DeleteWordBeforeCursor []string
	DeleteUnderCursor      []string
	DeleteWordAfterCursor  []string
	DeleteAllAfterCursor   []string
	DeleteAllBeforeCursor  []string
	InsertNewline          []string
	Paste                  []string
	Submit                 []string
	Abort                  []string
}

AreaKeyMap defines the keys that trigger certain actions in the text area.

func NewDefaultAreaKeyMap added in v0.12.0

func NewDefaultAreaKeyMap() *AreaKeyMap

NewDefaultAreaKeyMap returns an AreaKeyMap with sensible default key mappings that can also be used as a starting point for customization.

type AreaModel added in v0.12.0

type AreaModel struct {
	*TextArea

	// Err holds errors that may occur during the execution of the text area.
	Err error

	// MaxWidth limits the width of the view using the TextArea's WrapMode.
	MaxWidth int
	// contains filtered or unexported fields
}

AreaModel implements the bubbletea.Model for a text area.

func NewAreaModel added in v0.12.0

func NewAreaModel(textArea *TextArea) *AreaModel

NewAreaModel returns a new model based on the provided text area.

func (*AreaModel) Init added in v0.12.0

func (m *AreaModel) Init() tea.Cmd

Init initializes the text area model.

func (*AreaModel) Update added in v0.12.0

func (m *AreaModel) Update(message tea.Msg) (tea.Model, tea.Cmd)

Update updates the model based on the received message.

func (*AreaModel) Value added in v0.12.0

func (m *AreaModel) Value() (string, error)

Value returns the current value and error.

func (*AreaModel) View added in v0.12.0

func (m *AreaModel) View() tea.View

View renders the text area.

type KeyMap

type KeyMap struct {
	MoveBackward           []string
	MoveForward            []string
	JumpToBeginning        []string
	JumpToEnd              []string
	DeleteBeforeCursor     []string
	DeleteWordBeforeCursor []string
	DeleteUnderCursor      []string
	DeleteAllAfterCursor   []string
	DeleteAllBeforeCursor  []string
	AutoComplete           []string
	Paste                  []string
	Clear                  []string
	Reset                  []string
	Submit                 []string
	Abort                  []string
}

KeyMap defines the keys that trigger certain actions.

func NewDefaultKeyMap

func NewDefaultKeyMap() *KeyMap

NewDefaultKeyMap returns a KeyMap with sensible default key mappings that can also be used as a starting point for customization.

type Model

type Model struct {
	*TextInput

	// Err holds errors that may occur during the execution of
	// the textinput.
	Err error

	// MaxWidth limits the width of the view using the TextInput's WrapMode.
	MaxWidth int
	// contains filtered or unexported fields
}

Model implements the bubbletea.Model for a text input.

func NewModel

func NewModel(textInput *TextInput) *Model

NewModel returns a new model based on the provided text input.

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init initializes the text input model.

func (*Model) Update

func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd)

Update updates the model based on the received message.

func (*Model) Value

func (m *Model) Value() (string, error)

Value returns the current value and error.

func (*Model) View

func (m *Model) View() tea.View

View renders the text input.

type TextArea added in v0.12.0

type TextArea struct {
	// Prompt holds the prompt text or question that is printed above the
	// text area in the default template (if not empty).
	Prompt string

	// Placeholder holds the text that is displayed in the text area when no
	// input has been entered yet.
	Placeholder string

	// InitialValue sets the initial content of the text area, as if it had
	// been entered by the user. This can be used to provide an editable
	// default value.
	InitialValue string

	// Validate is a function that validates whether the current input is
	// valid. If it is not, the data cannot be submitted. By default, Validate
	// ensures that the input is not empty. If Validate is set to nil, no
	// validation is performed.
	Validate func(string) error

	// CharLimit is the maximum number of characters this text area will
	// accept. If 0 or less, there is no limit.
	CharLimit int

	// Height is the number of visible rows in the text area. If 0 or less,
	// the text area automatically expands and contracts to fit the content.
	// Defaults to 0 (auto-expand). Set to DefaultAreaHeight or another
	// positive value for a fixed-height text area.
	Height int

	// ShowLineNumbers specifies whether line numbers are displayed. Defaults
	// to false.
	ShowLineNumbers bool

	// Template holds the display template. A custom template can be used to
	// completely customize the appearance of the text area. If empty,
	// DefaultAreaTemplate is used. The following variables and functions are
	// available:
	//
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value.
	//  * Placeholder string: The configured placeholder.
	//  * Input string: The rendered text area widget.
	//  * ValidationError error: The error returned by Validate.
	//  * TerminalWidth int: The width of the terminal.
	//  * KeyMap *AreaKeyMap: The configured key map.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	Template string

	// ResultTemplate is rendered once input has been confirmed. It is
	// intended to permanently indicate the result of the prompt. This
	// template is only rendered in RunPrompt() and NOT when the text area is
	// used as a model. The following variables and functions are available:
	//
	//  * FinalValue string: The submitted text.
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value.
	//  * Placeholder string: The configured placeholder.
	//  * TerminalWidth int: The width of the terminal.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	ResultTemplate string

	// ExtendedTemplateFuncs can be used to add additional functions to the
	// evaluation scope of the templates.
	ExtendedTemplateFuncs template.FuncMap

	// InputTextStyle is the style applied to the text in the text area.
	InputTextStyle lipgloss.Style

	// InputPlaceholderStyle is the style applied to the placeholder text.
	InputPlaceholderStyle lipgloss.Style

	// KeyMap determines with which keys the text area is controlled. By
	// default, NewDefaultAreaKeyMap() is used.
	KeyMap *AreaKeyMap

	// WrapMode decides which way the prompt view is wrapped if it does not
	// fit the terminal. It can be a WrapMode provided by promptkit or a
	// custom function. By default it is promptkit.WordWrap. It can also be
	// nil which disables wrapping and likely causes output glitches.
	WrapMode promptkit.WrapMode

	// Output is the output writer, by default os.Stdout is used.
	Output io.Writer
	// Input is the input reader, by default os.Stdin is used.
	Input io.Reader

	// ColorProfile determines how colors are rendered. By default, the
	// terminal is queried.
	ColorProfile termenv.Profile
}

TextArea represents a configurable multi-line text area prompt.

func NewArea added in v0.12.0

func NewArea(prompt string) *TextArea

NewArea creates a new text area prompt. See the TextArea properties for more documentation.

func (*TextArea) RunPrompt added in v0.12.0

func (t *TextArea) RunPrompt() (string, error)

RunPrompt executes the text area prompt.

type TextInput

type TextInput struct {
	// Prompt holds the prompt text or question that is printed above the
	// choices in the default template (if not empty).
	Prompt string

	// Placeholder holds the text that is displayed in the input field when the
	// input data is empty, e.g. when no text was entered yet.
	Placeholder string

	// InitialValue is similar to Placeholder, however, the actual input data is
	// set to InitialValue such that as if it was entered by the user. This can
	// be used to provide an editable default value.
	InitialValue string

	// Validate is a function that validates whether the current input data is
	// valid. If it is not, the data cannot be submitted. By default, Validate
	// ensures that the input data is not empty. If Validate is set to nil, no
	// validation is performed.
	Validate func(string) error

	// AutoComplete is a function that suggests multiple candidates for
	// auto-completion based on a given input. If it returns only a single
	// candidate, this candidate is auto-completed. If it returns multiple
	// candidates, these candidates may be displayed in custom templates using
	// the variables AutoCompleteTriggered, AutoCompleteIndecisive as well as
	// the function AutoCompleteSuggestions. If AutoComplete is nil, no
	// auto-completion is performed.
	AutoComplete func(string) []string

	// Hidden specified whether or not the input data is considered secret and
	// should be masked. This is useful for password prompts.
	Hidden bool

	// HideMask specified the character with which the input data should be
	// masked when Hidden is set to true.
	HideMask rune

	// CharLimit is the maximum amount of characters this input element will
	// accept. If 0 or less, there's no limit.
	CharLimit int

	// InputWidth is the maximum number of characters that can be displayed at
	// once. It essentially treats the text field like a horizontally scrolling
	// viewport. If 0 or less this setting is ignored.
	InputWidth int

	// Template holds the display template. A custom template can be used to
	// completely customize the appearance of the text input. If empty,
	// the DefaultTemplate is used. The following variables and functions are
	// available:
	//
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value of the input.
	//  * Placeholder string: The configured placeholder of the input.
	//  * Input string: The actual input field.
	//  * InputValue string: The raw current input value.
	//  * ValidationError error: The error value returned by Validate.
	//    to the configured Validate function.
	//  * TerminalWidth int: The width of the terminal.
	//  * AutoCompleteTriggered bool: An indication that auto-complete was
	//    just triggered by the user. It resets after further input.
	//  * AutoCompleteIndecisive bool: An indication that auto-complete was
	//    just triggered by the user with an indecisive result. It resets
	//    after further input.
	//  * CursorOffset int: The column offset of the cursor in the current line,
	//    useful for aligning content below the input.
	//  * AutoCompleteSuggestions() []string: A function that returns the
	//    auto-complete suggestions for the current input.
	//  * KeyMap *KeyMap: The configured key map.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	Template string

	// ResultTemplate is rendered as soon as a input has been confirmed.
	// It is intended to permanently indicate the result of the prompt when the
	// input itself has disappeared. This template is only rendered in the Run()
	// method and NOT when the text input is used as a model. The following
	// variables and functions are available:
	//
	//  * FinalChoice: The choice that was selected by the user.
	//  * Prompt string: The configured prompt.
	//  * InitialValue string: The configured initial value of the input.
	//  * Placeholder string: The configured placeholder of the input.
	//  * InputValue string: The raw current input value.
	//  * TerminalWidth int: The width of the terminal.
	//  * AutoCompleteTriggered bool: An indication that auto-complete was
	//    just triggered by the user. It resets after further input.
	//  * AutoCompleteIndecisive bool: An indication that auto-complete was
	//    just triggered by the user with an indecisive result. It resets
	//    after further input.
	//  * CursorOffset int: The column offset of the cursor in the current line,
	//    useful for aligning content below the input.
	//  * AutoCompleteSuggestions() []string: A function that returns the
	//    auto-complete suggestions for the current input.
	//  * Mask(string) string: A function that replaces all characters of
	//    a string with the character specified in HideMask if Hidden is
	//    true and returns the input string if Hidden is false.
	//  * promptkit.UtilFuncMap: Handy helper functions.
	//  * termenv TemplateFuncs (see https://github.com/muesli/termenv).
	//  * The functions specified in ExtendedTemplateFuncs.
	ResultTemplate string

	// ExtendedTemplateFuncs can be used to add additional functions to the
	// evaluation scope of the templates.
	ExtendedTemplateFuncs template.FuncMap

	// Styles of the actual input field. These will be applied as inline styles.
	//
	// For an introduction to styling with Lip Gloss see:
	// https://github.com/charmbracelet/lipgloss
	InputTextStyle        lipgloss.Style
	InputBackgroundStyle  lipgloss.Style // Deprecated: This property is not used anymore.
	InputPlaceholderStyle lipgloss.Style
	InputCursorStyle      lipgloss.Style

	// KeyMap determines with which keys the text input is controlled. By
	// default, DefaultKeyMap is used.
	KeyMap *KeyMap

	// WrapMode decides which way the prompt view is wrapped if it does not fit
	// the terminal. It can be a WrapMode provided by promptkit or a custom
	// function. By default it is promptkit.WordWrap. It can also be nil which
	// disables wrapping and likely causes output glitches.
	WrapMode promptkit.WrapMode

	// Output is the output writer, by default os.Stdout is used.
	Output io.Writer
	// Input is the input reader, by default, os.Stdin is used.
	Input io.Reader

	// ColorProfile determines how colors are rendered. By default, the terminal
	// is queried.
	ColorProfile termenv.Profile
}

TextInput represents a configurable selection prompt.

func New

func New(prompt string) *TextInput

New creates a new text input. See the TextInput properties for more documentation.

func (*TextInput) RunPrompt

func (t *TextInput) RunPrompt() (string, error)

RunPrompt executes the text input prompt.

Jump to

Keyboard shortcuts

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