promptx

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2023 License: MIT Imports: 22 Imported by: 0

README


* promptx

promptx是可定制化的交互式 cli 应用程序的库。从[[https://github.com/c-bata/go-prompt/][go-prompt]]复制了部分文件.初版实现时候也有参考 [[https://github.com/abiosoft/ishell][ishell]].

支持简单命令以及命令集.

简单命令就是所有命令初始都显示出来.

命令集是根据需要将命令拆分成不同的组,只有处在某个状态下的时候才会显示.不同命令集下不共享操作的历史记录.

所有交互式命令都使用链式调用创建.

默认 Control-C 放弃输入, Control-D 退出进程.

允许异步打印日志.例:
#+begin_src go
p := promptx.NewPromptx()
log.SetOutput(p.Stdout())
#+end_src
这样即使在其他gorountine使用 ~log~ 打印日志也不会影响正在输入的的选项.

zap日志需要通过 ~p.Stdout()~ 定制实现zapcore. 

** 安装
#+begin_src shell
go get github.com/aggronmagi/promptx@latest
#+end_src
** 简单命令
#+begin_src go
func loginCommand() *promptx.Cmd {
	return promptx.NewCommand("login", "登录游戏",
		promptx.WithArgSelect("选择登录的游戏服务器", []string{"开发服", "测试服", "体验服"}),
		promptx.WithArgsInput("账号:", promptx.InputNotEmpty()),
	).ExecFunc(func(ctx promptx.CommandContext) {
		// 选择的登录服索引
		index := ctx.CheckSelectIndex(0)
		// 登录的服务字符串
		svcName := ctx.CheckString(0)
		// 输入的账号
		account := ctx.CheckString(1)
		
		// custom logic
		// ....

		//
		ctx.Println("login success")
	})
}

func main() {
    p := promptx.NewCommandPromptx(
		loginCommand,
		// other command ...
	)
	p.Run()
}
#+end_src
完整例子 [[./_example/demo/main.go][Common Command]]
** 命令集
#+begin_src go

func loginCommand() *promptx.Cmd {
	return promptx.NewCommand("login", "登录游戏",
		promptx.WithArgSelect("选择登录的游戏服务器", []string{"开发服", "测试服", "体验服"}),
		promptx.WithArgsInput("账号:", promptx.InputNotEmpty()),
	).ExecFunc(func(ctx promptx.CommandContext) {
		// 输入的string
		id := ctx.CheckString(1)
		ctx.Println(id, "login success")
		state = 1
		//
		ctx.SwitchCommandSet("linked")
	})
}

func logoutCommand() *promptx.Cmd {
	return promptx.NewCommand("logout", "退出游戏").ExecFunc(func(ctx promptx.CommandContext) {
		state = 0
		ctx.SwitchCommandSet("")
	})
}

func main() {
	p := promptx.NewPromptx()
	// default set
	p.AddCommandSet("", []*promptx.Cmd{
		loginCommand(),
	},promptx.WithCommandSetOptionPrompt("not login >> "))
	//
	p.AddCommandSet("linked", []*promptx.Cmd{
		logoutCommand(),
	}, promptx.WithCommandSetOptionPrompt("linked >> "))

	p.Run()
}
#+end_src
完整例子 [[./_example/commandset/main.go][Command Set]]
** API
*** 创建命令
#+begin_src go
// NewCommand 创建交互式命令 name:命令名称 help:提示信息 args 命令参数 
func NewCommand(name, help string, args ...CommandParameter) *Cmd
// 设置命令执行函数 
func (c *Cmd) ExecFunc(f func(ctx CommandContext)) *Cmd 
// 设置命令别名  
func (c *Cmd) Aliases(aliases ...string) *Cmd 
// SubCommands 添加子命令 
func (c *Cmd) SubCommands(cmds ...*Cmd) *Cmd
#+end_src
*** 命令参数 需要设置提示信息,如果用户没有一次性输入完整,提示用户输入.
#+begin_src go
// 手动输入string作为参数
func WithArgsInput(tip string, check InputChecker, opts ...InputOption) CommandParameter
// 单选参数 多选一
func WithArgSelect(tip string, list []string, opts ...SelectOption) CommandParameter 
#+end_src
*** Input类型参数的检测
#+begin_src go
// 检测输入必须是非空字符串
func InputNotEmpty() InputChecker
// 检测输入必须是数值类型 
func InputInteger() InputChecker
// 检测输入必须是非0数字
func InputNotZeroInteger() InputChecker
// 检测输入必须是自然数 (1,2,3....)
func InputNaturalNumber() InputChecker
// 检测输入必须是在min,max区间的数字 
func InputIntegerRange(min, max int64) InputChecker
// 检测输入必须是IP端口(例 127.0.0.1:8080)
func InputIPPort() InputChecker
// 检测输入必须是IP端口数组,使用","分隔
func InputAddrsArray() InputChecker 
#+end_src
*** 命令执行函数的签名 
#+begin_src go
// 函数签名
func xx(ctx CommandContext) {
}
#+end_src
*** 命令上下文 CommandContext
命令执行函数内 使用 ~CommandContext~ 提供的 ~Check...~ 方法获取参数.

所有Check方法,如果没有用户没有输入,会通过panic打断流程.或者是输入了不符合预期的值,也会通过panic打断流程.

Check 函数的调用应该和创建命令时候输入的 ~CommandParameter~ 一一匹配.

Check 函数的Index参数从0开始.

~CommandParameter~ 检测通过之后,内部保留的玩家输入都是string类型.所以 ~CheckString~ 只要索引位置输入了值,都是有效的.

~CheckSelectIndex~ 仅用于 ~WithArgSelect~ 对应的参数,获取玩家输入的是第几个选项(从0开始)
#+begin_src go
// CommandContext
type CommandContext interface {
	Context

	CheckString(index int) string
	CheckInteger(index int) int64
	CheckIPPort(index int) (ip, port string)
	CheckAddrs(index int) (addrs []string)
	CheckSelectIndex(index int) int
}
#+end_src
*** 命令集
可以添加不同的命令集合,首次添加的命令集合会设置为默认的命令集.
#+begin_src go
type Context interface {
	// others interface function ...
	// AddCommandSet 添加命令集,首次添加命令集时会自动切换。
	AddCommandSet(name string, cmds []*Cmd, opts ...CommandSetOption) 
	// SwitchCommandSet 切换到指定命令集,参数会传递给 ChangeNotify 函数
	SwitchCommandSet(name string, args ...interface{})
}
#+end_src
**** 选项
命令集添加时候,允许设置以下选项:
#+begin_src go
// 设置当前命令集的操作记录持久化保存的文件.如果不设置,每次切换命令集都会清空历史操作记录.
func WithCommandSetOptionHistoryFile(v string) CommandSetOption 
// 设置当前命令集内所有命令执行的前置检测函数
func WithCommandSetOptionPreCheck(v func(ctx Context) error) CommandSetOption 
// 设置切换到命令集时的提示字符串(自定义文字颜色)
func WithCommandSetOptionPromptWords(v ...*Word) CommandSetOption
// 设置切换到命令集时的提示字符串(默认颜色)
func WithCommandSetOptionPrompt(prompt string) CommandSetOption
// 设置切换到命令集时候的通知函数,args为 SwitchCommandSet 传递的参数.
func WithCommandSetOptionChangeNotify(v func(ctx Context, args []interface{})) CommandSetOption 
#+end_src

*** Word 彩色文字
#+begin_src go
// WordDefault color text
func WordDefault(str string) *Word 
// WordBlue color text
func WordBlue(str string) *Word 
// WordBrown color text
func WordBrown(str string) *Word 
// WordCyan color text
func WordCyan(str string) *Word 
// WordGreen color text
func WordGreen(str string) *Word 
// WordPurple color text
func WordPurple(str string) *Word 
// WordRed color text
func WordRed(str string) *Word 
// WordTurquoise color text
func WordTurquoise(str string) *Word 
// WordWhite color text
func WordWhite(str string) *Word 
// WordYellow color text
func WordYellow(str string) *Word 
#+end_src
** 完整例子
[[./_example/demo/main.go][Common Command]]

[[./_example/commandset/main.go][Command Set]]

** 从[[https://github.com/c-bata/go-prompt/][go-prompt]]复制文件列表
| dir-or-files                            | source-repo | modify |
|-----------------------------------------+-------------+--------|
| internal/ debug,strings,bisect          | [[https://github.com/c-bata/go-prompt/][go-prompt]]   |        |
| output/input/terminal/completion/buffer | [[https://github.com/c-bata/go-prompt/][go-prompt]]   |        |


** 编辑快捷键
*** emacs key bind

Moving the cursor
-----------------
| ok  | key       | description                                                  |
|-----+-----------+--------------------------------------------------------------|
| [x] | Ctrl + a  | Go to the beginning of the line (Home)                       |
| [x] | Ctrl + e  | Go to the End of the line (End)                              |
| [x] | Ctrl + p  | Previous command (Up arrow)                                  |
| [x] | Ctrl + n  | Next command (Down arrow)                                    |
| [x] | Ctrl + f  | Forward one character                                        |
| [x] | Ctrl + b  | Backward one character                                       |
| [x] | Meta + B  |                                                              |
| [x] | Meta + F  |                                                              |

Editing
-------
| ok  | key      | description                                             |
|-----+----------+---------------------------------------------------------|
| [x] | Ctrl + L | Clear the Screen, similar to the clear command          |
| [x] | Ctrl + d | Delete character under the cursor                       |
| [x] | Ctrl + h | Delete character before the cursor (Backspace)          |
| [x] | Ctrl + w | Cut the Word before the cursor to the clipboard.        |
| [x] | Ctrl + k | Cut the Line after the cursor to the clipboard.         |
| [x] | Ctrl + u | Cut/delete the Line before the cursor to the clipboard. |
| [ ] | Ctrl + t | Swap the last two characters before the cursor (typo).  |
| [ ] | Esc  + t | Swap the last two words before the cursor.              |
| [ ] | ctrl + y | Paste the last thing to be cut (yank)                   |
| [ ] | ctrl + _ | Undo                                                    |
** 定制化
promptx 将很多逻辑都做成了可配置项. 查看 "gen_options_*.go"

Documentation

Index

Constants

View Source
const (
	// NormalStatus for normal state
	NormalStatus = iota
	// FinishStatus last input finish
	FinishStatus
	// CancelStatus cancel input
	CancelStatus
)
View Source
const (
	// Matches any key.
	Any            = input.Any
	BackTab        = input.BackTab
	Backspace      = input.Backspace
	BracketedPaste = input.BracketedPaste
	// Special
	CPRResponse        = input.CPRResponse
	ControlA           = input.ControlA
	ControlB           = input.ControlB
	ControlBackslash   = input.ControlBackslash
	ControlC           = input.ControlC
	ControlCircumflex  = input.ControlCircumflex
	ControlD           = input.ControlD
	ControlDelete      = input.ControlDelete
	ControlDown        = input.ControlDown
	ControlE           = input.ControlE
	ControlF           = input.ControlF
	ControlG           = input.ControlG
	ControlH           = input.ControlH
	ControlK           = input.ControlK
	ControlL           = input.ControlL
	ControlLeft        = input.ControlLeft
	ControlN           = input.ControlN
	ControlO           = input.ControlO
	ControlP           = input.ControlP
	ControlQ           = input.ControlQ
	ControlR           = input.ControlR
	ControlRight       = input.ControlRight
	ControlS           = input.ControlS
	ControlSpace       = input.ControlSpace
	ControlSquareClose = input.ControlSquareClose
	ControlT           = input.ControlT
	ControlU           = input.ControlU
	ControlUnderscore  = input.ControlUnderscore
	ControlUp          = input.ControlUp
	ControlV           = input.ControlV
	ControlW           = input.ControlW
	ControlX           = input.ControlX
	ControlY           = input.ControlY
	ControlZ           = input.ControlZ
	Delete             = input.Delete
	Down               = input.Down
	End                = input.End
	Enter              = input.Enter
	Escape             = input.Escape
	F1                 = input.F1
	F10                = input.F10
	F11                = input.F11
	F12                = input.F12
	F13                = input.F13
	F14                = input.F14
	F15                = input.F15
	F16                = input.F16
	F17                = input.F17
	F18                = input.F18
	F19                = input.F19
	F2                 = input.F2
	F20                = input.F20
	F21                = input.F21
	F22                = input.F22
	F23                = input.F23
	F24                = input.F24
	F3                 = input.F3
	F4                 = input.F4
	F5                 = input.F5
	F6                 = input.F6
	F7                 = input.F7
	F8                 = input.F8
	F9                 = input.F9
	Home               = input.Home
	// Key which is ignored. (The key binding for this key should not do anything.)
	Ignore = input.Ignore
	Insert = input.Insert
	Left   = input.Left
	// Meta[Alt] + [a-f]
	MetaA = input.MetaA
	MetaB = input.MetaB
	MetaC = input.MetaC
	MetaD = input.MetaD
	MetaE = input.MetaE
	MetaF = input.MetaF
	MetaG = input.MetaG
	MetaH = input.MetaH
	MetaI = input.MetaI
	MetaJ = input.MetaJ
	MetaK = input.MetaK
	MetaL = input.MetaL
	MetaM = input.MetaM
	MetaN = input.MetaN
	MetaO = input.MetaO
	MetaP = input.MetaP
	MetaQ = input.MetaQ
	MetaR = input.MetaR
	MetaS = input.MetaS
	// Meta[Alt] + Shift [a-z]
	// Meta[Alt] + [A-Z]
	MetaShiftA = input.MetaShiftA
	MetaShiftB = input.MetaShiftB
	MetaShiftC = input.MetaShiftC
	MetaShiftD = input.MetaShiftD
	MetaShiftE = input.MetaShiftE
	MetaShiftF = input.MetaShiftF
	MetaShiftG = input.MetaShiftG
	MetaShiftH = input.MetaShiftH
	MetaShiftI = input.MetaShiftI
	MetaShiftJ = input.MetaShiftJ
	MetaShiftK = input.MetaShiftK
	MetaShiftL = input.MetaShiftL
	MetaShiftM = input.MetaShiftM
	MetaShiftN = input.MetaShiftN
	MetaShiftO = input.MetaShiftO
	MetaShiftP = input.MetaShiftP
	MetaShiftQ = input.MetaShiftQ
	MetaShiftR = input.MetaShiftR
	MetaShiftS = input.MetaShiftS
	MetaShiftT = input.MetaShiftT
	MetaShiftU = input.MetaShiftU
	MetaShiftV = input.MetaShiftV
	MetaShiftW = input.MetaShiftW
	MetaShiftX = input.MetaShiftX
	MetaShiftY = input.MetaShiftY
	MetaShiftZ = input.MetaShiftZ
	MetaT      = input.MetaT
	MetaU      = input.MetaU
	MetaV      = input.MetaV
	MetaW      = input.MetaW
	MetaX      = input.MetaX
	MetaY      = input.MetaY
	MetaZ      = input.MetaZ
	// Key is not defined
	NotDefined  = input.NotDefined
	PageDown    = input.PageDown
	PageUp      = input.PageUp
	Right       = input.Right
	ShiftDelete = input.ShiftDelete
	ShiftDown   = input.ShiftDown
	ShiftLeft   = input.ShiftLeft
	ShiftRight  = input.ShiftRight
	ShiftUp     = input.ShiftUp
	// Aliases.
	Tab               = input.Tab
	Up                = input.Up
	Vt100MouseEvent   = input.Vt100MouseEvent
	WindowsMouseEvent = input.WindowsMouseEvent
)
View Source
const (
	// Black represents a black.
	Black = output.Black
	// Blue represents a blue.
	Blue = output.Blue
	// Brown represents a brown.
	Brown = output.Brown
	// Cyan represents a cyan.
	Cyan = output.Cyan
	// DarkBlue represents a dark blue.
	DarkBlue = output.DarkBlue
	// DarkGray represents a dark gray.
	DarkGray = output.DarkGray
	// DarkGreen represents a dark green.
	DarkGreen = output.DarkGreen
	// DarkRed represents a dark red.
	DarkRed = output.DarkRed
	// DefaultColor represents a default color.
	DefaultColor = output.DefaultColor
	// Fuchsia represents a fuchsia.
	Fuchsia = output.Fuchsia
	// Green represents a green.
	Green = output.Green
	// LightGray represents a light gray.
	LightGray = output.LightGray
	// Purple represents a purple.
	Purple = output.Purple
	// Red represents a red.
	Red = output.Red
	// Turquoise represents a turquoise.
	Turquoise = output.Turquoise
	// White represents a white.
	White = output.White
	// Yellow represents a yellow.
	Yellow = output.Yellow
)

Variables

View Source
var (
	// SuccessWord success word
	SuccessWord = Word{
		Text:      "✔ ",
		TextColor: Green,
		BGColor:   DefaultColor,
		Bold:      false,
	}
	// FailureWord failure word
	FailureWord = Word{
		Text:      "✗ ",
		TextColor: Red,
		BGColor:   DefaultColor,
		Bold:      false,
	}
	AskWord = Word{
		Text:      "? ",
		TextColor: Blue,
		BGColor:   DefaultColor,
		Bold:      false,
	}
	SelectWord = Word{
		Text:      "▸ ",
		TextColor: DefaultColor,
		BGColor:   DefaultColor,
		Bold:      false,
	}
	NewLineWord = Word{
		Text:      "\n",
		TextColor: 0,
		BGColor:   0,
		Bold:      false,
	}
)

preset word for display select,input prefix word.

Functions

func Equal

func Equal(a, b []rune) bool

func HasPrefix

func HasPrefix(r, prefix []rune) bool

func InstallCommandSetOptionsWatchDog added in v0.0.2

func InstallCommandSetOptionsWatchDog(dog func(cc *CommandSetOptions))

InstallCommandSetOptionsWatchDog install watch dog

func InstallCommonOptionsWatchDog

func InstallCommonOptionsWatchDog(dog func(cc *CommonOptions))

InstallCommonOptionsWatchDog install watch dog

func InstallCompleteOptionsWatchDog

func InstallCompleteOptionsWatchDog(dog func(cc *CompleteOptions))

InstallCompleteOptionsWatchDog install watch dog

func InstallInputOptionsWatchDog

func InstallInputOptionsWatchDog(dog func(cc *InputOptions))

InstallInputOptionsWatchDog install watch dog

func InstallPromptOptionsWatchDog

func InstallPromptOptionsWatchDog(dog func(cc *PromptOptions))

InstallPromptOptionsWatchDog install watch dog

func InstallSelectOptionsWatchDog

func InstallSelectOptionsWatchDog(dog func(cc *SelectOptions))

InstallSelectOptionsWatchDog install watch dog

func TrimFirstSpace

func TrimFirstSpace(in []rune) []rune

func TrimSpaceLeft

func TrimSpaceLeft(in []rune) []rune

Types

type ASCIICode

type ASCIICode = input.ASCIICode

ASCIICode is the type contains Key and it's ascii byte array.

type BlocksBaseManager

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

BlocksBaseManager manage some blocks to merge self view

func (*BlocksBaseManager) AddMirrorMode

func (m *BlocksBaseManager) AddMirrorMode(mode ...ConsoleBlocks)

AddMirrorMode add mirror mode

func (*BlocksBaseManager) Backward

func (m *BlocksBaseManager) Backward(from, n int) int

Backward moves cursor to Backward from a current cursor position regardless there is a line break.

func (*BlocksBaseManager) ChangeStatus

func (m *BlocksBaseManager) ChangeStatus()

ChangeStatus change status notify. revert internal status

func (*BlocksBaseManager) Clear

func (m *BlocksBaseManager) Clear()

Clear erases the screen from a beginning of input even if there is line break which means input length exceeds a window's width.

func (*BlocksBaseManager) Columns

func (m *BlocksBaseManager) Columns() int

Columns return console window col count

func (*BlocksBaseManager) Event

func (m *BlocksBaseManager) Event(key Key, in []byte) (exit bool)

Event deal console key press

func (*BlocksBaseManager) ExitSign

func (m *BlocksBaseManager) ExitSign(code int)

func (*BlocksBaseManager) GetContext

func (m *BlocksBaseManager) GetContext() Context

func (*BlocksBaseManager) IsInTask

func (m *BlocksBaseManager) IsInTask() bool

func (*BlocksBaseManager) LineWrap

func (m *BlocksBaseManager) LineWrap(cursor int)

LineWrap line wrap

func (*BlocksBaseManager) Move

func (m *BlocksBaseManager) Move(from, to int) int

Move moves cursor to specified position from the beginning of input even if there is a line break.

func (*BlocksBaseManager) OnEventBefore

func (m *BlocksBaseManager) OnEventBefore(ctx PressContext, key Key, in []byte) (exit bool)

OnEventBefore deal console key press

func (*BlocksBaseManager) OnEventBehind

func (m *BlocksBaseManager) OnEventBehind(ctx PressContext, key Key, in []byte) (exit bool)

OnEventBehind deal console key press

func (*BlocksBaseManager) PrepareArea

func (m *BlocksBaseManager) PrepareArea(lines int)

PrepareArea prepare enough area to display info

func (*BlocksBaseManager) Refresh

func (m *BlocksBaseManager) Refresh()

func (*BlocksBaseManager) Render

func (m *BlocksBaseManager) Render(status int)

BlocksManager renders to the console.

func (*BlocksBaseManager) Rows

func (m *BlocksBaseManager) Rows() int

Rows return console window row count

func (*BlocksBaseManager) SetBeforeEvent

func (m *BlocksBaseManager) SetBeforeEvent(f EventCall)

func (*BlocksBaseManager) SetBehindEvent

func (m *BlocksBaseManager) SetBehindEvent(f EventCall)

func (*BlocksBaseManager) SetCallBack

func (m *BlocksBaseManager) SetCallBack(f func(status int, doc *Buffer) bool)

SetCallBack set call back notify

func (*BlocksBaseManager) SetCancelKey

func (m *BlocksBaseManager) SetCancelKey(k Key)

SetCancelKey set cancel key

func (*BlocksBaseManager) SetCancelKeyAutoExit

func (m *BlocksBaseManager) SetCancelKeyAutoExit(exit bool)

SetCancelKeyAutoExit set exit if press cancel key and input buffer is ""

func (*BlocksBaseManager) SetChangeStatus

func (m *BlocksBaseManager) SetChangeStatus(st int)

SetChangeStatus modify change status

func (*BlocksBaseManager) SetExecContext

func (m *BlocksBaseManager) SetExecContext(ctx Context)

func (*BlocksBaseManager) SetFinishKey

func (m *BlocksBaseManager) SetFinishKey(k Key)

SetFinishKey set finish key press

func (*BlocksBaseManager) SetPreCheck

func (m *BlocksBaseManager) SetPreCheck(f func(status int, doc *Buffer) bool)

SetPreCheck pre check function its arg status is CancelStatus or FinishStatus return true will call callback function later, otherwise render normal

func (*BlocksBaseManager) SetWriter

func (m *BlocksBaseManager) SetWriter(out ConsoleWriter)

func (*BlocksBaseManager) Setup

func (m *BlocksBaseManager) Setup(size *WinSize)

Setup to initialize console output.

func (*BlocksBaseManager) TearDown

func (m *BlocksBaseManager) TearDown()

TearDown to clear title and erasing.

func (*BlocksBaseManager) ToPos

func (m *BlocksBaseManager) ToPos(cursor int) (x, y int)

ToPos returns the relative position from the beginning of the string.

func (*BlocksBaseManager) UpdateWinSize

func (m *BlocksBaseManager) UpdateWinSize(size *WinSize)

UpdateWinSize called when window size is changed.

func (*BlocksBaseManager) Writer

func (m *BlocksBaseManager) Writer() ConsoleWriter

Writer get console writer interface

type BlocksCompletion

type BlocksCompletion struct {
	EmptyBlocks

	Cfg *CompleteOptions

	Completions *CompletionManager
	// contains filtered or unexported fields
}

BlocksCompletion completion blocks

func (*BlocksCompletion) ApplyOptions

func (c *BlocksCompletion) ApplyOptions(opt ...CompleteOption)

func (*BlocksCompletion) EnterSelect

func (c *BlocksCompletion) EnterSelect(buf *Buffer) (ok bool)

func (*BlocksCompletion) InitBlocks

func (c *BlocksCompletion) InitBlocks()

func (*BlocksCompletion) Render

func (c *BlocksCompletion) Render(ctx PrintContext, preCursor int) int

Render render to console

func (*BlocksCompletion) Update

func (c *BlocksCompletion) Update(doc *Document)

type BlocksEmacsBuffer

type BlocksEmacsBuffer struct {
	EmptyBlocks

	// colors
	TextColor Color
	BGColor   Color
	// contains filtered or unexported fields
}

Editing ------- | ok | key | description | |-----+----------+---------------------------------------------------------| | [x] | Ctrl + L | Clear the Screen, similar to the clear command | | [x] | Ctrl + d | Delete character under the cursor | | [x] | Ctrl + h | Delete character before the cursor (Backspace) | | [x] | Ctrl + w | Cut the Word before the cursor to the clipboard. | | [x] | Ctrl + k | Cut the Line after the cursor to the clipboard. | | [x] | Ctrl + u | Cut/delete the Line before the cursor to the clipboard. | | [ ] | Ctrl + t | Swap the last two characters before the cursor (typo). | | [ ] | Esc + t | Swap the last two words before the cursor. | | [ ] | ctrl + y | Paste the last thing to be cut (yank) | | [ ] | ctrl + _ | Undo |

func (*BlocksEmacsBuffer) GetBuffer

func (c *BlocksEmacsBuffer) GetBuffer() *Buffer

func (*BlocksEmacsBuffer) InitBlocks

func (c *BlocksEmacsBuffer) InitBlocks()

func (*BlocksEmacsBuffer) Render

func (c *BlocksEmacsBuffer) Render(ctx PrintContext, preCursor int) int

Render render to console

func (*BlocksEmacsBuffer) ResetBuffer

func (c *BlocksEmacsBuffer) ResetBuffer()

type BlocksManager

type BlocksManager interface {
	// Setup to initialize console output.
	Setup(size *WinSize)
	// TearDown to clear title and erasing.
	TearDown()

	Refresh()
	ExitSign(code int)

	// SetWriter set console writer
	SetWriter(out ConsoleWriter)
	// Writer get console writer interface
	Writer() ConsoleWriter
	// SetChangeStatus  change mode status
	//
	// 0: not change(default value)
	// 1: ready to leave
	SetChangeStatus(st int)
	// change status notify
	ChangeStatus()

	// UpdateWinSize called when window size is changed.
	UpdateWinSize(size *WinSize)
	// Columns return console window col count
	Columns() int
	// Rows return console window row count
	Rows() int

	// Event deal console key press
	Event(key Key, in []byte) (exit bool)
	// Render renders to the console.
	Render(status int)
	// clear blocks last render
	Clear()

	// use for context
	SetExecContext(ctx Context)
	GetContext() Context

	// IsInTask is running event
	IsInTask() bool
}

type BlocksNewLine

type BlocksNewLine struct {
	// BlocksSuffix
	EmptyBlocks
	// context
	Text string
	// colors
	TextColor Color
	BGColor   Color
}

BlocksNewLine render one new line

func (*BlocksNewLine) Render

func (c *BlocksNewLine) Render(ctx PrintContext, preCursor int) int

Render render to console

type BlocksPrefix

type BlocksPrefix struct {
	EmptyBlocks
	// context
	Text string
	// colors
	TextColor Color
	BGColor   Color
	Words     []*Word
}

BlocksPrefix render line prefix

func (*BlocksPrefix) Render

func (c *BlocksPrefix) Render(ctx PrintContext, preCursor int) int

Render render to console

type BlocksSelect

type BlocksSelect struct {
	EmptyBlocks

	SelectFunc func(sels []int)
	// contains filtered or unexported fields
}

BlocksSelect render select

func (*BlocksSelect) GetSelects

func (c *BlocksSelect) GetSelects() []int

func (*BlocksSelect) InitBlocks

func (c *BlocksSelect) InitBlocks()

func (*BlocksSelect) Next

func (c *BlocksSelect) Next(ctx PressContext) (exit bool)

Next to select the next suggestion item.

func (*BlocksSelect) Previous

func (c *BlocksSelect) Previous(ctx PressContext) (exit bool)

Previous to select the previous suggestion item.

func (*BlocksSelect) Render

func (c *BlocksSelect) Render(ctx PrintContext, preCursor int) int

Render render to console

func (*BlocksSelect) Select

func (c *BlocksSelect) Select(ctx PressContext) (exit bool)

type BlocksSuffix

type BlocksSuffix struct {
	EmptyBlocks
	// context
	Text string
	// colors
	TextColor Color
	BGColor   Color
}

BlocksSuffix render one line

func (*BlocksSuffix) Render

func (c *BlocksSuffix) Render(ctx PrintContext, preCursor int) int

Render render to console

type BlocksWords

type BlocksWords struct {
	EmptyBlocks
	Words []*Word
}

BlocksWords words display

func (*BlocksWords) Render

func (c *BlocksWords) Render(ctx PrintContext, preCursor int) (nextCursor int)

Render render to console

type Buffer

type Buffer = buffer.Buffer

Buffer emulates the console buffer.

type Cmd

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

Cmd is a shell command handler.

NOTE: Args and Flags are mutually exclusive with SubCommands, and SubCommands is used first. input sequence is:

command1 [subcommand ...] [arg... ] [flag ...]

like:

query user     userid --log-lv=1
  |    |         |       |
cmd1  sub-cmds  arg     flags

Args must input if it defines.

func NewCommand added in v0.0.2

func NewCommand(name, help string, args ...CommandParameter) *Cmd

NewCommand Create an interactive command

name: command name help: prompt information args: command parameters

func NewCommandWithFunc added in v0.0.2

func NewCommandWithFunc(name, help string, f func(ctx CommandContext), args ...CommandParameter) *Cmd

NewCommandWithFunc create one command

func (*Cmd) Aliases

func (c *Cmd) Aliases(aliases ...string) *Cmd

Aliases Set command alias

func (*Cmd) Children

func (c *Cmd) Children() []*Cmd

Children returns the subcommands of c.

func (*Cmd) DeleteSubCommand added in v0.0.2

func (c *Cmd) DeleteSubCommand(name string)

DeleteSubCommand deletes cmd from subcommands.

func (*Cmd) DynamicTip added in v0.0.2

func (c *Cmd) DynamicTip(f func(line string) []*Suggest) *Cmd

func (*Cmd) ExecFunc added in v0.0.2

func (c *Cmd) ExecFunc(f func(ctx CommandContext)) *Cmd

ExecFunc Set command execution function

see CommondContext for detail.

func (*Cmd) FindSuggest

func (c *Cmd) FindSuggest(doc *Document) []*Suggest

func (*Cmd) FixCommandLine added in v0.0.2

func (c *Cmd) FixCommandLine(line string, args []string) string

func (Cmd) HelpText

func (c Cmd) HelpText() string

HelpText returns the computed help of the command and its subcommands.

func (*Cmd) LogHelp added in v0.0.2

func (c *Cmd) LogHelp(long string) *Cmd

func (*Cmd) ParseInput

func (c *Cmd) ParseInput(line string) (cmds []*Cmd, args []string, err error)

ParseInput parse input,and check valid

func (*Cmd) SubCommands

func (c *Cmd) SubCommands(cmds ...*Cmd) *Cmd

SubCommands adds cmd as a subcommand.

type CmdContext added in v0.0.2

type CmdContext struct {
	Context
	// command and subcommands
	Cmds []*Cmd
	// input args
	Args []string
	// input line
	Line string
	// Root root command. use for dynamic modify command.
	Root *Cmd
	// 当前命令
	Cur *Cmd
	// default select options
	SelectCC *SelectOptions
	// default input options
	InputCC *InputOptions
	// change flag,command args changed by auto action
	ChangeFlag bool
}

CmdContext run context

func (*CmdContext) ArgInput added in v0.0.7

func (ctx *CmdContext) ArgInput(index int, tip string, opts ...InputOption) (result string, eof error)

func (*CmdContext) ArgSelect added in v0.0.7

func (ctx *CmdContext) ArgSelect(index int, tip string, list []string, defaultSelect ...int) int

func (*CmdContext) ArgSelectString added in v1.0.1

func (ctx *CmdContext) ArgSelectString(index int, tip string, list []string, defaultSelect ...int) string

func (*CmdContext) CheckAddrs added in v0.0.2

func (ctx *CmdContext) CheckAddrs(index int) (addrs []string)

func (*CmdContext) CheckIPPort added in v0.0.2

func (ctx *CmdContext) CheckIPPort(index int) (ip, port string)

func (*CmdContext) CheckInteger added in v0.0.2

func (ctx *CmdContext) CheckInteger(index int) int64

func (*CmdContext) CheckSelectIndex added in v0.0.2

func (ctx *CmdContext) CheckSelectIndex(index int) int

func (*CmdContext) CheckString added in v0.0.2

func (ctx *CmdContext) CheckString(index int) string

func (*CmdContext) GetArgs added in v0.0.7

func (ctx *CmdContext) GetArgs() []string

type Color

type Color = output.Color

Color represents color on terminal.

type CommandContext

type CommandContext interface {
	Context

	CheckString(index int) string
	CheckInteger(index int) int64
	CheckIPPort(index int) (ip, port string)
	CheckAddrs(index int) (addrs []string)
	CheckSelectIndex(index int) int

	ArgSelect(index int, tip string, list []string, defaultSelect ...int) int
	ArgSelectString(index int, tip string, list []string, defaultSelect ...int) string
	ArgInput(index int, tip string, opts ...InputOption) (result string, eof error)
	GetArgs() []string
}

CommandContext command context

The command execution function uses the ~Check...~ method provided by ~CommandContext~ to get the parameters. All Check methods, if there is no input from the user, interrupt the process through panic. Or if you enter a value that does not meet expectations, the process will be interrupted by panic. The call to the Check function should match the ~CommandParameter~ entered when creating the command. The Index parameter of the Check function starts at 0. After the ~CommandParameter~ detection passes, the player input retained internally is of string type. So ~CheckString~ is valid as long as the index position is entered. ~CheckSelectIndex~ is only used for the parameters corresponding to ~WithArgSelect~ to get the first few options entered by the player (starting from 0)

type CommandParameter added in v0.0.2

type CommandParameter interface {
	Check(ctx *CmdContext, index int) (err error)
}

CommandParameter command args checker

func WithArgSelect added in v0.0.2

func WithArgSelect(tip string, list []string, opts ...SelectOption) CommandParameter

WithArgSelect Single choice parameter Choose one of many

func WithArgsInput added in v0.0.2

func WithArgsInput(tip string, check InputChecker, opts ...InputOption) CommandParameter

WithArgsInput Manually enter a string as a parameter

type CommandSetOption added in v0.0.2

type CommandSetOption func(cc *CommandSetOptions) CommandSetOption

CommandSetOption option define

func WithCommandSetOptionChangeNotify added in v0.0.2

func WithCommandSetOptionChangeNotify(v func(ctx Context, args []interface{})) CommandSetOption

Set the notification function when switching to the command set, args is the parameter passed by SwitchCommandSet.

func WithCommandSetOptionHistoryFile added in v0.0.2

func WithCommandSetOptionHistoryFile(v string) CommandSetOption

Set the operation record of the current command set to persist the saved file. If not set, the history operation record will be cleared every time the command set is switched.

func WithCommandSetOptionPreCheck added in v0.0.2

func WithCommandSetOptionPreCheck(v func(ctx Context) error) CommandSetOption

Set the pre-detection function for all commands executed in the current command set

func WithCommandSetOptionPrompt added in v0.0.2

func WithCommandSetOptionPrompt(prompt string) CommandSetOption

WithCommandSetOptionPrompt Set the prompt string when switching to the command set(default color)

func WithCommandSetOptionPromptWords added in v0.0.2

func WithCommandSetOptionPromptWords(v ...*Word) CommandSetOption

Set the prompt string when switching to the command set(custom word color)

type CommandSetOptions added in v0.0.2

type CommandSetOptions struct {
	// comman set name
	Name string
	// command set commands
	Commands []*Cmd
	// Set the operation record of the current command set to persist the saved file. If not set, the history operation record will be cleared every time the command set is switched.
	HistoryFile string
	// Set the pre-detection function for all commands executed in the current command set
	PreCheck func(ctx Context) error
	// Set the prompt string when switching to the command set(custom word color)
	PromptWords []*Word
	// Set the notification function when switching to the command set, args is the parameter passed by SwitchCommandSet.
	ChangeNotify func(ctx Context, args []interface{})
}

CommandSetOptions command set options generate by https://github.com/aggronmagi/gogen/

func NewCommandSetOptions added in v0.0.2

func NewCommandSetOptions(opts ...CommandSetOption) *CommandSetOptions

NewCommandSetOptions create options instance.

func (*CommandSetOptions) ApplyOption added in v0.0.2

func (cc *CommandSetOptions) ApplyOption(opts ...CommandSetOption)

ApplyOption modify options

func (*CommandSetOptions) GetSetOption added in v0.0.2

func (cc *CommandSetOptions) GetSetOption(opt CommandSetOption) CommandSetOption

GetSetOption modify and get last option

func (*CommandSetOptions) SetOption added in v0.0.2

func (cc *CommandSetOptions) SetOption(opt CommandSetOption)

SetOption modify options

type CommonBlockManager

type CommonBlockManager struct {
	*BlocksBaseManager
	Tip        *BlocksWords
	PreWords   *BlocksWords
	Input      *BlocksEmacsBuffer
	Validate   *BlocksNewLine
	Completion *BlocksCompletion
	// contains filtered or unexported fields
}

CommonBlockManager default block manager.

func NewDefaultBlockManger

func NewDefaultBlockManger(opts ...CommonOption) (m *CommonBlockManager)

NewDefaultBlockManger default blocks manager.

func (*CommonBlockManager) AddHistory added in v0.0.2

func (m *CommonBlockManager) AddHistory(line string)

AddHistory add line to history

func (*CommonBlockManager) ApplyOption

func (m *CommonBlockManager) ApplyOption(opts ...CommonOption)

func (*CommonBlockManager) BeforeEvent

func (m *CommonBlockManager) BeforeEvent(ctx PressContext, key Key, in []byte) (exit bool)

func (*CommonBlockManager) BehindEvent

func (m *CommonBlockManager) BehindEvent(ctx PressContext, key Key, in []byte) (exit bool)

func (*CommonBlockManager) ExecCommand

func (m *CommonBlockManager) ExecCommand(args []string)

func (*CommonBlockManager) FinishCallBack

func (m *CommonBlockManager) FinishCallBack(status int, buf *Buffer) bool

FinishCallBack call back

func (*CommonBlockManager) PreCheckCallBack

func (m *CommonBlockManager) PreCheckCallBack(status int, buf *Buffer) (success bool)

PreCheckCallBack change status pre check

func (*CommonBlockManager) RemoveHistory added in v0.0.2

func (m *CommonBlockManager) RemoveHistory(line string)

RemoveHistory remove from history

func (*CommonBlockManager) ResetCommands added in v0.0.2

func (m *CommonBlockManager) ResetCommands(cmds ...*Cmd)

ResetCommands 重置命令集合

func (*CommonBlockManager) ResetHistoryFile added in v0.0.2

func (m *CommonBlockManager) ResetHistoryFile(filename string)

func (*CommonBlockManager) SetCommandPreCheck added in v0.0.2

func (m *CommonBlockManager) SetCommandPreCheck(f func(ctx Context) error)

func (*CommonBlockManager) SetOption

func (m *CommonBlockManager) SetOption(opt CommonOption)

func (*CommonBlockManager) SetPrompt

func (m *CommonBlockManager) SetPrompt(text string)

SetPrompt set prefix text

func (*CommonBlockManager) SetPromptWords

func (m *CommonBlockManager) SetPromptWords(words ...*Word)

SetPromptWords update prompt string. custom display.

func (*CommonBlockManager) TearDown

func (m *CommonBlockManager) TearDown()

TearDown to clear title and erasing.

type CommonOption

type CommonOption func(cc *CommonOptions) CommonOption

CommonOption option define

func WithCommonOptionAlwaysCheckCommand

func WithCommonOptionAlwaysCheckCommand(v bool) CommonOption

alway check input command

func WithCommonOptionCancelKey

func WithCommonOptionCancelKey(v Key) CommonOption

func WithCommonOptionCommandPreCheck added in v0.0.2

func WithCommonOptionCommandPreCheck(v func(ctx Context) error) CommonOption

CommandPreCheck check before exec Cmd. only use for promptx.Cmd.

func WithCommonOptionCommands

func WithCommonOptionCommands(v ...*Cmd) CommonOption

if command slice size > 0. it will ignore ExecFunc and ValidFunc options

func WithCommonOptionCompletion

func WithCommonOptionCompletion(v ...CompleteOption) CommonOption

func WithCommonOptionExecFunc

func WithCommonOptionExecFunc(v func(ctx Context, command string)) CommonOption

exec input command

func WithCommonOptionFinishKey

func WithCommonOptionFinishKey(v Key) CommonOption

func WithCommonOptionHistory

func WithCommonOptionHistory(v string) CommonOption

history file

func WithCommonOptionPrefixBGColor

func WithCommonOptionPrefixBGColor(v Color) CommonOption

func WithCommonOptionPrefixText

func WithCommonOptionPrefixText(v string) CommonOption

func WithCommonOptionPrefixTextColor

func WithCommonOptionPrefixTextColor(v Color) CommonOption

func WithCommonOptionTipBGColor

func WithCommonOptionTipBGColor(v Color) CommonOption

func WithCommonOptionTipText

func WithCommonOptionTipText(v string) CommonOption

func WithCommonOptionTipTextColor

func WithCommonOptionTipTextColor(v Color) CommonOption

func WithCommonOptionValidBGColor

func WithCommonOptionValidBGColor(v Color) CommonOption

func WithCommonOptionValidFunc

func WithCommonOptionValidFunc(v func(status int, in *Document) error) CommonOption

check input valid

func WithCommonOptionValidTextColor

func WithCommonOptionValidTextColor(v Color) CommonOption

type CommonOptions

type CommonOptions struct {
	TipText         string
	TipTextColor    Color
	TipBGColor      Color
	PrefixText      string
	PrefixTextColor Color
	PrefixBGColor   Color
	// check input valid
	ValidFunc      func(status int, in *Document) error
	ValidTextColor Color
	ValidBGColor   Color
	// exec input command
	ExecFunc   func(ctx Context, command string)
	FinishKey  Key
	CancelKey  Key
	Completion []CompleteOption
	// if command slice size > 0. it will ignore ExecFunc and ValidFunc options
	Commands []*Cmd
	// alway check input command
	AlwaysCheckCommand bool
	// history file
	History string
	// CommandPreCheck check before exec Cmd. only use for promptx.Cmd.
	CommandPreCheck func(ctx Context) error
}

CommonOptions promptx options generate by https://github.com/aggronmagi/gogen/

func NewCommonOptions

func NewCommonOptions(opts ...CommonOption) *CommonOptions

NewCommonOptions create options instance.

func (*CommonOptions) ApplyOption

func (cc *CommonOptions) ApplyOption(opts ...CommonOption)

ApplyOption modify options

func (*CommonOptions) GetSetOption

func (cc *CommonOptions) GetSetOption(opt CommonOption) CommonOption

GetSetOption modify and get last option

func (*CommonOptions) SetOption

func (cc *CommonOptions) SetOption(opt CommonOption)

SetOption modify options

type CompleteOption

type CompleteOption func(cc *CompleteOptions) CompleteOption

CompleteOption option define

func WithCompleteOptionCompleteMax

func WithCompleteOptionCompleteMax(v int) CompleteOption

func WithCompleteOptionCompleter

func WithCompleteOptionCompleter(v Completer) CompleteOption

func WithCompleteOptionCompletionFillSpace

func WithCompleteOptionCompletionFillSpace(v bool) CompleteOption

func WithCompleteOptionDescriptionBGColor

func WithCompleteOptionDescriptionBGColor(v Color) CompleteOption

func WithCompleteOptionDescriptionTextColor

func WithCompleteOptionDescriptionTextColor(v Color) CompleteOption

func WithCompleteOptionScrollbarBGColor

func WithCompleteOptionScrollbarBGColor(v Color) CompleteOption

func WithCompleteOptionScrollbarThumbColor

func WithCompleteOptionScrollbarThumbColor(v Color) CompleteOption

func WithCompleteOptionSelectedDescriptionBGColor

func WithCompleteOptionSelectedDescriptionBGColor(v Color) CompleteOption

func WithCompleteOptionSelectedDescriptionTextColor

func WithCompleteOptionSelectedDescriptionTextColor(v Color) CompleteOption

func WithCompleteOptionSelectedSuggestionBGColor

func WithCompleteOptionSelectedSuggestionBGColor(v Color) CompleteOption

func WithCompleteOptionSelectedSuggestionTextColor

func WithCompleteOptionSelectedSuggestionTextColor(v Color) CompleteOption

func WithCompleteOptionSuggestionBGColor

func WithCompleteOptionSuggestionBGColor(v Color) CompleteOption

func WithCompleteOptionSuggestionTextColor

func WithCompleteOptionSuggestionTextColor(v Color) CompleteOption

type CompleteOptions

type CompleteOptions struct {
	SuggestionTextColor          Color
	SuggestionBGColor            Color
	SelectedSuggestionTextColor  Color
	SelectedSuggestionBGColor    Color
	DescriptionTextColor         Color
	DescriptionBGColor           Color
	SelectedDescriptionTextColor Color
	SelectedDescriptionBGColor   Color
	ScrollbarThumbColor          Color
	ScrollbarBGColor             Color
	Completer                    Completer
	CompleteMax                  int
	CompletionFillSpace          bool
}

CompleteOptions promptx options generate by https://github.com/aggronmagi/gogen/

func NewCompleteOptions

func NewCompleteOptions(opts ...CompleteOption) *CompleteOptions

NewCompleteOptions create options instance.

func (*CompleteOptions) ApplyOption

func (cc *CompleteOptions) ApplyOption(opts ...CompleteOption)

ApplyOption modify options

func (*CompleteOptions) GetSetOption

func (cc *CompleteOptions) GetSetOption(opt CompleteOption) CompleteOption

GetSetOption modify and get last option

func (*CompleteOptions) SetOption

func (cc *CompleteOptions) SetOption(opt CompleteOption)

SetOption modify options

type Completer

type Completer func(in Document) []*Suggest

Completer should return the suggest item from Document.

type CompletionManager

type CompletionManager = completion.CompletionManager

CompletionManager manages which suggestion is now selected.

type ConsoleBlocks

type ConsoleBlocks interface {
	InitBlocks()
	Active() bool
	SetActive(active bool)
	IsDraw(status int) bool
	Render(ctx PrintContext, preCursor int) (cursor int)
	OnEvent(ctx PressContext, key Key, in []byte) (exit bool)
	ResetBuffer()
	GetBuffer() *Buffer
}

ConsoleBlocks Terminal block interface. Used for combination providing functions.

type ConsoleParser

type ConsoleParser = input.ConsoleParser

ConsoleParser is an interface to abstract input layer.

type ConsoleWriter

type ConsoleWriter = output.ConsoleWriter

ConsoleWriter is an interface to abstract output layer.

type Context

type Context interface {
	// Stop stop run
	Stop()
	// EnterRawMode enter raw mode for read key press real time
	EnterRawMode() (err error)
	// ExitRawMode exit raw mode
	ExitRawMode() (err error)
	// Stdout return a wrap stdout writer. it can refersh view correct
	Stdout() io.Writer
	// Stderr std err
	Stderr() io.Writer
	// ClearScreen clears the screen.
	ClearScreen()
	// SetTitle set window title
	SetTitle(title string)
	// ClearTitle clear window title
	ClearTitle()
	// SetPrompt update prompt string. prompt will auto add space suffix.
	SetPrompt(prompt string)
	// SetPromptWords update prompt string. custom display.
	SetPromptWords(words ...*Word)
	// ResetCommands reset all command set.
	ResetCommands(commands ...*Cmd)
	// RemoveHistory remove from history
	RemoveHistory(line string)
	// AddHistory add line to history
	AddHistory(line string)
	// reset history file
	ResetHistoryFile(filename string)
	// SetCommandPreCheck check before exec *promptx.Cmd
	SetCommandPreCheck(f func(ctx Context) error)
	// AddCommandSet add command set,it will auto switch when first add commandset.
	AddCommandSet(name string, cmds []*Cmd, opts ...CommandSetOption)
	// SwitchCommandSet switch to specify commands set,args will pass to ChangeNotify func.
	SwitchCommandSet(name string, args ...interface{})
	// Print = fmt.Print
	Print(v ...interface{})
	// Printf = fmt.Printf
	Printf(fmt string, v ...interface{})
	// Println = fmt.Println
	Println(v ...interface{})

	// WPrint  print words
	WPrint(words ...*Word)
	// WPrintln print words and newline
	WPrintln(words ...*Word)

	RawInput(tip string, opts ...InputOption) (result string, err error)
	Input(tip string, checker InputChecker, defaultValue ...string) (result string, err error)
	MustInput(tip string, checker InputChecker) string
	InputInt(tip string, val int, check ...func(in int) error) (_ int, eof error)
	MustInputInt(tip string, val int, check ...func(in int) error) int
	InputIntSlice(tip string, val []int, check ...func(in []int) error) (_ []int, eof error)
	MustInputIntSlice(tip string, val []int, check ...func(in []int) error) []int
	InputInt64(tip string, val int64, check ...func(in int64) error) (_ int64, eof error)
	MustInputInt64(tip string, val int64, check ...func(in int64) error) int64
	InputInt64Slice(tip string, val []int64, check ...func(in []int64) error) (_ []int64, eof error)
	MustInputInt64Slice(tip string, val []int64, check ...func(in []int64) error) []int64
	InputInt32(tip string, val int32, check ...func(in int32) error) (_ int32, eof error)
	MustInputInt32(tip string, val int32, check ...func(in int32) error) int32
	InputInt32Slice(tip string, val []int32, check ...func(in []int32) error) (_ []int32, eof error)
	MustInputInt32Slice(tip string, val []int32, check ...func(in []int32) error) []int32
	InputString(tip string, val string, check ...func(in string) error) (_ string, eof error)
	MustInputString(tip string, val string, check ...func(in string) error) string
	InputStringSlice(tip string, val []string, check ...func(in []string) error) (_ []string, eof error)
	MustInputStringSlice(tip string, val []string, check ...func(in []string) error) []string
	InputFloat32(tip string, val float32, check ...func(in float32) error) (_ float32, eof error)
	MustInputFloat32(tip string, val float32, check ...func(in float32) error) float32
	InputFloat32Slice(tip string, val []float32, check ...func(in []float32) error) (_ []float32, eof error)
	MustInputFloat32Slice(tip string, val []float32, check ...func(in []float32) error) []float32
	InputFloat64(tip string, val float64, check ...func(in float64) error) (_ float64, eof error)
	MustInputFloat64(tip string, val float64, check ...func(in float64) error) float64
	InputFloat64Slice(tip string, val []float64, check ...func(in []float64) error) (_ []float64, eof error)
	MustInputFloat64Slice(tip string, val []float64, check ...func(in []float64) error) []float64
	RawSelect(tip string, list []string, opts ...SelectOption) (result int)
	Select(tip string, list []string, defaultSelect ...int) (result int)
	MustSelect(tip string, list []string, defaultSelect ...int) (result int)
	SelectString(tip string, list []string, defaultSelect ...int) (_ string, cancel bool)
	MustSelectString(tip string, list []string, defaultSelect ...int) string
	RawMulSel(tip string, list []string, opts ...SelectOption) (result []int)
	MulSel(tip string, list []string, defaultSelects ...int) (result []int)
	MustMulSel(tip string, list []string, defaultSelects ...int) (result []int)
	MulSelString(tip string, list []string, defaultSelects ...int) (result []string)
	MustMulSelString(tip string, list []string, defaultSelects ...int) (result []string)
}

Context Run Command Context

type Document

type Document = buffer.Document

Document has text displayed in terminal and cursor position.

type EmptyBlocks

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

EmptyBlocks empty for basic operation

func (*EmptyBlocks) Active

func (m *EmptyBlocks) Active() bool

Active is blocks active

func (*EmptyBlocks) BindASCII

func (m *EmptyBlocks) BindASCII(bind KeyBindFunc, ins ...byte)

BindASCII bind ascii code func

func (*EmptyBlocks) BindKey

func (m *EmptyBlocks) BindKey(bind KeyBindFunc, keys ...Key)

BindKey bind key funcs

func (*EmptyBlocks) GetBuffer

func (m *EmptyBlocks) GetBuffer() *Buffer

GetBuffer get input buffer

func (*EmptyBlocks) InitBlocks

func (m *EmptyBlocks) InitBlocks()

InitBlocks init blocks

func (*EmptyBlocks) IsBind

func (m *EmptyBlocks) IsBind(key Key) bool

func (*EmptyBlocks) IsDraw

func (m *EmptyBlocks) IsDraw(status int) bool

func (*EmptyBlocks) OnEvent

func (m *EmptyBlocks) OnEvent(ctx PressContext, key Key, in []byte) (exit bool)

OnEvent deal console key press

func (*EmptyBlocks) Render

func (m *EmptyBlocks) Render(ctx PrintContext, preCursor int) (cursor int)

Render rendering blocks.

func (EmptyBlocks) ResetBuffer

func (m EmptyBlocks) ResetBuffer()

ResetBuffer reset buffer

func (*EmptyBlocks) SetActive

func (m *EmptyBlocks) SetActive(active bool)

SetActive set active status

func (*EmptyBlocks) SetIsDraw

func (m *EmptyBlocks) SetIsDraw(f func(status int) (draw bool))

type EventCall

type EventCall func(ctx PressContext, key Key, in []byte) (exit bool)

type Filter

type Filter = completion.Filter

Filter is the type to filter the prompt.Suggestion array.

type InputBlockManager

type InputBlockManager struct {
	*BlocksBaseManager
	PreWords *BlocksWords
	Input    *BlocksEmacsBuffer
	Validate *BlocksNewLine
	// contains filtered or unexported fields
}

func NewInputManager

func NewInputManager(cc *InputOptions) (m *InputBlockManager)

NewInputManager new input text

func (*InputBlockManager) BeforeEvent

func (m *InputBlockManager) BeforeEvent(ctx PressContext, key Key, in []byte) (exit bool)

func (*InputBlockManager) FinishCallBack

func (m *InputBlockManager) FinishCallBack(status int, buf *Buffer) bool

FinishCallBack call back

func (*InputBlockManager) PreCheckCallBack

func (m *InputBlockManager) PreCheckCallBack(status int, buf *Buffer) (success bool)

PreCheckCallBack change status pre check

type InputChecker added in v0.0.2

type InputChecker func(d *Document) (err error)

InputChecker input checker

func InputAddrsArray added in v0.0.2

func InputAddrsArray() InputChecker

InputAddrsArray The detection input must be an array of IP ports, separated by ",".

func InputFloat32 added in v1.0.1

func InputFloat32() InputChecker

func InputFloat32Slice added in v1.0.1

func InputFloat32Slice() InputChecker

func InputFloat64 added in v1.0.1

func InputFloat64() InputChecker

func InputFloat64Slice added in v1.0.1

func InputFloat64Slice() InputChecker

func InputIPPort added in v0.0.2

func InputIPPort() InputChecker

InputIPPort The detection input must be an IP port(example 127.0.0.1:8080)

func InputInteger added in v0.0.2

func InputInteger() InputChecker

InputInteger The detection input must be a non-zero value

func InputIntegerRange added in v0.0.2

func InputIntegerRange(min, max int64) InputChecker

InputIntegerRange The detection input must be a number in the min, max interval

func InputNaturalNumber added in v0.0.2

func InputNaturalNumber() InputChecker

InputNaturalNumber Detection input must be a natural number (1,2,3....)

func InputNotEmpty added in v0.0.2

func InputNotEmpty() InputChecker

InputNotEmpty Detection input must be a non-empty string

func InputNotEmptyAndSpace added in v0.0.7

func InputNotEmptyAndSpace() InputChecker

InputNotEmptyAndSpace Detection input must be a non-empty string,can't contain space.

func InputNotZeroInteger added in v0.0.2

func InputNotZeroInteger() InputChecker

InputNotZeroInteger The detection input must be a non-zero number

type InputFinishTextFunc

type InputFinishTextFunc func(cc *InputOptions, status int, doc *Document, defaultText string) (words []*Word)

InputFinishTextFunc modify finish text display

type InputOption

type InputOption func(cc *InputOptions) InputOption

InputOption option define

func WithInputOptionCancelKey

func WithInputOptionCancelKey(v Key) InputOption

func WithInputOptionDefaultText added in v1.0.1

func WithInputOptionDefaultText(v string) InputOption

func WithInputOptionDefaultTextAny added in v1.0.1

func WithInputOptionDefaultTextAny(v interface{}) InputOption

func WithInputOptionDefaultTextBGColor added in v1.0.1

func WithInputOptionDefaultTextBGColor(v Color) InputOption

func WithInputOptionDefaultTextColor added in v1.0.1

func WithInputOptionDefaultTextColor(v Color) InputOption

func WithInputOptionFinishFunc

func WithInputOptionFinishFunc(v func(input string, eof error)) InputOption

func WithInputOptionFinishKey

func WithInputOptionFinishKey(v Key) InputOption

func WithInputOptionPrefixBGColor

func WithInputOptionPrefixBGColor(v Color) InputOption

func WithInputOptionPrefixText

func WithInputOptionPrefixText(v string) InputOption

func WithInputOptionPrefixTextColor

func WithInputOptionPrefixTextColor(v Color) InputOption

func WithInputOptionResultBGColor

func WithInputOptionResultBGColor(v Color) InputOption

func WithInputOptionResultText

func WithInputOptionResultText(v InputFinishTextFunc) InputOption

result display

func WithInputOptionResultTextColor

func WithInputOptionResultTextColor(v Color) InputOption

func WithInputOptionTipBGColor

func WithInputOptionTipBGColor(v Color) InputOption

func WithInputOptionTipText

func WithInputOptionTipText(v string) InputOption

func WithInputOptionTipTextColor

func WithInputOptionTipTextColor(v Color) InputOption

func WithInputOptionValidBGColor

func WithInputOptionValidBGColor(v Color) InputOption

func WithInputOptionValidFunc

func WithInputOptionValidFunc(v func(*Document) error) InputOption

func WithInputOptionValidTextColor

func WithInputOptionValidTextColor(v Color) InputOption

type InputOptions

type InputOptions struct {
	TipText         string
	TipTextColor    Color
	TipBGColor      Color
	PrefixText      string
	PrefixTextColor Color
	PrefixBGColor   Color
	ValidFunc       func(*Document) error
	ValidTextColor  Color
	ValidBGColor    Color
	FinishFunc      func(input string, eof error)
	FinishKey       Key
	CancelKey       Key
	// result display
	ResultText         InputFinishTextFunc
	ResultTextColor    Color
	ResultBGColor      Color
	DefaultText        string
	DefaultTextColor   Color
	DefaultTextBGColor Color
}

InputOptions promptx options generate by https://github.com/aggronmagi/gogen/

func NewInputOptions

func NewInputOptions(opts ...InputOption) *InputOptions

NewInputOptions create options instance.

func (*InputOptions) ApplyOption

func (cc *InputOptions) ApplyOption(opts ...InputOption)

ApplyOption modify options

func (*InputOptions) GetSetOption

func (cc *InputOptions) GetSetOption(opt InputOption) InputOption

GetSetOption modify and get last option

func (*InputOptions) SetOption

func (cc *InputOptions) SetOption(opt InputOption)

SetOption modify options

type Key

type Key = input.Key

Key is the type express the key inserted from user.

type KeyBind

type KeyBind struct {
	Key Key
	Fn  KeyBindFunc
}

KeyBind represents which key should do what operation.

type KeyBindFunc

type KeyBindFunc func(ctx PressContext) (exit bool)

KeyBindFunc receives context and process

type PressContext

type PressContext interface {
	// GetBuffer get input buffer
	GetBuffer() *Buffer
	// console writer
	Writer() ConsoleWriter
	// GetKey get input keys
	GetKey() Key
	// GetInput get input bytes
	GetInput() []byte
}

PressContext export for logic loop

type PrintContext

type PrintContext interface {
	// console writer
	Writer() ConsoleWriter

	// ToPos returns the relative position from the beginning of the string.
	ToPos(cursor int) (x, y int)
	// Columns return console window col count
	Columns() int
	// Rows return console window row count
	Rows() int

	// Backward moves cursor to Backward from a current cursor position
	// regardless there is a line break.
	Backward(from, n int) int
	// Move moves cursor to specified position from the beginning of input
	// even if there is a line break.
	Move(from, to int) int
	// PrepareArea prepare enough area to display info
	PrepareArea(lines int)
	// LineWrap line wrap
	LineWrap(cursor int)

	// InputCursor get input buffer cursor pos. if no cursor,return -1.
	InputCursor() int
	// GetBuffer get input buffer
	GetBuffer() *Buffer
	// SetBuffer set input buffer. if not set, cursor will be hided.
	SetBuffer(buf *Buffer)
	// Prepare pre calc line to prepare area
	Prepare() bool
	// Status return current status. 0: normal 1: finish 2:canel
	Status() int
}

PrintContext context

type PromptMain added in v0.0.4

type PromptMain interface {
	Context
	Run() error
	ExecCommand(args []string)
}

func NewCommandPromptx

func NewCommandPromptx(cmds ...*Cmd) PromptMain

NewCommandPromptx new with command

func NewOptionCommandPromptx

func NewOptionCommandPromptx(cc *PromptOptions, cmds ...*Cmd) PromptMain

NewOptionCommandPromptx new with command and options use for replace NewCommandPromptx when you need apply other options. example: NewCommandPromptx(cmds...) => NewOptionCommandPromptx(NewPromptOptions(....),cmds...)

func NewPromptx

func NewPromptx(opts ...PromptOption) PromptMain

NewPromptx new prompt

type PromptOption

type PromptOption func(cc *PromptOptions) PromptOption

PromptOption option define

func WithBlocksManager

func WithBlocksManager(v BlocksManager) PromptOption

default manager. if it is not nil, ignore CommonOpions.

func WithCommonOpions

func WithCommonOpions(v ...CommonOption) PromptOption

default common options. use to create default optins

func WithInput

func WithInput(v input.ConsoleParser) PromptOption

input

func WithInputOptions

func WithInputOptions(v ...InputOption) PromptOption

default global input options

func WithOutput

func WithOutput(v output.ConsoleWriter) PromptOption

output

func WithSelectOptions

func WithSelectOptions(v ...SelectOption) PromptOption

default global select options

func WithStderr

func WithStderr(v output.ConsoleWriter) PromptOption

type PromptOptions

type PromptOptions struct {
	// default global input options
	InputOptions []InputOption
	// default global select options
	SelectOptions []SelectOption
	// default common options. use to create default optins
	CommonOpions []CommonOption
	// default manager. if it is not nil, ignore CommonOpions.
	BlocksManager BlocksManager
	// input
	Input input.ConsoleParser
	// output
	Output output.ConsoleWriter
	Stderr output.ConsoleWriter
}

PromptOptions promptx options generate by https://github.com/aggronmagi/gogen/

func NewPromptOptions

func NewPromptOptions(opts ...PromptOption) *PromptOptions

NewPromptOptions create options instance.

func (*PromptOptions) ApplyOption

func (cc *PromptOptions) ApplyOption(opts ...PromptOption)

ApplyOption modify options

func (*PromptOptions) GetSetOption

func (cc *PromptOptions) GetSetOption(opt PromptOption) PromptOption

GetSetOption modify and get last option

func (*PromptOptions) SetOption

func (cc *PromptOptions) SetOption(opt PromptOption)

SetOption modify options

type Promptx

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

Promptx prompt command line

func (*Promptx) AddCommandSet added in v0.0.2

func (p *Promptx) AddCommandSet(name string, cmds []*Cmd, opts ...CommandSetOption)

AddCommandSet add command set,it will auto switch when first add commandset.

func (*Promptx) AddHistory added in v0.0.2

func (p *Promptx) AddHistory(line string)

AddHistory add line to history

func (*Promptx) ClearScreen

func (p *Promptx) ClearScreen()

ClearScreen clears the screen.

func (*Promptx) ClearTitle

func (p *Promptx) ClearTitle()

ClearTitle clear title

func (*Promptx) EnterRawMode

func (p *Promptx) EnterRawMode() (err error)

EnterRawMode enter raw mode for read key press real time

func (*Promptx) ExecCommand

func (p *Promptx) ExecCommand(args []string)

func (*Promptx) ExitRawMode

func (p *Promptx) ExitRawMode() (err error)

ExitRawMode exit raw mode

func (*Promptx) Input

func (p *Promptx) Input(tip string, checker InputChecker, defaultValue ...string) (result string, err error)

Input get input

func (*Promptx) InputFloat32 added in v1.0.1

func (p *Promptx) InputFloat32(tip string, val float32, check ...func(in float32) error) (_ float32, eof error)

func (*Promptx) InputFloat32Slice added in v1.0.1

func (p *Promptx) InputFloat32Slice(tip string, val []float32, check ...func(in []float32) error) (_ []float32, eof error)

func (*Promptx) InputFloat64 added in v1.0.1

func (p *Promptx) InputFloat64(tip string, val float64, check ...func(in float64) error) (_ float64, eof error)

func (*Promptx) InputFloat64Slice added in v1.0.1

func (p *Promptx) InputFloat64Slice(tip string, val []float64, check ...func(in []float64) error) (_ []float64, eof error)

func (*Promptx) InputInt added in v1.0.1

func (p *Promptx) InputInt(tip string, val int, check ...func(in int) error) (_ int, eof error)

func (*Promptx) InputInt32 added in v1.0.1

func (p *Promptx) InputInt32(tip string, val int32, check ...func(in int32) error) (_ int32, eof error)

func (*Promptx) InputInt32Slice added in v1.0.1

func (p *Promptx) InputInt32Slice(tip string, val []int32, check ...func(in []int32) error) (_ []int32, eof error)

func (*Promptx) InputInt64 added in v1.0.1

func (p *Promptx) InputInt64(tip string, val int64, check ...func(in int64) error) (_ int64, eof error)

func (*Promptx) InputInt64Slice added in v1.0.1

func (p *Promptx) InputInt64Slice(tip string, val []int64, check ...func(in []int64) error) (_ []int64, eof error)

func (*Promptx) InputIntSlice added in v1.0.1

func (p *Promptx) InputIntSlice(tip string, val []int, check ...func(in []int) error) (_ []int, eof error)

func (*Promptx) InputString added in v1.0.1

func (p *Promptx) InputString(tip string, val string, check ...func(in string) error) (_ string, eof error)

func (*Promptx) InputStringSlice added in v1.0.1

func (p *Promptx) InputStringSlice(tip string, val []string, check ...func(in []string) error) (_ []string, eof error)

func (*Promptx) MulSel

func (p *Promptx) MulSel(tip string, list []string, defaultSelects ...int) (result []int)

MulSel get multiple value with raw option

func (*Promptx) MulSelString added in v1.0.1

func (p *Promptx) MulSelString(tip string, list []string, defaultSelects ...int) (result []string)

MulSel get multiple value with raw option

func (*Promptx) MustInput added in v1.0.2

func (p *Promptx) MustInput(tip string, checker InputChecker) string

Input get input

func (*Promptx) MustInputFloat32 added in v1.0.1

func (p *Promptx) MustInputFloat32(tip string, val float32, check ...func(in float32) error) float32

func (*Promptx) MustInputFloat32Slice added in v1.0.1

func (p *Promptx) MustInputFloat32Slice(tip string, val []float32, check ...func(in []float32) error) []float32

func (*Promptx) MustInputFloat64 added in v1.0.1

func (p *Promptx) MustInputFloat64(tip string, val float64, check ...func(in float64) error) float64

func (*Promptx) MustInputFloat64Slice added in v1.0.1

func (p *Promptx) MustInputFloat64Slice(tip string, val []float64, check ...func(in []float64) error) []float64

func (*Promptx) MustInputInt added in v1.0.1

func (p *Promptx) MustInputInt(tip string, val int, check ...func(in int) error) int

func (*Promptx) MustInputInt32 added in v1.0.1

func (p *Promptx) MustInputInt32(tip string, val int32, check ...func(in int32) error) int32

func (*Promptx) MustInputInt32Slice added in v1.0.1

func (p *Promptx) MustInputInt32Slice(tip string, val []int32, check ...func(in []int32) error) []int32

func (*Promptx) MustInputInt64 added in v1.0.1

func (p *Promptx) MustInputInt64(tip string, val int64, check ...func(in int64) error) int64

func (*Promptx) MustInputInt64Slice added in v1.0.1

func (p *Promptx) MustInputInt64Slice(tip string, val []int64, check ...func(in []int64) error) []int64

func (*Promptx) MustInputIntSlice added in v1.0.1

func (p *Promptx) MustInputIntSlice(tip string, val []int, check ...func(in []int) error) []int

func (*Promptx) MustInputString added in v1.0.1

func (p *Promptx) MustInputString(tip string, val string, check ...func(in string) error) string

func (*Promptx) MustInputStringSlice added in v1.0.1

func (p *Promptx) MustInputStringSlice(tip string, val []string, check ...func(in []string) error) []string

func (*Promptx) MustMulSel added in v1.0.1

func (p *Promptx) MustMulSel(tip string, list []string, defaultSelects ...int) (result []int)

MulSel get multiple value with raw option

func (*Promptx) MustMulSelString added in v1.0.1

func (p *Promptx) MustMulSelString(tip string, list []string, defaultSelects ...int) (result []string)

MustMulSelString get multiple value with raw option

func (*Promptx) MustSelect added in v1.0.1

func (p *Promptx) MustSelect(tip string, list []string, defaultSelect ...int) (result int)

Select get select value

func (*Promptx) MustSelectString added in v1.0.1

func (p *Promptx) MustSelectString(tip string, list []string, defaultSelect ...int) string

Select get select value

func (*Promptx) Print

func (p *Promptx) Print(v ...interface{})

Print = fmt.Print

func (*Promptx) Printf

func (p *Promptx) Printf(format string, v ...interface{})

Printf = fmt.Printf

func (*Promptx) Println

func (p *Promptx) Println(v ...interface{})

Println = fmt.Println

func (*Promptx) RawInput added in v1.0.1

func (p *Promptx) RawInput(tip string, opts ...InputOption) (result string, err error)

RawInput get input

func (*Promptx) RawMulSel added in v1.0.1

func (p *Promptx) RawMulSel(tip string, list []string, opts ...SelectOption) (result []int)

RawMulSel get multiple value with raw option

func (*Promptx) RawSelect added in v1.0.1

func (p *Promptx) RawSelect(tip string, list []string, opts ...SelectOption) (result int)

RawSelect get select value with raw option

func (*Promptx) RemoveHistory added in v0.0.2

func (p *Promptx) RemoveHistory(line string)

RemoveHistory remove from history

func (*Promptx) ResetCommands added in v0.0.2

func (p *Promptx) ResetCommands(commands ...*Cmd)

ResetCommands 重置命令集合

func (*Promptx) ResetHistoryFile added in v0.0.2

func (p *Promptx) ResetHistoryFile(filename string)

func (*Promptx) Run

func (p *Promptx) Run() (err error)

Run run prompt

func (*Promptx) Select

func (p *Promptx) Select(tip string, list []string, defaultSelect ...int) (result int)

Select get select value

func (*Promptx) SelectString added in v1.0.1

func (p *Promptx) SelectString(tip string, list []string, defaultSelect ...int) (_ string, cancel bool)

Select get select value

func (*Promptx) SetCommandPreCheck added in v0.0.2

func (p *Promptx) SetCommandPreCheck(f func(ctx Context) error)

func (*Promptx) SetPrompt

func (p *Promptx) SetPrompt(prompt string)

SetPrompt update prompt.

func (*Promptx) SetPromptWords

func (p *Promptx) SetPromptWords(words ...*Word)

SetPromptWords update prompt string. custom display.

func (*Promptx) SetTitle

func (p *Promptx) SetTitle(title string)

SetTitle set title

func (*Promptx) Stderr

func (p *Promptx) Stderr() io.Writer

Stderr std err

func (*Promptx) Stdout

func (p *Promptx) Stdout() io.Writer

Stdout return a wrap stdout writer. it can refersh view correct

func (*Promptx) Stop

func (p *Promptx) Stop()

func (*Promptx) SwitchCommandSet added in v0.0.2

func (p *Promptx) SwitchCommandSet(name string, args ...interface{})

SwitchCommandSet switch to specify comands set

func (*Promptx) WPrint

func (p *Promptx) WPrint(words ...*Word)

WPrint print words

func (*Promptx) WPrintln

func (p *Promptx) WPrintln(words ...*Word)

WPrintln print words and newline

type SelFinishTextFunc

type SelFinishTextFunc func(cc *SelectOptions, result []int) (words []*Word)

SelFinishTextFunc modify finish text display

type SelHelpTextFunc

type SelHelpTextFunc func(mul bool) (help string)

SelHelpTextFunc modify help text func

type SelectBlockManager

type SelectBlockManager struct {
	*BlocksBaseManager
	PreWords *BlocksWords
	Select   *BlocksSelect
	Validate *BlocksNewLine
	// contains filtered or unexported fields
}

SelectBlockManager select mode

func NewSelectManager

func NewSelectManager(cc *SelectOptions) (m *SelectBlockManager)

NewSelectManager new input text

func (*SelectBlockManager) FinishCallBack

func (m *SelectBlockManager) FinishCallBack(status int, buf *Buffer) bool

FinishCallBack call back

func (*SelectBlockManager) PreCheckCallBack

func (m *SelectBlockManager) PreCheckCallBack(status int, buf *Buffer) (success bool)

PreCheckCallBack change status pre check

func (*SelectBlockManager) TearDown added in v0.0.6

func (m *SelectBlockManager) TearDown()

TearDown to clear title and erasing.

type SelectOption

type SelectOption func(cc *SelectOptions) SelectOption

SelectOption option define

func WithSelectOptionCancelKey

func WithSelectOptionCancelKey(v Key) SelectOption

func WithSelectOptionDefaultSelects added in v1.0.1

func WithSelectOptionDefaultSelects(v ...int) SelectOption

default select

func WithSelectOptionDescriptionBGColor

func WithSelectOptionDescriptionBGColor(v Color) SelectOption

func WithSelectOptionDescriptionTextColor

func WithSelectOptionDescriptionTextColor(v Color) SelectOption

func WithSelectOptionFinishFunc

func WithSelectOptionFinishFunc(v func(sels []int)) SelectOption

func WithSelectOptionFinishKey

func WithSelectOptionFinishKey(v Key) SelectOption

func WithSelectOptionFinishText

func WithSelectOptionFinishText(v SelFinishTextFunc) SelectOption

finish text show

func WithSelectOptionHelpBGColor

func WithSelectOptionHelpBGColor(v Color) SelectOption

func WithSelectOptionHelpText

func WithSelectOptionHelpText(v SelHelpTextFunc) SelectOption

func WithSelectOptionHelpTextColor

func WithSelectOptionHelpTextColor(v Color) SelectOption

func WithSelectOptionMulti

func WithSelectOptionMulti(v bool) SelectOption

func WithSelectOptionOptions

func WithSelectOptionOptions(v ...*Suggest) SelectOption

func WithSelectOptionResultBGColor

func WithSelectOptionResultBGColor(v Color) SelectOption

func WithSelectOptionResultShowItem

func WithSelectOptionResultShowItem(v bool) SelectOption

contrl selct result display select context

func WithSelectOptionResultTextColor

func WithSelectOptionResultTextColor(v Color) SelectOption

func WithSelectOptionRowsLimit

func WithSelectOptionRowsLimit(v int) SelectOption

func WithSelectOptionScrollbarBGColor

func WithSelectOptionScrollbarBGColor(v Color) SelectOption

func WithSelectOptionScrollbarThumbColor

func WithSelectOptionScrollbarThumbColor(v Color) SelectOption

func WithSelectOptionSelectedDescriptionBGColor

func WithSelectOptionSelectedDescriptionBGColor(v Color) SelectOption

func WithSelectOptionSelectedDescriptionTextColor

func WithSelectOptionSelectedDescriptionTextColor(v Color) SelectOption

func WithSelectOptionSelectedSuggestionBGColor

func WithSelectOptionSelectedSuggestionBGColor(v Color) SelectOption

func WithSelectOptionSelectedSuggestionTextColor

func WithSelectOptionSelectedSuggestionTextColor(v Color) SelectOption

func WithSelectOptionShowHelpText

func WithSelectOptionShowHelpText(v bool) SelectOption

help text info

func WithSelectOptionSuggestionBGColor

func WithSelectOptionSuggestionBGColor(v Color) SelectOption

func WithSelectOptionSuggestionTextColor

func WithSelectOptionSuggestionTextColor(v Color) SelectOption

select options info

func WithSelectOptionTipBGColor

func WithSelectOptionTipBGColor(v Color) SelectOption

func WithSelectOptionTipText

func WithSelectOptionTipText(v string) SelectOption

select tip info

func WithSelectOptionTipTextColor

func WithSelectOptionTipTextColor(v Color) SelectOption

func WithSelectOptionValidBGColor

func WithSelectOptionValidBGColor(v Color) SelectOption

func WithSelectOptionValidFunc

func WithSelectOptionValidFunc(v func(sels []int) error) SelectOption

valid info

func WithSelectOptionValidTextColor

func WithSelectOptionValidTextColor(v Color) SelectOption

type SelectOptions

type SelectOptions struct {
	Options    []*Suggest
	RowsLimit  int
	FinishFunc func(sels []int)
	Multi      bool
	FinishKey  Key
	CancelKey  Key
	// select tip info
	TipText      string
	TipTextColor Color
	TipBGColor   Color
	// help text info
	ShowHelpText  bool
	HelpText      SelHelpTextFunc
	HelpTextColor Color
	HelpBGColor   Color
	// valid info
	ValidFunc      func(sels []int) error
	ValidTextColor Color
	ValidBGColor   Color
	// select options info
	SuggestionTextColor          Color
	SuggestionBGColor            Color
	SelectedSuggestionTextColor  Color
	SelectedSuggestionBGColor    Color
	DescriptionTextColor         Color
	DescriptionBGColor           Color
	SelectedDescriptionTextColor Color
	SelectedDescriptionBGColor   Color
	ScrollbarThumbColor          Color
	ScrollbarBGColor             Color
	// finish text show
	FinishText SelFinishTextFunc
	// contrl selct result display select context
	ResultShowItem  bool
	ResultTextColor Color
	ResultBGColor   Color
	// default select
	DefaultSelects []int
}

InputOptions promptx options generate by https://github.com/aggronmagi/gogen/

func NewSelectOptions

func NewSelectOptions(opts ...SelectOption) *SelectOptions

NewSelectOptions create options instance.

func (*SelectOptions) ApplyOption

func (cc *SelectOptions) ApplyOption(opts ...SelectOption)

ApplyOption modify options

func (*SelectOptions) GetSetOption

func (cc *SelectOptions) GetSetOption(opt SelectOption) SelectOption

GetSetOption modify and get last option

func (*SelectOptions) SetOption

func (cc *SelectOptions) SetOption(opt SelectOption)

SetOption modify options

type Suggest

type Suggest = completion.Suggest

Suggest is printed when completing.

type SugguestPrint

type SugguestPrint []*Suggest

func (SugguestPrint) String

func (s SugguestPrint) String() string

type WinSize

type WinSize = input.WinSize

WinSize represents the width and height of terminal.

type Word

type Word struct {
	// content
	Text string
	// colors
	TextColor Color
	BGColor   Color
	// bold font
	Bold bool
}

Word terminal displayed text

func WordBlue

func WordBlue(str string) *Word

WordBlue color text

func WordBrown

func WordBrown(str string) *Word

WordBrown color text

func WordCyan

func WordCyan(str string) *Word

WordCyan color text

func WordDefault

func WordDefault(str string) *Word

WordDefault color text

func WordGreen

func WordGreen(str string) *Word

WordGreen color text

func WordPurple

func WordPurple(str string) *Word

WordPurple color text

func WordRed

func WordRed(str string) *Word

WordRed color text

func WordTurquoise

func WordTurquoise(str string) *Word

WordTurquoise color text

func WordWhite

func WordWhite(str string) *Word

WordWhite color text

func WordYellow

func WordYellow(str string) *Word

WordYellow color text

func (*Word) Render

func (w *Word) Render(ctx PrintContext, preCursor int) (nextCursor int)

Width calc display pos

Directories

Path Synopsis
_example
internal
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

Jump to

Keyboard shortcuts

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