Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add history operations #279

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ module github.com/c-bata/go-prompt
go 1.14

require (
github.com/mattn/go-colorable v0.1.7
github.com/mattn/go-runewidth v0.0.9
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-runewidth v0.0.15
github.com/mattn/go-tty v0.0.3
github.com/noborus/ov v0.33.3
github.com/olekukonko/tablewriter v0.0.5
github.com/pkg/term v1.2.0-beta.2
golang.org/x/sys v0.0.0-20200918174421-af09f7315aff
golang.org/x/sys v0.18.0
golang.org/x/term v0.18.0
)
2,556 changes: 2,550 additions & 6 deletions go.sum

Large diffs are not rendered by default.

57 changes: 57 additions & 0 deletions history.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,74 @@
package prompt

import (
"bytes"
"fmt"
"strconv"

"github.com/olekukonko/tablewriter"
)

// History stores the texts that are entered.
type History struct {
histories []string
tmp []string
selected int
size int
}

// Add to add text in history.
func (h *History) Add(input string) {
h.histories = append(h.histories, input)
if len(h.histories) > h.size {
h.histories = h.histories[1:]
}
h.Clear()
}

func (h *History) Get(i int) string {
if i < 0 || i >= len(h.histories) {
return ""
}
return h.histories[i]
}

func (h *History) Entries() []string {
return h.histories
}

func (h *History) List(bShouldUsePager bool) {
if len(h.histories) <= 0 {
return
}
tableString := &bytes.Buffer{}
table := tablewriter.NewWriter(tableString)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderLine(false)
table.SetAutoWrapText(false)
table.SetHeaderAlignment(tablewriter.ALIGN_CENTER)
table.SetColumnAlignment([]int{tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_LEFT})
data := [][]string{}
for i, s := range h.histories {
data = append(data, []string{strconv.Itoa(i + 1), s})
}
table.AppendBulk(data)
table.Render()
b := tableString.Bytes()
if bShouldUsePager {
pager_print(b, nil)
} else {
fmt.Printf(string(b))
}
}

func (h *History) DeleteAll() {
(*h).histories = []string{}
(*h).tmp = []string{""}
(*h).selected = 0
}

// Clear to clear the history.
func (h *History) Clear() {
h.tmp = make([]string, len(h.histories))
Expand Down Expand Up @@ -57,5 +113,6 @@ func NewHistory() *History {
histories: []string{},
tmp: []string{""},
selected: 0,
size: 1000,
}
}
35 changes: 35 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package prompt

import "fmt"

// Option is the type to replace default parameters.
// prompt.New accepts any number of options (this is functional option pattern).
type Option func(prompt *Prompt) error
Expand Down Expand Up @@ -37,6 +39,14 @@ func OptionPrefix(x string) Option {
}
}

func OptionPrefixWithAnsiEscape(x string) Option {
return func(p *Prompt) error {
p.renderer.prefix = x
p.renderer.allowPrefixAnsiEscape = true
return nil
}
}

