forked from bobappleyard/readline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readline.go
313 lines (263 loc) · 6.65 KB
/
readline.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
This package provides access to basic GNU Readline functions. Currently supported are:
- getting text from a prompt (via the String() and NewReader() functions).
- managing the prompt's history (via the AddHistory(), GetHistory(), ClearHistory() and HistorySize() functions).
- controlling tab completion (via the Completer variable).
Here is a simple example:
package main
import (
"fmt"
"io"
"github.com/bobappleyard/readline"
)
func main() {
for {
l, err := readline.String("> ")
if err == io.EOF {
break
}
if err != nil {
fmt.Println("error: ", err)
break
}
fmt.Println(l)
readline.AddHistory(l)
}
}
*/
package readline
/*
#cgo darwin CFLAGS: -I/usr/local/opt/readline/include
#cgo darwin LDFLAGS: -L/usr/local/opt/readline/lib
#cgo LDFLAGS: -lreadline -lhistory
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <readline/keymaps.h>
extern char *_completion_function(char *s, int i);
static char *_completion_function_trans(const char *s, int i) {
return _completion_function((char *) s, i);
}
static void register_readline() {
rl_completion_entry_function = _completion_function_trans;
using_history();
}
*/
import "C"
import (
"io"
"regexp"
"syscall"
"unsafe"
)
// The prompt used by Reader(). The prompt can contain ANSI escape
// sequences, they will be escaped as necessary.
var Prompt = "> "
// The continue prompt used by Reader(). The prompt can contain ANSI escape
// sequences, they will be escaped as necessary.
var Continue = ".."
const (
promptStartIgnore = string(C.RL_PROMPT_START_IGNORE)
promptEndIgnore = string(C.RL_PROMPT_END_IGNORE)
)
// If CompletionAppendChar is non-zero, readline will append the
// corresponding character to the prompt after each completion. A
// typical value would be a space.
var CompletionAppendChar = 0
type state byte
const (
readerStart state = iota
readerContinue
readerEnd
)
type reader struct {
buf []byte
state state
}
var shortEscRegex = "\x1b[@-Z\\-_]"
var csiPrefix = "(\x1b[[]|\xC2\x9b)"
var csiParam = "([0-9]+|\"[^\"]*\")"
var csiSuffix = "[@-~]"
var csiRegex = csiPrefix + "(" + csiParam + "(;" + csiParam + ")*)?" + csiSuffix
var escapeSeq = regexp.MustCompile(shortEscRegex + "|" + csiRegex)
var initialized = false
// Begin reading lines. If more than one line is required, the continue prompt
// is used for subsequent lines.
func NewReader() io.Reader {
return new(reader)
}
func (r *reader) getLine() error {
prompt := Prompt
if r.state == readerContinue {
prompt = Continue
}
s, err := String(prompt)
if err != nil {
return err
}
r.buf = []byte(s)
return nil
}
func (r *reader) Read(buf []byte) (int, error) {
if r.state == readerEnd {
return 0, io.EOF
}
if len(r.buf) == 0 {
err := r.getLine()
if err == io.EOF {
r.state = readerEnd
}
if err != nil {
return 0, err
}
r.state = readerContinue
}
copy(buf, r.buf)
l := len(buf)
if len(buf) > len(r.buf) {
l = len(r.buf)
}
r.buf = r.buf[l:]
return l, nil
}
// Read a line with the given prompt. The prompt can contain ANSI
// escape sequences, they will be escaped as necessary.
func String(prompt string) (string, error) {
prompt = "\x1b[0m" + prompt // Prepend a 'reset' ANSI escape sequence
prompt = escapeSeq.ReplaceAllString(prompt, promptStartIgnore+"$0"+promptEndIgnore)
p := C.CString(prompt)
rp := C.readline(p)
s := C.GoString(rp)
C.free(unsafe.Pointer(p))
if rp != nil {
C.free(unsafe.Pointer(rp))
return s, nil
}
return s, io.EOF
}
// This function provides entries for the tab completer.
var Completer = func(query, ctx string) []string {
return nil
}
var entries []*C.char
// This function can be assigned to the Completer variable to use
// readline's default filename completion, or it can be called by a
// custom completer function to get a list of files and filter it.
func FilenameCompleter(query, ctx string) []string {
var compls []string
var c *C.char
q := C.CString(query)
for i := 0; ; i++ {
if c = C.rl_filename_completion_function(q, C.int(i)); c == nil {
break
}
compls = append(compls, C.GoString(c))
C.free(unsafe.Pointer(c))
}
C.free(unsafe.Pointer(q))
return compls
}
//export _completion_function
func _completion_function(p *C.char, _i C.int) *C.char {
C.rl_completion_append_character = C.int(CompletionAppendChar)
i := int(_i)
if i == 0 {
es := Completer(C.GoString(p), C.GoString(C.rl_line_buffer))
entries = make([]*C.char, len(es))
for i, x := range es {
entries[i] = C.CString(x)
}
}
if i >= len(entries) {
return nil
}
return entries[i]
}
func SetWordBreaks(cs string) {
C.rl_completer_word_break_characters = C.CString(cs)
}
// Add an item to the history.
func AddHistory(s string) {
n := HistorySize()
if n == 0 || s != GetHistory(n-1) {
C.add_history(C.CString(s))
}
}
// Retrieve a line from the history.
func GetHistory(i int) string {
e := C.history_get(C.int(i + 1))
if e == nil {
return ""
}
return C.GoString(e.line)
}
// Clear the screen
func ClearScreen() {
var x, y C.int = 0, 0
C.rl_clear_screen(x, y)
}
// rl_forced_update_display / redraw
func ForceUpdateDisplay() {
C.rl_forced_update_display()
}
// Replace current line
func ReplaceLine(text string, clearUndo int) {
C.rl_replace_line(C.CString(text), C.int(clearUndo))
}
// Redraw current line
func RefreshLine() {
var x, y C.int = 0, 0
C.rl_refresh_line(x, y)
}
// Deletes all the items in the history.
func ClearHistory() {
C.clear_history()
}
// Returns the number of items in the history.
func HistorySize() int {
return int(C.history_length)
}
// Load the history from a file.
func LoadHistory(path string) error {
p := C.CString(path)
e := C.read_history(p)
C.free(unsafe.Pointer(p))
if e == 0 {
return nil
}
return syscall.Errno(e)
}
// Save the history to a file.
func SaveHistory(path string) error {
p := C.CString(path)
e := C.write_history(p)
C.free(unsafe.Pointer(p))
if e == 0 {
return nil
}
return syscall.Errno(e)
}
// Cleanup() frees internal memory and restores terminal
// attributes. This function should be called when program execution
// stops before the return of a String() call, so as not to leave the
// terminal in a corrupted state.
func Cleanup() {
C.rl_free_line_state()
C.rl_cleanup_after_signal()
}
func Resize() {
if initialized {
C.rl_resize_terminal()
}
}
func Init() {
C.rl_catch_signals = 0
C.rl_catch_sigwinch = 0
C.rl_completer_quote_characters = C.CString("\"")
C.rl_filename_quote_characters = C.CString("\\ ")
C.rl_filename_completion_desired = 1
C.rl_filename_quoting_desired = 1
C.register_readline()
initialized = true
}