Improve remove performance

This commit is contained in:
Zachary Yedidia 2020-02-09 14:58:37 -05:00
parent ca9d102267
commit 8ddf335e68
3 changed files with 18 additions and 15 deletions

View File

@ -2,7 +2,6 @@ package buffer
import (
"bytes"
"log"
"time"
"unicode/utf8"
@ -124,33 +123,35 @@ func (eh *EventHandler) InsertBytes(start Loc, text []byte) {
Deltas: []Delta{{text, start, Loc{0, 0}}},
Time: time.Now(),
}
// oldl := eh.buf.LinesNum()
oldl := eh.buf.LinesNum()
eh.Execute(e)
// linecount := eh.buf.LinesNum() - oldl
linecount := eh.buf.LinesNum() - oldl
textcount := utf8.RuneCount(text)
lastnl := bytes.LastIndex(text, []byte{'\n'})
var endX int
var textX int
if lastnl >= 0 {
endX = utf8.RuneCount(text[lastnl:])
endX = utf8.RuneCount(text[lastnl+1:])
textX = endX
} else {
// endX = start.X + textcount
endX = start.X + textcount
textX = textcount
}
e.Deltas[0].End = start.MoveLA(textcount, eh.buf.LineArray)
// e.Deltas[0].End = clamp(Loc{endX, start.Y + linecount}, eh.buf.LineArray)
e.Deltas[0].End = clamp(Loc{endX, start.Y + linecount}, eh.buf.LineArray)
end := e.Deltas[0].End
for _, c := range eh.cursors {
move := func(loc Loc) Loc {
log.Println("move", loc)
if start.Y != end.Y && loc.GreaterThan(start) {
loc.Y += end.Y - start.Y
} else if loc.Y == start.Y && loc.GreaterEqual(start) {
loc.Y += end.Y - start.Y
loc.X += textX
if lastnl >= 0 {
loc.X = textX
} else {
loc.X += textX
}
}
return loc
}

View File

@ -224,20 +224,18 @@ func (la *LineArray) split(pos Loc) {
// removes from start to end
func (la *LineArray) remove(start, end Loc) []byte {
sub := la.Substr(start, end)
// sub := la.Substr(start, end)
startX := runeToByteIndex(start.X, la.lines[start.Y].data)
endX := runeToByteIndex(end.X, la.lines[end.Y].data)
if start.Y == end.Y {
la.lines[start.Y].data = append(la.lines[start.Y].data[:startX], la.lines[start.Y].data[endX:]...)
} else {
for i := start.Y + 1; i <= end.Y-1; i++ {
la.deleteLine(start.Y + 1)
}
la.deleteLines(start.Y, end.Y-1)
la.deleteToEnd(Loc{startX, start.Y})
la.deleteFromStart(Loc{endX - 1, start.Y + 1})
la.joinLines(start.Y, start.Y+1)
}
return sub
return []byte{}
}
// deleteToEnd deletes from the end of a line to the position
@ -255,6 +253,10 @@ func (la *LineArray) deleteLine(y int) {
la.lines = la.lines[:y+copy(la.lines[y:], la.lines[y+1:])]
}
func (la *LineArray) deleteLines(y1, y2 int) {
la.lines = la.lines[:y1+copy(la.lines[y1:], la.lines[y2:])]
}
// DeleteByte deletes the byte at a position
func (la *LineArray) deleteByte(pos Loc) {
la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X+copy(la.lines[pos.Y].data[pos.X:], la.lines[pos.Y].data[pos.X+1:])]

View File

@ -139,7 +139,7 @@ func ByteOffset(pos Loc, buf *Buffer) int {
// clamps a loc within a buffer
func clamp(pos Loc, la *LineArray) Loc {
if pos.GreaterEqual(la.End()) {
return la.End().MoveLA(-1, la)
return la.End()
} else if pos.LessThan(la.Start()) {
return la.Start()
}