forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
renderer.go
528 lines (457 loc) · 13.6 KB
/
renderer.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package prompt
import (
"strings"
"unicode/utf8"
"github.com/elk-language/go-prompt/debug"
istrings "github.com/elk-language/go-prompt/strings"
)
const multilinePrefixCharacter = '.'
// Takes care of the rendering process
type Renderer struct {
out Writer
prefixCallback PrefixCallback
breakLineCallback func(*Document)
title string
row int
col istrings.Width
indentSize int // How many spaces constitute a single indentation level
previousCursor Position
// colors,
prefixTextColor Color
prefixBGColor Color
inputTextColor Color
inputBGColor Color
suggestionTextColor Color
suggestionBGColor Color
selectedSuggestionTextColor Color
selectedSuggestionBGColor Color
descriptionTextColor Color
descriptionBGColor Color
selectedDescriptionTextColor Color
selectedDescriptionBGColor Color
scrollbarThumbColor Color
scrollbarBGColor Color
}
// Build a new Renderer.
func NewRenderer() *Renderer {
defaultWriter := NewStdoutWriter()
registerWriter(defaultWriter)
return &Renderer{
out: defaultWriter,
indentSize: DefaultIndentSize,
prefixCallback: DefaultPrefixCallback,
prefixTextColor: Blue,
prefixBGColor: DefaultColor,
inputTextColor: DefaultColor,
inputBGColor: DefaultColor,
suggestionTextColor: White,
suggestionBGColor: Cyan,
selectedSuggestionTextColor: Black,
selectedSuggestionBGColor: Turquoise,
descriptionTextColor: Black,
descriptionBGColor: Turquoise,
selectedDescriptionTextColor: White,
selectedDescriptionBGColor: Cyan,
scrollbarThumbColor: DarkGray,
scrollbarBGColor: Cyan,
}
}
// Setup to initialize console output.
func (r *Renderer) Setup() {
if r.title != "" {
r.out.SetTitle(r.title)
r.flush()
}
}
func (r *Renderer) renderPrefix(prefix string) {
r.out.SetColor(r.prefixTextColor, r.prefixBGColor, false)
if _, err := r.out.WriteString("\r"); err != nil {
panic(err)
}
if _, err := r.out.WriteString(prefix); err != nil {
panic(err)
}
r.out.SetColor(DefaultColor, DefaultColor, false)
}
// Close to clear title and erase.
func (r *Renderer) Close() {
r.out.ClearTitle()
r.out.EraseDown()
r.flush()
}
func (r *Renderer) prepareArea(lines int) {
for i := 0; i < lines; i++ {
r.out.ScrollDown()
}
for i := 0; i < lines; i++ {
r.out.ScrollUp()
}
}
// UpdateWinSize called when window size is changed.
func (r *Renderer) UpdateWinSize(ws *WinSize) {
r.row = int(ws.Row)
r.col = istrings.Width(ws.Col)
}
func (r *Renderer) renderCompletion(buf *Buffer, completions *CompletionManager) {
suggestions := completions.GetSuggestions()
if len(suggestions) == 0 {
return
}
prefix := r.prefixCallback()
prefixWidth := istrings.GetWidth(prefix)
formatted, width := formatSuggestions(
suggestions,
r.col-istrings.GetWidth(prefix)-1, // -1 means a width of scrollbar
)
// +1 means a width of scrollbar.
width++
windowHeight := len(formatted)
if windowHeight > int(completions.max) {
windowHeight = int(completions.max)
}
formatted = formatted[completions.verticalScroll : completions.verticalScroll+windowHeight]
r.prepareArea(windowHeight)
cursor := positionAtEndOfString(buf.Document().TextBeforeCursor(), r.col-prefixWidth)
cursor.X += prefixWidth
x := cursor.X
if x+width >= r.col {
cursor = r.backward(cursor, x+width-r.col)
}
contentHeight := len(completions.tmp)
fractionVisible := float64(windowHeight) / float64(contentHeight)
fractionAbove := float64(completions.verticalScroll) / float64(contentHeight)
scrollbarHeight := int(clamp(float64(windowHeight), 1, float64(windowHeight)*fractionVisible))
scrollbarTop := int(float64(windowHeight) * fractionAbove)
isScrollThumb := func(row int) bool {
return scrollbarTop <= row && row <= scrollbarTop+scrollbarHeight
}
selected := completions.selected - completions.verticalScroll
cursorColumnSpacing := cursor
r.out.SetColor(White, Cyan, false)
for i := 0; i < windowHeight; i++ {
alignNextLine(r, cursorColumnSpacing.X)
if i == selected {
r.out.SetColor(r.selectedSuggestionTextColor, r.selectedSuggestionBGColor, true)
} else {
r.out.SetColor(r.suggestionTextColor, r.suggestionBGColor, false)
}
if _, err := r.out.WriteString(formatted[i].Text); err != nil {
panic(err)
}
if i == selected {
r.out.SetColor(r.selectedDescriptionTextColor, r.selectedDescriptionBGColor, false)
} else {
r.out.SetColor(r.descriptionTextColor, r.descriptionBGColor, false)
}
if _, err := r.out.WriteString(formatted[i].Description); err != nil {
panic(err)
}
if isScrollThumb(i) {
r.out.SetColor(DefaultColor, r.scrollbarThumbColor, false)
} else {
r.out.SetColor(DefaultColor, r.scrollbarBGColor, false)
}
if _, err := r.out.WriteString(" "); err != nil {
panic(err)
}
r.out.SetColor(DefaultColor, DefaultColor, false)
c := cursor.Add(Position{X: width})
r.backward(c, width)
}
if x+width >= r.col {
r.out.CursorForward(int(x + width - r.col))
}
r.out.CursorUp(windowHeight)
r.out.SetColor(DefaultColor, DefaultColor, false)
}
// Render renders to the console.
func (r *Renderer) Render(buffer *Buffer, completion *CompletionManager, lexer Lexer) {
// In situations where a pseudo tty is allocated (e.g. within a docker container),
// window size via TIOCGWINSZ is not immediately available and will result in 0,0 dimensions.
if r.col == 0 {
return
}
defer func() { r.flush() }()
r.clear(r.previousCursor)
text := buffer.Text()
prefix := r.prefixCallback()
prefixWidth := istrings.GetWidth(prefix)
col := r.col - prefixWidth
endLine := buffer.startLine + int(r.row) - 1
cursor := positionAtEndOfStringLine(text, col, endLine)
cursor.X += prefixWidth
// Rendering
r.out.HideCursor()
defer r.out.ShowCursor()
r.renderText(lexer, buffer.Text(), buffer.startLine)
r.out.SetColor(DefaultColor, DefaultColor, false)
targetCursor := buffer.DisplayCursorPosition(col)
targetCursor.X += prefixWidth
// Log("col: %#v, targetCursor: %#v, cursor: %#v\n", col, targetCursor, cursor)
cursor = r.move(cursor, targetCursor)
r.renderCompletion(buffer, completion)
r.previousCursor = cursor
}
func (r *Renderer) renderText(lexer Lexer, input string, startLine int) {
if lexer != nil {
r.lex(lexer, input, startLine)
return
}
prefix := r.prefixCallback()
prefixWidth := istrings.GetWidth(prefix)
col := r.col - prefixWidth
multilinePrefix := r.getMultilinePrefix(prefix)
if startLine != 0 {
prefix = multilinePrefix
}
firstIteration := true
endLine := startLine + int(r.row)
var lineBuffer strings.Builder
var lineCharIndex istrings.Width
var lineNumber int
for _, char := range input {
if lineCharIndex >= col || char == '\n' {
lineNumber++
lineCharIndex = 0
if lineNumber-1 < startLine {
continue
}
if lineNumber >= endLine {
break
}
lineBuffer.WriteRune('\n')
r.renderLine(prefix, lineBuffer.String(), r.inputTextColor)
lineBuffer.Reset()
if char != '\n' {
lineBuffer.WriteRune(char)
lineCharIndex += istrings.GetRuneWidth(char)
}
if firstIteration {
prefix = multilinePrefix
firstIteration = false
}
continue
}
lineCharIndex += istrings.GetRuneWidth(char)
if lineNumber < startLine {
continue
}
lineBuffer.WriteRune(char)
}
r.renderLine(prefix, lineBuffer.String(), r.inputTextColor)
}
func (r *Renderer) flush() {
debug.AssertNoError(r.out.Flush())
}
func (r *Renderer) renderLine(prefix, line string, color Color) {
r.renderPrefix(prefix)
r.writeStringColor(line, color)
}
func (r *Renderer) writeStringColor(text string, color Color) {
r.out.SetColor(color, r.inputBGColor, false)
if _, err := r.out.WriteString(text); err != nil {
panic(err)
}
}
func (r *Renderer) write(b []byte) {
if _, err := r.out.Write(b); err != nil {
panic(err)
}
}
func (r *Renderer) getMultilinePrefix(prefix string) string {
var spaceCount int
var dotCount int
var nonSpaceCharSeen bool
for {
if len(prefix) == 0 {
break
}
char, size := utf8.DecodeLastRuneInString(prefix)
prefix = prefix[:len(prefix)-size]
charWidth := istrings.GetRuneWidth(char)
if nonSpaceCharSeen {
dotCount += int(charWidth)
continue
}
if char != ' ' {
nonSpaceCharSeen = true
dotCount += int(charWidth)
continue
}
spaceCount += int(charWidth)
}
var multilinePrefixBuilder strings.Builder
for i := 0; i < dotCount; i++ {
multilinePrefixBuilder.WriteByte(multilinePrefixCharacter)
}
for i := 0; i < spaceCount; i++ {
multilinePrefixBuilder.WriteByte(IndentUnit)
}
return multilinePrefixBuilder.String()
}
// lex processes the given input with the given lexer
// and writes the result
func (r *Renderer) lex(lexer Lexer, input string, startLine int) {
prefix := r.prefixCallback()
prefixWidth := istrings.GetWidth(prefix)
col := r.col - prefixWidth
multilinePrefix := r.getMultilinePrefix(prefix)
var lineCharIndex istrings.Width
var lineNumber int
endLine := startLine + int(r.row)
previousByteIndex := istrings.ByteNumber(-1)
lineBuffer := make([]byte, 8)
runeBuffer := make([]byte, utf8.UTFMax)
lexer.Init(input)
if startLine != 0 {
prefix = multilinePrefix
}
r.renderPrefix(prefix)
tokenLoop:
for {
token, ok := lexer.Next()
var currentFirstByteIndex istrings.ByteNumber
var currentLastByteIndex istrings.ByteNumber
var tokenColor Color
var tokenBackgroundColor Color
var tokenDisplayAttributes []DisplayAttribute
var noToken bool
if ok {
currentFirstByteIndex = token.FirstByteIndex()
currentLastByteIndex = token.LastByteIndex()
tokenColor = token.Color()
tokenBackgroundColor = token.BackgroundColor()
tokenDisplayAttributes = token.DisplayAttributes()
} else if previousByteIndex == istrings.Len(input)-1 {
break tokenLoop
} else {
currentFirstByteIndex = istrings.Len(input)
tokenColor = r.inputTextColor
tokenBackgroundColor = r.inputBGColor
tokenDisplayAttributes = nil
noToken = true
}
color := r.inputTextColor
backgroundColor := r.inputBGColor
displayAttributes := tokenDisplayAttributes
text := input[previousByteIndex+1 : currentFirstByteIndex]
previousByteIndex = currentLastByteIndex
lineBuffer = lineBuffer[:0]
interToken := true
repeatLoop:
for {
charLoop:
for _, char := range text {
if lineCharIndex >= col || char == '\n' {
lineNumber++
lineCharIndex = 0
if lineNumber-1 < startLine {
continue charLoop
}
if lineNumber >= endLine {
break tokenLoop
}
lineBuffer = append(lineBuffer, '\n')
r.out.SetDisplayAttributes(color, backgroundColor, displayAttributes...)
r.write(lineBuffer)
r.resetFormatting()
r.renderPrefix(multilinePrefix)
lineBuffer = lineBuffer[:0]
if char != '\n' {
size := utf8.EncodeRune(runeBuffer, char)
lineBuffer = append(lineBuffer, runeBuffer[:size]...)
lineCharIndex += istrings.GetRuneWidth(char)
}
continue charLoop
}
lineCharIndex += istrings.GetRuneWidth(char)
if lineNumber < startLine {
continue charLoop
}
size := utf8.EncodeRune(runeBuffer, char)
lineBuffer = append(lineBuffer, runeBuffer[:size]...)
}
if len(lineBuffer) > 0 {
r.out.SetDisplayAttributes(color, backgroundColor, displayAttributes...)
r.write(lineBuffer)
r.resetFormatting()
}
if !interToken {
break repeatLoop
}
if noToken {
break tokenLoop
}
color = tokenColor
backgroundColor = tokenBackgroundColor
displayAttributes = tokenDisplayAttributes
text = input[currentFirstByteIndex : currentLastByteIndex+1]
lineBuffer = lineBuffer[:0]
interToken = false
}
}
r.resetFormatting()
}
func (r *Renderer) resetFormatting() {
r.out.SetDisplayAttributes(r.inputTextColor, r.inputBGColor, DisplayReset)
}
// BreakLine to break line.
func (r *Renderer) BreakLine(buffer *Buffer, lexer Lexer) {
// Erasing and Renderer
prefix := r.prefixCallback()
prefixWidth := istrings.GetWidth(prefix)
cursor := positionAtEndOfString(buffer.Document().TextBeforeCursor(), r.col-prefixWidth)
cursor.X += prefixWidth
r.clear(cursor)
r.renderText(lexer, buffer.Text(), buffer.startLine)
if _, err := r.out.WriteString("\n"); err != nil {
panic(err)
}
r.out.SetColor(DefaultColor, DefaultColor, false)
r.flush()
if r.breakLineCallback != nil {
r.breakLineCallback(buffer.Document())
}
r.previousCursor = Position{}
}
// Get the number of columns that are available
// for user input.
func (r *Renderer) UserInputColumns() istrings.Width {
return r.col - istrings.GetWidth(r.prefixCallback())
}
// 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 (r *Renderer) clear(cursor Position) {
r.move(cursor, Position{})
r.out.EraseDown()
}
// backward moves cursor to backward from a current cursor position
// regardless there is a line break.
func (r *Renderer) backward(from Position, n istrings.Width) Position {
return r.move(from, Position{X: from.X - n, Y: from.Y})
}
// move moves cursor to specified position from the beginning of input
// even if there is a line break.
func (r *Renderer) move(from, to Position) Position {
newPosition := from.Subtract(to)
r.out.CursorUp(newPosition.Y)
r.out.CursorBackward(int(newPosition.X))
return to
}
func clamp(high, low, x float64) float64 {
switch {
case high < x:
return high
case x < low:
return low
default:
return x
}
}
func alignNextLine(r *Renderer, col istrings.Width) {
r.out.CursorDown(1)
if _, err := r.out.WriteString("\r"); err != nil {
panic(err)
}
r.out.CursorForward(int(col))
}