Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix slice out of range when using insert text with overwrite option #241

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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