prompt

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultHistoryExecPrefix = "!"              // !13 => exec 13th command in history
	DefaultHistoryListPrefix = "!!"             // !! => list all history
	DefaultRefreshInterval   = time.Second / 60 // 60hz

)
View Source
const (
	DefaultPrefix = "> "
)

Variables

View Source
var (
	// StyleLineNumbersNone - line numbers not enabled.
	StyleLineNumbersNone = StyleLineNumbers{
		Enabled: false,
	}

	// StyleLineNumbersEnabled - enabled with sane defaults.
	StyleLineNumbersEnabled = StyleLineNumbers{
		Enabled: true,
		Color: Color{
			Foreground: termenv.ANSI256Color(239),
			Background: termenv.ANSI256Color(235),
		},
		ZeroPrefixed: false,
	}
)
View Source
var (
	// StyleScrollbarDefault - default style when none provided.
	StyleScrollbarDefault = StyleScrollbar{
		Color: Color{
			Foreground: termenv.ANSI256Color(237),
			Background: termenv.ANSI256Color(233),
		},
		Indicator:      '█',
		IndicatorEmpty: '░',
	}

	// StyleScrollbarAutoComplete - default style for the auto-complete
	// drop-down.
	StyleScrollbarAutoComplete = StyleScrollbar{
		Color: Color{
			Foreground: termenv.ANSI256Color(27),
			Background: termenv.ANSI256Color(39),
		},
		Indicator:      '█',
		IndicatorEmpty: '░',
	}
)
View Source
var ErrAborted = errors.New("aborted")

ErrAborted is returned when the execution is terminated for any unexpected reason

View Source
var ErrDuplicateKeyAssignment = errors.New("duplicate key assignment")

ErrDuplicateKeyAssignment is returned when the key map has the same keys defined for multiple incompatible actions.

View Source
var ErrInvalidDimensions = errors.New("invalid dimensions")

ErrInvalidDimensions is returned when the style sheet has dimensions that does not make sense.

View Source
var ErrUnsupportedChromaLanguage = errors.New("unsupported language for chroma")

ErrUnsupportedChromaLanguage is returned when Syntax-Highlighting is requested with Chroma library with a language that it does not understand.

View Source
var ErrUnsupportedInput = errors.New("unsupported input")

ErrUnsupportedInput is returned when the input given to a function is not supported or handled.

View Source
var KeyMapDefault = KeyMapSingleLine

KeyMapDefault uses KeyMapSingleLine as the default key-map.

View Source
var KeyMapMultiLine = KeyMap{
	AutoComplete: AutoCompleteKeyMap{
		ChooseNext:     KeySequences{ArrowDown},
		ChoosePrevious: KeySequences{ArrowUp},
		Select:         KeySequences{Tab},
	},
	Insert: InsertKeyMap{
		Abort:                  KeySequences{CtrlC, CtrlD, Escape},
		AutoComplete:           KeySequences{CtrlSpace},
		DeleteCharCurrent:      KeySequences{Delete},
		DeleteCharPrevious:     KeySequences{Backspace, CtrlH},
		DeleteWordNext:         KeySequences{AltD},
		DeleteWordPrevious:     KeySequences{CtrlW},
		EraseEverything:        KeySequences{AltW},
		EraseToBeginningOfLine: KeySequences{CtrlU},
		EraseToEndOfLine:       KeySequences{CtrlK},
		HistoryNext:            KeySequences{ShiftArrowDown},
		HistoryPrevious:        KeySequences{ShiftArrowUp},
		MakeWordCapitalCase:    KeySequences{AltC},
		MakeWordLowerCase:      KeySequences{AltL},
		MakeWordUpperCase:      KeySequences{AltU},
		MoveDownOneLine:        KeySequences{ArrowDown},
		MoveLeftOneCharacter:   KeySequences{ArrowLeft},
		MoveRightOneCharacter:  KeySequences{ArrowRight},
		MoveToBeginning:        KeySequences{CtrlHome},
		MoveToBeginningOfLine:  KeySequences{Home},
		MoveToEnd:              KeySequences{CtrlEnd},
		MoveToEndOfLine:        KeySequences{End},
		MoveToWordNext:         KeySequences{CtrlArrowRight, AltF},
		MoveToWordPrevious:     KeySequences{CtrlArrowLeft, AltB},
		MoveUpOneLine:          KeySequences{ArrowUp},
		SwapCharacterNext:      KeySequences{CtrlN},
		SwapCharacterPrevious:  KeySequences{CtrlT},
		SwapWordNext:           KeySequences{AltN},
		SwapWordPrevious:       KeySequences{AltT},
		Terminate:              KeySequences{Enter},
	},
}

