Skip to content

Commit

Permalink
Merge pull request #87 from mjarkk/set-cursor-give-less-errors
Browse files Browse the repository at this point in the history
Less strict rules for SetCursor
  • Loading branch information
mjarkk authored Mar 28, 2021
2 parents f695483 + 771d398 commit 5f7be97
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
1 change: 0 additions & 1 deletion edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,6 @@ func (v *View) EditNewLine() {
v.ox = 0
v.cy = v.cy + 1
v.cx = 0
v.moveCursor(0, 1)
}

// MoveCursor mores the cursor relative from it's current possition
Expand Down
33 changes: 28 additions & 5 deletions view.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,14 @@ func (v *View) setRune(x, y int, ch rune, fgColor, bgColor Attribute) error {
return nil
}

// SetCursor sets the cursor position of the view at the given point,
// SetCursorUnrestricted sets the cursor position of the view at the given point
// This does NOT check if the x and y location are available in the buffer
//
// Rules:
// y < total lines && y > 0
// (x < view width || x < y's line width) && x > 0
func (v *View) SetCursor(x, y int) error {
if x < 0 || y < 0 || (y >= len(v.lines) && y != 0) || (x > 0 && (len(v.lines) == 0 || len(v.lines[y]) < x)) {
// y >= 0
// x >= 0
func (v *View) SetCursorUnrestricted(x, y int) error {
if x < 0 || y < 0 {
return ErrInvalidPoint
}

Expand All @@ -244,6 +245,28 @@ func (v *View) SetCursor(x, y int) error {
return nil
}

// SetCursor tries sets the cursor position of the view at the given point
// If the x or y are outside of the buffer this function will place the cursor on the nearest buffer location
//
// Rules:
// y >= 0
// x >= 0
func (v *View) SetCursor(x, y int) error {
if y >= len(v.lines) && y != 0 {
y = len(v.lines) - 1
}

if x > 0 && (len(v.lines) == 0 || len(v.lines[y]) < x) {
if len(v.lines) == 0 {
x = 0
} else {
x = len(v.lines[y])
}
}

return v.SetCursorUnrestricted(x, y)
}

// Cursor returns the cursor position of the view.
func (v *View) Cursor() (x, y int) {
return v.cx, v.cy
Expand Down

0 comments on commit 5f7be97

Please sign in to comment.