-
Notifications
You must be signed in to change notification settings - Fork 1
/
consoleLiner.go
95 lines (81 loc) · 1.64 KB
/
consoleLiner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/peterh/liner"
)
const historyFilename = ".bbzhistory"
type consoleLiner struct {
liner *liner.State
prompt string
env *environment
}
func newConsoleLiner(env *environment) *consoleLiner {
var c consoleLiner
c.liner = liner.NewLiner()
c.env = env
c.liner.SetCtrlCAborts(true)
if f, err := os.Open(historyFilename); err == nil {
c.liner.ReadHistory(f)
f.Close()
}
return &c
}
func (c *consoleLiner) close() {
if f, err := os.Create(historyFilename); err == nil {
c.liner.WriteHistory(f)
f.Close()
}
c.liner.Close()
}
func (c *consoleLiner) readline() (string, bool) {
fmt.Printf("\r")
line, err := c.liner.Prompt(c.prompt)
if errors.Is(err, liner.ErrInvalidPrompt) {
fmt.Println()
line, err = c.liner.Prompt("")
}
c.prompt = ""
if errors.Is(err, liner.ErrPromptAborted) {
c.env.escape()
return "", false
}
if errors.Is(err, io.EOF) {
return "", true
}
if err != nil {
panic(err)
}
if line != "" {
c.liner.AppendHistory(line)
}
c.env.writeSpool(line)
c.env.writeSpool("\n")
return line, false
}
func (c *consoleLiner) readChar() (uint8, bool) {
// TODO: capture keystrokes. We will just get the first char of the line
// and ignore the rest.
s, stop := c.readline()
if s == "" {
return ' ', stop
} else {
return s[0], stop
}
}
func (c *consoleLiner) write(s string) {
if strings.HasSuffix(s, "\n") || strings.HasSuffix(s, "\r") {
c.prompt = ""
} else {
c.prompt += s
}
fmt.Print(s)
c.env.writeSpool(s)
}
func (c *consoleLiner) writef(format string, a ...interface{}) {
s := fmt.Sprintf(format, a...)
c.write(s)
}