KeyMapMultiLine defines sane key sequences for each supported action for a prompt that supports multi-line inputs.

View Source
var KeyMapSingleLine = KeyMap{
	AutoComplete: AutoCompleteKeyMap{
		ChooseNext:     KeySequences{ArrowDown},
		ChoosePrevious: KeySequences{ArrowUp},
		Select:         KeySequences{Tab},
	},
	Insert: InsertKeyMap{
		Abort:                  KeySequences{CtrlC, CtrlD, Escape},
		AutoComplete:           KeySequences{CtrlSpace},
		DeleteCharCurrent:      KeySequences{Delete},
		DeleteCharPrevious:     KeySequences{Backspace, CtrlH},
		DeleteWordNext:         KeySequences{AltD},
		DeleteWordPrevious:     KeySequences{CtrlW},
		EraseEverything:        KeySequences{AltW},
		EraseToBeginningOfLine: KeySequences{CtrlU},
		EraseToEndOfLine:       KeySequences{CtrlK},
		HistoryNext:            KeySequences{ArrowDown},
		HistoryPrevious:        KeySequences{ArrowUp},
		MakeWordCapitalCase:    KeySequences{AltC},
		MakeWordLowerCase:      KeySequences{AltL},
		MakeWordUpperCase:      KeySequences{AltU},
		MoveDownOneLine:        KeySequences{},
		MoveLeftOneCharacter:   KeySequences{ArrowLeft},
		MoveRightOneCharacter:  KeySequences{ArrowRight},
		MoveToBeginning:        KeySequences{CtrlHome},
		MoveToBeginningOfLine:  KeySequences{Home},
		MoveToEnd:              KeySequences{CtrlEnd},
		MoveToEndOfLine:        KeySequences{End},
		MoveToWordNext:         KeySequences{CtrlArrowRight, AltF},
		MoveToWordPrevious:     KeySequences{CtrlArrowLeft, AltB},
		MoveUpOneLine:          KeySequences{},
		SwapCharacterNext:      KeySequences{CtrlN},
		SwapCharacterPrevious:  KeySequences{CtrlT},
		SwapWordNext:           KeySequences{AltN},
		SwapWordPrevious:       KeySequences{AltT},
		Terminate:              KeySequences{Enter},
	},
}

KeyMapSingleLine defines sane key sequences for each supported action for a prompt that supports single-line inputs. Quite a few of these are the default short-cuts in BASH.

View Source
var StyleAutoCompleteDefault = StyleAutoComplete{
	HintColor: Color{
		Foreground: termenv.ANSI256Color(0),
		Background: termenv.ANSI256Color(39),
	},
	HintSelectedColor: Color{
		Foreground: termenv.ANSI256Color(16),
		Background: termenv.ANSI256Color(208),
	},
	HintLengthMin: 8,
	HintLengthMax: 32,
	MinChars:      0,
	NumItems:      4,
	Scrollbar:     StyleScrollbarAutoComplete,
	ValueColor: Color{
		Foreground: termenv.ANSI256Color(16),
		Background: termenv.ANSI256Color(45),
	},
	ValueSelectedColor: Color{
		Foreground: termenv.ANSI256Color(16),
		Background: termenv.ANSI256Color(214),
	},
	ValueLengthMin: 8,
	ValueLengthMax: 32,
	WordDelimiters: map[byte]bool{
		' ':  true,
		'(':  true,
		')':  true,
		',':  true,
		';':  true,
		'[':  true,
		'\n': true,
		'\t': true,
		']':  true,
		'{':  true,
		'}':  true,
	},
}

StyleAutoCompleteDefault - default Style when none provided.

View Source
var StyleColorsDefault = StyleColors{
	Debug: Color{
		Foreground: termenv.ANSI256Color(22),
		Background: termenv.ANSI256Color(232),
	},
	Error: Color{
		Foreground: termenv.ANSI256Color(9),
		Background: termenv.BackgroundColor(),
	},
}

