Skip to content

Commit

Permalink
Store cursor position when changing lines (#749)
Browse files Browse the repository at this point in the history
## What is the goal of this PR?

We store cursor positions when changing lines as described in
#748. This is standard
behaviour in other IDEs, such as IntelliJ IDEA and VSCode.

## What are the changes implemented in this PR?

We store an additional piece of data in `Cursor`, `lastCol`. This
remembers the last position of the column, which we only forget upon the
creation of a new cursor by a method other than moving up or down a
line.

## Additional info
Closes #748
  • Loading branch information
James Williams authored Apr 12, 2024
1 parent 42a5297 commit 1345227
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions framework/editor/InputTarget.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ internal class InputTarget constructor(
}
}

internal data class Cursor constructor(val row: Int, val col: Int) : Comparable<Cursor> {
internal data class Cursor constructor(val row: Int, val col: Int, val lastCol: Int = col) : Comparable<Cursor> {

companion object {
fun min(first: Cursor, second: Cursor): Cursor {
Expand Down Expand Up @@ -371,23 +371,19 @@ internal class InputTarget constructor(
}

internal fun moveCursorUpByLine(isSelecting: Boolean = false) {
var newRow = cursor.row - 1
var newCol = cursor.col
if (newRow < 0) {
newRow = 0
newCol = 0
} else newCol = newCol.coerceAtMost(content[newRow].length)
updateCursor(Cursor(newRow, newCol), isSelecting)
if (cursor.row != 0) {
val newRow = cursor.row - 1
val newCol = cursor.lastCol.coerceAtMost(content[newRow].length)
updateCursor(Cursor(newRow, newCol, lastCol = cursor.lastCol), isSelecting)
}
}

internal fun moveCursorDownByLine(isSelecting: Boolean = false) {
var newRow = cursor.row + 1
var newCol = cursor.col
if (newRow >= content.size) {
newRow = content.size - 1
newCol = content[newRow].length
} else newCol = newCol.coerceAtMost(content[newRow].length)
updateCursor(Cursor(newRow, newCol), isSelecting)
if (cursor.row != content.size - 1) {
val newRow = cursor.row + 1
val newCol = cursor.lastCol.coerceAtMost(content[newRow].length)
updateCursor(Cursor(newRow, newCol, lastCol = cursor.lastCol), isSelecting)
}
}

internal fun moveCursorUpByPage(isSelecting: Boolean = false) {
Expand Down

0 comments on commit 1345227

Please sign in to comment.