/
runs.go
136 lines (114 loc) · 2.13 KB
/
runs.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
package terminal
// Runs should always be consecutive
type Run struct {
start int
text string
style Style
}
func (r Run) end() int {
return r.start + len(r.text)
}
func (r Run) CopyTo(x int) Run {
if x > r.end() {
return r
}
return Run{
start: r.start,
text: r.text[:x-r.start],
style: r.style,
}
}
func (r Run) CopyFrom(i int) Run {
return Run{
start: i,
text: r.text[i-r.start:],
style: r.style,
}
}
func (r Run) IsEmpty() bool {
return len(r.text) == 0
}
func (r Run) length() int {
return len(r.text)
}
// Shift the start position of this run by length
func (r Run) offset(o int) Run {
if o == 0 {
return r
}
r.start += o
return r
}
func (r Run) Split(maxLength int) (Run, Run, bool) {
if r.end() <= maxLength {
return r, Run{}, false
} else {
l := maxLength - r.start
if l < 0 {
panic("should not occur")
}
head := Run{
start: r.start,
text: r.text[0:l],
style: r.style,
}
tail := Run{
start: r.start + l,
text: r.text[l:],
style: r.style,
}
return head, tail, true
}
}
func appendRun(runs []Run, tail Run) []Run {
if len(runs) == 0 {
return []Run{tail}
}
i := len(runs) - 1
last := runs[i]
if last.end() == tail.start && last.style == tail.style {
runs[i].text += tail.text
return runs
} else {
return append(runs, tail)
}
}
func writeText(in []Run, text string, x int, style Style) []Run {
// We want to write the given text to the screen at position x. First add the runs preceding the position of the
// new text. A run that overlaps with the position of the new text we only copy that part just before it.
var out []Run
var i = 0
// Check preceding
for i < len(in) {
r := in[i]
if r.start < x && r.end() < x {
out = append(out, r)
i++
} else if r.start < x {
out = append(out, r.CopyTo(x))
break
} else {
break
}
}
out = append(out, Run{
start: x,
text: text,
style: style,
})
// Add remaining runs
for i < len(in) {
r := in[i]
i++
end := x + len(text)
if r.end() <= end {
continue
}
if r.start >= end {
out = append(out, r)
} else {
out = append(out, r.CopyFrom(end))
}
}
return out
}