// OptionInitialBufferText to set the initial buffer text
func OptionInitialBufferText(x string) Option {
return func(p *Prompt) error {
Expand All @@ -61,6 +71,14 @@ func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option {
}
}

func OptionLivePrefixWithAnsiEscape(f func() (prefix string, useLivePrefix bool)) Option {
return func(p *Prompt) error {
p.renderer.livePrefixCallback = f
p.renderer.allowPrefixAnsiEscape = true
return nil
}
}

// OptionPrefixTextColor change a text color of prefix string
func OptionPrefixTextColor(x Color) Option {
return func(p *Prompt) error {
Expand Down Expand Up @@ -266,6 +284,23 @@ func OptionSetExitCheckerOnInput(fn ExitChecker) Option {
}
}

func OptionHistorySize(size int) Option {
return func(p *Prompt) error {
if size < 0 {
return fmt.Errorf("history size should be greater than or equal to 0, but got %d", size)
}
p.history.size = size
return nil
}
}

func OptionParseBashStyleHistoryNumber() Option {
return func(p *Prompt) error {
(*p).bShouldParseBashStyleHistoryNumber = true
return nil
}
}

// New returns a Prompt with powerful auto-completion.
func New(executor Executor, completer Completer, opts ...Option) *Prompt {
defaultWriter := NewStdoutWriter()
Expand Down
47 changes: 47 additions & 0 deletions pager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package prompt

import (
"bytes"
"fmt"
"os"

"github.com/noborus/ov/oviewer"
"golang.org/x/term"
)

func pager_print(b []byte, config *oviewer.Config) {
// set console redirect (https://github.com/noborus/ov/blob/879f450a792e56646d038d726ca0aa1559e4ae3b/main.go)
if term.IsTerminal(int(os.Stdout.Fd())) {
tmpStdout := os.Stdout
os.Stdout = nil
defer func() {
os.Stdout = tmpStdout
}()
} else {
oviewer.STDOUTPIPE = os.Stdout
}
if term.IsTerminal(int(os.Stderr.Fd())) {
tmpStderr := os.Stderr
os.Stderr = nil
defer func() {
os.Stderr = tmpStderr
}()
} else {
oviewer.STDERRPIPE = os.Stderr
}

// print (https://github.com/noborus/ov/blob/879f450a792e56646d038d726ca0aa1559e4ae3b/main.go#L147)
ov, err := oviewer.NewRoot(bytes.NewReader(b))
if config != nil {
ov.SetConfig(*config)
}
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
return
}
if err := ov.Run(); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
return
}
ov.WriteOriginal()
}
52 changes: 49 additions & 3 deletions prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package prompt

import (
"bytes"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"

"github.com/c-bata/go-prompt/internal/debug"
Expand Down Expand Up @@ -35,6 +39,9 @@ type Prompt struct {
completionOnDown bool
exitChecker ExitChecker
skipTearDown bool

// whether to parse history number ('!' + number) in bash style or not
bShouldParseBashStyleHistoryNumber bool
}

// Exec is the struct contains user input context.
Expand Down Expand Up @@ -81,7 +88,21 @@ func (p *Prompt) Run() {
// Unset raw mode
// Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
debug.AssertNoError(p.in.TearDown())
p.executor(e.input)
if p.bShouldParseBashStyleHistoryNumber {
bIsHistoryNum, bFoundHistory, parsed := p.parseBashStyleHistoryNumber(e.input)
if !bIsHistoryNum {
p.executor(e.input)
} else {
if !bFoundHistory {
fmt.Fprintf(os.Stderr, "%s: history command not found\n", strings.TrimSpace(e.input))
p.executor("")
} else {
p.executor(parsed)
}
}
} else {
p.executor(e.input)
}

p.completion.Update(*p.buf.Document())

Expand Down Expand Up @@ -125,8 +146,17 @@ func (p *Prompt) feed(b []byte) (shouldExit bool, exec *Exec) {

exec = &Exec{input: p.buf.Text()}
p.buf = NewBuffer()
if exec.input != "" {
p.history.Add(exec.input)
if strings.TrimSpace(exec.input) != "" {
if p.bShouldParseBashStyleHistoryNumber {
bIsHistoryNum, bFoundHistory, parsed := p.parseBashStyleHistoryNumber(exec.input)
if !bIsHistoryNum {
p.history.Add(exec.input)
} else if bFoundHistory && parsed != "" {
p.history.Add(parsed)
}
} else {
p.history.Add(exec.input)
}
}
case ControlC:
p.renderer.BreakLine(p.buf)
Expand Down Expand Up @@ -294,3 +324,19 @@ func (p *Prompt) tearDown() {
}
p.renderer.TearDown()
}

func (p *Prompt) History() *History {
return p.history
}

func (p *Prompt) parseBashStyleHistoryNumber(s string) (bIsBashHistoryNumber, bFoundHistory bool, historyCommand string) {
r := regexp.MustCompile(`^\s*!(?P<history_number>\d+)\s*$`)
tokens := r.FindStringSubmatch(s)
if len(tokens) <= 0 {
return false, false, ""
}
histNumIndex := r.SubexpIndex("history_number")
historyNumber, _ := strconv.Atoi(tokens[histNumIndex])
historyCommand = p.history.Get(historyNumber - 1)
return true, (len(historyCommand) > 0), historyCommand
}
8 changes: 7 additions & 1 deletion render.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Render struct {

// colors,
prefixTextColor Color
allowPrefixAnsiEscape bool
prefixBGColor Color
inputTextColor Color
inputBGColor Color
Expand Down Expand Up @@ -57,7 +58,12 @@ func (r *Render) getCurrentPrefix() string {

func (r *Render) renderPrefix() {
r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
r.out.WriteStr(r.getCurrentPrefix())
strPrefix := r.getCurrentPrefix()
if r.allowPrefixAnsiEscape {
r.out.WriteRawStr(strPrefix)
} else {
r.out.WriteStr(strPrefix)
}
r.out.SetColor(DefaultColor, DefaultColor, false)
}

Expand Down