Skip to content

Commit

Permalink
Merge pull request #6 from mbrostami/fix-inser-text-overwrite-out-of-…
Browse files Browse the repository at this point in the history
…range

Fix insert text overwrite out of range
  • Loading branch information
Verseth authored Jul 1, 2023
2 parents ac65f23 + b782bd0 commit cad76d9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
5 changes: 4 additions & 1 deletion buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ func (b *Buffer) InsertText(v string, overwrite bool, moveCursor bool) {
oc := b.cursorPosition

if overwrite {
overwritten := string(or[oc : oc+len(v)])
overwritten := string(or[oc:])
if len(overwritten) >= oc+len(v) {
overwritten = string(or[oc : oc+len(v)])
}
if strings.Contains(overwritten, "\n") {
i := strings.IndexAny(overwritten, "\n")
overwritten = overwritten[:i]
Expand Down
46 changes: 46 additions & 0 deletions buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,52 @@ func TestBuffer_InsertText(t *testing.T) {
}
}

func TestBuffer_InsertText_Overwrite(t *testing.T) {
b := NewBuffer()
b.InsertText("ABC", false, true)

if b.Text() != "ABC" {
t.Errorf("Text should be %#v, got %#v", "ABC", b.Text())
}

if b.cursorPosition != len("ABC") {
t.Errorf("cursorPosition should be %#v, got %#v", len("ABC"), b.cursorPosition)
}

b.CursorLeft(1)
// Replace C with DEF in ABC
b.InsertText("DEF", true, true)

if b.Text() != "ABDEF" {
t.Errorf("Text should be %#v, got %#v", "ABDEF", b.Text())
}

b.CursorLeft(100)
// Replace ABD with GHI in ABDEF
b.InsertText("GHI", true, true)

if b.Text() != "GHIEF" {
t.Errorf("Text should be %#v, got %#v", "GHIEF", b.Text())
}

b.CursorLeft(100)
// Replace GHI with J\nK in GHIEF
b.InsertText("J\nK", true, true)

if b.Text() != "J\nKEF" {
t.Errorf("Text should be %#v, got %#v", "J\nKEF", b.Text())
}

b.CursorUp(100)
b.CursorLeft(100)
// Replace J with LMN in J\nKEF test end of line
b.InsertText("LMN", true, true)

if b.Text() != "LMN\nKEF" {
t.Errorf("Text should be %#v, got %#v", "LMN\nKEF", b.Text())
}
}

func TestBuffer_CursorMovement(t *testing.T) {
b := NewBuffer()
b.InsertText("some_text", false, true)
Expand Down

0 comments on commit cad76d9

Please sign in to comment.