StyleColorsDefault - default style when none provided.

View Source
var StyleCursorDefault = StyleCursor{
	Blink:         true,
	BlinkInterval: time.Millisecond * 500,
	Color: Color{
		Foreground: termenv.ANSI256Color(232),
		Background: termenv.ANSI256Color(6),
	},
	ColorAlt: Color{
		Foreground: termenv.ANSI256Color(232),
		Background: termenv.ANSI256Color(14),
	},
	Enabled: true,
}

StyleCursorDefault - default style when none provided.

View Source
var StyleDefault = Style{
	AutoComplete: StyleAutoCompleteDefault,
	Colors:       StyleColorsDefault,
	Cursor:       StyleCursorDefault,
	Dimensions:   StyleDimensionsDefault,
	LineNumbers:  StyleLineNumbersNone,
	Scrollbar:    StyleScrollbarDefault,
	TabString:    "    ",
}

StyleDefault - default Style when none provided.

View Source
var StyleDimensionsDefault = StyleDimensions{
	HeightMin: 0,
	HeightMax: 0,
	WidthMin:  0,
	WidthMax:  0,
}

StyleDimensionsDefault - default style when none provided.

Functions

func WidthEnforcerDefault

func WidthEnforcerDefault(str string, maxLen int) string

WidthEnforcerDefault -

Types

type Action

type Action string

Action defines an activity that is done based on a key sequence.

const (
	None  Action = ""      // no action
	Abort Action = "Abort" // abort the prompt completely and return to caller

	/*
	 * Auto-complete Actions
	 */
	AutoCompleteChooseNext     Action = "AutoCompleteChooseNext"     // choose the next suggestion
	AutoCompleteChoosePrevious Action = "AutoCompleteChoosePrevious" // choose the previous suggestion
	AutoCompleteSelect         Action = "AutoCompleteSelect"         // select the current suggestion

	/*
	 * Insert-mode Actions
	 */
	AutoComplete           Action = "AutoComplete"           // force an auto-complete
	DeleteCharCurrent      Action = "DeleteCharCurrent"      // delete the character at the cursor
	DeleteCharPrevious     Action = "DeleteCharPrevious"     // delete the character before the cursor
	DeleteWordNext         Action = "DeleteWordNext"         // delete the next work
	DeleteWordPrevious     Action = "DeleteWordPrevious"     // delete the previous word
	EraseEverything        Action = "EraseEverything"        // erase the entire prompt
	EraseToBeginningOfLine Action = "EraseToBeginningOfLine" // erase from cursor to the beginning of current line
	EraseToEndOfLine       Action = "EraseToEndOfLine"       // erase from cursor to the end of current line
	HistoryNext            Action = "HistoryNext"            // show command executed after current command if any
	HistoryPrevious        Action = "HistoryPrevious"        // show previously executed command if any
	MakeWordCapitalCase    Action = "MakeWordCapitalCase"    // make the word at the cursor capitalized
	MakeWordLowerCase      Action = "MakeWordLowerCase"      // make the word at the cursor lower case
	MakeWordUpperCase      Action = "MakeWordUpperCase"      // make the word at the cursor upper case
	MoveDownOneLine        Action = "MoveDownOneLine"        // move the cursor down one line
	MoveLeftOneCharacter   Action = "MoveLeftOneCharacter"   // move the cursor left one character
	MoveRightOneCharacter  Action = "MoveRightOneCharacter"  // move the cursor right one character
	MoveUpOneLine          Action = "MoveUpOneLine"          // move the cursor up one line
	MoveToBeginning        Action = "MoveToBeginning"        // move to the beginning of the entire prompt text
	MoveToBeginningOfLine  Action = "MoveToBeginningOfLine"  // move to the beginning of the current line
	MoveToEnd              Action = "MoveToEnd"              // move to the end of the entire prompt text
	MoveToEndOfLine        Action = "MoveToEndOfLine"        // move to the end of the current line
	MoveToWordNext         Action = "MoveToWordNext"         // move to the beginning of the next word
	MoveToWordPrevious     Action = "MoveToWordPrevious"     // move to the beginning of the previous word
	Terminate              Action = "Terminate"              // trigger the termination checker if any, or return the text
)

