readline

package module
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2023 License: MIT Imports: 15 Imported by: 33

README

GoDoc Go Report Card

go-readline-ny

go-readline-ny is the readline library used in the command line shell NYAGOS.

  • Emacs-like key-bindings
  • On Windows Terminal
    • Surrogate-pair
    • Emoji (via clipboard)
    • Zero-Width-Joiner (via clipboard)
    • Variation Selector (via clipboard pasted by Ctrl-Y)
  • Colored commandline

Zero-Width-Joiner sample on Windows-Terminal

example1.go

The most simple sample.

package main

import (
    "context"
    "fmt"

    "github.com/nyaosorg/go-readline-ny"
)

func main() {
    var editor readline.Editor
    text, err := editor.ReadLine(context.Background())
    if err != nil {
        fmt.Printf("ERR=%s\n", err.Error())
    } else {
        fmt.Printf("TEXT=%s\n", text)
    }
}

If the target platform includes Windows, you have to import and use go-colorable like example2.go .

example2.go

Tiny Shell

package main

import (
    "context"
    "fmt"
    "os"
    "os/exec"
    "strings"

    "github.com/mattn/go-colorable"

    "github.com/nyaosorg/go-readline-ny"
    "github.com/nyaosorg/go-readline-ny/coloring"
    "github.com/nyaosorg/go-readline-ny/simplehistory"
)

