package promptui
Import Path
github.com/manifoldco/promptui (on go.dev)
Dependency Relation
imports 12 packages, and imported by 2 packages
Involved Source Files
codes.go
cursor.go
keycodes.go
keycodes_other.go
prompt.go
Package promptui is a library providing a simple interface to create command-line prompts for go.
It can be easily integrated into spf13/cobra, urfave/cli or any cli go application.
promptui has two main input modes:
Prompt provides a single line for user input. It supports optional live validation,
confirmation and masking the input.
Select provides a list of options to choose from. It supports pagination, search,
detailed view and custom templates.
select.go
styles.go
Code Examples
{
validate := func(input string) error {
_, err := strconv.ParseFloat(input, 64)
return err
}
templates := &PromptTemplates{
Prompt: "{{ . }} ",
Valid: "{{ . | green }} ",
Invalid: "{{ . | red }} ",
Success: "{{ . | bold }} ",
}
prompt := Prompt{
Label: "Spicy Level",
Templates: templates,
Validate: validate,
}
result, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
fmt.Printf("You answered %s\n", result)
}
package main
import (
"fmt"
"strings"
)
// Any type can be given to the select's item as long as the templates properly implement the dot notation
// to display it.
type pepper struct {
Name string
HeatUnit int
Peppers int
}
// This examples shows a complex and customized select.
func main() {
// The select will show a series of peppers stored inside a slice of structs. To display the content of the struct,
// the usual dot notation is used inside the templates to select the fields and color them.
peppers := []pepper{
{Name: "Bell Pepper", HeatUnit: 0, Peppers: 0},
{Name: "Banana Pepper", HeatUnit: 100, Peppers: 1},
{Name: "Poblano", HeatUnit: 1000, Peppers: 2},
{Name: "Jalapeño", HeatUnit: 3500, Peppers: 3},
{Name: "Aleppo", HeatUnit: 10000, Peppers: 4},
{Name: "Tabasco", HeatUnit: 30000, Peppers: 5},
{Name: "Malagueta", HeatUnit: 50000, Peppers: 6},
{Name: "Habanero", HeatUnit: 100000, Peppers: 7},
{Name: "Red Savina Habanero", HeatUnit: 350000, Peppers: 8},
{Name: "Dragon’s Breath", HeatUnit: 855000, Peppers: 9},
}
// The Active and Selected templates set a small pepper icon next to the name colored and the heat unit for the
// active template. The details template is show at the bottom of the select's list and displays the full info
// for that pepper in a multi-line template.
templates := &SelectTemplates{
Label: "{{ . }}?",
Active: "\U0001F336 {{ .Name | cyan }} ({{ .HeatUnit | red }})",
Inactive: " {{ .Name | cyan }} ({{ .HeatUnit | red }})",
Selected: "\U0001F336 {{ .Name | red | cyan }}",
Details: `
--------- Pepper ----------
{{ "Name:" | faint }} {{ .Name }}
{{ "Heat Unit:" | faint }} {{ .HeatUnit }}
{{ "Peppers:" | faint }} {{ .Peppers }}`,
}
// A searcher function is implemented which enabled the search mode for the select. The function follows
// the required searcher signature and finds any pepper whose name contains the searched string.
searcher := func(input string, index int) bool {
pepper := peppers[index]
name := strings.Replace(strings.ToLower(pepper.Name), " ", "", -1)
input = strings.Replace(strings.ToLower(input), " ", "", -1)
return strings.Contains(name, input)
}
prompt := Select{
Label: "Spicy Level",
Items: peppers,
Templates: templates,
Size: 4,
Searcher: searcher,
}
i, _, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
// The selected pepper will be displayed with its name and index in a formatted message.
fmt.Printf("You choose number %d: %s\n", i+1, peppers[i].Name)
}
{
items := []string{"Vim", "Emacs", "Sublime", "VSCode", "Atom"}
index := -1
var result string
var err error
for index < 0 {
prompt := SelectWithAdd{
Label: "What's your text editor",
Items: items,
AddLabel: "Add your own",
}
index, result, err = prompt.Run()
if index == -1 {
items = append(items, result)
}
}
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
fmt.Printf("You choose %s\n", result)
}
{
validate := func(input string) error {
_, err := strconv.ParseFloat(input, 64)
if err != nil {
return errors.New("Invalid number")
}
return nil
}
prompt := Prompt{
Label: "Number",
Validate: validate,
}
result, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
fmt.Printf("You choose %q\n", result)
}
{
prompt := Select{
Label: "Select Day",
Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"},
}
_, result, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
fmt.Printf("You choose %q\n", result)
}
Package-Level Type Names (total 11, in which 10 are exported)
Cursor tracks the state associated with the movable cursor
The strategy is to keep the prompt, input pristine except for requested
modifications. The insertion of the cursor happens during a `format` call
and we read in new input via an `Update` call
shows where the user inserts/updates text
Put the cursor before this slice
erase bool
what the user entered, and what we will echo back to them, after
insertion of the cursor and prefixing with the prompt
Backspace removes the rune that precedes the cursor
It handles being at the beginning or end of the row, and moves the cursor to
the appropriate position.
End is a convenience for c.Place(len(c.input)) so you don't have to know how I
indexed.
Format renders the input with the Cursor appropriately positioned.
FormatMask replaces all input runes with the mask rune.
Get returns a copy of the input
GetMask returns a mask string with length equal to the input
Listen is a readline Listener that updates internal cursor state appropriately.
Move moves the cursor over in relative terms, by shift indices.
Place moves the cursor to the absolute array index specified by position
Replace replaces the previous input with whatever is specified, and moves the
cursor to the end position
Start is convenience for c.Place(0) so you don't have to know how I
indexed.
(*T) String() string
Update inserts newinput into the input []rune in the appropriate place.
The cursor is moved to the end of the inputed sequence.
ensures we are in bounds.
*T : fmt.Stringer
*T : context.stringer
*T : os/signal.stringer
*T : runtime.stringer
func NewCursor(startinginput string, pointer Pointer, eraseDefault bool) Cursor
func format(a []rune, c *Cursor) string
Key defines a keyboard code and a display representation for the help menu.
Code is a rune that will be used to compare against typed keys with readline.
Check https://github.com/chzyer/readline for a list of codes
Display is the string that will be displayed inside the help menu to help inform the user
of which key to use on his keyboard for various functions.
Pointer is A specific type that translates a given set of runes into a given
set of runes pointed at by the cursor.
func NewCursor(startinginput string, pointer Pointer, eraseDefault bool) Cursor
var BlockCursor
var DefaultCursor
var PipeCursor
Prompt represents a single line text field input with options for validation and input masks.
AllowEdit lets the user edit the default value. If false, any key press
other than <Enter> automatically clears the default value.
Default is the initial value for the prompt. This value will be displayed next to the prompt's label
and the user will be able to view or change it depending on the options.
HideEntered sets whether to hide the text after the user has pressed enter.
IsConfirm makes the prompt ask for a yes or no ([Y/N]) question rather than request an input. When set,
most properties related to input will be ignored.
IsVimMode enables vi-like movements (hjkl) and editing.
Label is the value displayed on the command line prompt.
The value for Label can be a simple string or a struct that will need to be accessed by dot notation
inside the templates. For example, `{{ .Name }}` will display the name property of a struct.
Mask is an optional rune that sets which character to display instead of the entered characters. This
allows hiding private information like passwords.
the Pointer defines how to render the cursor.
Stdin io.ReadCloser
Stdout io.WriteCloser
Templates can be used to customize the prompt output. If nil is passed, the
default templates are used. See the PromptTemplates docs for more info.
Validate is an optional function that fill be used against the entered value in the prompt to validate it.
Run executes the prompt. Its displays the label and default value if any, asking the user to enter a value.
Run will keep the prompt alive until it has been canceled from the command prompt or it has received a valid
value. It will return the value and an error if any occurred during the prompt's execution.
(*T) prepareTemplates() error
PromptTemplates allow a prompt to be customized following stdlib
text/template syntax. Custom state, colors and background color are available for use inside
the templates and are documented inside the Variable section of the docs.
Examples
text/templates use a special notation to display programmable content. Using the double bracket notation,
the value can be printed with specific helper functions. For example
This displays the value given to the template as pure, unstylized text.
'{{ . }}'
This displays the value colored in cyan
'{{ . | cyan }}'
This displays the value colored in red with a cyan background-color
'{{ . | red | cyan }}'
See the doc of text/template for more info: https://golang.org/pkg/text/template/
Prompt is a text/template for the prompt label when IsConfirm is set as true.
FuncMap is a map of helper functions that can be used inside of templates according to the text/template
documentation.
By default, FuncMap contains the color functions used to color the text in templates. If FuncMap
is overridden, the colors functions must be added in the override from promptui.FuncMap to work.
Invalid is a text/template for the prompt label when the value entered is invalid.
Prompt is a text/template for the prompt label displayed on the left side of the prompt.
Success is a text/template for the prompt label when the user has pressed entered and the value has been
deemed valid by the validation function. The label will keep using this template even when the prompt ends
inside the console.
Valid is a text/template for the prompt label when the value entered is valid.
Prompt is a text/template for the prompt label when the value is invalid due to an error triggered by
the prompt's validation function.
invalid *template.Template
prompt *template.Template
success *template.Template
valid *template.Template
validation *template.Template
Select represents a list of items used to enable selections, they can be used as search engines, menus
or as a list of items in a cli based prompt.
CursorPos is the initial position of the cursor.
HideHelp sets whether to hide help information.
HideSelected sets whether to hide the text displayed after an item is successfully selected.
IsVimMode sets whether to use vim mode when using readline in the command prompt. Look at
https://godoc.org/github.com/chzyer/readline#Config for more information on readline.
Items are the items to display inside the list. It expect a slice of any kind of values, including strings.
If using a slice of strings, promptui will use those strings directly into its base templates or the
provided templates. If using any other type in the slice, it will attempt to transform it into a string
before giving it to its templates. Custom templates will override this behavior if using the dot notation
inside the templates.
For example, `{{ .Name }}` will display the name property of a struct.
Keys is the set of keys used in select mode to control the command line interface. See the SelectKeys docs for
more info.
Label is the text displayed on top of the list to direct input. The IconInitial value "?" will be
appended automatically to the label so it does not need to be added.
The value for Label can be a simple string or a struct that will need to be accessed by dot notation
inside the templates. For example, `{{ .Name }}` will display the name property of a struct.
A function that determines how to render the cursor
Searcher is a function that can be implemented to refine the base searching algorithm in selects.
Search is a function that will receive the searched term and the item's index and should return a boolean
for whether or not the terms are alike. It is unimplemented by default and search will not work unless
it is implemented.
Size is the number of items that should appear on the select before scrolling is necessary. Defaults to 5.
StartInSearchMode sets whether or not the select mode should start in search mode or selection mode.
For search mode to work, the Search property must be implemented.
Stdin io.ReadCloser
Stdout io.WriteCloser
Templates can be used to customize the select output. If nil is passed, the
default templates are used. See the SelectTemplates docs for more info.
list *list.List
Run executes the select list. It displays the label and the list of items, asking the user to chose any
value within to list. Run will keep the prompt alive until it has been canceled from
the command prompt or it has received a valid value. It will return the value and an error if any
occurred during the select's execution.
RunCursorAt executes the select list, initializing the cursor to the given
position. Invalid cursor positions will be clamped to valid values. It
displays the label and the list of items, asking the user to chose any value
within to list. Run will keep the prompt alive until it has been canceled
from the command prompt or it has received a valid value. It will return
the value and an error if any occurred during the select's execution.
ScrollPosition returns the current scroll position.
(*T) innerRun(cursorPos, scroll int, top rune) (int, string, error)
(*T) prepareTemplates() error
(*T) renderDetails(item interface{}) [][]byte
(*T) renderHelp(b bool) []byte
(*T) setKeys()
SelectKeys defines the available keys used by select mode to enable the user to move around the list
and trigger search mode. See the Key struct docs for more information on keys.
Next is the key used to move to the next element inside the list. Defaults to down arrow key.
PageUp is the key used to jump forward to the last element inside the list. Defaults to right arrow key.
PageUp is the key used to jump back to the first element inside the list. Defaults to left arrow key.
Prev is the key used to move to the previous element inside the list. Defaults to up arrow key.
Search is the key used to trigger the search mode for the list. Default to the "/" key.
SelectTemplates allow a select list to be customized following stdlib
text/template syntax. Custom state, colors and background color are available for use inside
the templates and are documented inside the Variable section of the docs.
Examples
text/templates use a special notation to display programmable content. Using the double bracket notation,
the value can be printed with specific helper functions. For example
This displays the value given to the template as pure, unstylized text. Structs are transformed to string
with this notation.
'{{ . }}'
This displays the name property of the value colored in cyan
'{{ .Name | cyan }}'
This displays the label property of value colored in red with a cyan background-color
'{{ .Label | red | cyan }}'
See the doc of text/template for more info: https://golang.org/pkg/text/template/
Notes
Setting any of these templates will remove the icons from the default templates. They must
be added back in each of their specific templates. The styles.go constants contains the default icons.
Active is a text/template for when an item is currently active within the list.
Details is a text/template for when an item current active to show
additional information. It can have multiple lines.
Detail will always be displayed for the active element and thus can be used to display additional
information on the element beyond its label.
promptui will not trim spaces and tabs will be displayed if the template is indented.
FuncMap is a map of helper functions that can be used inside of templates according to the text/template
documentation.
By default, FuncMap contains the color functions used to color the text in templates. If FuncMap
is overridden, the colors functions must be added in the override from promptui.FuncMap to work.
Help is a text/template for displaying instructions at the top. By default
it shows keys for movement and search.
Inactive is a text/template for when an item is not currently active inside the list. This
template is used for all items unless they are active or selected.
Label is a text/template for the main command line label. Defaults to printing the label as it with
the IconInitial.
Selected is a text/template for when an item was successfully selected.
active *template.Template
details *template.Template
help *template.Template
inactive *template.Template
label *template.Template
selected *template.Template
var gitlab.com/pcanilho/go-jira-cli/cmd/interactive.issueListTemplate *SelectTemplates
var gitlab.com/pcanilho/go-jira-cli/cmd/interactive.issueProjectTemplate *SelectTemplates
var gitlab.com/pcanilho/go-jira-cli/cmd/interactive.mainTemplate *SelectTemplates
var gitlab.com/pcanilho/go-jira-cli/cmd/interactive.userTemplate *SelectTemplates
var gitlab.com/pcanilho/go-jira-cli/cmd/interactive.userTopTemplate *SelectTemplates
SelectWithAdd represents a list for selecting a single item inside a list of items with the possibility to
add new items to the list.
AddLabel is the label used for the first item of the list that enables adding a new item.
Selecting this item in the list displays the add item prompt using promptui/prompt.
HideHelp sets whether to hide help information.
IsVimMode sets whether to use vim mode when using readline in the command prompt. Look at
https://godoc.org/github.com/chzyer/readline#Config for more information on readline.
Items are the items to display inside the list. Each item will be listed individually with the
AddLabel as the first item of the list.
Label is the text displayed on top of the list to direct input. The IconInitial value "?" will be
appended automatically to the label so it does not need to be added.
a function that defines how to render the cursor
Validate is an optional function that fill be used against the entered value in the prompt to validate it.
If the value is valid, it is returned to the callee to be added in the list.
Run executes the select list. Its displays the label and the list of items, asking the user to chose any
value within to list or add his own. Run will keep the prompt alive until it has been canceled from
the command prompt or it has received a valid value.
If the addLabel is selected in the list, this function will return a -1 index with the added label and no error.
Otherwise, it will return the index and the value of the selected item. In any case, if an error is triggered, it
will also return the error as its third return value.
ValidateFunc is a placeholder type for any validation functions that validates a given input. It should return
a ValidationError if the input is not valid.
Package-Level Functions (total 10, in which 2 are exported)
NewCursor create a new cursor, with the DefaultCursor, the specified input,
and position at the end of the specified starting input.
Styler is a function that accepts multiple possible styling transforms from the state,
color and background colors constants and transforms them into a templated string
to apply those styles in the CLI.
The returned styling function accepts a string that will be extended with
the wrapping function's styling attributes.
Package-Level Variables (total 25, all are exported)
BlockCursor is a cursor which highlights a character by inverting colors
on it.
DefaultCursor is a big square block character. Obscures whatever was
input.
ErrAbort is the error returned when confirm prompts are supplied "n"
ErrEOF is the error returned from prompts when EOF is encountered.
ErrInterrupt is the error returned from prompts when an interrupt (ctrl-c) is
encountered.
FuncMap defines template helpers for the output. It can be extended as a regular map.
The functions inside the map link the state, color and background colors strings detected in templates to a Styler
function that applies the given style using the corresponding constant.
IconBad is the icon used when a bad answer is entered in prompt mode.
IconGood is the icon used when a good answer is entered in prompt mode.
IconInitial is the icon used when starting in prompt mode and the icon next to the label when
starting in select mode.
IconSelect is the icon used to identify the currently selected item in select mode.
IconWarn is the icon used when a good, but potentially invalid answer is entered in prompt mode.
KeyBackspace is the default key for deleting input text.
KeyBackward is the default key to page up during selection.
These runes are used to identify the commands entered by the user in the command prompt. They map
to specific actions of promptui in prompt mode and can be remapped if necessary.
KeyCtrlH is the key for deleting input text.
KeyEnter is the default key for submission/selection.
KeyForward is the default key to page down during selection.
These runes are used to identify the commands entered by the user in the command prompt. They map
to specific actions of promptui in prompt mode and can be remapped if necessary.
KeyNext is the default key to go down during selection.
These runes are used to identify the commands entered by the user in the command prompt. They map
to specific actions of promptui in prompt mode and can be remapped if necessary.
KeyPrev is the default key to go up during selection.
These runes are used to identify the commands entered by the user in the command prompt. They map
to specific actions of promptui in prompt mode and can be remapped if necessary.
PipeCursor is a pipe character "|" which appears before the input
character.
ResetCode is the character code used to reset the terminal formatting
SearchPrompt is the prompt displayed in search mode.
Package-Level Constants (total 26, in which 21 are exported)
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible background colors of text inside the application.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible state of text inside the application, either Bold, faint, italic or underline.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible state of text inside the application, either Bold, faint, italic or underline.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible state of text inside the application, either Bold, faint, italic or underline.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible state of text inside the application, either Bold, faint, italic or underline.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
The possible colors of text inside the application.
These constants are called through the use of the Styler function.
SelectedAdd is used internally inside SelectWithAdd when the add option is selected in select mode.
Since -1 is not a possible selected index, this ensure that add mode is always unique inside
SelectWithAdd's logic.
The pages are generated with Golds v0.3.2. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |