diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt index d521e8cb..d0969e6f 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextState.kt @@ -790,7 +790,7 @@ class RichTextState internal constructor( */ private fun handleAddingCharacters() { val typedCharsCount = tempTextFieldValue.text.length - textFieldValue.text.length - var startTypeIndex = tempTextFieldValue.selection.min - typedCharsCount + var startTypeIndex = tempTextFieldValue.selection.max - typedCharsCount val typedText = tempTextFieldValue.text.substring( startIndex = startTypeIndex, endIndex = startTypeIndex + typedCharsCount, @@ -817,7 +817,10 @@ class RichTextState internal constructor( val newTypedText = beforeTypedText + paragraphStartText + typedText + afterTypedText tempTextFieldValue = tempTextFieldValue.copy( text = newTypedText, - selection = TextRange(tempTextFieldValue.selection.min + indexDiff), + selection = TextRange( + (tempTextFieldValue.selection.min + indexDiff).coerceAtLeast(0), + (tempTextFieldValue.selection.max + indexDiff).coerceAtMost(newTypedText.length), + ), ) }