func main() {
    history := simplehistory.New()

    editor := &readline.Editor{
        Prompt:         func() (int, error) { return fmt.Print("$ ") },
        Writer:         colorable.NewColorableStdout(),
        History:        history,
        Coloring:       &coloring.VimBatch{},
        HistoryCycling: true,
    }
    fmt.Println("Tiny Shell. Type Ctrl-D to quit.")
    for {
        text, err := editor.ReadLine(context.Background())

        if err != nil {
            fmt.Printf("ERR=%s\n", err.Error())
            return
        }

        fields := strings.Fields(text)
        if len(fields) <= 0 {
            continue
        }
        cmd := exec.Command(fields[0], fields[1:]...)
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        cmd.Stdin = os.Stdin

        cmd.Run()

        history.Add(text)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CmdAcceptLine = NewGoCommand("ACCEPT_LINE", cmdAcceptLine)
View Source
var CmdBackwardChar = NewGoCommand("BACKWARD_CHAR", cmdBackwardChar)
View Source
var CmdBackwardDeleteChar = NewGoCommand("BACKWARD_DELETE_CHAR", cmdBackwardDeleteChar)
View Source
var CmdBackwardWord = NewGoCommand("BACKWARD_WORD", cmdBackwardWord)
View Source
var CmdBeginningOfLine = NewGoCommand("BEGINNING_OF_LINE", cmdBeginningOfLine)
View Source
var CmdClearScreen = NewGoCommand("CLEAR_SCREEN", cmdClearScreen)
View Source
var CmdDeleteChar = NewGoCommand("DELETE_CHAR", cmdDeleteChar)
View Source
var CmdDeleteOrAbort = NewGoCommand("DELETE_OR_ABORT", cmdDeleteOrAbort)
View Source
var CmdEndOfLine = NewGoCommand("END_OF_LINE", cmdEndOfLine)
View Source
var CmdForwardChar = NewGoCommand("FORWARD_CHAR", cmdForwardChar)
View Source
var CmdForwardWord = NewGoCommand("FORWARD_WORD", cmdForwardWord)
View Source
var CmdISearchBackward = NewGoCommand("ISEARCH_BACKWARD", cmdISearchBackward)
View Source
var CmdInterrupt = NewGoCommand("INTR", cmdInterrupt)
View Source
var CmdKillLine = NewGoCommand("KILL_LINE", cmdKillLine)
View Source
var CmdKillWholeLine = NewGoCommand("KILL_WHOLE_LINE", cmdKillWholeLine)
View Source
var CmdNextHistory = NewGoCommand("NEXT_HISTORY", cmdNextHistory)
View Source
var CmdPreviousHistory = NewGoCommand("PREVIOUS_HISTORY", cmdPreviousHistory)
View Source
var CmdQuotedInsert = NewGoCommand("QUOTED_INSERT", cmdQuotedInsert)
View Source
var CmdRepaintOnNewline = NewGoCommand("REPAINT_ON_NEWLINE", cmdRepaintOnNewline)
View Source
var CmdSwapChar = NewGoCommand("SWAPCHAR", cmdSwapChar)
View Source
var CmdUndo = NewGoCommand("UNDO", cmdUndo)
View Source
var CmdUnixLineDiscard = NewGoCommand("UNIX_LINE_DISCARD", cmdUnixLineDiscard)
View Source
var CmdUnixWordRubout = NewGoCommand("UNIX_WORD_RUBOUT", cmdUnixWordRubout)
View Source
var CmdYank = NewGoCommand("YANK", cmdYank)
View Source
var CmdYankWithQuote = NewGoCommand("YANK_WITH_QUOTE", cmdYankWithQuote)
View Source
var CtrlC = errors.New("^C")

CtrlC is the error when Ctrl-C is pressed.

View Source
var Delimiters = "\"'"

Delimiters means the quationmarks. The whitespace enclosed by them are not treat as parameters separator.

Functions

func EnableSurrogatePair added in v0.11.0

func EnableSurrogatePair(value bool)

func IsSurrogatePairEnabled added in v0.11.0

func IsSurrogatePairEnabled() bool

func ResetCharWidth

func ResetCharWidth()

func SetCharWidth

func SetCharWidth(c rune, width int)

Types

type Buffer

type Buffer struct {
	*Editor
	Buffer    []Cell
	ViewStart int
	// contains filtered or unexported fields
}

Buffer is ReadLine's internal data structure

func (*Buffer) CurrentWord

func (B *Buffer) CurrentWord() (string, int)

CurrentWord returns the current word the cursor exists and word's position

func (*Buffer) CurrentWordTop

func (B *Buffer) CurrentWordTop() (wordTop int)

CurrentWordTop returns the position of the current word the cursor exists

func (*Buffer) Delete

func (B *Buffer) Delete(pos int, n int) WidthT

Delete remove Buffer[pos:pos+n]. It returns the width to clear the end of line. It does not update screen.

func (*Buffer) DrawFromHead

func (B *Buffer) DrawFromHead()

DrawFromHead draw all text in viewarea and move screen-cursor to the position where it should be.

func (*Buffer) GetKey

func (B *Buffer) GetKey() (string, error)

GetKey reads one-key from Tty.

func (*Buffer) GetWidthBetween

func (B *Buffer) GetWidthBetween(from int, to int) WidthT

GetWidthBetween returns the width between start and end

func (*Buffer) GotoHead

func (B *Buffer) GotoHead()

GotoHead move screen-cursor to the top of the viewarea. It should be called before text is changed.

func (*Buffer) InsertAndRepaint

func (B *Buffer) InsertAndRepaint(str string)

InsertAndRepaint inserts str and repaint the editline.

func (*Buffer) InsertString

func (B *Buffer) InsertString(pos int, s string) int

InsertString inserts string s at pos (Do not update screen) It returns the count of runes

func (*Buffer) RefreshColor added in v0.6.0

func (B *Buffer) RefreshColor() ColorSequence

func (*Buffer) RepaintAfterPrompt

func (B *Buffer) RepaintAfterPrompt()

RepaintAfterPrompt repaints the all characters in the editline except for prompt.

func (*Buffer) RepaintAll

func (B *Buffer) RepaintAll()

RepaintAll repaints the all characters in the editline including prompt.

func (*Buffer) ReplaceAndRepaint

func (B *Buffer) ReplaceAndRepaint(pos int, str string)

ReplaceAndRepaint replaces the string between `pos` and cursor's position to `str`

func (*Buffer) ResetViewStart

func (B *Buffer) ResetViewStart()

ResetViewStart set ViewStart the new value which should be. It does not update screen.

func (Buffer) String

func (B Buffer) String() string

func (*Buffer) SubString

func (B *Buffer) SubString(start, end int) string

SubString returns the readline string between start and end

func (*Buffer) ViewWidth

func (B *Buffer) ViewWidth() WidthT

ViewWidth returns the cell-width screen can show in the one-line.

func (*Buffer) Write added in v0.8.0

func (B *Buffer) Write(b []byte) (int, error)

type Cell added in v0.9.0

type Cell struct {
	Moji Moji
	// contains filtered or unexported fields
}

type ColorSequence added in v0.10.0

type ColorSequence int64
const (
	Black ColorSequence = 3 | ((30 + iota) << colorCodeBitSize) | (49 << (colorCodeBitSize * 2)) | (1 << (colorCodeBitSize * 3))
	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	White

	DefaultForeGroundColor
)
const (
	DarkGray ColorSequence = 3 | ((30 + iota) << colorCodeBitSize) | (22 << (colorCodeBitSize * 2)) | (49 << (colorCodeBitSize * 3))
	DarkRed
	DarkGree
	DarkYellow
	DarkBlue
	DarkMagenta
	DarkCyan
	DarkWhite
)

func SGR1 added in v0.6.3

func SGR1(n1 int) ColorSequence

func SGR2 added in v0.6.3

func SGR2(n1, n2 int) ColorSequence

func SGR3 added in v0.6.3

func SGR3(n1, n2, n3 int) ColorSequence

func SGR4 added in v0.6.3

func SGR4(n1, n2, n3, n4 int) ColorSequence

func (ColorSequence) WriteTo added in v0.10.0

func (c ColorSequence) WriteTo(w io.Writer) (int64, error)

type Coloring added in v0.6.0

type Coloring interface {
	// Reset has to initialize receiver's fields and return default color.
	Init() ColorSequence
	// Next has to return color for the given rune.
	Next(rune) ColorSequence
}

type Command added in v0.11.1

type Command interface {
	String() string
	Call(ctx context.Context, buffer *Buffer) Result
}

Command is the interface for object bound to key-mapping

func GetFunc

func GetFunc(name string) (Command, error)

GetFunc returns Command-object by name

type Editor

type Editor struct {
	KeyMap
	History        IHistory
	Writer         io.Writer
	Out            *bufio.Writer
	Prompt         func() (int, error)
	Default        string
	Cursor         int
	LineFeed       func(Result)
	Tty            ITty
	Coloring       Coloring
	HistoryCycling bool
}

Editor is the main class to hold the parameter for ReadLine

func (*Editor) GetBindKey added in v0.8.4

func (editor *Editor) GetBindKey(key string) Command

GetBindKey returns the function assigned to given key

func (*Editor) ReadLine

func (editor *Editor) ReadLine(ctx context.Context) (string, error)

ReadLine calls LineEditor - ENTER typed -> returns TEXT and nil - CTRL-C typed -> returns "" and readline.CtrlC - CTRL-D typed -> returns "" and io.EOF

type GoCommand added in v0.11.1

type GoCommand struct {
	Name string
	Func func(ctx context.Context, buffer *Buffer) Result
}

GoCommand is the implement of Command which has a name and a function

func NewGoCommand added in v0.11.1

func NewGoCommand(name string, f func(context.Context, *Buffer) Result) *GoCommand

func (*GoCommand) Call added in v0.11.1

func (K *GoCommand) Call(ctx context.Context, buffer *Buffer) Result

Call calls the function the receiver contains

func (GoCommand) String added in v0.11.1

func (K GoCommand) String() string

String returns GoCommand's name

type IHistory

type IHistory interface {
	Len() int
	At(int) string
}

IHistory is the interface ReadLine can use as container for history. It can be set to Editor.History field

type ITty added in v0.11.0

type ITty interface {
	Raw() (func() error, error)
	ReadRune() (rune, error)
	Buffered() bool
	Open() error
	Close() error
	Size() (int, int, error)
	GetResizeNotifier() func() (int, int, bool)
}

type KeyGoFuncT

type KeyGoFuncT = GoCommand

Deprecate: use GoCommand instead

type KeyMap

type KeyMap struct {
	KeyMap map[keys.Code]Command
}

KeyMap is the class for key-bindings

var GlobalKeyMap KeyMap

GlobalKeyMap is the global keymap for users' customizing

func (*KeyMap) BindKey added in v0.11.1

func (km *KeyMap) BindKey(key keys.Code, f Command)

func (*KeyMap) BindKeyClosure

func (km *KeyMap) BindKeyClosure(name string, f func(context.Context, *Buffer) Result) error

BindKeyClosure binds closure to key by name

func (*KeyMap) BindKeyFunc

func (km *KeyMap) BindKeyFunc(key string, f Command) error

BindKeyFunc binds function to key

func (*KeyMap) BindKeySymbol

func (km *KeyMap) BindKeySymbol(key, funcName string) error

BindKeySymbol assigns function to key by names.

func (*KeyMap) GetBindKey

func (km *KeyMap) GetBindKey(key string) Command

GetBindKey returns the function assigned to given key

type Moji

type Moji = moji.Moji

func StringToMoji added in v0.9.0

func StringToMoji(s string) []Moji

type Result

type Result int

Result is the type for readline's result.

const (
	// CONTINUE is returned by key-functions to continue the line editor
	CONTINUE Result = iota
	// ENTER is returned by key-functions when Enter key is pressed
	ENTER Result = iota
	// ABORT is returned by key-functions when Ctrl-D is pressed with no command-line
	ABORT Result = iota
	// INTR is returned by key-functions when Ctrl-C is pressed
	INTR Result = iota
)

type WidthT

type WidthT = moji.WidthT

func GetStringWidth deprecated

func GetStringWidth(s string) WidthT

Deprecated: GetStringWidth returns the width of the string. ( Used on github.com/nyaosorg/nyagos/internal/functions/prompt.go )

Directories

Path Synopsis
cmd
example1 command
farmer command
runeview command
internal
test
color-sgr command
unicodetest command

Jump to

Keyboard shortcuts

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