diff --git a/server/types/rope.go b/server/types/rope.go index 06736da..a157e5d 100644 --- a/server/types/rope.go +++ b/server/types/rope.go @@ -102,7 +102,7 @@ func (r *Rope) OffsetFromPosition(position lsp.Position) int { // Ensure character is within valid range if position.Character >= uint32(len(line)) { - position.Character = uint32(len(line) - 1) + position.Character = uint32(len(line)) } // Calculate byte offset @@ -110,6 +110,7 @@ func (r *Rope) OffsetFromPosition(position lsp.Position) int { for i := 0; i < int(position.Line); i++ { offset += len(lines[i]) + 1 // Add 1 for the newline character } + offset += int(position.Character) return offset diff --git a/server/types/rope_test.go b/server/types/rope_test.go index 3f0a867..cb356e2 100644 --- a/server/types/rope_test.go +++ b/server/types/rope_test.go @@ -83,6 +83,10 @@ func TestOffsetFromPosition(t *testing.T) { if offset != expected { t.Errorf("Expected offset: %d, Got offset: %d", expected, offset) } + + if r.text[:offset] != "Hello, World!\nThis i" { + t.Errorf("Expected text: %s, Got text: %s", "Hello, World!\nThis ", r.text[:offset]) + } }) t.Run("Position Exceeds Line Length", func(t *testing.T) { @@ -91,10 +95,14 @@ func TestOffsetFromPosition(t *testing.T) { offset := r.OffsetFromPosition(position) - expected := 28 // Maximum offset is 28 (end of text) + expected := 29 // Maximum offset is 29 (end of text) if offset != expected { t.Errorf("Expected offset: %d, Got offset: %d", expected, offset) } + + if r.text[:offset] != "Hello, World!\nThis is a test." { + t.Errorf("Expected text: %s, Got text: %s", "Hello, World!\nThis is a test.", r.text[:offset]) + } }) t.Run("Position Exceeds Line Count", func(t *testing.T) { @@ -107,5 +115,9 @@ func TestOffsetFromPosition(t *testing.T) { if offset != expected { t.Errorf("Expected offset: %d, Got offset: %d", expected, offset) } + + if r.text[:offset] != "Hello, World!\nThis i" { + t.Errorf("Expected text: %s, Got text: %s", "Hello, World!\nThis i", r.text[:offset]) + } }) }