Supported Actions.

type AutoCompleteKeyMap

type AutoCompleteKeyMap struct {
	ChooseNext     KeySequences
	ChoosePrevious KeySequences
	Select         KeySequences
}

AutoCompleteKeyMap is the KeyMap used in AutoComplete mode.

type AutoCompleter

type AutoCompleter func(sentence string, word string, location uint) []Suggestion

AutoCompleter defines a function that takes the entire user input, the word the user is specifically on, and the location of the cursor on the entire sentence. It is expected to return zero or more strings that match what the user may type.

func AutoCompleteGoLangKeywords

func AutoCompleteGoLangKeywords() AutoCompleter

AutoCompleteGoLangKeywords is a simple auto-completer that helps auto-complete most of the known GoLang suggestions.

func AutoCompletePythonKeywords

func AutoCompletePythonKeywords() AutoCompleter

AutoCompletePythonKeywords is a simple auto-completer that helps auto-complete most of the known Python suggestions.

func AutoCompleteSQLKeywords

func AutoCompleteSQLKeywords() AutoCompleter

AutoCompleteSQLKeywords is a simple auto-completer that helps auto-complete most of the known SQL suggestions.

func AutoCompleteSimple

func AutoCompleteSimple(suggestions []Suggestion, caseInsensitive bool) AutoCompleter

AutoCompleteSimple returns an AutoCompleter which will use the given list of suggestions in an optimized fashion for look-ups.

type Color

type Color struct {
	Foreground termenv.Color
	Background termenv.Color
	// contains filtered or unexported fields
}

Color contain the foreground and background colors to use to format text.

func (Color) Invert

func (c Color) Invert() Color

Invert flips the background and foreground colors and returns a new Color object.

func (Color) Sprint

func (c Color) Sprint(a ...any) string

Sprint behaves like fmt.Sprint but with color sequence wrapping the output.

func (Color) Sprintf

func (c Color) Sprintf(msg string, a ...any) string

Sprintf behaves like fmt.Sprintf but with color sequence wrapping the output.

type CursorLocation

type CursorLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

CursorLocation contains the current cursor position in a 2d-wall-of-text; the values are 0-indexed to keep it simple to manipulate the wall of text

func (CursorLocation) String

func (cl CursorLocation) String() string

String returns the co-ordinates in human-readable format.

type History

type History struct {
	Commands []HistoryCommand
	Index    int
	// contains filtered or unexported fields
}

History contains the past commands executed by the user using Prompt.

func (*History) Append

func (h *History) Append(cmd string, optionalTimestamp ...time.Time)

Append appends a command to the history.

func (*History) Get

func (h *History) Get(n int) string

Get returns the Nth command from history. N is zero-indexed.

func (*History) GetNext

func (h *History) GetNext() string

GetNext returns the next command in history.

func (*History) GetPrev

func (h *History) GetPrev() string

GetPrev returns the previous command in history.

func (*History) Render

func (h *History) Render(numItems int, dispWidth int) string

Render renders the list of historic commands to a table and returns the string to the client for printing.

type HistoryCommand

type HistoryCommand struct {
	Command   string          `json:"command"`
	Timestamp strfmt.DateTime `json:"timestamp"`
}

HistoryCommand contains the command and associated timestamp.

type InsertKeyMap

type InsertKeyMap struct {
	Abort                  KeySequences
	AutoComplete           KeySequences
	DeleteCharCurrent      KeySequences
	DeleteCharPrevious     KeySequences
	DeleteWordNext         KeySequences
	DeleteWordPrevious     KeySequences
	EraseEverything        KeySequences
	EraseToBeginningOfLine KeySequences
	EraseToEndOfLine       KeySequences
	HistoryNext            KeySequences
	HistoryPrevious        KeySequences
	MakeWordCapitalCase    KeySequences
	MakeWordLowerCase      KeySequences
	MakeWordUpperCase      KeySequences
	MoveDownOneLine        KeySequences
	MoveLeftOneCharacter   KeySequences
	MoveRightOneCharacter  KeySequences
	MoveToBeginning        KeySequences
	MoveToBeginningOfLine  KeySequences
	MoveToEnd              KeySequences
	MoveToEndOfLine        KeySequences
	MoveToWordNext         KeySequences
	MoveToWordPrevious     KeySequences
	MoveUpOneLine          KeySequences
	SwapCharacterNext      KeySequences
	SwapCharacterPrevious  KeySequences
	SwapWordNext           KeySequences
	SwapWordPrevious       KeySequences
	Terminate              KeySequences
}

