From 89c468924e9c94cb80f2fe09b3581b12b6697588 Mon Sep 17 00:00:00 2001 From: Zachary Yedidia Date: Fri, 11 Nov 2016 20:12:21 -0500 Subject: [PATCH] Fix rare out of bounds error with selections Fixes #446 --- cmd/micro/cursor.go | 9 ++++++--- cmd/micro/loc.go | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/cmd/micro/cursor.go b/cmd/micro/cursor.go index c6eb92ae..a40aa9cf 100644 --- a/cmd/micro/cursor.go +++ b/cmd/micro/cursor.go @@ -73,10 +73,13 @@ func (c *Cursor) DeleteSelection() { // GetSelection returns the cursor's selection func (c *Cursor) GetSelection() string { - if c.CurSelection[0].GreaterThan(c.CurSelection[1]) { - return c.buf.Substr(c.CurSelection[1], c.CurSelection[0]) + if InBounds(c.CurSelection[0], c.buf) && InBounds(c.CurSelection[1], c.buf) { + if c.CurSelection[0].GreaterThan(c.CurSelection[1]) { + return c.buf.Substr(c.CurSelection[1], c.CurSelection[0]) + } + return c.buf.Substr(c.CurSelection[0], c.CurSelection[1]) } - return c.buf.Substr(c.CurSelection[0], c.CurSelection[1]) + return "" } // SelectLine selects the current line diff --git a/cmd/micro/loc.go b/cmd/micro/loc.go index ce0806a1..263e0fb3 100644 --- a/cmd/micro/loc.go +++ b/cmd/micro/loc.go @@ -28,6 +28,15 @@ func ToCharPos(start Loc, buf *Buffer) int { return loc } +// InBounds returns whether the given location is a valid character position in the given buffer +func InBounds(pos Loc, buf *Buffer) bool { + if pos.Y < 0 || pos.Y >= buf.NumLines || pos.X < 0 || pos.X > Count(buf.Line(pos.Y)) { + return false + } + + return true +} + // ByteOffset is just like ToCharPos except it counts bytes instead of runes func ByteOffset(pos Loc, buf *Buffer) int { x, y := pos.X, pos.Y