buffer.go 11.9 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package readline

import (
	"fmt"
	"os"

	"github.com/emirpasic/gods/lists/arraylist"
	"github.com/mattn/go-runewidth"
	"golang.org/x/term"
)

type Buffer struct {
	DisplayPos int
	Pos        int
	Buf        *arraylist.List
xuxzh1's avatar
init  
xuxzh1 committed
16
	// LineHasSpace is an arraylist of bools to keep track of whether a line has a space at the end
mashun1's avatar
v1  
mashun1 committed
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
	LineHasSpace *arraylist.List
	Prompt       *Prompt
	LineWidth    int
	Width        int
	Height       int
}

func NewBuffer(prompt *Prompt) (*Buffer, error) {
	fd := int(os.Stdout.Fd())
	width, height := 80, 24
	if termWidth, termHeight, err := term.GetSize(fd); err == nil {
		width, height = termWidth, termHeight
	}

	lwidth := width - len(prompt.prompt())

	b := &Buffer{
		DisplayPos:   0,
		Pos:          0,
		Buf:          arraylist.New(),
		LineHasSpace: arraylist.New(),
		Prompt:       prompt,
		Width:        width,
		Height:       height,
		LineWidth:    lwidth,
	}

	return b, nil
}

func (b *Buffer) GetLineSpacing(line int) bool {
	hasSpace, _ := b.LineHasSpace.Get(line)

	if hasSpace == nil {
		return false
	}

	return hasSpace.(bool)
}

func (b *Buffer) MoveLeft() {
	if b.Pos > 0 {
xuxzh1's avatar
init  
xuxzh1 committed
59
		// asserts that we retrieve a rune
mashun1's avatar
v1  
mashun1 committed
60
61
62
63
64
		if e, ok := b.Buf.Get(b.Pos - 1); ok {
			if r, ok := e.(rune); ok {
				rLength := runewidth.RuneWidth(r)

				if b.DisplayPos%b.LineWidth == 0 {
xuxzh1's avatar
update  
xuxzh1 committed
65
					fmt.Print(CursorUp + CursorBOL + CursorRightN(b.Width))
mashun1's avatar
v1  
mashun1 committed
66
67
68
69
70
71
72
73
74
75
76
					if rLength == 2 {
						fmt.Print(CursorLeft)
					}

					line := b.DisplayPos/b.LineWidth - 1
					hasSpace := b.GetLineSpacing(line)
					if hasSpace {
						b.DisplayPos -= 1
						fmt.Print(CursorLeft)
					}
				} else {
xuxzh1's avatar
update  
xuxzh1 committed
77
					fmt.Print(CursorLeftN(rLength))
mashun1's avatar
v1  
mashun1 committed
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
				}

				b.Pos -= 1
				b.DisplayPos -= rLength
			}
		}
	}
}

func (b *Buffer) MoveLeftWord() {
	if b.Pos > 0 {
		var foundNonspace bool
		for {
			v, _ := b.Buf.Get(b.Pos - 1)
			if v == ' ' {
				if foundNonspace {
					break
				}
			} else {
				foundNonspace = true
			}
			b.MoveLeft()

			if b.Pos == 0 {
				break
			}
		}
	}
}