InsertKeyMap is the KeyMap used in Insert mode.

type KeyMap

type KeyMap struct {
	AutoComplete AutoCompleteKeyMap
	Insert       InsertKeyMap
	// contains filtered or unexported fields
}

KeyMap can be used to customize or define the behavior of the Prompt for each special Key sequences that is entered by the User.

type KeySequence

type KeySequence string

KeySequence defines a special key-sequence that the user presses.

const (
	AltA            KeySequence = "alt+a"
	AltB            KeySequence = "alt+b"
	AltC            KeySequence = "alt+c"
	AltD            KeySequence = "alt+d"
	AltE            KeySequence = "alt+e"
	AltF            KeySequence = "alt+f"
	AltG            KeySequence = "alt+g"
	AltH            KeySequence = "alt+h"
	AltI            KeySequence = "alt+i"
	AltJ            KeySequence = "alt+j"
	AltK            KeySequence = "alt+k"
	AltL            KeySequence = "alt+l"
	AltM            KeySequence = "alt+m"
	AltN            KeySequence = "alt+n"
	AltO            KeySequence = "alt+o"
	AltP            KeySequence = "alt+p"
	AltQ            KeySequence = "alt+q"
	AltR            KeySequence = "alt+r"
	AltS            KeySequence = "alt+s"
	AltT            KeySequence = "alt+t"
	AltU            KeySequence = "alt+u"
	AltV            KeySequence = "alt+v"
	AltW            KeySequence = "alt+w"
	AltX            KeySequence = "alt+x"
	AltY            KeySequence = "alt+y"
	AltZ            KeySequence = "alt+z"
	ArrowDown       KeySequence = "arrow-down"
	ArrowLeft       KeySequence = "arrow-left"
	ArrowRight      KeySequence = "arrow-right"
	ArrowUp         KeySequence = "arrow-up"
	Backspace       KeySequence = "backspace"
	CtrlA           KeySequence = "ctrl+a"
	CtrlArrowDown   KeySequence = "ctrl+down"
	CtrlArrowLeft   KeySequence = "ctrl+left"
	CtrlArrowRight  KeySequence = "ctrl+right"
	CtrlArrowUp     KeySequence = "ctrl+up"
	CtrlB           KeySequence = "ctrl+b"
	CtrlC           KeySequence = "ctrl+c"
	CtrlD           KeySequence = "ctrl+d"
	CtrlE           KeySequence = "ctrl+e"
	CtrlEnd         KeySequence = "ctrl+end"
	CtrlF           KeySequence = "ctrl+f"
	CtrlG           KeySequence = "ctrl+g"
	CtrlH           KeySequence = "ctrl+h"
	CtrlHome        KeySequence = "ctrl+home"
	CtrlI           KeySequence = "ctrl+i"
	CtrlJ           KeySequence = "ctrl+j"
	CtrlK           KeySequence = "ctrl+k"
	CtrlL           KeySequence = "ctrl+l"
	CtrlM           KeySequence = "ctrl+m"
	CtrlN           KeySequence = "ctrl+n"
	CtrlO           KeySequence = "ctrl+o"
	CtrlP           KeySequence = "ctrl+p"
	CtrlQ           KeySequence = "ctrl+q"
	CtrlR           KeySequence = "ctrl+r"
	CtrlS           KeySequence = "ctrl+s"
	CtrlSpace       KeySequence = "ctrl+space"
	CtrlT           KeySequence = "ctrl+t"
	CtrlU           KeySequence = "ctrl+u"
	CtrlV           KeySequence = "ctrl+v"
	CtrlW           KeySequence = "ctrl+w"
	CtrlX           KeySequence = "ctrl+x"
	CtrlY           KeySequence = "ctrl+y"
	CtrlZ           KeySequence = "ctrl+z"
	Delete          KeySequence = "delete"
	End             KeySequence = "end"
	Enter           KeySequence = "enter"
	Escape          KeySequence = "escape"
	F1              KeySequence = "f1"
	F10             KeySequence = "f10"
	F11             KeySequence = "f11"
	F12             KeySequence = "f12"
	F2              KeySequence = "f2"
	F3              KeySequence = "f3"
	F4              KeySequence = "f4"
	F5              KeySequence = "f5"
	F6              KeySequence = "f6"
	F7              KeySequence = "f7"
	F8              KeySequence = "f8"
	F9              KeySequence = "f9"
	Home            KeySequence = "home"
	Insert          KeySequence = "insert"
	PageDown        KeySequence = "page-down"
	PageUp          KeySequence = "page-up"
	ShiftArrowDown  KeySequence = "shift+down"
	ShiftArrowLeft  KeySequence = "shift+left"
	ShiftArrowRight KeySequence = "shift+right"
	ShiftArrowUp    KeySequence = "shift+up"
	ShiftEnd        KeySequence = "shift+end"
	ShiftHome       KeySequence = "shift+home"
	ShiftTab        KeySequence = "shift-tab"
	Space           KeySequence = "space"
	Tab             KeySequence = "tab"
)

