gilo/editor/row.go

104 lines
1.8 KiB
Go
Raw Normal View History

2021-03-30 16:05:33 -04:00
package editor
2021-04-01 16:17:13 -04:00
import (
"strings"
)
2021-04-02 14:52:44 -04:00
type Row struct {
chars []rune
render []rune
2021-03-30 16:05:33 -04:00
}
2021-04-02 14:52:44 -04:00
func newRow(s string) *Row {
2021-03-30 18:00:06 -04:00
var chars []rune
var render []rune
2021-03-30 18:00:06 -04:00
for _, ch := range s {
chars = append(chars, ch)
render = append(render, ch)
2021-03-30 18:00:06 -04:00
}
2021-04-02 14:52:44 -04:00
return &Row{chars, render}
2021-03-30 16:05:33 -04:00
}
2021-04-02 14:52:44 -04:00
func (r *Row) Size() int {
2021-03-30 16:05:33 -04:00
return len(r.chars)
}
2021-04-02 14:52:44 -04:00
func (r *Row) RenderSize() int {
return len(r.render)
}
2021-04-02 14:52:44 -04:00
func (r *Row) insertRune(ch rune, at int) {
2021-04-01 16:17:13 -04:00
// If insertion index is invalid, just
// append the rune to the end of the array
2021-04-02 14:52:44 -04:00
if at < 0 || at >= r.Size() {
2021-04-01 16:17:13 -04:00
r.chars = append(r.chars, ch)
r.update()
return
}
var newSlice []rune
// Split the character array at the insertion point
start := r.chars[0:at]
2021-04-02 14:52:44 -04:00
end := r.chars[at:r.Size()]
2021-04-01 16:17:13 -04:00
// Splice it back together
newSlice = append(newSlice, start...)
newSlice = append(newSlice, ch)
newSlice = append(newSlice, end...)
r.chars = newSlice
r.update()
}
2021-04-02 14:52:44 -04:00
func (r *Row) deleteRune(at int) {
if at < 0 || at >= r.Size() {
2021-04-02 10:48:51 -04:00
return
}
var newSlice []rune
// Split the character array at the insertion point
start := r.chars[0:at]
2021-04-02 14:52:44 -04:00
end := r.chars[at+1 : r.Size()] // Skip the index in question
2021-04-02 10:48:51 -04:00
// Splice it back together
newSlice = append(newSlice, start...)
newSlice = append(newSlice, end...)
r.chars = newSlice
r.update()
}
2021-04-02 14:52:44 -04:00
func (r *Row) update() {
r.render = r.render[:0]
replacement := strings.Repeat(" ", KiloTabStop)
str := strings.ReplaceAll(string(r.chars), "\t", replacement)
for _, ch := range str {
r.render = append(r.render, ch)
}
}
2021-03-30 16:05:33 -04:00
2021-04-02 14:52:44 -04:00
func (r *Row) toString() string {
2021-04-01 16:17:13 -04:00
return string(r.chars)
}
2021-04-02 14:52:44 -04:00
func (r *Row) cursorXToRenderX(cursorX int) int {
2021-03-31 14:56:46 -04:00
renderX := 0
i := 0
for ; i < cursorX; i++ {
if r.chars[i] == '\t' {
renderX += (KiloTabStop - 1) - (renderX % KiloTabStop)
}
renderX += 1
}
return renderX
2021-04-01 16:17:13 -04:00
}