func (b *Buffer) MoveRight() {
	if b.Pos < b.Buf.Size() {
		if e, ok := b.Buf.Get(b.Pos); ok {
			if r, ok := e.(rune); ok {
				rLength := runewidth.RuneWidth(r)
				b.Pos += 1
				hasSpace := b.GetLineSpacing(b.DisplayPos / b.LineWidth)
				b.DisplayPos += rLength

				if b.DisplayPos%b.LineWidth == 0 {
xuxzh1's avatar
update  
xuxzh1 committed
118
					fmt.Print(CursorDown + CursorBOL + CursorRightN(len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
119
				} else if (b.DisplayPos-rLength)%b.LineWidth == b.LineWidth-1 && hasSpace {
xuxzh1's avatar
update  
xuxzh1 committed
120
					fmt.Print(CursorDown + CursorBOL + CursorRightN(len(b.Prompt.prompt())+rLength))
mashun1's avatar
v1  
mashun1 committed
121
122
					b.DisplayPos += 1
				} else if b.LineHasSpace.Size() > 0 && b.DisplayPos%b.LineWidth == b.LineWidth-1 && hasSpace {
xuxzh1's avatar
update  
xuxzh1 committed
123
					fmt.Print(CursorDown + CursorBOL + CursorRightN(len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
124
125
					b.DisplayPos += 1
				} else {
xuxzh1's avatar
update  
xuxzh1 committed
126
					fmt.Print(CursorRightN(rLength))
mashun1's avatar
v1  
mashun1 committed
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
				}
			}
		}
	}
}

func (b *Buffer) MoveRightWord() {
	if b.Pos < b.Buf.Size() {
		for {
			b.MoveRight()
			v, _ := b.Buf.Get(b.Pos)
			if v == ' ' {
				break
			}

			if b.Pos == b.Buf.Size() {
				break
			}
		}
	}
}

func (b *Buffer) MoveToStart() {
	if b.Pos > 0 {
		currLine := b.DisplayPos / b.LineWidth
		if currLine > 0 {
xuxzh1's avatar
init  
xuxzh1 committed
153
			for range currLine {
mashun1's avatar
v1  
mashun1 committed
154
155
156
				fmt.Print(CursorUp)
			}
		}
xuxzh1's avatar
update  
xuxzh1 committed
157
		fmt.Print(CursorBOL + CursorRightN(len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
158
159
160
161
162
163
164
165
166
167
		b.Pos = 0
		b.DisplayPos = 0
	}
}

func (b *Buffer) MoveToEnd() {
	if b.Pos < b.Buf.Size() {
		currLine := b.DisplayPos / b.LineWidth
		totalLines := b.DisplaySize() / b.LineWidth
		if currLine < totalLines {
xuxzh1's avatar
init  
xuxzh1 committed
168
			for range totalLines - currLine {
mashun1's avatar
v1  
mashun1 committed
169
170
171
				fmt.Print(CursorDown)
			}
			remainder := b.DisplaySize() % b.LineWidth
xuxzh1's avatar
update  
xuxzh1 committed
172
			fmt.Print(CursorBOL + CursorRightN(len(b.Prompt.prompt())+remainder))
mashun1's avatar
v1  
mashun1 committed
173
		} else {
xuxzh1's avatar
update  
xuxzh1 committed
174
			fmt.Print(CursorRightN(b.DisplaySize() - b.DisplayPos))
mashun1's avatar
v1  
mashun1 committed
175
176
177
178
179
180
181
182
183
		}

		b.Pos = b.Buf.Size()
		b.DisplayPos = b.DisplaySize()
	}
}

func (b *Buffer) DisplaySize() int {
	sum := 0
xuxzh1's avatar
init  
xuxzh1 committed
184
	for i := range b.Buf.Size() {
mashun1's avatar
v1  
mashun1 committed
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
		if e, ok := b.Buf.Get(i); ok {
			if r, ok := e.(rune); ok {
				sum += runewidth.RuneWidth(r)
			}
		}
	}

	return sum
}

func (b *Buffer) Add(r rune) {
	if b.Pos == b.Buf.Size() {
		b.AddChar(r, false)
	} else {
		b.AddChar(r, true)
	}
}

func (b *Buffer) AddChar(r rune, insert bool) {
	rLength := runewidth.RuneWidth(r)
	b.DisplayPos += rLength

	if b.Pos > 0 {
		if b.DisplayPos%b.LineWidth == 0 {
			fmt.Printf("%c", r)
			fmt.Printf("\n%s", b.Prompt.AltPrompt)

			if insert {
				b.LineHasSpace.Set(b.DisplayPos/b.LineWidth-1, false)
			} else {
				b.LineHasSpace.Add(false)
			}

			// this case occurs when a double-width rune crosses the line boundary
		} else if b.DisplayPos%b.LineWidth < (b.DisplayPos-rLength)%b.LineWidth {
			if insert {
				fmt.Print(ClearToEOL)
			}
			fmt.Printf("\n%s", b.Prompt.AltPrompt)
			b.DisplayPos += 1
			fmt.Printf("%c", r)

			if insert {
				b.LineHasSpace.Set(b.DisplayPos/b.LineWidth-1, true)
			} else {
				b.LineHasSpace.Add(true)
			}
		} else {
			fmt.Printf("%c", r)
		}
	} else {
		fmt.Printf("%c", r)
	}

	if insert {
		b.Buf.Insert(b.Pos, r)
	} else {
		b.Buf.Add(r)
	}

	b.Pos += 1

	if insert {
		b.drawRemaining()
	}
}

func (b *Buffer) countRemainingLineWidth(place int) int {
	var sum int
	counter := -1
	var prevLen int

	for place <= b.LineWidth {
		counter += 1
		sum += prevLen
		if e, ok := b.Buf.Get(b.Pos + counter); ok {
			if r, ok := e.(rune); ok {
				place += runewidth.RuneWidth(r)
				prevLen = len(string(r))
			}
		} else {
			break
		}
	}

	return sum
}

func (b *Buffer) drawRemaining() {
	var place int
	remainingText := b.StringN(b.Pos)
	if b.Pos > 0 {
		place = b.DisplayPos % b.LineWidth
	}
	fmt.Print(CursorHide)

	// render the rest of the current line
	currLineLength := b.countRemainingLineWidth(place)

	currLine := remainingText[:min(currLineLength, len(remainingText))]
	currLineSpace := runewidth.StringWidth(currLine)
	remLength := runewidth.StringWidth(remainingText)

	if len(currLine) > 0 {
xuxzh1's avatar
update  
xuxzh1 committed
289
		fmt.Print(ClearToEOL + currLine + CursorLeftN(currLineSpace))
mashun1's avatar
v1  
mashun1 committed
290
291
292
293
294
295
296
297
298
299
300
301
302
	} else {
		fmt.Print(ClearToEOL)
	}

	if currLineSpace != b.LineWidth-place && currLineSpace != remLength {
		b.LineHasSpace.Set(b.DisplayPos/b.LineWidth, true)
	} else if currLineSpace != b.LineWidth-place {
		b.LineHasSpace.Remove(b.DisplayPos / b.LineWidth)
	} else {
		b.LineHasSpace.Set(b.DisplayPos/b.LineWidth, false)
	}

	if (b.DisplayPos+currLineSpace)%b.LineWidth == 0 && currLine == remainingText {
xuxzh1's avatar
update  
xuxzh1 committed
303
		fmt.Print(CursorRightN(currLineSpace))
mashun1's avatar
v1  
mashun1 committed
304
		fmt.Printf("\n%s", b.Prompt.AltPrompt)
xuxzh1's avatar
update  
xuxzh1 committed
305
		fmt.Print(CursorUp + CursorBOL + CursorRightN(b.Width-currLineSpace))
mashun1's avatar
v1  
mashun1 committed
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
	}

	// render the other lines
	if remLength > currLineSpace {
		remaining := (remainingText[len(currLine):])
		var totalLines int
		var displayLength int
		var lineLength int = currLineSpace

		for _, c := range remaining {
			if displayLength == 0 || (displayLength+runewidth.RuneWidth(c))%b.LineWidth < displayLength%b.LineWidth {
				fmt.Printf("\n%s", b.Prompt.AltPrompt)
				totalLines += 1

				if displayLength != 0 {
					if lineLength == b.LineWidth {
						b.LineHasSpace.Set(b.DisplayPos/b.LineWidth+totalLines-1, false)
					} else {
						b.LineHasSpace.Set(b.DisplayPos/b.LineWidth+totalLines-1, true)
					}
				}

				lineLength = 0
			}

			displayLength += runewidth.RuneWidth(c)
			lineLength += runewidth.RuneWidth(c)
			fmt.Printf("%c", c)
		}
xuxzh1's avatar
update  
xuxzh1 committed
335
		fmt.Print(ClearToEOL + CursorUpN(totalLines) + CursorBOL + CursorRightN(b.Width-currLineSpace))
mashun1's avatar
v1  
mashun1 committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

		hasSpace := b.GetLineSpacing(b.DisplayPos / b.LineWidth)

		if hasSpace && b.DisplayPos%b.LineWidth != b.LineWidth-1 {
			fmt.Print(CursorLeft)
		}
	}

	fmt.Print(CursorShow)
}

func (b *Buffer) Remove() {
	if b.Buf.Size() > 0 && b.Pos > 0 {
		if e, ok := b.Buf.Get(b.Pos - 1); ok {
			if r, ok := e.(rune); ok {
				rLength := runewidth.RuneWidth(r)
				hasSpace := b.GetLineSpacing(b.DisplayPos/b.LineWidth - 1)

				if b.DisplayPos%b.LineWidth == 0 {
					// if the user backspaces over the word boundary, do this magic to clear the line
					// and move to the end of the previous line
xuxzh1's avatar
update  
xuxzh1 committed
357
					fmt.Print(CursorBOL + ClearToEOL + CursorUp + CursorBOL + CursorRightN(b.Width))
mashun1's avatar
v1  
mashun1 committed
358
359
360
361
362
363
364
365
366
367
368

					if b.DisplaySize()%b.LineWidth < (b.DisplaySize()-rLength)%b.LineWidth {
						b.LineHasSpace.Remove(b.DisplayPos/b.LineWidth - 1)
					}

					if hasSpace {
						b.DisplayPos -= 1
						fmt.Print(CursorLeft)
					}

					if rLength == 2 {
xuxzh1's avatar
update  
xuxzh1 committed
369
						fmt.Print(CursorLeft + "  " + CursorLeftN(2))
mashun1's avatar
v1  
mashun1 committed
370
371
372
373
					} else {
						fmt.Print(" " + CursorLeft)
					}
				} else if (b.DisplayPos-rLength)%b.LineWidth == 0 && hasSpace {
xuxzh1's avatar
update  
xuxzh1 committed
374
					fmt.Print(CursorBOL + ClearToEOL + CursorUp + CursorBOL + CursorRightN(b.Width))
mashun1's avatar
v1  
mashun1 committed
375
376
377
378
379
380

					if b.Pos == b.Buf.Size() {
						b.LineHasSpace.Remove(b.DisplayPos/b.LineWidth - 1)
					}
					b.DisplayPos -= 1
				} else {
xuxzh1's avatar
update  
xuxzh1 committed
381
					fmt.Print(CursorLeftN(rLength))
xuxzh1's avatar
init  
xuxzh1 committed
382
					for range rLength {
mashun1's avatar
v1  
mashun1 committed
383
384
						fmt.Print(" ")
					}
xuxzh1's avatar
update  
xuxzh1 committed
385
					fmt.Print(CursorLeftN(rLength))
mashun1's avatar
v1  
mashun1 committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
				}

				var eraseExtraLine bool
				if (b.DisplaySize()-1)%b.LineWidth == 0 || (rLength == 2 && ((b.DisplaySize()-2)%b.LineWidth == 0)) || b.DisplaySize()%b.LineWidth == 0 {
					eraseExtraLine = true
				}

				b.Pos -= 1
				b.DisplayPos -= rLength
				b.Buf.Remove(b.Pos)

				if b.Pos < b.Buf.Size() {
					b.drawRemaining()
					// this erases a line which is left over when backspacing in the middle of a line and there
					// are trailing characters which go over the line width boundary
					if eraseExtraLine {
						remainingLines := (b.DisplaySize() - b.DisplayPos) / b.LineWidth
xuxzh1's avatar
update  
xuxzh1 committed
403
						fmt.Print(CursorDownN(remainingLines+1) + CursorBOL + ClearToEOL)
mashun1's avatar
v1  
mashun1 committed
404
						place := b.DisplayPos % b.LineWidth
xuxzh1's avatar
update  
xuxzh1 committed
405
						fmt.Print(CursorUpN(remainingLines+1) + CursorRightN(place+len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
					}
				}
			}
		}
	}
}

func (b *Buffer) Delete() {
	if b.Buf.Size() > 0 && b.Pos < b.Buf.Size() {
		b.Buf.Remove(b.Pos)
		b.drawRemaining()
		if b.DisplaySize()%b.LineWidth == 0 {
			if b.DisplayPos != b.DisplaySize() {
				remainingLines := (b.DisplaySize() - b.DisplayPos) / b.LineWidth
xuxzh1's avatar
update  
xuxzh1 committed
420
				fmt.Print(CursorDownN(remainingLines) + CursorBOL + ClearToEOL)
mashun1's avatar
v1  
mashun1 committed
421
				place := b.DisplayPos % b.LineWidth
xuxzh1's avatar
update  
xuxzh1 committed
422
				fmt.Print(CursorUpN(remainingLines) + CursorRightN(place+len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
			}
		}
	}
}

func (b *Buffer) DeleteBefore() {
	if b.Pos > 0 {
		for cnt := b.Pos - 1; cnt >= 0; cnt-- {
			b.Remove()
		}
	}
}

func (b *Buffer) DeleteRemaining() {
	if b.DisplaySize() > 0 && b.Pos < b.DisplaySize() {
		charsToDel := b.Buf.Size() - b.Pos
xuxzh1's avatar
init  
xuxzh1 committed
439
		for range charsToDel {
mashun1's avatar
v1  
mashun1 committed
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
			b.Delete()
		}
	}
}

func (b *Buffer) DeleteWord() {
	if b.Buf.Size() > 0 && b.Pos > 0 {
		var foundNonspace bool
		for {
			v, _ := b.Buf.Get(b.Pos - 1)
			if v == ' ' {
				if !foundNonspace {
					b.Remove()
				} else {
					break
				}
			} else {
				foundNonspace = true
				b.Remove()
			}

			if b.Pos == 0 {
				break
			}
		}
	}
}

func (b *Buffer) ClearScreen() {
xuxzh1's avatar
update  
xuxzh1 committed
469
	fmt.Print(ClearScreen + CursorReset + b.Prompt.prompt())
mashun1's avatar
v1  
mashun1 committed
470
471
	if b.IsEmpty() {
		ph := b.Prompt.placeholder()
xuxzh1's avatar
update  
xuxzh1 committed
472
		fmt.Print(ColorGrey + ph + CursorLeftN(len(ph)) + ColorDefault)
mashun1's avatar
v1  
mashun1 committed
473
474
475
476
477
478
	} else {
		currPos := b.DisplayPos
		currIndex := b.Pos
		b.Pos = 0
		b.DisplayPos = 0
		b.drawRemaining()
xuxzh1's avatar
update  
xuxzh1 committed
479
		fmt.Print(CursorReset + CursorRightN(len(b.Prompt.prompt())))
mashun1's avatar
v1  
mashun1 committed
480
481
482
		if currPos > 0 {
			targetLine := currPos / b.LineWidth
			if targetLine > 0 {
xuxzh1's avatar
init  
xuxzh1 committed
483
				for range targetLine {
mashun1's avatar
v1  
mashun1 committed
484
485
486
487
488
					fmt.Print(CursorDown)
				}
			}
			remainder := currPos % b.LineWidth
			if remainder > 0 {
xuxzh1's avatar
update  
xuxzh1 committed
489
				fmt.Print(CursorRightN(remainder))
mashun1's avatar
v1  
mashun1 committed
490
491
			}
			if currPos%b.LineWidth == 0 {
xuxzh1's avatar
update  
xuxzh1 committed
492
				fmt.Print(CursorBOL + b.Prompt.AltPrompt)
mashun1's avatar
v1  
mashun1 committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
			}
		}
		b.Pos = currIndex
		b.DisplayPos = currPos
	}
}

func (b *Buffer) IsEmpty() bool {
	return b.Buf.Empty()
}

func (b *Buffer) Replace(r []rune) {
	b.DisplayPos = 0
	b.Pos = 0
	lineNums := b.DisplaySize() / b.LineWidth

	b.Buf.Clear()

xuxzh1's avatar
update  
xuxzh1 committed
511
	fmt.Print(CursorBOL + ClearToEOL)
mashun1's avatar
v1  
mashun1 committed
512

xuxzh1's avatar
init  
xuxzh1 committed
513
	for range lineNums {
mashun1's avatar
v1  
mashun1 committed
514
515
516
		fmt.Print(CursorUp + CursorBOL + ClearToEOL)
	}

xuxzh1's avatar
update  
xuxzh1 committed
517
	fmt.Print(CursorBOL + b.Prompt.prompt())
mashun1's avatar
v1  
mashun1 committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

	for _, c := range r {
		b.Add(c)
	}
}

func (b *Buffer) String() string {
	return b.StringN(0)
}

func (b *Buffer) StringN(n int) string {
	return b.StringNM(n, 0)
}

func (b *Buffer) StringNM(n, m int) string {
	var s string
	if m == 0 {
		m = b.Buf.Size()
	}
	for cnt := n; cnt < m; cnt++ {
		c, _ := b.Buf.Get(cnt)
		s += string(c.(rune))
	}
	return s
}