Supported Keys

type KeySequences

type KeySequences []KeySequence

KeySequences are a slice of KeySequence(s).

type LineGenerator

type LineGenerator func(width int) string

LineGenerator is a function that takes the width of the terminal as input and generates a "line" of content to be display on the terminal above or below the prompt.

func LineCentered

func LineCentered(title string, optionalColor ...Color) LineGenerator

LineCentered uses the given text as the "header" text and centers it.

func LineRuler

func LineRuler(optionalColor ...Color) LineGenerator

LineRuler prints a ruler above the prompt.

func LineSimple

func LineSimple(title string, optionalColor ...Color) LineGenerator

LineSimple uses the given text as the "header" text.

type Prefixer

type Prefixer func() string

Prefixer returns the string to precede any new prompt.

func PrefixNone

func PrefixNone() Prefixer

PrefixNone uses no prompt prefix.

func PrefixSimple

func PrefixSimple() Prefixer

PrefixSimple uses "> " as the prompt prefix.

func PrefixText

func PrefixText(text string) Prefixer

PrefixText uses the given text as the prompt prefix.

func PrefixTimestamp

func PrefixTimestamp(timeLayout string, prefix string) Prefixer

PrefixTimestamp uses a timestamp and a prefix as the prompt prefix.

type Prompter

