Skip to content

Commit a65bb08

Browse files
committed
Adjust cursor position calculation to account for newlines during text insertion
1 parent 36632b3 commit a65bb08

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

  • ComposeTextEditor/src/commonMain/kotlin/com/darkrockstudios/texteditor/state

ComposeTextEditor/src/commonMain/kotlin/com/darkrockstudios/texteditor/state/TextEditorState.kt

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,11 +186,23 @@ class TextEditorState(
186186
fun insertStringAtCursor(string: String) = insertStringAtCursor(string.toAnnotatedString())
187187
fun insertStringAtCursor(text: AnnotatedString) {
188188
val styledText = cursor.applyCursorStyle(text)
189+
190+
// Calculate cursor position after insertion, accounting for newlines
191+
val textString = text.text
192+
val lastNewlineIndex = textString.lastIndexOf('\n')
193+
val cursorAfter = if (lastNewlineIndex >= 0) {
194+
val newlineCount = textString.count { it == '\n' }
195+
val charsAfterLastNewline = textString.length - lastNewlineIndex - 1
196+
CharLineOffset(cursorPosition.line + newlineCount, charsAfterLastNewline)
197+
} else {
198+
CharLineOffset(cursorPosition.line, cursorPosition.char + text.length)
199+
}
200+
189201
val operation = TextEditOperation.Insert(
190202
position = cursorPosition,
191203
text = styledText,
192204
cursorBefore = cursorPosition,
193-
cursorAfter = CharLineOffset(cursorPosition.line, cursorPosition.char + text.length)
205+
cursorAfter = cursorAfter
194206
)
195207
editManager.applyOperation(operation)
196208
}

0 commit comments

Comments
 (0)