type Prompter interface {
	// ClearHistory clears all record of previously executed commands.
	ClearHistory()

	// CursorLocation returns the current location of the cursor on the prompt.
	CursorLocation() CursorLocation

	// History returns all the commands executed until now.
	History() []HistoryCommand

	// IsActive returns true if there is an active prompt at the moment.
	IsActive() bool

	// KeyMap returns the current KeyMap for inspection/customization.
	KeyMap() KeyMap

	// NumLines returns the number of lines of text in the current active
	//prompt.
	NumLines() int

	// Prompt prompts. It also watches for cancel KeyEvents on the Context to
	// abort the prompt and return control to client.
	Prompt(ctx context.Context) (string, error)

	// SendInput lets you send strings/runes/KeySequence to the currently active
	// prompt.
	SendInput(a []any, delayBetweenRunes ...time.Duration) error

	// SetAutoCompleter sets up the AutoCompleter that will be used to provide
	// suggestions. Consider this as an auto completer which will be useful for
	// suggesting global stuff like language keywords, or global variables.
	//
	// This should ideally be set ONCE for the lifetime of a Prompter object.
	SetAutoCompleter(global AutoCompleter)

	// SetAutoCompleterContextual sets up the AutoCompleter that will be used to
	// provide suggestions with more priority than the regular AutoCompleter.
	// This is supposed to play the role of providing suggestions like local
	// variables or table names when connected to a database because of a
	// previous command.
	SetAutoCompleterContextual(autoCompleter AutoCompleter)

	// SetCommandShortcuts sets up command shortcuts. For example, if you want
	// to get the prompt input as "/help" when the user presses F1, you'd call
	// this function with the argument:
	//
	//	map[KeySequence]string{
	//	   F1: "/help",
	//	}
	//
	// These shortcuts will take precedence over anything in the prompt and
	// overwrite the contents of the prompt and return control to the caller.
	SetCommandShortcuts(shortcuts map[KeySequence]string)

	// SetDebug enables/disables debug logs/messages in the prompt.
	SetDebug(debug bool)

	// SetFooter sets up the footer line below the prompt line for each render
	// cycle.
	SetFooter(header string)

	// SetFooterGenerator sets up the LineGenerator to be used to generate the
	// footer line below the prompt line for each render cycle.
	SetFooterGenerator(footer LineGenerator)

	// SetHeader sets up the header line above the prompt line for each render
	// cycle.
	SetHeader(header string)

	// SetHeaderGenerator sets up the LineGenerator to be used to generate the
	// header line above the prompt line for each render cycle.
	SetHeaderGenerator(header LineGenerator)

	// SetHistory sets up the history (past inputs) for use when the user wants
	// to move backwards/forwards through the command list
	SetHistory(commands []HistoryCommand)

	// SetHistoryExecPrefix sets up the pattern used to exec command from
	// history. Example (prefix="!"):
	//   - !10 == execute 10th command
	//   - ! == execute last command in history
	SetHistoryExecPrefix(prefix string)

	// SetHistoryListPrefix sets up the prefix used to list commands from
	// history. Example (prefix="!!"):
	//   - !! == list all commands in history;
	//   - !! 10 == list last 10 commands
	SetHistoryListPrefix(prefix string)

	// SetInput sets up the input to be read from the given io.Reader instead of
	// os.Stdin.
	SetInput(input io.Reader)

	// SetKeyMap sets up the KeyMap used for interacting with the user's input.
	SetKeyMap(keyMap KeyMap) error

	// SetOutput sets up the output to go to the given io.Writer instead of
	// os.Stdout.
	SetOutput(output io.Writer)

	// SetPrefix sets up the prefix to use before the prompt.
	//
	// SetPrefix and SetPrefixer override the same property and the last
	// function called takes priority.
	SetPrefix(prefix string)

	// SetPrefixer sets up the prefixer to be called to generate the prefix
	// before the prompt for each render cycle.
	//
	// SetPrefix and SetPrefixer override the same property and the last
	// function called takes priority.
	SetPrefixer(prefixer Prefixer)

	// SetRefreshInterval sets up the minimum interval between consecutive
	// renders. Note that this can be overridden in case of a mandatory override
	// event like a cursor blink.
	SetRefreshInterval(interval time.Duration)

	// SetStyle sets up the Style sheet to be followed for the render.
	SetStyle(s Style)

	// SetSyntaxHighlighter sets up the function that will colorize and
	// highlight keywords in the user-input.
	SetSyntaxHighlighter(highlighter SyntaxHighlighter)

	// SetTerminationChecker sets up the termination checker to check if the
	// user input is done and can be returned to caller on "Terminate" action.
	SetTerminationChecker(checker TerminationChecker)

	// SetWidthEnforcer sets up the function to wrap lines longer than the
	// prompt width.
	SetWidthEnforcer(enforcer WidthEnforcer)

	// Style returns the current Style in use, so it can be modified on the fly
	// in between two prompts.
	Style() *Style
}

Prompter in the interface to create and manage a shell-like interactive command prompt.

func New

func New() (Prompter, error)

New returns a Prompter than can be used over and over to run a CLI.

It sets some sane defaults: - no auto-complete - command patterns to invoke history (list old commands, invoke old command) - simple prefix "> " for the prompt - 60hz refresh rate - the default style with a 500ms cursor blink - no termination checker (i.e., Enter terminates command)

type Style

type Style struct {
	AutoComplete StyleAutoComplete `json:"auto_complete"`
	Colors       StyleColors       `json:"colors"`
	Cursor       StyleCursor       `json:"cursor"`
	Dimensions   StyleDimensions   `json:"dimensions"`
	LineNumbers  StyleLineNumbers  `json:"line_numbers"`
	Scrollbar    StyleScrollbar    `json:"scrollbar"`
	TabString    string            `json:"tab_string"`
}

Style is used to customize the look and feel of everything about the prompt.

func (Style) Validate added in v0.0.4

func (s Style) Validate() error

Validate ensures that the Style can be used without issues.

type StyleAutoComplete

type StyleAutoComplete struct {
	HintColor          Color          `json:"hint_color"`
	HintSelectedColor  Color          `json:"hint_selected_color"`
	HintLengthMin      int            `json:"hint_length_min"`
	HintLengthMax      int            `json:"hint_length_max"`
	MinChars           int            `json:"min_chars"`
	NumItems           int            `json:"num_items"`
	Scrollbar          StyleScrollbar `json:"scrollbar"`
	ValueColor         Color          `json:"value_color"`
	ValueSelectedColor Color          `json:"value_selected_color"`
	ValueLengthMin     int            `json:"value_length_min"`
	ValueLengthMax     int            `json:"value_length_max"`
	WordDelimiters     map[byte]bool  `json:"word_delimiters"`
}

StyleAutoComplete is used to customize the look and feel of the auto-complete dropdown.

type StyleColors

type StyleColors struct {
	Debug Color `json:"debug"`
	Error Color `json:"error"`
}

StyleColors is used to customize the colors used on the prompt.

type StyleCursor

type StyleCursor struct {
	Blink         bool          `json:"blink"`
	BlinkInterval time.Duration `json:"blink_interval"`
	Color         Color         `json:"color"`
	ColorAlt      Color         `json:"color_alt"`
	Enabled       bool          `json:"enabled"`
}

StyleCursor is used to customize the look and feel of the cursor.

type StyleDimensions

type StyleDimensions struct {
	HeightMin uint `json:"height_min"`
	HeightMax uint `json:"height_max"`
	WidthMin  uint `json:"width_min"`
	WidthMax  uint `json:"width_max"`
}

StyleDimensions is used to customize the sizing of the prompt

type StyleLineNumbers

type StyleLineNumbers struct {
	Enabled      bool  `json:"enabled"`
	Color        Color `json:"color"`
	ZeroPrefixed bool  `json:"zero_prefixed"`
}

StyleLineNumbers is used to customize the look and feel of the line numbers in the prompt.

type StyleScrollbar

type StyleScrollbar struct {
	Color          Color
	Indicator      rune
	IndicatorEmpty rune
}

StyleScrollbar is used to customize the look and feel of the scrollbar.

func (StyleScrollbar) Generate

func (s StyleScrollbar) Generate(contentHeight int, cursorLine int, scrollbarHeight int) ([]string, bool)

Generate generates the scroll bar strings to be used as suffixes for the content lines.

type Suggestion

type Suggestion struct {
	Value string
	Hint  string
}

Suggestion is what is returned by the auto-completer.

func (Suggestion) String

func (s Suggestion) String() string

String appeases the stringer interface.

type SyntaxHighlighter

type SyntaxHighlighter func(input string) string

SyntaxHighlighter helps do syntax highlighting by using ANSI color codes on the prompt text.

func SyntaxHighlighterChroma

func SyntaxHighlighterChroma(language, formatter, style string) (SyntaxHighlighter, error)

SyntaxHighlighterChroma uses the "github.com/alecthomas/chroma" library to do the syntax highlighting. Please refer to the documentation on that project for possible values for "language", "formatter" and "style".

func SyntaxHighlighterSQL

func SyntaxHighlighterSQL() (SyntaxHighlighter, error)

SyntaxHighlighterSQL uses Chroma to return a SQL syntax highlighter.

type TerminationChecker

type TerminationChecker func(input string) bool

TerminationChecker returns true if the command is terminated and is ready to be processed. This is called once the "Terminate" action is invoked by the appropriate key sequence - this function can skip the "terminate" action if it returns false.

func TerminationCheckerNone

func TerminationCheckerNone() TerminationChecker

TerminationCheckerNone returns true for all inputs and does not abort the "terminate" action. Basically an "Enter" key would terminate input, and return the accumulated command back to caller.

func TerminationCheckerSQL

func TerminationCheckerSQL() TerminationChecker

TerminationCheckerSQL returns true if the input is supposed to be a SQL statement, and is terminated properly with a semicolon, or is a command starting with "/".

type WidthEnforcer

type WidthEnforcer func(input string, maxLen int) string

WidthEnforcer is a function that will enforce a "max-length" condition on the given text.

Jump to

Keyboard shortcuts

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