From 848a06ac82985b67efdb3454c829dc7b3d7cd4a4 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 19:00:29 +0100 Subject: [PATCH 01/16] feat: add a syntax tokenizer with Kotlin support --- .../richeditor/highlight/CodeHighlighter.kt | 15 +++ .../richeditor/highlight/CodeLanguage.kt | 21 +++ .../richeditor/highlight/CodeScanner.kt | 123 ++++++++++++++++++ .../richeditor/highlight/CodeToken.kt | 24 ++++ .../richeditor/highlight/LanguageSpec.kt | 26 ++++ .../highlight/languages/KotlinSpec.kt | 25 ++++ .../highlight/CodeHighlighterTest.kt | 94 +++++++++++++ .../highlight/HighlightTestUtils.kt | 7 + 8 files changed, 335 insertions(+) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeScanner.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeToken.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/KotlinSpec.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightTestUtils.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt new file mode 100644 index 00000000..807b09be --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt @@ -0,0 +1,15 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +/** Finds the parts of a piece of code that are drawn in a colour of their own. */ +@ExperimentalRichTextApi +public object CodeHighlighter { + + /** + * The tokens of [code], in order, inside the text and never overlapping. It never throws: + * a string or comment that is not closed runs to the end of its line or of the code. + */ + public fun tokenize(code: String, language: CodeLanguage): List = + CodeScanner.scan(code, language.spec) +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt new file mode 100644 index 00000000..9301bf18 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt @@ -0,0 +1,21 @@ +package com.mohamedrejeb.richeditor.highlight + +import androidx.compose.runtime.Immutable +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.languages.KotlinSpec + +/** A language the library can colour. Get one from the companion, by [fromName] or by [fromFileName]. */ +@ExperimentalRichTextApi +@Immutable +public class CodeLanguage internal constructor( + public val name: String, + internal val aliases: List, + internal val extensions: List, + internal val spec: LanguageSpec, +) { + override fun toString(): String = "CodeLanguage($name)" + + public companion object { + public val Kotlin: CodeLanguage = CodeLanguage("kotlin", listOf("kt", "kts"), listOf("kt", "kts"), KotlinSpec) + } +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeScanner.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeScanner.kt new file mode 100644 index 00000000..b7c85e4b --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeScanner.kt @@ -0,0 +1,123 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +/** + * Reads code left to right once. Every branch moves forward by at least one character and the + * rule lists are short and fixed, so the work is linear in the length of the code. + */ +@OptIn(ExperimentalRichTextApi::class) +internal object CodeScanner { + + fun scan(code: String, spec: LanguageSpec): List { + val tokens = ArrayList() + var index = 0 + while (index < code.length) { + val char = code[index] + val end = when { + char.isWhitespace() -> index + 1 + else -> tokenEnd(code, index, spec, tokens) + } + index = end + } + return tokens + } + + /** Adds the token starting at [start], if there is one, and returns where to read next. */ + private fun tokenEnd(code: String, start: Int, spec: LanguageSpec, tokens: MutableList): Int { + val char = code[start] + + val blockComment = spec.blockComments.firstOrNull { code.startsWith(it.open, start) } + if (blockComment != null) { + return blockCommentEnd(code, start, blockComment).also { tokens += CodeToken(start, it, CodeTokenKind.Comment) } + } + if (startsLineComment(code, start, spec)) { + return lineEnd(code, start).also { tokens += CodeToken(start, it, CodeTokenKind.Comment) } + } + val string = spec.strings.firstOrNull { code.startsWith(it.open, start) } + if (string != null) { + return stringEnd(code, start, string).also { tokens += CodeToken(start, it, CodeTokenKind.String) } + } + if ( + char == spec.annotationPrefix && + isIdentifierStart(code.getOrNull(start + 1)) && + !isIdentifierPart(code.getOrNull(start - 1)) + ) { + return identifierEnd(code, start + 1).also { tokens += CodeToken(start, it, CodeTokenKind.Annotation) } + } + if (char.isDigit()) { + return numberEnd(code, start).also { tokens += CodeToken(start, it, CodeTokenKind.Number) } + } + if (isIdentifierStart(char)) { + val end = identifierEnd(code, start) + val word = code.substring(start, end) + if ((if (spec.ignoreKeywordCase) word.lowercase() else word) in spec.keywords) { + tokens += CodeToken(start, end, CodeTokenKind.Keyword) + } + return end + } + return start + 1 + } + + private fun startsLineComment(code: String, start: Int, spec: LanguageSpec): Boolean = + spec.lineComments.any { code.startsWith(it, start) } && + (!spec.commentNeedsLeadingSpace || start == 0 || code[start - 1].isWhitespace()) + + private fun lineEnd(code: String, start: Int): Int = + code.indexOf('\n', start).let { if (it == -1) code.length else it } + + private fun blockCommentEnd(code: String, start: Int, rule: BlockComment): Int { + var depth = 1 + var index = start + rule.open.length + while (index < code.length) { + when { + code.startsWith(rule.close, index) -> { + index += rule.close.length + depth-- + if (depth == 0) return index + } + rule.nests && code.startsWith(rule.open, index) -> { + index += rule.open.length + depth++ + } + else -> index++ + } + } + return code.length + } + + private fun stringEnd(code: String, start: Int, rule: StringRule): Int { + var index = start + rule.open.length + while (index < code.length) { + val char = code[index] + when { + char == rule.escape -> index += 2 + code.startsWith(rule.close, index) -> return index + rule.close.length + char == '\n' && !rule.multiline -> return index + else -> index++ + } + } + return code.length + } + + private fun numberEnd(code: String, start: Int): Int { + var index = start + while (index < code.length) { + val char = code[index] + val isFraction = char == '.' && code.getOrNull(index + 1)?.isDigit() == true + if (!char.isLetterOrDigit() && char != '_' && !isFraction) break + index++ + } + return index + } + + private fun identifierEnd(code: String, start: Int): Int { + var index = start + while (index < code.length && isIdentifierPart(code[index])) index++ + return index + } + + private fun isIdentifierStart(char: Char?): Boolean = char != null && (char.isLetter() || char == '_') + + private fun isIdentifierPart(char: Char?): Boolean = char != null && (char.isLetterOrDigit() || char == '_') +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeToken.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeToken.kt new file mode 100644 index 00000000..55a6bf68 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeToken.kt @@ -0,0 +1,24 @@ +package com.mohamedrejeb.richeditor.highlight + +import androidx.compose.runtime.Immutable +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +/** What a piece of code is, for colouring. */ +@ExperimentalRichTextApi +public enum class CodeTokenKind { Keyword, String, Number, Comment, Annotation } + +/** A coloured piece of code: the characters from [start] up to, not including, [end]. */ +@ExperimentalRichTextApi +@Immutable +public class CodeToken( + public val start: Int, + public val end: Int, + public val kind: CodeTokenKind, +) { + override fun equals(other: Any?): Boolean = + this === other || (other is CodeToken && start == other.start && end == other.end && kind == other.kind) + + override fun hashCode(): Int = 31 * (31 * start + end) + kind.hashCode() + + override fun toString(): String = "CodeToken($start, $end, $kind)" +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt new file mode 100644 index 00000000..3a7f88b0 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt @@ -0,0 +1,26 @@ +package com.mohamedrejeb.richeditor.highlight + +internal class BlockComment(val open: String, val close: String, val nests: Boolean = false) + +/** A string literal form. [escape] is null for raw strings. A string that is not [multiline] ends at the line end. */ +internal class StringRule( + val open: String, + val close: String = open, + val escape: Char? = '\\', + val multiline: Boolean = false, +) + +/** + * What the scanner needs to know about a language. [strings] and [blockComments] are tried in + * order, so a longer opener (triple quotes) must come before a shorter one that it starts with. + */ +internal class LanguageSpec( + val keywords: Set, + val lineComments: List = emptyList(), + val blockComments: List = emptyList(), + val strings: List = emptyList(), + val annotationPrefix: Char? = null, + val ignoreKeywordCase: Boolean = false, + /** True where a comment marker only counts at the start or after whitespace (shell, YAML). */ + val commentNeedsLeadingSpace: Boolean = false, +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/KotlinSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/KotlinSpec.kt new file mode 100644 index 00000000..4cb3067e --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/KotlinSpec.kt @@ -0,0 +1,25 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val KotlinSpec = LanguageSpec( + keywords = setOf( + "abstract", "actual", "annotation", "as", "break", "by", "catch", "class", "companion", "const", + "constructor", "continue", "crossinline", "data", "do", "else", "enum", "expect", "external", "false", + "final", "finally", "for", "fun", "get", "if", "import", "in", "infix", "init", "inline", "inner", + "interface", "internal", "is", "lateinit", "noinline", "null", "object", "open", "operator", "out", + "override", "package", "private", "protected", "public", "reified", "return", "sealed", "set", "super", + "suspend", "tailrec", "this", "throw", "true", "try", "typealias", "val", "value", "var", "vararg", + "when", "where", "while", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/", nests = true)), + strings = listOf( + StringRule("\"\"\"", escape = null, multiline = true), + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterTest.kt new file mode 100644 index 00000000..8596cee3 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterTest.kt @@ -0,0 +1,94 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Annotation +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Comment +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Keyword +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Number +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.String +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalRichTextApi::class) +class CodeHighlighterTest { + + @Test + fun `keywords numbers and strings are found`() { + assertEquals( + listOf("val" to Keyword, "42" to Number, "\"hi\"" to String), + tokenTexts("val x = 42 + \"hi\".length", CodeLanguage.Kotlin), + ) + } + + @Test + fun `a keyword inside an identifier is not a keyword`() { + assertEquals(emptyList(), tokenTexts("valid = interval", CodeLanguage.Kotlin)) + } + + @Test + fun `a line comment runs to the end of its line`() { + assertEquals( + listOf("// val x" to Comment, "val" to Keyword), + tokenTexts("// val x\nval y", CodeLanguage.Kotlin), + ) + } + + @Test + fun `a block comment spans lines and nests`() { + assertEquals( + listOf("/* a /* b */ c\n*/" to Comment, "fun" to Keyword), + tokenTexts("/* a /* b */ c\n*/ fun", CodeLanguage.Kotlin), + ) + } + + @Test + fun `an escaped quote does not end a string`() { + assertEquals( + listOf("\"a\\\"b\"" to String), + tokenTexts("\"a\\\"b\"", CodeLanguage.Kotlin), + ) + } + + @Test + fun `a raw string spans lines`() { + val code = "\"\"\"a\nval\"\"\" val" + assertEquals( + listOf("\"\"\"a\nval\"\"\"" to String, "val" to Keyword), + tokenTexts(code, CodeLanguage.Kotlin), + ) + } + + @Test + fun `an unterminated string stops at the end of its line`() { + assertEquals( + listOf("\"abc" to String, "val" to Keyword), + tokenTexts("\"abc\nval", CodeLanguage.Kotlin), + ) + } + + @Test + fun `an unterminated block comment runs to the end`() { + assertEquals(listOf("/* val x" to Comment), tokenTexts("/* val x", CodeLanguage.Kotlin)) + } + + @Test + fun `an annotation is found and a label is not one`() { + assertEquals( + listOf("@Composable" to Annotation, "fun" to Keyword, "return" to Keyword), + tokenTexts("@Composable fun a() { return@forEach }", CodeLanguage.Kotlin), + ) + } + + @Test + fun `hex and decimal numbers are single tokens`() { + assertEquals( + listOf("0xFF" to Number, "1.5f" to Number, "1_000" to Number, "1" to Number, "10" to Number), + tokenTexts("0xFF 1.5f 1_000 1..10", CodeLanguage.Kotlin), + ) + } + + @Test + fun `empty code has no tokens`() { + assertEquals(emptyList(), CodeHighlighter.tokenize("", CodeLanguage.Kotlin)) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightTestUtils.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightTestUtils.kt new file mode 100644 index 00000000..824d3b10 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightTestUtils.kt @@ -0,0 +1,7 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +@OptIn(ExperimentalRichTextApi::class) +internal fun tokenTexts(code: String, language: CodeLanguage): List> = + CodeHighlighter.tokenize(code, language).map { code.substring(it.start, it.end) to it.kind } From 5544b74703dc0e43c1dc7501a059d5fce4206b03 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 19:26:30 +0100 Subject: [PATCH 02/16] feat: tokenize sixteen languages and whole files line by line --- .../richeditor/highlight/CodeHighlighter.kt | 28 +++++ .../richeditor/highlight/CodeLanguage.kt | 55 +++++++++ .../richeditor/highlight/LanguageSpec.kt | 2 + .../highlight/languages/CSharpSpec.kt | 25 ++++ .../richeditor/highlight/languages/CSpec.kt | 20 ++++ .../richeditor/highlight/languages/CppSpec.kt | 25 ++++ .../highlight/languages/DartSpec.kt | 25 ++++ .../richeditor/highlight/languages/GoSpec.kt | 20 ++++ .../highlight/languages/JavaScriptSpec.kt | 21 ++++ .../highlight/languages/JavaSpec.kt | 24 ++++ .../highlight/languages/JsonSpec.kt | 9 ++ .../highlight/languages/PythonSpec.kt | 20 ++++ .../highlight/languages/RustSpec.kt | 19 +++ .../highlight/languages/ShellSpec.kt | 17 +++ .../richeditor/highlight/languages/SqlSpec.kt | 26 ++++ .../highlight/languages/SwiftSpec.kt | 23 ++++ .../highlight/languages/TypeScriptSpec.kt | 25 ++++ .../highlight/languages/YamlSpec.kt | 14 +++ .../highlight/CodeHighlighterFuzzTest.kt | 79 +++++++++++++ .../highlight/CodeHighlighterLinesTest.kt | 50 ++++++++ .../highlight/CodeLanguageLookupTest.kt | 51 ++++++++ .../richeditor/highlight/CodeLanguagesTest.kt | 111 ++++++++++++++++++ 22 files changed, 689 insertions(+) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSharpSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CppSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/DartSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/GoSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaScriptSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JsonSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/PythonSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/RustSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/ShellSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SqlSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SwiftSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/TypeScriptSpec.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/YamlSpec.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterFuzzTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterLinesTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguageLookupTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguagesTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt index 807b09be..4ec7e833 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighter.kt @@ -12,4 +12,32 @@ public object CodeHighlighter { */ public fun tokenize(code: String, language: CodeLanguage): List = CodeScanner.scan(code, language.spec) + + /** + * The tokens of each line, with offsets relative to that line. The lines are read as one + * piece of code, so a comment or string opened on one line is still coloured on the next. + * This is what a view that draws its own rows, such as a diff, needs. Lines that do not + * follow each other in the file (two hunks) are two calls. + */ + public fun tokenizeLines(lines: List, language: CodeLanguage): List> { + if (lines.isEmpty()) return emptyList() + val clean = lines.map { it.removeSuffix("\r") } + val tokens = tokenize(clean.joinToString("\n"), language) + var lineStart = 0 + var next = 0 + return clean.map { line -> + val lineEnd = lineStart + line.length + val lineTokens = ArrayList() + while (next < tokens.size && tokens[next].start < lineEnd) { + val token = tokens[next] + val start = maxOf(token.start, lineStart) + val end = minOf(token.end, lineEnd) + if (start < end) lineTokens += CodeToken(start - lineStart, end - lineStart, token.kind) + if (token.end > lineEnd + 1) break + next++ + } + lineStart = lineEnd + 1 + lineTokens + } + } } diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt index 9301bf18..8e2c213e 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguage.kt @@ -2,7 +2,22 @@ package com.mohamedrejeb.richeditor.highlight import androidx.compose.runtime.Immutable import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.languages.CSharpSpec +import com.mohamedrejeb.richeditor.highlight.languages.CSpec +import com.mohamedrejeb.richeditor.highlight.languages.CppSpec +import com.mohamedrejeb.richeditor.highlight.languages.DartSpec +import com.mohamedrejeb.richeditor.highlight.languages.GoSpec +import com.mohamedrejeb.richeditor.highlight.languages.JavaScriptSpec +import com.mohamedrejeb.richeditor.highlight.languages.JavaSpec +import com.mohamedrejeb.richeditor.highlight.languages.JsonSpec import com.mohamedrejeb.richeditor.highlight.languages.KotlinSpec +import com.mohamedrejeb.richeditor.highlight.languages.PythonSpec +import com.mohamedrejeb.richeditor.highlight.languages.RustSpec +import com.mohamedrejeb.richeditor.highlight.languages.ShellSpec +import com.mohamedrejeb.richeditor.highlight.languages.SqlSpec +import com.mohamedrejeb.richeditor.highlight.languages.SwiftSpec +import com.mohamedrejeb.richeditor.highlight.languages.TypeScriptSpec +import com.mohamedrejeb.richeditor.highlight.languages.YamlSpec /** A language the library can colour. Get one from the companion, by [fromName] or by [fromFileName]. */ @ExperimentalRichTextApi @@ -17,5 +32,45 @@ public class CodeLanguage internal constructor( public companion object { public val Kotlin: CodeLanguage = CodeLanguage("kotlin", listOf("kt", "kts"), listOf("kt", "kts"), KotlinSpec) + public val Java: CodeLanguage = CodeLanguage("java", emptyList(), listOf("java"), JavaSpec) + public val JavaScript: CodeLanguage = + CodeLanguage("javascript", listOf("js", "jsx", "mjs", "cjs", "node"), listOf("js", "jsx", "mjs", "cjs"), JavaScriptSpec) + public val TypeScript: CodeLanguage = CodeLanguage("typescript", listOf("ts", "tsx"), listOf("ts", "tsx"), TypeScriptSpec) + public val Python: CodeLanguage = CodeLanguage("python", listOf("py", "python3"), listOf("py"), PythonSpec) + public val Swift: CodeLanguage = CodeLanguage("swift", emptyList(), listOf("swift"), SwiftSpec) + public val Go: CodeLanguage = CodeLanguage("go", listOf("golang"), listOf("go"), GoSpec) + public val Rust: CodeLanguage = CodeLanguage("rust", listOf("rs"), listOf("rs"), RustSpec) + public val C: CodeLanguage = CodeLanguage("c", listOf("h"), listOf("c", "h"), CSpec) + public val Cpp: CodeLanguage = + CodeLanguage("cpp", listOf("c++", "cc", "cxx", "hpp"), listOf("cpp", "cc", "cxx", "hpp", "hh"), CppSpec) + public val CSharp: CodeLanguage = CodeLanguage("csharp", listOf("cs", "c#"), listOf("cs"), CSharpSpec) + public val Dart: CodeLanguage = CodeLanguage("dart", emptyList(), listOf("dart"), DartSpec) + public val Shell: CodeLanguage = + CodeLanguage("shell", listOf("sh", "bash", "zsh", "shellscript"), listOf("sh", "bash", "zsh"), ShellSpec) + public val Sql: CodeLanguage = CodeLanguage("sql", emptyList(), listOf("sql"), SqlSpec) + public val Json: CodeLanguage = CodeLanguage("json", emptyList(), listOf("json"), JsonSpec) + public val Yaml: CodeLanguage = CodeLanguage("yaml", listOf("yml"), listOf("yaml", "yml"), YamlSpec) + + /** Every language the library can colour. */ + public val all: List = listOf( + Kotlin, Java, JavaScript, TypeScript, Python, Swift, Go, Rust, C, Cpp, CSharp, Dart, Shell, Sql, Json, Yaml, + ) + + private val byName: Map = + all.flatMap { language -> (language.aliases + language.name).map { it to language } }.toMap() + + private val byExtension: Map = + all.flatMap { language -> language.extensions.map { it to language } }.toMap() + + /** + * The language a fenced code block or a `language-x` class names, such as "kotlin", "kt" + * or "js". Case is ignored and only the first word counts. Null when it is not known. + */ + public fun fromName(name: String): CodeLanguage? = + byName[name.trim().substringBefore(' ').lowercase()] + + /** The language of a file, going by the ending of its name or path. Null when it is not known. */ + public fun fromFileName(fileName: String): CodeLanguage? = + byExtension[fileName.substringAfterLast('/').substringAfterLast('.', "").lowercase()] } } diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt index 3a7f88b0..b4eca094 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/LanguageSpec.kt @@ -13,6 +13,8 @@ internal class StringRule( /** * What the scanner needs to know about a language. [strings] and [blockComments] are tried in * order, so a longer opener (triple quotes) must come before a shorter one that it starts with. + * Every opener ([BlockComment.open], [StringRule.open], each line comment marker) must be + * non-empty, because an empty one would never advance the scanner. */ internal class LanguageSpec( val keywords: Set, diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSharpSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSharpSpec.kt new file mode 100644 index 00000000..f27761fb --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSharpSpec.kt @@ -0,0 +1,25 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val CSharpSpec = LanguageSpec( + keywords = setOf( + "abstract", "as", "async", "await", "base", "bool", "break", "byte", "case", "catch", "char", "checked", + "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", + "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "get", "goto", "if", + "implicit", "in", "init", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", + "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "record", + "ref", "return", "sbyte", "sealed", "set", "short", "sizeof", "static", "string", "struct", "switch", + "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "var", + "virtual", "void", "volatile", "while", "yield", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("\"\"\"", escape = null, multiline = true), + StringRule("\""), + StringRule("'"), + ), +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSpec.kt new file mode 100644 index 00000000..77dbee21 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CSpec.kt @@ -0,0 +1,20 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val CSpec = LanguageSpec( + keywords = setOf( + "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", + "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", + "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "NULL", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '#', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CppSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CppSpec.kt new file mode 100644 index 00000000..e5defbc1 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/CppSpec.kt @@ -0,0 +1,25 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val CppSpec = LanguageSpec( + keywords = setOf( + "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", + "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", + "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "NULL", + "alignas", "alignof", "bool", "catch", "class", "concept", "const_cast", "constexpr", "co_await", + "co_return", "co_yield", "decltype", "delete", "dynamic_cast", "explicit", "export", "false", "friend", + "mutable", "namespace", "new", "noexcept", "nullptr", "operator", "override", "private", "protected", + "public", "reinterpret_cast", "requires", "static_cast", "template", "this", "throw", "true", "try", + "typeid", "typename", "using", "virtual", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '#', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/DartSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/DartSpec.kt new file mode 100644 index 00000000..a4f99fef --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/DartSpec.kt @@ -0,0 +1,25 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val DartSpec = LanguageSpec( + keywords = setOf( + "abstract", "as", "assert", "async", "await", "base", "break", "case", "catch", "class", "const", + "continue", "covariant", "default", "deferred", "do", "dynamic", "else", "enum", "export", "extends", + "extension", "external", "factory", "false", "final", "finally", "for", "get", "if", "implements", + "import", "in", "interface", "is", "late", "library", "mixin", "new", "null", "on", "operator", "part", + "required", "rethrow", "return", "sealed", "set", "static", "super", "switch", "this", "throw", "true", + "try", "typedef", "var", "void", "when", "while", "with", "yield", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("\"\"\"", multiline = true), + StringRule("'''", multiline = true), + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/GoSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/GoSpec.kt new file mode 100644 index 00000000..685df330 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/GoSpec.kt @@ -0,0 +1,20 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val GoSpec = LanguageSpec( + keywords = setOf( + "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "false", "for", + "func", "go", "goto", "if", "import", "interface", "iota", "map", "nil", "package", "range", "return", + "select", "struct", "switch", "true", "type", "var", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("`", escape = null, multiline = true), + StringRule("\""), + StringRule("'"), + ), +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaScriptSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaScriptSpec.kt new file mode 100644 index 00000000..92ac85be --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaScriptSpec.kt @@ -0,0 +1,21 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val JavaScriptSpec = LanguageSpec( + keywords = setOf( + "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", + "do", "else", "export", "extends", "false", "finally", "for", "from", "function", "get", "if", "import", + "in", "instanceof", "let", "new", "null", "of", "return", "set", "static", "super", "switch", "this", + "throw", "true", "try", "typeof", "undefined", "var", "void", "while", "with", "yield", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("`", multiline = true), + StringRule("\""), + StringRule("'"), + ), +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaSpec.kt new file mode 100644 index 00000000..470e10f7 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JavaSpec.kt @@ -0,0 +1,24 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val JavaSpec = LanguageSpec( + keywords = setOf( + "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", + "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", + "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", + "private", "protected", "public", "record", "return", "sealed", "short", "static", "strictfp", "super", + "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "var", "void", "volatile", + "while", "yield", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("\"\"\"", multiline = true), + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JsonSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JsonSpec.kt new file mode 100644 index 00000000..36431551 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/JsonSpec.kt @@ -0,0 +1,9 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val JsonSpec = LanguageSpec( + keywords = setOf("true", "false", "null"), + strings = listOf(StringRule("\"")), +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/PythonSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/PythonSpec.kt new file mode 100644 index 00000000..b749b7fa --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/PythonSpec.kt @@ -0,0 +1,20 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val PythonSpec = LanguageSpec( + keywords = setOf( + "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", + "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", + "match", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", + ), + lineComments = listOf("#"), + strings = listOf( + StringRule("\"\"\"", multiline = true), + StringRule("'''", multiline = true), + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/RustSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/RustSpec.kt new file mode 100644 index 00000000..e53c31ed --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/RustSpec.kt @@ -0,0 +1,19 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val RustSpec = LanguageSpec( + keywords = setOf( + "as", "async", "await", "bool", "break", "char", "const", "continue", "crate", "dyn", "else", "enum", + "extern", "f32", "f64", "false", "fn", "for", "i8", "i16", "i32", "i64", "i128", "if", "impl", "in", + "isize", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", + "str", "struct", "super", "trait", "true", "type", "u8", "u16", "u32", "u64", "u128", "unsafe", "use", + "usize", "where", "while", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/", nests = true)), + // A single quote also starts a lifetime, so it is not a string opener. + strings = listOf(StringRule("\"", multiline = true)), +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/ShellSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/ShellSpec.kt new file mode 100644 index 00000000..e2c7d171 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/ShellSpec.kt @@ -0,0 +1,17 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val ShellSpec = LanguageSpec( + keywords = setOf( + "case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in", "local", + "readonly", "return", "select", "then", "until", "while", + ), + lineComments = listOf("#"), + strings = listOf( + StringRule("\"", multiline = true), + StringRule("'", escape = null, multiline = true), + ), + commentNeedsLeadingSpace = true, +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SqlSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SqlSpec.kt new file mode 100644 index 00000000..0c0b3864 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SqlSpec.kt @@ -0,0 +1,26 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +/** SQL's line comment marker, spelled with escapes because the project bans the doubled dash in source text. */ +internal const val SqlLineComment: String = "\u002D\u002D" + +internal val SqlSpec = LanguageSpec( + keywords = setOf( + "add", "all", "alter", "and", "as", "asc", "begin", "between", "by", "case", "check", "column", "commit", + "constraint", "create", "cross", "database", "default", "delete", "desc", "distinct", "drop", "else", + "end", "exists", "false", "foreign", "from", "full", "group", "having", "if", "in", "index", "inner", + "insert", "into", "is", "join", "key", "left", "like", "limit", "not", "null", "offset", "on", "or", + "order", "outer", "primary", "references", "right", "rollback", "select", "set", "table", "then", "true", + "union", "unique", "update", "values", "view", "when", "where", "with", + ), + lineComments = listOf(SqlLineComment), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("'", escape = null), + StringRule("\"", escape = null), + ), + ignoreKeywordCase = true, +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SwiftSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SwiftSpec.kt new file mode 100644 index 00000000..767b0895 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/SwiftSpec.kt @@ -0,0 +1,23 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val SwiftSpec = LanguageSpec( + keywords = setOf( + "actor", "any", "as", "associatedtype", "async", "await", "break", "case", "catch", "class", "continue", + "default", "defer", "deinit", "do", "else", "enum", "extension", "fallthrough", "false", "fileprivate", + "final", "for", "func", "guard", "if", "import", "in", "indirect", "init", "inout", "internal", "is", + "lazy", "let", "mutating", "nil", "nonisolated", "open", "operator", "override", "private", "protocol", + "public", "repeat", "rethrows", "return", "self", "Self", "some", "static", "struct", "subscript", + "super", "switch", "throw", "throws", "true", "try", "typealias", "var", "weak", "where", "while", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/", nests = true)), + strings = listOf( + StringRule("\"\"\"", multiline = true), + StringRule("\""), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/TypeScriptSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/TypeScriptSpec.kt new file mode 100644 index 00000000..a214a3eb --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/TypeScriptSpec.kt @@ -0,0 +1,25 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.BlockComment +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val TypeScriptSpec = LanguageSpec( + keywords = setOf( + "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", + "do", "else", "export", "extends", "false", "finally", "for", "from", "function", "get", "if", "import", + "in", "instanceof", "let", "new", "null", "of", "return", "set", "static", "super", "switch", "this", + "throw", "true", "try", "typeof", "undefined", "var", "void", "while", "with", "yield", + "abstract", "any", "as", "boolean", "declare", "enum", "implements", "interface", "is", "keyof", + "namespace", "never", "number", "object", "private", "protected", "public", "readonly", "string", + "symbol", "type", "unknown", + ), + lineComments = listOf("//"), + blockComments = listOf(BlockComment("/*", "*/")), + strings = listOf( + StringRule("`", multiline = true), + StringRule("\""), + StringRule("'"), + ), + annotationPrefix = '@', +) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/YamlSpec.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/YamlSpec.kt new file mode 100644 index 00000000..51185972 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/languages/YamlSpec.kt @@ -0,0 +1,14 @@ +package com.mohamedrejeb.richeditor.highlight.languages + +import com.mohamedrejeb.richeditor.highlight.LanguageSpec +import com.mohamedrejeb.richeditor.highlight.StringRule + +internal val YamlSpec = LanguageSpec( + keywords = setOf("true", "false", "null", "yes", "no", "on", "off"), + lineComments = listOf("#"), + strings = listOf( + StringRule("\""), + StringRule("'"), + ), + commentNeedsLeadingSpace = true, +) diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterFuzzTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterFuzzTest.kt new file mode 100644 index 00000000..20bd073c --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterFuzzTest.kt @@ -0,0 +1,79 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Oracles: tokenizing never throws, tokens are in bounds, non-empty, sorted and never overlap, + * and the per-line tokens are the whole-text tokens cut at line ends. Covers every language. + */ +@OptIn(ExperimentalRichTextApi::class) +class CodeHighlighterFuzzTest { + + private val alphabet = "ab_1 \n\t\"'`/*#@\\.-{}<>\$val fun if 0x".toList() + + private fun randomCode(random: Random): String = + buildString { repeat(random.nextInt(0, 200)) { append(alphabet[random.nextInt(alphabet.size)]) } } + + private fun assertWellFormed(code: String, tokens: List) { + var previousEnd = 0 + tokens.forEach { token -> + assertTrue(token.start >= previousEnd, "overlap or disorder at $token in <$code>") + assertTrue(token.start < token.end, "empty token $token in <$code>") + assertTrue(token.end <= code.length, "out of bounds $token in <$code>") + previousEnd = token.end + } + } + + @Test + fun `random code gives well formed tokens in every language`() { + val random = Random(20261008) + repeat(2_000) { + val code = randomCode(random) + CodeLanguage.all.forEach { language -> + assertWellFormed(code, CodeHighlighter.tokenize(code, language)) + } + } + } + + @Test + fun `line tokens are the whole text tokens cut at line ends`() { + val random = Random(8102026) + repeat(1_000) { + val code = randomCode(random) + val lines = code.split('\n') + CodeLanguage.all.forEach { language -> + val whole = CodeHighlighter.tokenize(code, language) + var lineStart = 0 + val rebuilt = CodeHighlighter.tokenizeLines(lines, language).flatMapIndexed { index, lineTokens -> + val start = lineStart + lineStart += lines[index].length + 1 + lineTokens.map { Triple(it.start + start, it.end + start, it.kind) } + } + val expected = whole.flatMap { token -> + var start = 0 + lines.mapNotNull { line -> + val from = maxOf(token.start, start) + val to = minOf(token.end, start + line.length) + start += line.length + 1 + if (from < to) Triple(from, to, token.kind) else null + } + } + assertEquals(expected, rebuilt, "language ${language.name} code <$code>") + } + } + } + + @Test + fun `huge unterminated and nested input finishes`() { + val nested = "/*".repeat(100_000) + val unterminated = "\"" + "a\\".repeat(100_000) + CodeLanguage.all.forEach { language -> + assertWellFormed(nested, CodeHighlighter.tokenize(nested, language)) + assertWellFormed(unterminated, CodeHighlighter.tokenize(unterminated, language)) + } + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterLinesTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterLinesTest.kt new file mode 100644 index 00000000..0fecd7a4 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeHighlighterLinesTest.kt @@ -0,0 +1,50 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Comment +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Keyword +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalRichTextApi::class) +class CodeHighlighterLinesTest { + + @Test + fun `offsets are relative to each line`() { + val lines = CodeHighlighter.tokenizeLines(listOf("val a", " val b"), CodeLanguage.Kotlin) + assertEquals( + listOf(listOf(CodeToken(0, 3, Keyword)), listOf(CodeToken(2, 5, Keyword))), + lines, + ) + } + + @Test + fun `a comment opened on one line colours the next lines`() { + val lines = CodeHighlighter.tokenizeLines(listOf("a /* b", "val c", "d */ val"), CodeLanguage.Kotlin) + assertEquals( + listOf( + listOf(CodeToken(2, 6, Comment)), + listOf(CodeToken(0, 5, Comment)), + listOf(CodeToken(0, 4, Comment), CodeToken(5, 8, Keyword)), + ), + lines, + ) + } + + @Test + fun `an empty line inside a comment has no token`() { + val lines = CodeHighlighter.tokenizeLines(listOf("/*", "", "*/"), CodeLanguage.Kotlin) + assertEquals(listOf(listOf(CodeToken(0, 2, Comment)), emptyList(), listOf(CodeToken(0, 2, Comment))), lines) + } + + @Test + fun `a carriage return at a line end is not part of a token`() { + val lines = CodeHighlighter.tokenizeLines(listOf("// a\r", "val\r"), CodeLanguage.Kotlin) + assertEquals(listOf(listOf(CodeToken(0, 4, Comment)), listOf(CodeToken(0, 3, Keyword))), lines) + } + + @Test + fun `no lines give no lines`() { + assertEquals(emptyList(), CodeHighlighter.tokenizeLines(emptyList(), CodeLanguage.Kotlin)) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguageLookupTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguageLookupTest.kt new file mode 100644 index 00000000..e226adc2 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguageLookupTest.kt @@ -0,0 +1,51 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +@OptIn(ExperimentalRichTextApi::class) +class CodeLanguageLookupTest { + + @Test + fun `names and aliases resolve without regard to case`() { + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromName("kotlin")) + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromName("Kotlin")) + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromName("kt")) + assertSame(CodeLanguage.JavaScript, CodeLanguage.fromName("js")) + assertSame(CodeLanguage.Shell, CodeLanguage.fromName("bash")) + assertSame(CodeLanguage.Cpp, CodeLanguage.fromName("c++")) + assertSame(CodeLanguage.CSharp, CodeLanguage.fromName("c#")) + assertSame(CodeLanguage.Yaml, CodeLanguage.fromName("yml")) + } + + @Test + fun `only the first word of a tag is the language`() { + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromName(" kotlin title=\"x\"")) + } + + @Test + fun `unknown and empty names are null`() { + assertNull(CodeLanguage.fromName("")) + assertNull(CodeLanguage.fromName(" ")) + assertNull(CodeLanguage.fromName("brainfuck")) + } + + @Test + fun `file names resolve by their ending`() { + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromFileName("src/main/Foo.kt")) + assertSame(CodeLanguage.Kotlin, CodeLanguage.fromFileName("build.gradle.kts")) + assertSame(CodeLanguage.TypeScript, CodeLanguage.fromFileName("App.TSX")) + assertSame(CodeLanguage.C, CodeLanguage.fromFileName("a.h")) + assertNull(CodeLanguage.fromFileName("Makefile")) + assertNull(CodeLanguage.fromFileName("dir.kt/readme")) + } + + @Test + fun `every language has a unique name`() { + assertEquals(16, CodeLanguage.all.size) + assertEquals(16, CodeLanguage.all.map { it.name }.toSet().size) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguagesTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguagesTest.kt new file mode 100644 index 00000000..e54b50c0 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/CodeLanguagesTest.kt @@ -0,0 +1,111 @@ +package com.mohamedrejeb.richeditor.highlight + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Annotation +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Comment +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Keyword +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.Number +import com.mohamedrejeb.richeditor.highlight.CodeTokenKind.String +import com.mohamedrejeb.richeditor.highlight.languages.SqlLineComment +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalRichTextApi::class) +class CodeLanguagesTest { + + @Test + fun java() = assertEquals( + listOf("@Override" to Annotation, "public" to Keyword, "int" to Keyword, "return" to Keyword, "1" to Number, "// x" to Comment), + tokenTexts("@Override public int a() { return 1; } // x", CodeLanguage.Java), + ) + + @Test + fun javascript() = assertEquals( + listOf("const" to Keyword, "`x\ny`" to String, "'z'" to String, "/* c */" to Comment), + tokenTexts("const a = `x\ny` + 'z' /* c */", CodeLanguage.JavaScript), + ) + + @Test + fun typescript() = assertEquals( + listOf("interface" to Keyword, "readonly" to Keyword, "string" to Keyword), + tokenTexts("interface A { readonly b: string }", CodeLanguage.TypeScript), + ) + + @Test + fun python() = assertEquals( + listOf("@cache" to Annotation, "def" to Keyword, "\"\"\"doc\nmore\"\"\"" to String, "return" to Keyword, "None" to Keyword, "# c" to Comment), + tokenTexts("@cache\ndef a():\n \"\"\"doc\nmore\"\"\"\n return None # c", CodeLanguage.Python), + ) + + @Test + fun swift() = assertEquals( + listOf("@MainActor" to Annotation, "func" to Keyword, "let" to Keyword, "/* a /* b */ */" to Comment), + tokenTexts("@MainActor func a() { let b = c } /* a /* b */ */", CodeLanguage.Swift), + ) + + @Test + fun go() = assertEquals( + listOf("func" to Keyword, "`raw\\`" to String, "nil" to Keyword), + tokenTexts("func a() { b := `raw\\`; _ = nil }", CodeLanguage.Go), + ) + + @Test + fun `rust lifetimes are not strings`() = assertEquals( + listOf("fn" to Keyword, "str" to Keyword, "\"s\"" to String), + tokenTexts("fn a<'a>(b: &'a str) { \"s\" }", CodeLanguage.Rust), + ) + + @Test + fun c() = assertEquals( + listOf("#include" to Annotation, "int" to Keyword, "return" to Keyword, "0" to Number), + tokenTexts("#include \nint main() { return 0; }", CodeLanguage.C), + ) + + @Test + fun cpp() = assertEquals( + listOf("class" to Keyword, "public" to Keyword, "virtual" to Keyword, "void" to Keyword, "nullptr" to Keyword), + tokenTexts("class A { public: virtual void b() { c = nullptr; } }", CodeLanguage.Cpp), + ) + + @Test + fun csharp() = assertEquals( + listOf("namespace" to Keyword, "var" to Keyword, "await" to Keyword), + tokenTexts("namespace A { var b = await c; }", CodeLanguage.CSharp), + ) + + @Test + fun dart() = assertEquals( + listOf("@override" to Annotation, "final" to Keyword, "'''a\nb'''" to String), + tokenTexts("@override final a = '''a\nb'''", CodeLanguage.Dart), + ) + + @Test + fun `shell comments need a leading space`() = assertEquals( + listOf("if" to Keyword, "\"\$x\"" to String, "then" to Keyword, "fi" to Keyword, "# done" to Comment), + tokenTexts("if [ \$# = \"\$x\" ]; then a; fi # done", CodeLanguage.Shell), + ) + + @Test + fun `sql keywords ignore case`() = assertEquals( + listOf("select" to Keyword, "FROM" to Keyword, "Where" to Keyword, "'x'" to String, "${SqlLineComment} note" to Comment), + tokenTexts("select a FROM b Where c = 'x' ${SqlLineComment} note", CodeLanguage.Sql), + ) + + @Test + fun json() = assertEquals( + listOf("\"a\"" to String, "1.5" to Number, "\"b\"" to String, "true" to Keyword, "null" to Keyword), + tokenTexts("{\"a\": 1.5, \"b\": [true, null]}", CodeLanguage.Json), + ) + + @Test + fun yaml() = assertEquals( + listOf("\"b#c\"" to String, "# note" to Comment, "true" to Keyword), + tokenTexts("a: \"b#c\" # note\nd: true", CodeLanguage.Yaml), + ) + + @Test + fun `yaml comments need a leading space`() = assertEquals( + listOf("# note" to Comment, "true" to Keyword), + tokenTexts("a: b#c # note\nd: true", CodeLanguage.Yaml), + ) +} From 1901d88ffd42c46eb1eb6e6ecc76f25b60b71e79 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 19:35:29 +0100 Subject: [PATCH 03/16] feat: turn code into a coloured AnnotatedString --- .../richeditor/highlight/CodeBlockColors.kt | 46 +++++++++++++++++ .../richeditor/highlight/HighlightCode.kt | 20 ++++++++ .../richeditor/highlight/HighlightCodeTest.kt | 51 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeBlockColors.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCode.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCodeTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeBlockColors.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeBlockColors.kt new file mode 100644 index 00000000..d9e0fdae --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/CodeBlockColors.kt @@ -0,0 +1,46 @@ +package com.mohamedrejeb.richeditor.highlight + +import androidx.compose.runtime.Immutable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.font.FontStyle +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +/** The style of each kind of token. A style, not just a colour, so a comment can be italic. */ +@ExperimentalRichTextApi +@Immutable +public class CodeBlockColors( + public val keyword: SpanStyle, + public val string: SpanStyle, + public val number: SpanStyle, + public val comment: SpanStyle, + public val annotation: SpanStyle, +) { + public fun styleOf(kind: CodeTokenKind): SpanStyle = when (kind) { + CodeTokenKind.Keyword -> keyword + CodeTokenKind.String -> string + CodeTokenKind.Number -> number + CodeTokenKind.Comment -> comment + CodeTokenKind.Annotation -> annotation + } + + override fun equals(other: Any?): Boolean = + this === other || ( + other is CodeBlockColors && keyword == other.keyword && string == other.string && + number == other.number && comment == other.comment && annotation == other.annotation + ) + + override fun hashCode(): Int = + listOf(keyword, string, number, comment, annotation).fold(0) { hash, style -> 31 * hash + style.hashCode() } + + public companion object { + /** Mid-tone colours that stay readable on both light and dark backgrounds. */ + public val Default: CodeBlockColors = CodeBlockColors( + keyword = SpanStyle(color = Color(0xFFC2619D)), + string = SpanStyle(color = Color(0xFF4E9A51)), + number = SpanStyle(color = Color(0xFFC77B2B)), + comment = SpanStyle(color = Color(0xFF8A8F98), fontStyle = FontStyle.Italic), + annotation = SpanStyle(color = Color(0xFFA9882F)), + ) + } +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCode.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCode.kt new file mode 100644 index 00000000..649f5597 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCode.kt @@ -0,0 +1,20 @@ +package com.mohamedrejeb.richeditor.highlight + +import androidx.compose.ui.text.AnnotatedString +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi + +/** + * [code] with the style of each token applied, for a `Text` of your own. A null [language] + * returns the code unstyled. For a ready composable see `BasicCodeText`. + */ +@ExperimentalRichTextApi +public fun highlightCode( + code: String, + language: CodeLanguage?, + colors: CodeBlockColors = CodeBlockColors.Default, +): AnnotatedString { + if (language == null) return AnnotatedString(code) + return AnnotatedString.Builder(code).apply { + CodeHighlighter.tokenize(code, language).forEach { addStyle(colors.styleOf(it.kind), it.start, it.end) } + }.toAnnotatedString() +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCodeTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCodeTest.kt new file mode 100644 index 00000000..3bd941db --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/highlight/HighlightCodeTest.kt @@ -0,0 +1,51 @@ +package com.mohamedrejeb.richeditor.highlight + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.font.FontStyle +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalRichTextApi::class) +class HighlightCodeTest { + + private val colors = CodeBlockColors( + keyword = SpanStyle(color = Color.Red), + string = SpanStyle(color = Color.Green), + number = SpanStyle(color = Color.Blue), + comment = SpanStyle(color = Color.Gray, fontStyle = FontStyle.Italic), + annotation = SpanStyle(color = Color.Yellow), + ) + + @Test + fun `each token gets the style of its kind`() { + val text = highlightCode("val a = 1 // c", CodeLanguage.Kotlin, colors) + assertEquals("val a = 1 // c", text.text) + assertEquals( + listOf( + AnnotatedString.Range(colors.keyword, 0, 3), + AnnotatedString.Range(colors.number, 8, 9), + AnnotatedString.Range(colors.comment, 10, 14), + ), + text.spanStyles, + ) + } + + @Test + fun `no language gives the code unstyled`() { + val text = highlightCode("val a = 1", null, colors) + assertEquals("val a = 1", text.text) + assertEquals(emptyList(), text.spanStyles) + } + + @Test + fun `styleOf returns the style of each kind`() { + assertEquals(colors.keyword, colors.styleOf(CodeTokenKind.Keyword)) + assertEquals(colors.string, colors.styleOf(CodeTokenKind.String)) + assertEquals(colors.number, colors.styleOf(CodeTokenKind.Number)) + assertEquals(colors.comment, colors.styleOf(CodeTokenKind.Comment)) + assertEquals(colors.annotation, colors.styleOf(CodeTokenKind.Annotation)) + } +} From 41ad4ec967c952193afa03325c276809d5f3da30 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 19:36:39 +0100 Subject: [PATCH 04/16] feat: add BasicCodeText for showing code alone --- .../richeditor/ui/BasicCodeText.kt | 43 ++++++++++++ .../richeditor/ui/BasicCodeTextTest.kt | 68 +++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeText.kt create mode 100644 richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeText.kt new file mode 100644 index 00000000..18de6935 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeText.kt @@ -0,0 +1,43 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import com.mohamedrejeb.richeditor.highlight.CodeLanguage +import com.mohamedrejeb.richeditor.highlight.highlightCode + +/** + * Read-only code, coloured by [language]. It draws the text and nothing else: give it a + * background, padding and shape through [modifier]. + * + * @param language the language to colour by, or null to draw the code plain. + * @param softWrap when false, a long line scrolls sideways instead of wrapping. + */ +@ExperimentalRichTextApi +@Composable +public fun BasicCodeText( + code: String, + language: CodeLanguage?, + modifier: Modifier = Modifier, + style: TextStyle = TextStyle(fontFamily = FontFamily.Monospace), + colors: CodeBlockColors = CodeBlockColors.Default, + softWrap: Boolean = false, + onTextLayout: (TextLayoutResult) -> Unit = {}, +) { + val text = remember(code, language, colors) { highlightCode(code, language, colors) } + BasicText( + text = text, + modifier = if (softWrap) modifier else modifier.horizontalScroll(rememberScrollState()), + style = style, + softWrap = softWrap, + onTextLayout = onTextLayout, + ) +} diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt new file mode 100644 index 00000000..945ea93c --- /dev/null +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt @@ -0,0 +1,68 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.unit.dp +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import com.mohamedrejeb.richeditor.highlight.CodeLanguage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalTestApi::class, ExperimentalRichTextApi::class) +class BasicCodeTextTest { + + private val longLine = "val a = " + "\"word \" + ".repeat(40) + "1" + + @Test + fun `the code is laid out with its token styles`() = runDesktopComposeUiTest { + var layout: TextLayoutResult? = null + setContent { + BasicCodeText(code = "val a = 1", language = CodeLanguage.Kotlin, onTextLayout = { layout = it }) + } + waitForIdle() + + val text = assertNotNull(layout).layoutInput.text + assertEquals("val a = 1", text.text) + assertEquals( + listOf( + AnnotatedString.Range(CodeBlockColors.Default.keyword, 0, 3), + AnnotatedString.Range(CodeBlockColors.Default.number, 8, 9), + ), + text.spanStyles, + ) + } + + @Test + fun `a long line stays on one line by default`() = runDesktopComposeUiTest { + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(120.dp)) { + BasicCodeText(code = longLine, language = CodeLanguage.Kotlin, onTextLayout = { layout = it }) + } + } + waitForIdle() + + assertEquals(1, assertNotNull(layout).lineCount) + } + + @Test + fun `a long line wraps when softWrap is on`() = runDesktopComposeUiTest { + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(120.dp)) { + BasicCodeText(code = longLine, language = CodeLanguage.Kotlin, softWrap = true, onTextLayout = { layout = it }) + } + } + waitForIdle() + + assertTrue(assertNotNull(layout).lineCount > 1) + } +} From 3c3335b4b930fbaf75b60367eed61cd787eb6c21 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 19:44:05 +0100 Subject: [PATCH 05/16] feat: add a code block paragraph type --- .../richeditor/model/RichTextConfig.kt | 29 ++++++++ .../richeditor/model/RichTextState.kt | 5 +- .../richeditor/paragraph/CodeBlocks.kt | 50 +++++++++++++ .../richeditor/paragraph/type/CodeBlock.kt | 43 +++++++++++ .../paragraph/CodeBlockParagraphTest.kt | 73 +++++++++++++++++++ 5 files changed, 198 insertions(+), 2 deletions(-) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/type/CodeBlock.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlockParagraphTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextConfig.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextConfig.kt index a6486fd9..97355acb 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextConfig.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextConfig.kt @@ -2,10 +2,12 @@ package com.mohamedrejeb.richeditor.model import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors import com.mohamedrejeb.richeditor.paragraph.type.ListMarkerStyleBehavior import com.mohamedrejeb.richeditor.paragraph.type.ListPrefixAlignment import com.mohamedrejeb.richeditor.paragraph.type.OrderedListStyleType @@ -70,6 +72,33 @@ public class RichTextConfig internal constructor( updateText() } + /** The background drawn behind a code block. */ + @ExperimentalRichTextApi + public var codeBlockBackgroundColor: Color = Color(0x1F808080) + set(value) { + if (field == value) return + field = value + updateText() + } + + /** The font of the text in a code block. */ + @ExperimentalRichTextApi + public var codeBlockFontFamily: FontFamily = FontFamily.Monospace + set(value) { + if (field == value) return + field = value + updateText() + } + + /** The style of each kind of token in a code block. */ + @ExperimentalRichTextApi + public var codeBlockColors: CodeBlockColors = CodeBlockColors.Default + set(value) { + if (field == value) return + field = value + updateText() + } + /** * The indent for ordered lists. */ 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 1dd2d970..7b5a6564 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 @@ -46,6 +46,7 @@ import com.mohamedrejeb.richeditor.model.trigger.Trigger import com.mohamedrejeb.richeditor.model.trigger.TriggerQuery import com.mohamedrejeb.richeditor.model.trigger.detectActiveTrigger import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.baseSpanStyle import com.mohamedrejeb.richeditor.paragraph.type.* import com.mohamedrejeb.richeditor.platform.currentPlatform import com.mohamedrejeb.richeditor.paragraph.type.ParagraphType.Companion.startText @@ -3578,7 +3579,7 @@ public class RichTextState internal constructor( richParagraph.type.startRichSpan.textRange = TextRange(index, index + richParagraphStartTextLength) index += richParagraphStartTextLength - withStyle(RichSpanStyle.DefaultSpanStyle) { + withStyle(richParagraph.baseSpanStyle(config)) { index = append( state = this@RichTextState, richSpanList = richParagraph.children, @@ -6280,7 +6281,7 @@ public class RichTextState internal constructor( richParagraph.type.startRichSpan.textRange = TextRange(index, index + richParagraphStartTextLength) index += richParagraphStartTextLength - withStyle(RichSpanStyle.DefaultSpanStyle) { + withStyle(richParagraph.baseSpanStyle(config)) { index = append( state = this@RichTextState, richSpanList = richParagraph.children, diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt new file mode 100644 index 00000000..613b864a --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt @@ -0,0 +1,50 @@ +package com.mohamedrejeb.richeditor.paragraph + +import androidx.compose.ui.text.SpanStyle +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichSpan +import com.mohamedrejeb.richeditor.model.RichSpanStyle +import com.mohamedrejeb.richeditor.model.RichTextConfig +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock + +/** The paragraph index range of each code block: a run of code lines, cut where a line starts a new block. */ +internal fun List.codeBlockGroups(): List { + val groups = mutableListOf() + var start = -1 + forEachIndexed { index, paragraph -> + val type = paragraph.type as? CodeBlock + if (start != -1 && (type == null || type.isBlockStart)) { + groups += start until index + start = -1 + } + if (type != null && start == -1) start = index + } + if (start != -1) groups += start..lastIndex + return groups +} + +/** The text of this paragraph without its list prefix and without any styling. */ +@OptIn(ExperimentalRichTextApi::class) +internal fun RichParagraph.plainText(): String = + buildString { children.forEach { appendPlainText(it) } } + +@OptIn(ExperimentalRichTextApi::class) +private fun StringBuilder.appendPlainText(span: RichSpan) { + append(span.text) + span.children.forEach { appendPlainText(it) } +} + +/** The paragraphs of a code block holding [lines]. A block always has at least one line. */ +@OptIn(ExperimentalRichTextApi::class) +internal fun codeBlockOf(language: String?, lines: List): List = + lines.ifEmpty { listOf("") }.mapIndexed { index, line -> + RichParagraph(type = CodeBlock(language = language, isBlockStart = index == 0)).also { paragraph -> + paragraph.children.add(RichSpan(paragraph = paragraph, text = line)) + } + } + +/** The style every character of this paragraph starts from. */ +@OptIn(ExperimentalRichTextApi::class) +internal fun RichParagraph.baseSpanStyle(config: RichTextConfig): SpanStyle = + if (type is CodeBlock) RichSpanStyle.DefaultSpanStyle.merge(SpanStyle(fontFamily = config.codeBlockFontFamily)) + else RichSpanStyle.DefaultSpanStyle diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/type/CodeBlock.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/type/CodeBlock.kt new file mode 100644 index 00000000..5a85f5c2 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/type/CodeBlock.kt @@ -0,0 +1,43 @@ +package com.mohamedrejeb.richeditor.paragraph.type + +import androidx.compose.ui.text.ParagraphStyle +import androidx.compose.ui.text.style.TextIndent +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.sp +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichSpan +import com.mohamedrejeb.richeditor.model.RichTextConfig +import com.mohamedrejeb.richeditor.paragraph.RichParagraph + +/** + * One line of a code block. Consecutive code lines form one block; [isBlockStart] is set on + * the first line so that two blocks next to each other stay two blocks. [language] is kept as + * it was written, so a language the library cannot colour still round-trips. + */ +internal class CodeBlock( + val language: String? = null, + val isBlockStart: Boolean = true, +) : ParagraphType { + + override fun getStyle(config: RichTextConfig): ParagraphStyle = Style + + @OptIn(ExperimentalRichTextApi::class) + override val startRichSpan: RichSpan = + RichSpan(paragraph = RichParagraph(type = this)) + + override fun getNextParagraphType(): ParagraphType = + CodeBlock(language = language, isBlockStart = false) + + override fun copy(): ParagraphType = + CodeBlock(language = language, isBlockStart = isBlockStart) + + override fun equals(other: Any?): Boolean = + this === other || (other is CodeBlock && language == other.language && isBlockStart == other.isBlockStart) + + override fun hashCode(): Int = 31 * language.hashCode() + isBlockStart.hashCode() + + companion object { + val Inset: TextUnit = 12.sp + private val Style = ParagraphStyle(textIndent = TextIndent(firstLine = Inset, restLine = Inset)) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlockParagraphTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlockParagraphTest.kt new file mode 100644 index 00000000..9be9c18a --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlockParagraphTest.kt @@ -0,0 +1,73 @@ +package com.mohamedrejeb.richeditor.paragraph + +import androidx.compose.ui.text.font.FontFamily +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichSpan +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.model.history.deepCopy +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockParagraphTest { + + private fun text(value: String) = RichParagraph().also { it.children.add(RichSpan(paragraph = it, text = value)) } + + @Test + fun `codeBlockOf makes one paragraph per line and marks the first`() { + val block = codeBlockOf("kotlin", listOf("val a", "", " val b")) + assertEquals(listOf("val a", "", " val b"), block.map { it.plainText() }) + assertEquals(listOf(true, false, false), block.map { (it.type as CodeBlock).isBlockStart }) + assertTrue(block.all { (it.type as CodeBlock).language == "kotlin" }) + } + + @Test + fun `codeBlockOf with no lines makes one empty line`() { + assertEquals(listOf(""), codeBlockOf(null, emptyList()).map { it.plainText() }) + } + + @Test + fun `adjacent blocks are separate groups`() { + val paragraphs = listOf(text("a")) + codeBlockOf("kotlin", listOf("b", "c")) + codeBlockOf(null, listOf("d")) + listOf(text("e")) + assertEquals(listOf(1..2, 3..3), paragraphs.codeBlockGroups()) + } + + @Test + fun `lines without a start line still form a group`() { + val orphan = codeBlockOf("kotlin", listOf("a", "b", "c")).drop(1) + assertEquals(listOf(0..1), orphan.codeBlockGroups()) + } + + @Test + fun `the next paragraph type continues the block`() { + val next = CodeBlock("kotlin", isBlockStart = true).getNextParagraphType() as CodeBlock + assertEquals("kotlin", next.language) + assertFalse(next.isBlockStart) + } + + @Test + fun `a deep copy keeps the language and the start mark`() { + val copy = codeBlockOf("kotlin", listOf("a")).first().deepCopy() + val type = copy.type as CodeBlock + assertEquals("kotlin", type.language) + assertTrue(type.isBlockStart) + assertEquals("a", copy.plainText()) + } + + @Test + fun `code lines are rendered in the code block font and other text is not`() { + val state = RichTextState(initialRichParagraphList = listOf(text("p")) + codeBlockOf(null, listOf("code"))) + state.config.codeBlockFontFamily = FontFamily.Cursive + val text = state.annotatedString + assertEquals("p code", text.text) + val fontAt = { offset: Int -> + text.spanStyles.lastOrNull { it.start <= offset && offset < it.end && it.item.fontFamily != null }?.item?.fontFamily + } + assertNull(fontAt(0)) + assertEquals(FontFamily.Cursive, fontAt(2)) + } +} From abb70df576921af64b3de457920c33e29c2f6db1 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:00:25 +0100 Subject: [PATCH 06/16] feat: import and export fenced code blocks in Markdown --- .../parser/markdown/MarkdownFences.kt | 66 ++++++++++++ .../parser/markdown/MarkdownUtils.kt | 41 +++++++ .../markdown/RichTextStateMarkdownParser.kt | 59 ++++++++-- .../parser/markdown/CodeBlockMarkdownTest.kt | 102 ++++++++++++++++++ .../parser/markdown/MarkdownFencesTest.kt | 35 ++++++ 5 files changed, 294 insertions(+), 9 deletions(-) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFences.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFencesTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFences.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFences.kt new file mode 100644 index 00000000..29d55b7f --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFences.kt @@ -0,0 +1,66 @@ +package com.mohamedrejeb.richeditor.parser.markdown + +private const val MinFenceLength = 3 +private const val MaxFenceIndent = 3 + +/** The fence a line opens: its marker character and length, or null when the line is not a fence. */ +private fun fenceOf(line: String): Pair? { + val indent = line.length - line.trimStart(' ').length + if (indent > MaxFenceIndent) return null + val marker = line.getOrNull(indent) ?: return null + if (marker != '`' && marker != '~') return null + val length = line.drop(indent).takeWhile { it == marker }.length + if (length < MinFenceLength) return null + // A backtick fence cannot have a backtick in its info string: that is inline code. + if (marker == '`' && '`' in line.drop(indent + length)) return null + return marker to length +} + +/** + * [correctMarkdownText] applied to everything outside fenced code blocks. Code is left exactly + * as written, because the correction moves spaces and indentation. + */ +internal fun correctMarkdownOutsideFences(text: String): String { + val segments = mutableListOf() + val pending = mutableListOf() + var open: Pair? = null + + fun flush(isCode: Boolean) { + if (pending.isEmpty()) return + val joined = pending.joinToString("\n") + segments += if (isCode) joined else correctMarkdownText(joined) + pending.clear() + } + + text.split('\n').forEach { line -> + val fence = fenceOf(line) + val opened = open + when { + opened == null && fence != null -> { + flush(isCode = false) + pending += line + open = fence + } + opened != null && fence != null && fence.first == opened.first && fence.second >= opened.second && + line.trim().all { it == opened.first } -> { + pending += line + flush(isCode = true) + open = null + } + else -> pending += line + } + } + flush(isCode = open != null) + return segments.joinToString("\n") +} + +/** A backtick fence long enough to hold [code]: longer than any run of backticks inside it. */ +internal fun fenceFor(code: String): String { + var longest = 0 + var run = 0 + code.forEach { char -> + run = if (char == '`') run + 1 else 0 + if (run > longest) longest = run + } + return "`".repeat(maxOf(MinFenceLength, longest + 1)) +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownUtils.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownUtils.kt index 4b7dd544..1be3868f 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownUtils.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownUtils.kt @@ -18,6 +18,7 @@ internal fun encodeMarkdownToRichText( onText: (text: String) -> Unit, onHtmlTag: (tag: String) -> Unit, onHtmlBlock: (html: String) -> Unit, + onCodeBlock: (language: String?, lines: List) -> Unit, ) { val parser = MarkdownParser(GFMFlavourDescriptor()) @@ -31,6 +32,7 @@ internal fun encodeMarkdownToRichText( onText = onText, onHtmlTag = onHtmlTag, onHtmlBlock = onHtmlBlock, + onCodeBlock = onCodeBlock, ) } } @@ -218,6 +220,7 @@ private fun encodeMarkdownNodeToRichText( onText: (text: String) -> Unit, onHtmlTag: (tag: String) -> Unit, onHtmlBlock: (html: String) -> Unit, + onCodeBlock: (language: String?, lines: List) -> Unit, ) { when (node.type) { MarkdownTokenTypes.TEXT -> onText(node.getTextInNode(markdown).toString()) @@ -250,6 +253,7 @@ private fun encodeMarkdownNodeToRichText( onText = onText, onHtmlTag = onHtmlTag, onHtmlBlock = onHtmlBlock, + onCodeBlock = onCodeBlock, ) } onCloseNode(node) @@ -269,6 +273,7 @@ private fun encodeMarkdownNodeToRichText( onText = onText, onHtmlTag = onHtmlTag, onHtmlBlock = onHtmlBlock, + onCodeBlock = onCodeBlock, ) } onCloseNode(node) @@ -300,6 +305,7 @@ private fun encodeMarkdownNodeToRichText( onText = onText, onHtmlTag = onHtmlTag, onHtmlBlock = onHtmlBlock, + onCodeBlock = onCodeBlock, ) } } @@ -314,6 +320,12 @@ private fun encodeMarkdownNodeToRichText( onHtmlBlock(node.getTextInNode(markdown).toString()) } + MarkdownElementTypes.CODE_FENCE -> { + val language = node.findChildOfType(MarkdownTokenTypes.FENCE_LANG) + ?.getTextInNode(markdown)?.toString()?.trim()?.ifEmpty { null } + onCodeBlock(language, codeFenceLines(node, markdown)) + } + else -> { onOpenNode(node) node.children.fastForEach { child -> @@ -325,9 +337,38 @@ private fun encodeMarkdownNodeToRichText( onText = onText, onHtmlTag = onHtmlTag, onHtmlBlock = onHtmlBlock, + onCodeBlock = onCodeBlock, ) } onCloseNode(node) } } +} + +/** + * The lines of a fenced block. Each line of code is one CODE_FENCE_CONTENT token and each line + * end is one EOL token, so two EOL tokens in a row are an empty line. + */ +private fun codeFenceLines(node: ASTNode, markdown: String): List { + val lines = mutableListOf() + var current: StringBuilder? = null + var started = false + var ended = false + node.children.fastForEach { child -> + if (ended) return@fastForEach + when (child.type) { + MarkdownTokenTypes.CODE_FENCE_END -> ended = true + MarkdownTokenTypes.EOL -> { + if (started) current?.let { lines += it.toString() } + started = true + current = StringBuilder() + } + MarkdownTokenTypes.CODE_FENCE_CONTENT -> + if (started) current?.append(child.getTextInNode(markdown)) + } + } + // The line that was open when the block ended: the closing fence's own line for a closed + // block (empty, dropped), or the last line of code for an unclosed one. + current?.toString()?.takeIf { it.isNotEmpty() }?.let { lines += it } + return lines } \ No newline at end of file diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt index 896aba65..93bb08ba 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt @@ -13,6 +13,10 @@ import com.mohamedrejeb.richeditor.model.RichSpanStyle import com.mohamedrejeb.richeditor.model.RichSpanStyleRegistry import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.codeBlockOf +import com.mohamedrejeb.richeditor.paragraph.plainText +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock import com.mohamedrejeb.richeditor.paragraph.type.ConfigurableListLevel import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph import com.mohamedrejeb.richeditor.paragraph.type.OrderedList @@ -50,6 +54,7 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { val openedNodes = mutableListOf() val openedHtmlTags = mutableListOf() val richParagraphList = mutableListOf(RichParagraph()) + val paragraphsAfterCodeBlocks = mutableListOf() var brParagraphIndices = mutableListOf() var currentRichSpan: RichSpan? = null var currentRichParagraphType: ParagraphType = DefaultParagraph() @@ -124,14 +129,26 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { } } - // Correct the markdown text first so we can use it in callbacks - val correctedMarkdown = correctMarkdownText(input) + // Correct the markdown text first so we can use it in callbacks. + // intellij-markdown does not close a fence whose line ends in CRLF, so normalise first. + val correctedMarkdown = correctMarkdownOutsideFences(input.replace("\r\n", "\n")) encodeMarkdownToRichText( markdown = correctedMarkdown, onText = { text -> onText(text) }, + onCodeBlock = { language, lines -> + // The blank lines before a fence are syntax, not content: each EOL opened a paragraph. + while (richParagraphList.lastOrNull()?.let { it.isBlank() && it.type is DefaultParagraph } == true) + richParagraphList.removeAt(richParagraphList.lastIndex) + richParagraphList.addAll(codeBlockOf(language, lines)) + // Text after the block must start a paragraph of its own, never join the last code line. + val after = RichParagraph() + richParagraphList.add(after) + paragraphsAfterCodeBlocks.add(after) + currentRichSpan = null + }, onOpenNode = { node -> val lastOpenedNode = openedNodes.lastOrNull() @@ -259,11 +276,7 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { if ( node.type == GFMTokenTypes.GFM_AUTOLINK || - node.type == MarkdownTokenTypes.CODE_LINE || - // Fenced code blocks (```...```) emit their body as - // CODE_FENCE_CONTENT tokens. Without this branch the - // content was dropped on decode (#253, #540). - node.type == MarkdownTokenTypes.CODE_FENCE_CONTENT + node.type == MarkdownTokenTypes.CODE_LINE ) { onText(node.getTextInNode(correctedMarkdown).toString()) } @@ -421,7 +434,7 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { var lastBrParagraphIndex = -1 richParagraphList.forEachIndexed { i, paragraph -> - paragraph.trim() + if (paragraph.type !is CodeBlock) paragraph.trim() val isEmpty = paragraph.isEmpty() val isBr = i in brParagraphIndices @@ -445,6 +458,11 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { richParagraphList.removeAt(i) } + // A paragraph opened after a code block is only kept when something was written to it. + richParagraphList.removeAll { paragraph -> + paragraph.isBlank() && paragraphsAfterCodeBlocks.any { it === paragraph } + } + return RichTextState( initialRichParagraphList = richParagraphList, ) @@ -455,7 +473,27 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { var useLineBreak = false + val codeGroups = richTextState.richParagraphList.toList().codeBlockGroups() + richTextState.richParagraphList.fastForEachIndexed { index, richParagraph -> + val codeBlock = richParagraph.type as? CodeBlock + if (codeBlock != null) { + val paragraphs = richTextState.richParagraphList + val group = codeGroups.first { index in it } + if (index == group.first) { + val code = group.joinToString("\n") { paragraphs[it].plainText() } + val fence = fenceFor(code) + builder.append(fence).append(codeBlock.language.orEmpty()).append('\n') + builder.append(code).append('\n').append(fence) + if (group.last < paragraphs.lastIndex) { + builder.appendLine() + if (paragraphs[group.last + 1].type !is CodeBlock) builder.appendLine() + } + } + useLineBreak = false + return@fastForEachIndexed + } + // Append paragraph start text builder.appendParagraphStartText(richParagraph) @@ -497,10 +535,13 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { ) { builder.appendLine() } + if (!isBlank && nextParagraph.type is CodeBlock) { + builder.appendLine() + } } } - return correctMarkdownText(builder.toString()) + return correctMarkdownOutsideFences(builder.toString()) } private fun ParagraphType.isList(): Boolean = diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt new file mode 100644 index 00000000..4ca179a4 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt @@ -0,0 +1,102 @@ +package com.mohamedrejeb.richeditor.parser.markdown + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.plainText +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock +import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockMarkdownTest { + + private fun stateOf(markdown: String) = RichTextState().apply { setMarkdown(markdown) } + + private fun RichTextState.codeLines(): List = + richParagraphList.filter { it.type is CodeBlock }.map { it.plainText() } + + @Test + fun `a fenced block becomes code lines with its language`() { + val state = stateOf("Before\n\n```kotlin\nfun a() {\n val b = 1\n}\n```\n\nAfter") + assertEquals(listOf("fun a() {", " val b = 1", "}"), state.codeLines()) + val types = state.richParagraphList.map { it.type } + assertEquals("kotlin", types.filterIsInstance().first().language) + assertTrue(types.first() is DefaultParagraph) + assertTrue(types.last() is DefaultParagraph) + assertEquals("Before", state.richParagraphList.first().plainText()) + assertEquals("After", state.richParagraphList.last().plainText()) + } + + @Test + fun `a block without a language has a null language`() { + val state = stateOf("```\na\n```") + assertEquals(null, (state.richParagraphList.first().type as CodeBlock).language) + assertEquals(listOf("a"), state.codeLines()) + } + + @Test + fun `blank lines tabs and inline markdown inside a block are kept as written`() { + val state = stateOf("```\n\ta **b**\n\n c * d\n```") + assertEquals(listOf("\ta **b**", "", " c * d"), state.codeLines()) + } + + @Test + fun `windows line endings leave no carriage return in code lines`() { + val state = stateOf("```kotlin\r\nval a\r\nval b\r\n```\r\n") + assertEquals(listOf("val a", "val b"), state.codeLines()) + } + + @Test + fun `an unclosed fence runs to the end`() { + val state = stateOf("text\n\n```kotlin\nval a\nval b") + assertEquals(listOf("val a", "val b"), state.codeLines()) + } + + @Test + fun `a document that ends with a block has no extra empty paragraph`() { + val state = stateOf("a\n\n```\nb\n```") + assertTrue(state.richParagraphList.last().type is CodeBlock) + } + + @Test + fun `blank lines around a block add no empty paragraph`() { + val state = stateOf("Before\n\n\n```\nb\n```\n\n\nAfter") + assertEquals(listOf("Before", "b", "After"), state.richParagraphList.map { it.plainText() }) + } + + @Test + fun `two blocks in a row stay two blocks`() { + val state = stateOf("```kotlin\na\n```\n```python\nb\n```") + assertEquals(2, state.richParagraphList.toList().codeBlockGroups().size) + } + + @Test + fun `an odd language tag is kept as written`() { + val state = stateOf("```c++ title=\"x\"\na\n```") + assertEquals("c++ title=\"x\"", (state.richParagraphList.first().type as CodeBlock).language) + } + + @Test + fun `export writes a fence with the language`() { + val markdown = "Before\n\n```kotlin\nfun a() {\n val b = 1 * 2\n}\n```\n\nAfter" + assertEquals(markdown, stateOf(markdown).toMarkdown()) + } + + @Test + fun `export uses a longer fence when the code holds backticks`() { + val markdown = "````\na ``` b\n````" + val state = stateOf(markdown) + assertEquals(listOf("a ``` b"), state.codeLines()) + assertEquals(markdown, state.toMarkdown()) + } + + @Test + fun `a round trip keeps the code lines`() { + val markdown = "```python\ndef a():\n\n return \"*x*\"\n```" + val again = stateOf(stateOf(markdown).toMarkdown()) + assertEquals(listOf("def a():", "", " return \"*x*\""), again.codeLines()) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFencesTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFencesTest.kt new file mode 100644 index 00000000..ed9f2a76 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownFencesTest.kt @@ -0,0 +1,35 @@ +package com.mohamedrejeb.richeditor.parser.markdown + +import kotlin.test.Test +import kotlin.test.assertEquals + +class MarkdownFencesTest { + + @Test + fun `text inside a fence is left exactly as written`() { + val markdown = "a\n```kotlin\n val a = b * c\n d ~ e\n```\nz" + val corrected = correctMarkdownOutsideFences(markdown) + assertEquals(" val a = b * c\n d ~ e", corrected.substringAfter("```kotlin\n").substringBefore("\n```")) + } + + @Test + fun `text without a fence is corrected as before`() { + val markdown = "**bold **text\n- item" + assertEquals(correctMarkdownText(markdown), correctMarkdownOutsideFences(markdown)) + } + + @Test + fun `a tilde fence and an unclosed fence are code to the end`() { + val markdown = "~~~\na * b\n~~~\nx\n```\nc * d" + val corrected = correctMarkdownOutsideFences(markdown) + assertEquals(true, "a * b" in corrected) + assertEquals(true, corrected.endsWith("c * d")) + } + + @Test + fun `a fence is longer than any backtick run in the code`() { + assertEquals("```", fenceFor("val a")) + assertEquals("````", fenceFor("a ``` b")) + assertEquals("``````", fenceFor("`````")) + } +} From aff3b2941fce72aa42ccec37f82de345604ed476 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:16:57 +0100 Subject: [PATCH 07/16] fix: keep br blank lines next to a fenced code block --- .../markdown/RichTextStateMarkdownParser.kt | 19 +++++++++----- .../parser/markdown/CodeBlockMarkdownTest.kt | 26 +++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt index 93bb08ba..a7c8aba5 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParser.kt @@ -129,8 +129,8 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { } } - // Correct the markdown text first so we can use it in callbacks. - // intellij-markdown does not close a fence whose line ends in CRLF, so normalise first. + // Correct the markdown text first so we can use it in callbacks + // intellij-markdown only reads LF line ends reliably, so normalise CRLF before parsing. val correctedMarkdown = correctMarkdownOutsideFences(input.replace("\r\n", "\n")) encodeMarkdownToRichText( @@ -140,7 +140,11 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { }, onCodeBlock = { language, lines -> // The blank lines before a fence are syntax, not content: each EOL opened a paragraph. - while (richParagraphList.lastOrNull()?.let { it.isBlank() && it.type is DefaultParagraph } == true) + // A paragraph made by
is content the author asked for, so stop there. + while ( + richParagraphList.lastIndex !in brParagraphIndices && + richParagraphList.lastOrNull()?.let { it.isBlank() && it.type is DefaultParagraph } == true + ) richParagraphList.removeAt(richParagraphList.lastIndex) richParagraphList.addAll(codeBlockOf(language, lines)) // Text after the block must start a paragraph of its own, never join the last code line. @@ -436,7 +440,8 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { richParagraphList.forEachIndexed { i, paragraph -> if (paragraph.type !is CodeBlock) paragraph.trim() - val isEmpty = paragraph.isEmpty() + // A blank code line is content, never a gap between line breaks. + val isEmpty = paragraph.type !is CodeBlock && paragraph.isEmpty() val isBr = i in brParagraphIndices // Delete empty paragraphs between line breaks to match Markdown rendering @@ -513,8 +518,9 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { // Append line break if needed val isBlank = richParagraph.isBlank() + val isLineBreak = useLineBreak && isBlank - if (useLineBreak && isBlank) + if (isLineBreak) builder.append("
") useLineBreak = isBlank @@ -535,7 +541,8 @@ internal object RichTextStateMarkdownParser : RichTextStateParser { ) { builder.appendLine() } - if (!isBlank && nextParagraph.type is CodeBlock) { + // A
line is an HTML block that would run on into the fence without a blank line. + if ((!isBlank || isLineBreak) && nextParagraph.type is CodeBlock) { builder.appendLine() } } diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt index 4ca179a4..d7a49845 100644 --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/CodeBlockMarkdownTest.kt @@ -1,8 +1,11 @@ package com.mohamedrejeb.richeditor.parser.markdown import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichSpan import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.paragraph.RichParagraph import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.codeBlockOf import com.mohamedrejeb.richeditor.paragraph.plainText import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph @@ -67,6 +70,29 @@ class CodeBlockMarkdownTest { assertEquals(listOf("Before", "b", "After"), state.richParagraphList.map { it.plainText() }) } + @Test + fun `a br blank line before a block is kept`() { + val state = stateOf("a
\n\n```\nb\n```") + assertEquals(listOf("a", "", "b"), state.richParagraphList.map { it.plainText() }) + assertTrue(state.richParagraphList[1].type is DefaultParagraph) + assertTrue(state.richParagraphList[2].type is CodeBlock) + } + + @Test + fun `blank code lines between two br lines are kept`() { + val state = stateOf("a
\n\n```\n\n\n```\n
") + assertEquals(listOf("", ""), state.codeLines()) + } + + @Test + fun `two blank paragraphs before a block survive an export and import`() { + val text = RichParagraph().also { it.children.add(RichSpan(paragraph = it, text = "a")) } + val paragraphs = listOf(text, RichParagraph(), RichParagraph()) + codeBlockOf(null, listOf("x")) + val again = stateOf(RichTextState(initialRichParagraphList = paragraphs).toMarkdown()) + assertEquals(listOf("a", "", "", "x"), again.richParagraphList.map { it.plainText() }) + assertTrue(again.richParagraphList.last().type is CodeBlock) + } + @Test fun `two blocks in a row stay two blocks`() { val state = stateOf("```kotlin\na\n```\n```python\nb\n```") From 2c043f241b2bfb8dc5cfe6414f9aae7d380b1fb8 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:28:43 +0100 Subject: [PATCH 08/16] feat: import and export code blocks in HTML --- .../parser/html/RichTextStateHtmlParser.kt | 85 +++++++- .../parser/html/CodeBlockHtmlTest.kt | 187 ++++++++++++++++++ .../RichTextStateMarkdownParserEncodeTest.kt | 6 +- 3 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/html/CodeBlockHtmlTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/html/RichTextStateHtmlParser.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/html/RichTextStateHtmlParser.kt index d1a4d769..a9cda519 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/html/RichTextStateHtmlParser.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/html/RichTextStateHtmlParser.kt @@ -9,6 +9,10 @@ import com.mohamedrejeb.ksoup.html.parser.KsoupHtmlParser import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi import com.mohamedrejeb.richeditor.model.* import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.codeBlockOf +import com.mohamedrejeb.richeditor.paragraph.plainText +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph import com.mohamedrejeb.richeditor.paragraph.type.ListStyleTypeKeywords import com.mohamedrejeb.richeditor.paragraph.type.OrderedList @@ -57,10 +61,19 @@ internal object RichTextStateHtmlParser : RichTextStateParser { val orderedListStartValues = mutableMapOf() // The `list-style-type` keyword of the open list per level, from
    /
      . val listStyleKeywords = mutableMapOf() + // Text of the
       being read, or null outside one. Code is collected whole and turned
      +        // into code block paragraphs when the element closes.
      +        var preText: StringBuilder? = null
      +        var preLanguage: String? = null
       
               val handler = KsoupHtmlHandler
                   .Builder()
                   .onText {
      +                preText?.let { buffer ->
      +                    buffer.append(KsoupEntities.decodeHtml(it))
      +                    return@onText
      +                }
      +
                       // In html text inside ul/ol tags is skipped
                       val lastOpenedTag = openedTags.lastOrNull()?.first
                       if (lastOpenedTag == "ul" || lastOpenedTag == "ol") return@onText
      @@ -116,6 +129,24 @@ internal object RichTextStateHtmlParser : RichTextStateParser {
                       if (name == "p" || name in HeadingStyle.headingTags)
                           explicitParagraphOpens.add(!isImplied)
       
      +                val openPre = preText
      +                if (openPre != null) {
      +                    if (name == BrElement) openPre.append('\n')
      +                    if (name == CodeSpanTagName && preLanguage == null) {
      +                        preLanguage = attributes["class"]
      +                            ?.split(' ')
      +                            ?.firstOrNull { it.startsWith(CodeLanguageClassPrefix) }
      +                            ?.removePrefix(CodeLanguageClassPrefix)
      +                            ?.ifEmpty { null }
      +                    }
      +                    return@onOpenTag
      +                }
      +                if (name == PreTagName) {
      +                    preText = StringBuilder()
      +                    preLanguage = null
      +                    return@onOpenTag
      +                }
      +
                       if (name in skippedHtmlElements) {
                           return@onOpenTag
                       }
      @@ -335,6 +366,33 @@ internal object RichTextStateHtmlParser : RichTextStateParser {
                           else
                               false
       
      +                val closingPre = preText
      +                if (closingPre != null) {
      +                    if (name != PreTagName) return@onCloseTag
      +
      +                    val last = richParagraphList.lastOrNull()
      +                    if (last != null && last.isBlank() && last !in preservedBlankParagraphs && last.type is DefaultParagraph) {
      +                        toKeepEmptyParagraphIndexSet.remove(richParagraphList.lastIndex)
      +                        richParagraphList.removeAt(richParagraphList.lastIndex)
      +                    }
      +                    val lines = closingPre.toString()
      +                        .replace("\r\n", "\n")
      +                        .removePrefix("\n")
      +                        .removeSuffix("\n")
      +                        .split('\n')
      +                    val block = codeBlockOf(preLanguage, lines)
      +                    richParagraphList.addAll(block)
      +                    // An empty code line is content: keep it through the blank paragraph sweep.
      +                    preservedBlankParagraphs.addAll(block)
      +                    stringBuilder.append(' ')
      +                    richParagraphList.add(RichParagraph())
      +                    toKeepEmptyParagraphIndexSet.add(richParagraphList.lastIndex)
      +                    currentRichSpan = null
      +                    preText = null
      +                    preLanguage = null
      +                    return@onCloseTag
      +                }
      +
                       val lastRichParagraph = richParagraphList.lastOrNull()
                       val isCurrentRichParagraphBlank = lastRichParagraph?.isBlank() == true &&
                           lastRichParagraph !in preservedBlankParagraphs
      @@ -504,7 +562,26 @@ internal object RichTextStateHtmlParser : RichTextStateParser {
                   }
               }
       
      +        val codeGroups = paragraphs.toList().codeBlockGroups()
      +
               paragraphs.fastForEachIndexed { index, richParagraph ->
      +            val codeBlock = richParagraph.type as? CodeBlock
      +            if (codeBlock != null) {
      +                val group = codeGroups.first { index in it }
      +                if (index == group.first) {
      +                    closeListsDownTo(0)
      +                    hostItemLevel = 0
      +                    builder.append("<$PreTagName><$CodeSpanTagName")
      +                    codeBlock.language?.let {
      +                        builder.append(" class=\"$CodeLanguageClassPrefix${escapeHtmlAttribute(it)}\"")
      +                    }
      +                    builder.append(">")
      +                    builder.append(group.joinToString("\n") { escapeCodeText(paragraphs[it].plainText()) })
      +                    builder.append("")
      +                }
      +                return@fastForEachIndexed
      +            }
      +
                   val richParagraphType = richParagraph.type
                   val isParagraphEmpty = richParagraph.isEmpty()
                   val paragraphGroupTagName = decodeHtmlElementFromRichParagraph(richParagraph)
      @@ -967,6 +1044,10 @@ internal object RichTextStateHtmlParser : RichTextStateParser {
               }
           }
       
      +    /** Escape code for `
      `, where spaces are kept as they are and must not become entities. */
      +    private fun escapeCodeText(text: String): String =
      +        text.replace("&", "&").replace("<", "<").replace(">", ">")
      +
           private val SpaceRunRegex = Regex(" {2,}")
       
           /** Numeric character references for a space: decimal, hex, and zero-padded forms. */
      @@ -1067,4 +1148,6 @@ internal val htmlElementsSpanStyleDecodeMap = mapOf(
       )
       
       internal const val CodeSpanTagName = "code"
      -internal const val OldCodeSpanTagName = "code-span"
      \ No newline at end of file
      +internal const val OldCodeSpanTagName = "code-span"
      +internal const val PreTagName = "pre"
      +internal const val CodeLanguageClassPrefix = "language-"
      \ No newline at end of file
      diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/html/CodeBlockHtmlTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/html/CodeBlockHtmlTest.kt
      new file mode 100644
      index 00000000..df9d7693
      --- /dev/null
      +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/html/CodeBlockHtmlTest.kt
      @@ -0,0 +1,187 @@
      +package com.mohamedrejeb.richeditor.parser.html
      +
      +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
      +import com.mohamedrejeb.richeditor.model.RichTextState
      +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups
      +import com.mohamedrejeb.richeditor.paragraph.plainText
      +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock
      +import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph
      +import com.mohamedrejeb.richeditor.paragraph.type.UnorderedList
      +import kotlin.test.Test
      +import kotlin.test.assertEquals
      +import kotlin.test.assertTrue
      +
      +@OptIn(ExperimentalRichTextApi::class)
      +class CodeBlockHtmlTest {
      +
      +    private fun stateOf(html: String) = RichTextState().apply { setHtml(html) }
      +
      +    private fun RichTextState.codeLines(): List =
      +        richParagraphList.filter { it.type is CodeBlock }.map { it.plainText() }
      +
      +    private fun RichTextState.lines(): List =
      +        richParagraphList.map { it.plainText() }
      +
      +    @Test
      +    fun `pre with code and a language class becomes a code block`() {
      +        val state = stateOf("

      Before

      fun a() {\n    val b = 1\n}

      After

      ") + assertEquals(listOf("fun a() {", " val b = 1", "}"), state.codeLines()) + assertEquals("kotlin", state.richParagraphList.map { it.type }.filterIsInstance().first().language) + assertEquals(listOf("Before", "fun a() {", " val b = 1", "}", "After"), state.richParagraphList.map { it.plainText() }) + assertTrue(state.richParagraphList.last().type is DefaultParagraph) + } + + @Test + fun `pre without code is a code block with no language`() { + val state = stateOf("
      a\n  b
      ") + assertEquals(listOf("a", " b"), state.codeLines()) + assertEquals(null, (state.richParagraphList.first().type as CodeBlock).language) + } + + @Test + fun `the newline after the opening tag and before the closing tag is not a line`() { + assertEquals(listOf("a", "b"), stateOf("
      \na\nb\n
      ").codeLines()) + } + + @Test + fun `blank lines tabs and entities inside pre are kept`() { + val state = stateOf("
      \ta < b\n\nc && d
      ") + assertEquals(listOf("\ta < b", "", "c && d"), state.codeLines()) + } + + @Test + fun `markup inside pre is read as plain code`() { + val state = stateOf("
      val a
      b
      ") + assertEquals(listOf("val a", "b"), state.codeLines()) + } + + @Test + fun `two pre elements stay two blocks`() { + val state = stateOf("
      a
      b
      ") + assertEquals(2, state.richParagraphList.toList().codeBlockGroups().size) + } + + @Test + fun `export writes pre and code with the language`() { + val html = "

      Before

      fun a() {\n    val b = 1 < 2\n}

      After

      " + assertEquals(html, stateOf(html).toHtml()) + } + + @Test + fun `export without a language has no class`() { + assertEquals("
      a\n\nb
      ", stateOf("
      a\n\nb
      ").toHtml()) + } + + @Test + fun `a language with a quote is escaped in the class`() { + val state = RichTextState().apply { setMarkdown("```a\"b\nx\n```") } + val html = state.toHtml() + assertTrue("a\"b" !in html.substringBefore(">x"), "the raw quote must not appear in the tag: $html") + assertEquals(listOf("x"), stateOf(html).codeLines()) + } + + @Test + fun `code inline outside pre is still a code span`() { + val state = stateOf("

      a b

      ") + assertTrue(state.richParagraphList.none { it.type is CodeBlock }) + assertEquals("

      a b

      ", state.toHtml()) + } + + @Test + fun `a document that is only a pre round trips`() { + val state = stateOf("
      a
      ") + assertEquals(listOf("a"), state.lines()) + assertEquals("
      a
      ", state.toHtml()) + } + + @Test + fun `an empty pre is one empty code line`() { + val state = stateOf("
      ") + assertEquals(listOf(""), state.codeLines()) + assertEquals("
      ", state.toHtml()) + } + + @Test + fun `crlf inside pre splits lines`() { + assertEquals(listOf("a", "b"), stateOf("
      a\r\nb
      ").codeLines()) + } + + @Test + fun `space runs inside pre are exported raw`() { + val html = "
      a  b\n\tc  
      " + assertEquals(html, stateOf(html).toHtml()) + } + + @Test + fun `text after a pre starts its own paragraph`() { + val state = stateOf("
      a
      b") + assertEquals(listOf("a", "b"), state.lines()) + assertTrue(state.richParagraphList.last().type is DefaultParagraph) + } + + @Test + fun `an unclosed pre is closed at the end`() { + assertEquals(listOf("a", "b"), stateOf("
      a\nb").codeLines())
      +    }
      +
      +    @Test
      +    fun `pre inside a p ends the paragraph and the rest follows the block`() {
      +        val state = stateOf("

      Before

      a
      After

      ") + assertEquals(listOf("Before", "a", "After"), state.lines()) + assertEquals(listOf("a"), state.codeLines()) + } + + @Test + fun `pre after a br keeps the br line`() { + assertEquals(listOf("a", "b"), stateOf("

      a

      b
      ").lines()) + assertEquals(listOf("a", "b", "c"), stateOf("

      a
      b

      c
      ").lines()) + } + + @Test + fun `an explicit empty paragraph before a pre is kept`() { + val state = stateOf("

      a
      ") + assertEquals(listOf("", "a"), state.lines()) + assertTrue(state.richParagraphList.first().type is DefaultParagraph) + } + + @Test + fun `pre between two lists round trips`() { + val html = "
      • x
      a
      • y
      " + val state = stateOf(html) + assertEquals(listOf("x", "a", "y"), state.lines()) + assertEquals(html, state.toHtml()) + } + + @Test + fun `pre inside a list item flattens to a top level block`() { + val state = stateOf("
      • x
        a
      • y
      ") + assertEquals(listOf("x", "a", "y"), state.lines()) + assertTrue(state.richParagraphList[0].type is UnorderedList) + assertTrue(state.richParagraphList[1].type is CodeBlock) + assertTrue(state.richParagraphList[2].type is UnorderedList) + assertEquals(listOf("x", "a", "y"), stateOf(state.toHtml()).lines()) + } + + @Test + fun `pre as the only content of a list item keeps the code`() { + val state = stateOf("
      • a
      ") + assertEquals(listOf("a"), state.lines()) + assertTrue(state.richParagraphList.single().type is CodeBlock) + } + + @Test + fun `pre inside a blockquote keeps the code`() { + val state = stateOf("
      a\nb
      ") + assertEquals(listOf("a", "b"), state.lines()) + } + + @Test + fun `an ide clipboard pre with coloured spans and br becomes plain code lines`() { + val html = "
      " +
      +            "println(\"a b)" +
      +            "

      val c = 1
      " + val state = stateOf(html) + assertEquals(listOf("println(\"a b)", "", "val c = 1"), state.codeLines()) + assertEquals(state.codeLines(), state.lines()) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParserEncodeTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParserEncodeTest.kt index abc41612..45b4f11a 100644 --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParserEncodeTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/parser/markdown/RichTextStateMarkdownParserEncodeTest.kt @@ -667,7 +667,7 @@ class RichTextStateMarkdownParserEncodeTest { @Test fun testHtmlEncodeSetRichSpanParentCorrectly() { - val html = "
      println(\"insertHtml: \$position\")
      " + val html = "
      println(\"insertHtml: \$position\")
      " val richTextState = RichTextStateHtmlParser.encode(html) richTextState.selection = TextRange(0) @@ -689,7 +689,7 @@ class RichTextStateMarkdownParserEncodeTest { @Test fun testHtmlEncodeInheritSpanStyleCorrectly() { - val html = "
      println(\"selection html: \$html\")
      println(\"selection text: \$text\")

      val htmlSelection = object : StringSelection(html), Transferable {
      " + val html = "
      println(\"selection html: \$html\")
      println(\"selection text: \$text\")

      val htmlSelection = object : StringSelection(html), Transferable {
      " val richTextState = RichTextStateHtmlParser.encode(html) val fontSize = richTextState.richParagraphList[0].getFirstNonEmptyChild()!!.fullSpanStyle.fontSize @@ -702,7 +702,7 @@ class RichTextStateMarkdownParserEncodeTest { @Test fun testHtmlEncodeInheritSpanStyleCorrectly2() { - val html = "
      val html = \"hello\"
      val richTextState = RichTextStateHtmlParser.encode(html)
      " + val html = "
      val html = \"hello\"
      val richTextState = RichTextStateHtmlParser.encode(html)
      " val richTextState = RichTextStateHtmlParser.encode(html) val fontSize = richTextState.richParagraphList[0].getFirstNonEmptyChild()!!.fullSpanStyle.fontSize From 4132a4b9ba48f9b10834082d157ee5d7a4464f55 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:40:22 +0100 Subject: [PATCH 09/16] feat: carry code blocks in the document model and JSON --- docs/features.md | 1 + .../richeditor/json/internal/BlockJson.kt | 12 ++++ .../richeditor/json/CodeBlockJsonTest.kt | 60 +++++++++++++++++++ .../richeditor/document/RichTextBlockType.kt | 10 ++++ .../document/RichTextDocumentDecoder.kt | 4 ++ .../document/RichTextDocumentEncoder.kt | 5 ++ .../richeditor/model/RichTextFeature.kt | 3 + .../richeditor/model/RichTextFeatureFilter.kt | 7 ++- .../document/CodeBlockDocumentTest.kt | 37 ++++++++++++ .../model/RichTextFeatureFilterTest.kt | 17 ++++++ .../model/RichTextFeaturesStateTest.kt | 9 +++ 11 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 richeditor-compose-json/src/commonTest/kotlin/com/mohamedrejeb/richeditor/json/CodeBlockJsonTest.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/document/CodeBlockDocumentTest.kt diff --git a/docs/features.md b/docs/features.md index 13286676..de5b924b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -56,6 +56,7 @@ if (RichTextFeature.Link in state.config.features) { | `OrderedList` | Ordered list items | | `UnorderedList` | Unordered list items | | `Heading` | Heading levels 1 to 6 | +| `CodeBlock` | Multi-line code blocks | | `ParagraphStyle` | Paragraph alignment, direction, first-line indent and line height | Each feature corresponds to one `RichTextSpanMark` or one block attribute of the [document model](rich_text_document.md). `RichTextFeature.All` is computed from the enum, so a library version that adds a feature keeps it allowed for editors on the default and excluded for editors with an explicit set. diff --git a/richeditor-compose-json/src/commonMain/kotlin/com/mohamedrejeb/richeditor/json/internal/BlockJson.kt b/richeditor-compose-json/src/commonMain/kotlin/com/mohamedrejeb/richeditor/json/internal/BlockJson.kt index b66a6901..79d20126 100644 --- a/richeditor-compose-json/src/commonMain/kotlin/com/mohamedrejeb/richeditor/json/internal/BlockJson.kt +++ b/richeditor-compose-json/src/commonMain/kotlin/com/mohamedrejeb/richeditor/json/internal/BlockJson.kt @@ -53,6 +53,13 @@ internal fun decodeBlock(json: JsonObject, registry: RichSpanStyleRegistry): Ric }, ) to ((json["heading"] as? JsonPrimitive)?.content?.toIntOrNull() ?: 0) } + "code-block" -> RichTextBlockType.CodeBlock( + language = json["language"]?.takeIf { it !is JsonNull }?.let { element -> + (element as? JsonPrimitive)?.takeIf { it.isString }?.content + ?: throw MalformedRichTextJsonException("code-block \"language\" must be a string") + }, + isBlockStart = (json["start"] as? JsonPrimitive)?.booleanOrNull == true, + ) to 0 else -> throw MalformedRichTextJsonException("Unknown block type: $typeName") } @@ -100,6 +107,11 @@ internal fun encodeBlock( type.listStyleType?.let { put("listStyle", it) } if (block.headingLevel > 0) put("heading", block.headingLevel) } + type is RichTextBlockType.CodeBlock -> { + put("type", "code-block") + type.language?.let { put("language", it) } + if (type.isBlockStart) put("start", true) + } block.headingLevel > 0 -> { put("type", "heading") put("level", block.headingLevel) diff --git a/richeditor-compose-json/src/commonTest/kotlin/com/mohamedrejeb/richeditor/json/CodeBlockJsonTest.kt b/richeditor-compose-json/src/commonTest/kotlin/com/mohamedrejeb/richeditor/json/CodeBlockJsonTest.kt new file mode 100644 index 00000000..1ad665d1 --- /dev/null +++ b/richeditor-compose-json/src/commonTest/kotlin/com/mohamedrejeb/richeditor/json/CodeBlockJsonTest.kt @@ -0,0 +1,60 @@ +package com.mohamedrejeb.richeditor.json + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.document.RichTextBlock +import com.mohamedrejeb.richeditor.document.RichTextBlockType +import com.mohamedrejeb.richeditor.document.RichTextDocument +import com.mohamedrejeb.richeditor.model.RichTextState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockJsonTest { + + private val document = RichTextDocument( + blocks = listOf( + RichTextBlock(text = "val a", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = true)), + RichTextBlock(text = "", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = false)), + RichTextBlock(text = "c", type = RichTextBlockType.CodeBlock(null, isBlockStart = true)), + RichTextBlock(text = "d", type = RichTextBlockType.CodeBlock(null, isBlockStart = false)), + ), + ) + + @Test + fun `language and start are written and left out when unset`() { + assertEquals( + """{"v":1,"blocks":[""" + + """{"id":"b0","type":"code-block","language":"kotlin","start":true,"text":"val a","spans":[]},""" + + """{"id":"b1","type":"code-block","language":"kotlin","text":"","spans":[]},""" + + """{"id":"b2","type":"code-block","start":true,"text":"c","spans":[]},""" + + """{"id":"b3","type":"code-block","text":"d","spans":[]}]}""", + codecEncode(document), + ) + } + + @Test + fun `code blocks survive a json round trip`() { + assertEquals(document.blocks, codecDecode(codecEncode(document)).blocks) + } + + @Test + fun `a language that is not a string is malformed`() { + assertFailsWith { + codecDecode("""{"v":1,"blocks":[{"id":"b0","type":"code-block","language":5,"text":"a","spans":[]}]}""") + } + } + + @Test + fun `a code block survives a state json round trip`() { + val html = "

      Before

      val a\n\n  val b
      " + + "
      c

      After

      " + val state = RichTextState().apply { setHtml(html) } + + val json = state.toJson() + val reloaded = RichTextState().setJson(json) + + assertEquals(html, reloaded.toHtml()) + assertEquals(json, reloaded.toJson()) + } +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextBlockType.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextBlockType.kt index bf6eaa7e..b572ab39 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextBlockType.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextBlockType.kt @@ -25,4 +25,14 @@ public sealed interface RichTextBlockType { require(startNumber == null || ordered) { "startNumber requires an ordered list" } } } + + /** + * One line of a code block. Consecutive code lines form one block; [isBlockStart] marks its + * first line, so two blocks next to each other stay apart. [language] is the tag as written + * (`kotlin`, `js`, ...), or null when the block names none. + */ + public data class CodeBlock( + public val language: String? = null, + public val isBlockStart: Boolean = true, + ) : RichTextBlockType } diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentDecoder.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentDecoder.kt index b49036ba..c9979131 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentDecoder.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentDecoder.kt @@ -16,6 +16,7 @@ import com.mohamedrejeb.richeditor.model.HeadingStyle import com.mohamedrejeb.richeditor.model.RichSpan import com.mohamedrejeb.richeditor.model.RichSpanStyle import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock import com.mohamedrejeb.richeditor.paragraph.type.ListStyleTypeKeywords import com.mohamedrejeb.richeditor.paragraph.type.OrderedList import com.mohamedrejeb.richeditor.paragraph.type.UnorderedList @@ -59,6 +60,9 @@ internal object RichTextDocumentDecoder { ) } } + if (type is RichTextBlockType.CodeBlock) { + paragraph.type = CodeBlock(language = type.language, isBlockStart = type.isBlockStart) + } val cuts = buildSet { add(0) diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentEncoder.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentEncoder.kt index d3d332ab..daf1e446 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentEncoder.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/document/RichTextDocumentEncoder.kt @@ -15,6 +15,7 @@ import com.mohamedrejeb.richeditor.model.RichSpan import com.mohamedrejeb.richeditor.model.RichSpanStyle import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock import com.mohamedrejeb.richeditor.paragraph.type.ListStyleTypeKeywords import com.mohamedrejeb.richeditor.paragraph.type.OrderedList import com.mohamedrejeb.richeditor.paragraph.type.UnorderedList @@ -75,6 +76,10 @@ internal object RichTextDocumentEncoder { listStyleType = ListStyleTypeKeywords.keywordOf(paragraphType), ) } + is CodeBlock -> { + orderedCounters.clear() + RichTextBlockType.CodeBlock(language = paragraphType.language, isBlockStart = paragraphType.isBlockStart) + } else -> { orderedCounters.clear() RichTextBlockType.Paragraph diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeature.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeature.kt index ebc15d77..bf3501d7 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeature.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeature.kt @@ -68,6 +68,9 @@ public enum class RichTextFeature { /** Heading levels 1 to 6. */ Heading, + /** Multi-line code blocks. */ + CodeBlock, + /** Paragraph alignment, direction, first-line indent and line height. */ ParagraphStyle; diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilter.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilter.kt index 32307c95..38b1f653 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilter.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilter.kt @@ -38,8 +38,11 @@ private fun RichTextBlock.restrictedTo(features: Set): RichText @OptIn(ExperimentalRichTextApi::class) private fun RichTextBlockType.restrictedTo(features: Set): RichTextBlockType { - if (this !is RichTextBlockType.ListItem) return this - val feature = if (ordered) RichTextFeature.OrderedList else RichTextFeature.UnorderedList + val feature = when (this) { + is RichTextBlockType.Paragraph -> return this + is RichTextBlockType.ListItem -> if (ordered) RichTextFeature.OrderedList else RichTextFeature.UnorderedList + is RichTextBlockType.CodeBlock -> RichTextFeature.CodeBlock + } return if (feature in features) this else RichTextBlockType.Paragraph } diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/document/CodeBlockDocumentTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/document/CodeBlockDocumentTest.kt new file mode 100644 index 00000000..cb3ae101 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/document/CodeBlockDocumentTest.kt @@ -0,0 +1,37 @@ +package com.mohamedrejeb.richeditor.document + +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.codeBlockOf +import com.mohamedrejeb.richeditor.paragraph.plainText +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockDocumentTest { + + private val paragraphs = codeBlockOf("kotlin", listOf("val a", "", " val b")) + codeBlockOf(null, listOf("c")) + + @Test + fun `code lines encode as code block blocks`() { + val document = RichTextDocumentEncoder.encode(paragraphs) + assertEquals( + listOf( + RichTextBlock(text = "val a", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = true)), + RichTextBlock(text = "", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = false)), + RichTextBlock(text = " val b", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = false)), + RichTextBlock(text = "c", type = RichTextBlockType.CodeBlock(null, isBlockStart = true)), + ), + document.blocks, + ) + } + + @Test + fun `a document round trip keeps lines languages and block boundaries`() { + val decoded = RichTextDocumentDecoder.decode(RichTextDocumentEncoder.encode(paragraphs)) + assertEquals(listOf("val a", "", " val b", "c"), decoded.map { it.plainText() }) + assertEquals(listOf("kotlin", "kotlin", "kotlin", null), decoded.map { (it.type as CodeBlock).language }) + assertEquals(listOf(0..2, 3..3), decoded.codeBlockGroups()) + } +} diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilterTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilterTest.kt index b1c02516..c96e676b 100644 --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilterTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeatureFilterTest.kt @@ -94,6 +94,23 @@ class RichTextFeatureFilterTest { assertEquals(doc(block("Hello")), document.restrictedTo(RichTextFeature.All - RichTextFeature.Bold)) } + @Test + fun `disallowed code blocks flatten to paragraphs and keep their text`() { + val document = doc( + RichTextBlock("val a", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = true)), + RichTextBlock("", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = false)), + ) + + assertEquals( + doc(RichTextBlock("val a"), RichTextBlock("")), + document.restrictedTo(RichTextFeature.All - RichTextFeature.CodeBlock), + ) + assertEquals( + document, + document.restrictedTo(RichTextFeature.All - RichTextFeature.Bold), + ) + } + @Test fun `disallowed lists flatten to paragraphs and keep their text`() { val document = doc( diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeaturesStateTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeaturesStateTest.kt index 0b79a14c..6f27dec1 100644 --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeaturesStateTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/RichTextFeaturesStateTest.kt @@ -51,6 +51,15 @@ class RichTextFeaturesStateTest { ) } + @Test + fun `setMarkdown turns a disallowed code block into plain paragraphs`() { + val state = RichTextState().apply { config.features = RichTextFeature.All - RichTextFeature.CodeBlock } + + state.setMarkdown("```kotlin\nval a\n val b\n```") + + assertEquals(listOf(RichTextBlock("val a"), RichTextBlock(" val b")), state.blocks()) + } + @Test fun `setMarkdown keeps only the allowed features`() { val state = RichTextState().apply { config.features = setOf(RichTextFeature.Italic) } From 73295b497157cb58487845f620999e242308fa9e Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:44:37 +0100 Subject: [PATCH 10/16] feat: draw code blocks with a background and token colours --- .../richeditor/model/CodeBlockRendering.kt | 91 ++++++++++ .../richeditor/model/EditPipeline.kt | 11 +- .../richeditor/model/RichTextState.kt | 12 ++ .../richeditor/ui/BasicRichText.kt | 5 +- .../richeditor/ui/ExpandableBasicRichText.kt | 8 +- .../mohamedrejeb/richeditor/ui/ModifierExt.kt | 24 ++- .../model/CodeBlockRenderingTest.kt | 125 +++++++++++++ .../richeditor/ui/CodeBlockRenderTest.kt | 166 ++++++++++++++++++ 8 files changed, 435 insertions(+), 7 deletions(-) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRenderingTest.kt create mode 100644 richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt new file mode 100644 index 00000000..b3e74ec3 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt @@ -0,0 +1,91 @@ +package com.mohamedrejeb.richeditor.model + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextRange +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import com.mohamedrejeb.richeditor.highlight.CodeHighlighter +import com.mohamedrejeb.richeditor.highlight.CodeLanguage +import com.mohamedrejeb.richeditor.highlight.CodeToken +import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock + +/** A code block as it sits in the rendered text: where it is and the token styles drawn over it. */ +internal data class RenderedCodeBlock( + val range: TextRange, + val styles: List>, +) + +/** + * Tokens of the blocks rendered last, so a rebuild that leaves a block's text alone (typing + * elsewhere, a style change) does not tokenize it again. + */ +@OptIn(ExperimentalRichTextApi::class) +internal class CodeBlockTokenCache { + private val tokens = HashMap, List>() + private val used = HashSet>() + + fun tokens(code: String, language: String?): List { + val key = code to language + used += key + return tokens.getOrPut(key) { + language?.let { CodeLanguage.fromName(it) }?.let { CodeHighlighter.tokenize(code, it) } ?: emptyList() + } + } + + /** Forgets every block that was not asked for since the last call. */ + fun keepOnlyUsed() { + tokens.keys.retainAll(used) + used.clear() + } +} + +/** + * The code blocks of [paragraphs] located in [annotated], which must be the text built from + * them: one ParagraphStyle range per paragraph, in order. + */ +@OptIn(ExperimentalRichTextApi::class) +internal fun renderCodeBlocks( + paragraphs: List, + annotated: AnnotatedString, + colors: CodeBlockColors, + cache: CodeBlockTokenCache, +): List { + val ranges = annotated.paragraphStyles + val groups = if (ranges.size == paragraphs.size) paragraphs.codeBlockGroups() else emptyList() + val blocks = groups.map { group -> + val start = ranges[group.first].start + val end = ranges[group.last].end + val chars = annotated.text.substring(start, end).toCharArray() + // The separator that ends each line but the last is read as the line end it stands for. + for (index in group.first until group.last) { + val separator = ranges[index].end - 1 - start + if (separator in chars.indices && chars[separator] == ' ') chars[separator] = '\n' + } + val language = (paragraphs[group.first].type as? CodeBlock)?.language + RenderedCodeBlock( + range = TextRange(start, end), + styles = cache.tokens(chars.concatToString(), language).map { token -> + AnnotatedString.Range(colors.styleOf(token.kind), start + token.start, start + token.end) + }, + ) + } + cache.keepOnlyUsed() + return blocks +} + +/** This text with the token styles of [blocks] added after its own styles. */ +internal fun AnnotatedString.withCodeBlockStyles(blocks: List): AnnotatedString { + if (blocks.all { it.styles.isEmpty() }) return this + return AnnotatedString.Builder(this).apply { + blocks.forEach { block -> + block.styles.forEach { range -> + val start = range.start.coerceIn(0, length) + val end = range.end.coerceIn(0, length) + if (start < end) addStyle(range.item, start, end) + } + } + }.toAnnotatedString() +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/EditPipeline.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/EditPipeline.kt index 904c3665..8085481a 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/EditPipeline.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/EditPipeline.kt @@ -345,8 +345,8 @@ internal fun TextLayoutResult.isForModelText(modelLength: Int): Boolean { } /** - * Projects annotatedString's style ranges into the BTF2 output buffer, then the highlights, which - * come after the span styles so they win where they overlap. + * Projects annotatedString's style ranges into the BTF2 output buffer, then the code block token + * styles, then the highlights, which come last so they win where they overlap. * * A trailing empty paragraph has a collapsed range, which BTF2 would drop: it gets the * [EmptyLineAnchor] and its ParagraphStyle on it. A collapsed range anywhere else (a shape only @@ -370,6 +370,13 @@ internal fun RichTextState.applyRichTextStyles(buffer: TextFieldBuffer) { buffer.addStyle(range.item, range.start, range.end) } } + renderedCodeBlocks.forEach { block -> + block.styles.forEach { range -> + if (range.start in 0..modelLength && range.end in 0..modelLength) { + buffer.addStyle(range.item, range.start, range.end) + } + } + } highlights.toSpanStyleRanges(textLength = modelLength, selection = selection).forEach { range -> buffer.addStyle(range.item, range.start, range.end) } 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 7b5a6564..0aa84218 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 @@ -374,6 +374,16 @@ public class RichTextState internal constructor( public var annotatedString: AnnotatedString by mutableStateOf(AnnotatedString(text = "")) private set + private val codeBlockTokenCache = CodeBlockTokenCache() + + /** The code blocks as located in [annotatedString], with their token styles. Not part of the document. */ + internal var renderedCodeBlocks: List by mutableStateOf(emptyList()) + private set + + private fun updateRenderedCodeBlocks() { + renderedCodeBlocks = renderCodeBlocks(richParagraphList, annotatedString, config.codeBlockColors, codeBlockTokenCache) + } + private var highlightsState: List by mutableStateOf(emptyList()) /** @@ -3622,6 +3632,7 @@ public class RichTextState internal constructor( ) setTextFieldStateFromValue(text = annotatedString.text, selection = clampedSelection) styledRichSpanList.addAll(newStyledRichSpanList) + updateRenderedCodeBlocks() } /** @@ -6324,6 +6335,7 @@ public class RichTextState internal constructor( styledRichSpanList.clear() setTextFieldStateFromValue(text = annotatedString.text, selection = selection) styledRichSpanList.addAll(newStyledRichSpanList) + updateRenderedCodeBlocks() // Clear un-applied styles toAddSpanStyle = SpanStyle() diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt index 058ed663..11a58c7b 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt @@ -33,6 +33,7 @@ import com.mohamedrejeb.richeditor.model.RichTextMaxImageWidthProvider import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.model.TokenClickHandler import com.mohamedrejeb.richeditor.model.TokenHoverHandler +import com.mohamedrejeb.richeditor.model.withCodeBlockStyles import com.mohamedrejeb.richeditor.model.withHighlights @OptIn(ExperimentalRichTextApi::class) @@ -63,8 +64,8 @@ public fun BasicRichText( } val maxImageWidthProvider = remember { RichTextMaxImageWidthProvider() } - val text = remember(state.annotatedString, state.highlights) { - state.annotatedString.withHighlights(state.highlights) + val text = remember(state.annotatedString, state.renderedCodeBlocks, state.highlights) { + state.annotatedString.withCodeBlockStyles(state.renderedCodeBlocks).withHighlights(state.highlights) } CompositionLocalProvider( diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ExpandableBasicRichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ExpandableBasicRichText.kt index dd15df15..f2132696 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ExpandableBasicRichText.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ExpandableBasicRichText.kt @@ -31,6 +31,7 @@ import com.mohamedrejeb.richeditor.model.LocalImageLoader import com.mohamedrejeb.richeditor.model.LocalRichTextMaxImageWidthProvider import com.mohamedrejeb.richeditor.model.RichTextMaxImageWidthProvider import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.model.withCodeBlockStyles import com.mohamedrejeb.richeditor.model.withHighlights /** @@ -97,11 +98,14 @@ public fun ExpandableBasicRichText( LinkInteractionListener { expandedListenerState.value(false) } } - val visualString = remember(state.annotatedString, state.highlights) { + val visualString = remember(state.annotatedString, state.renderedCodeBlocks, state.highlights) { // Strip paragraph styles so concatenating the See more / See less suffix doesn't push it // into a separate paragraph (which would render on a new line). Span styles and link // annotations on the content are preserved. - state.annotatedString.withHighlights(state.highlights).flattenToInlineParagraph() + state.annotatedString + .withCodeBlockStyles(state.renderedCodeBlocks) + .withHighlights(state.highlights) + .flattenToInlineParagraph() } val seeMoreSuffix = remember(seeMoreLabel, seeMoreStyle, seeMoreListener) { diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt index bf6411f8..467a6d4c 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt @@ -2,8 +2,12 @@ package com.mohamedrejeb.richeditor.ui import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.text.TextRange +import androidx.compose.ui.unit.dp import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi import com.mohamedrejeb.richeditor.model.RichSpanStyle import com.mohamedrejeb.richeditor.model.RichTextState @@ -37,6 +41,22 @@ internal fun Modifier.drawRichSpanStyle( } translate(top = -richTextState.scrollState.value.toFloat()) { + richTextState.textLayoutResult?.let { textLayoutResult -> + val textLength = textLayoutResult.layoutInput.text.length + if (textLength > 0 && textLayoutResult.isForModelText(richTextState.annotatedString.length)) { + richTextState.renderedCodeBlocks.fastForEach { block -> + val firstLine = textLayoutResult.getLineForOffset(block.range.min.coerceIn(0, textLength)) + val lastLine = textLayoutResult.getLineForOffset((block.range.max - 1).coerceIn(0, textLength)) + val top = textLayoutResult.getLineTop(firstLine) + drawRoundRect( + color = richTextState.config.codeBlockBackgroundColor, + topLeft = Offset(0f, top + topPadding), + size = Size(size.width, textLayoutResult.getLineBottom(lastLine) - top), + cornerRadius = CornerRadius(CodeBlockCornerRadius.toPx()), + ) + } + } + } styledRichSpanList.fastForEach { (style, textRange) -> richTextState.textLayoutResult?.let { textLayoutResult -> with(style) { @@ -54,4 +74,6 @@ internal fun Modifier.drawRichSpanStyle( } } } -} \ No newline at end of file +} + +private val CodeBlockCornerRadius = 8.dp diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRenderingTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRenderingTest.kt new file mode 100644 index 00000000..f940b733 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRenderingTest.kt @@ -0,0 +1,125 @@ +package com.mohamedrejeb.richeditor.model + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextRange +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** + * Code blocks as located in the rendered text: their range and the token styles drawn over + * them. The styles are presentation only and must never reach the document or an export. + */ +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockRenderingTest { + + private val colors = CodeBlockColors( + keyword = SpanStyle(color = Color.Red), + string = SpanStyle(color = Color.Green), + number = SpanStyle(color = Color.Blue), + comment = SpanStyle(color = Color.Gray), + annotation = SpanStyle(color = Color.Yellow), + ) + + private fun stateOf(markdown: String) = RichTextState().apply { + config.codeBlockColors = colors + setMarkdown(markdown) + } + + @Test + fun `tokens are placed at their offsets in the rendered text`() { + val state = stateOf("ab\n\n```kotlin\nval a = 1\n```") + assertEquals("ab val a = 1", state.annotatedString.text) + val block = state.renderedCodeBlocks.single() + assertEquals(TextRange(3, 12), block.range) + assertEquals( + listOf(AnnotatedString.Range(colors.keyword, 3, 6), AnnotatedString.Range(colors.number, 11, 12)), + block.styles, + ) + } + + @Test + fun `a comment that spans lines is one style across them`() { + val state = stateOf("```kotlin\n/* a\nb */ val\n```") + assertEquals( + listOf(AnnotatedString.Range(colors.comment, 0, 9), AnnotatedString.Range(colors.keyword, 10, 13)), + state.renderedCodeBlocks.single().styles, + ) + } + + @Test + fun `an unknown language has a block and no styles`() { + val block = stateOf("```whatever\nval a\n```").renderedCodeBlocks.single() + assertEquals(TextRange(0, 5), block.range) + assertEquals(emptyList(), block.styles) + } + + @Test + fun `two blocks are rendered separately`() { + val state = stateOf("```kotlin\nval a\n```\n```python\ndef b\n```") + assertEquals(2, state.renderedCodeBlocks.size) + assertEquals(listOf(colors.keyword, colors.keyword), state.renderedCodeBlocks.flatMap { it.styles }.map { it.item }) + } + + @Test + fun `text without a code block renders none`() { + assertEquals(emptyList(), stateOf("just **text**").renderedCodeBlocks) + } + + @Test + fun `token colours never reach an export`() { + val state = stateOf("```kotlin\nval a = 1\n```") + assertTrue(state.renderedCodeBlocks.single().styles.isNotEmpty()) + assertFalse("color" in state.toHtml(), state.toHtml()) + assertEquals("```kotlin\nval a = 1\n```", state.toMarkdown()) + assertTrue(state.annotatedString.spanStyles.none { it.item.color == Color.Red }) + assertTrue(state.toRichTextDocument().blocks.all { it.spans.isEmpty() }) + } + + @Test + fun `changing the colours restyles the block`() { + val state = stateOf("```kotlin\nval a\n```") + val other = CodeBlockColors(SpanStyle(color = Color.Cyan), colors.string, colors.number, colors.comment, colors.annotation) + state.config.codeBlockColors = other + assertEquals(Color.Cyan, state.renderedCodeBlocks.single().styles.single().item.color) + } + + @Test + fun `editing the code recomputes the tokens`() { + val state = stateOf("```kotlin\nval a\n```") + state.setMarkdown("```kotlin\nfoo val\n```") + assertEquals( + listOf(AnnotatedString.Range(colors.keyword, 4, 7)), + state.renderedCodeBlocks.single().styles, + ) + state.setMarkdown("plain") + assertEquals(emptyList(), state.renderedCodeBlocks) + } + + @Test + fun `withCodeBlockStyles adds the styles and keeps the text`() { + val state = stateOf("```kotlin\nval a\n```") + val styled = state.annotatedString.withCodeBlockStyles(state.renderedCodeBlocks) + assertEquals(state.annotatedString.text, styled.text) + assertTrue(styled.spanStyles.any { it.item == colors.keyword && it.start == 0 && it.end == 3 }) + assertSame(state.annotatedString, state.annotatedString.withCodeBlockStyles(emptyList())) + } + + @Test + fun `the cache tokenizes a block once while its text is unchanged`() { + val cache = CodeBlockTokenCache() + val first = cache.tokens("val a", "kotlin") + assertSame(first, cache.tokens("val a", "kotlin")) + cache.keepOnlyUsed() + assertSame(first, cache.tokens("val a", "kotlin")) + cache.keepOnlyUsed() + cache.keepOnlyUsed() + assertFalse(first === cache.tokens("val a", "kotlin")) + } +} diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt new file mode 100644 index 00000000..74ed7ad2 --- /dev/null +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt @@ -0,0 +1,166 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.DesktopComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import com.mohamedrejeb.richeditor.model.EmptyLineAnchor +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Code blocks as the real composables lay them out: token colours and the code font reach the + * read-only text and the editor, typing keeps a block a block, and the background is painted. + */ +@OptIn(ExperimentalTestApi::class, ExperimentalRichTextApi::class) +class CodeBlockRenderTest { + + private val markdown = "a\n\n```kotlin\nval b = 1\n```" + private val keyword = CodeBlockColors.Default.keyword + private val number = CodeBlockColors.Default.number + + @Test + fun `the read only text lays out token colours and the code font`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + var layout: TextLayoutResult? = null + setContent { BasicRichText(state = state, onTextLayout = { layout = it }) } + waitForIdle() + + val text = assertNotNull(layout).layoutInput.text + assertEquals("a val b = 1", text.text) + assertTrue(AnnotatedString.Range(keyword, 2, 5) in text.spanStyles) + assertTrue(AnnotatedString.Range(number, 10, 11) in text.spanStyles) + assertTrue(text.spanStyles.any { 2 in it.start until it.end && it.item.fontFamily == FontFamily.Monospace }) + assertTrue(text.spanStyles.none { 0 in it.start until it.end && it.item.fontFamily == FontFamily.Monospace }) + } + + @Test + fun `the editor lays out token colours`() = runEditorTest { state -> + val layout = editorLayout(state) + assertEquals(keyword.color, layout.colorAt(2)) + assertEquals(number.color, layout.colorAt(10)) + assertNotEquals(keyword.color, layout.colorAt(0)) + } + + @Test + fun `typing in a code block keeps the block and recolours it`() = runEditorTest { state -> + state.textFieldState.edit { selection = TextRange(length) } + waitForIdle() + + onNodeWithTag(EDITOR_TAG).performTextInput(" val") + waitForIdle() + + assertTrue(state.richParagraphList.last().type is CodeBlock) + assertEquals("a\n\n```kotlin\nval b = 1 val\n```", state.toMarkdown()) + val layout = editorLayout(state) + assertEquals("a val b = 1 val", layout.layoutInput.text.text.removeSuffix(EmptyLineAnchor)) + assertEquals(keyword.color, layout.colorAt(12)) + assertEquals(keyword.color, layout.colorAt(14)) + } + + @Test + fun `enter in a code block adds a line to the same block`() = runEditorTest { state -> + state.textFieldState.edit { selection = TextRange(length) } + waitForIdle() + + onNodeWithTag(EDITOR_TAG).performKeyInput { pressKey(Key.Enter) } + waitForIdle() + onNodeWithTag(EDITOR_TAG).performTextInput("x") + waitForIdle() + + assertEquals(listOf(1..2), state.richParagraphList.toList().codeBlockGroups()) + assertEquals("a\n\n```kotlin\nval b = 1\nx\n```", state.toMarkdown()) + } + + @Test + fun `the block background is drawn behind the code and not behind other text`() = runDesktopComposeUiTest { + val state = RichTextState().apply { + config.codeBlockBackgroundColor = Color.Red + setMarkdown("plain\n\n```\ncode\n```") + } + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(200.dp)) { + BasicRichText( + state = state, + modifier = Modifier.testTag(EDITOR_TAG).fillMaxWidth(), + onTextLayout = { layout = it }, + ) + } + } + waitForIdle() + + val lines = assertNotNull(layout) + val pixels = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap() + // Sampled near the right edge, where no glyph is drawn. + val x = pixels.width - 12 + fun isRedAtLine(line: Int): Boolean { + val y = ((lines.getLineTop(line) + lines.getLineBottom(line)) / 2).toInt() + val color = pixels[x, y] + return color.red > 0.8f && color.green < 0.3f && color.blue < 0.3f + } + assertTrue(isRedAtLine(1), "the code line has the block background") + assertTrue(!isRedAtLine(0), "the plain line has no block background") + } + + private fun runEditorTest(block: DesktopComposeUiTest.(state: RichTextState) -> Unit) = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + setContent { + val focusRequester = remember { FocusRequester() } + Box { + BasicRichTextEditor( + state = state, + modifier = Modifier + .focusRequester(focusRequester) + .testTag(EDITOR_TAG), + ) + } + LaunchedEffect(Unit) { focusRequester.requestFocus() } + } + waitForIdle() + block(state) + } + + private fun editorLayout(state: RichTextState): TextLayoutResult = + assertNotNull(state.textLayoutResult, "Expected a text layout result") + + /** The last range covering an offset is the one the text is drawn with. */ + private fun TextLayoutResult.colorAt(offset: Int): Color = + layoutInput.text.spanStyles + .filter { range: AnnotatedString.Range -> offset in range.start until range.end } + .lastOrNull { it.item.color != Color.Unspecified }?.item?.color ?: Color.Unspecified + + private companion object { + const val EDITOR_TAG = "editor" + } +} From e694ef14deca25888c8aa9c72025aa66e472b222 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 20:57:38 +0100 Subject: [PATCH 11/16] docs: document code blocks and add a sample screen --- docs/code_blocks.md | 191 ++++++++++++++- docs/html_import_export.md | 1 + docs/json_import_export.md | 3 +- docs/markdown_import_export.md | 1 + docs/rich_text_document.md | 2 +- .../api/desktop/richeditor-compose.api | 108 +++++++++ .../api/richeditor-compose.klib.api | 143 ++++++++++++ .../codeblocks/CodeBlocksSampleScreen.kt | 219 ++++++++++++++++++ .../sample/common/home/HomeScreen.kt | 12 + .../sample/common/navigation/NavGraph.kt | 9 + 10 files changed, 681 insertions(+), 8 deletions(-) create mode 100644 sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt diff --git a/docs/code_blocks.md b/docs/code_blocks.md index 8e07ed7b..417ba268 100644 --- a/docs/code_blocks.md +++ b/docs/code_blocks.md @@ -27,10 +27,189 @@ Normal text with `inline code` within it. ## Code Blocks -Multiline code blocks are planned for a future release. They will support: -- Syntax highlighting -- Multiple lines of code -- Language specification -- Copy to clipboard functionality +A fenced Markdown code block or an HTML `
      ` is imported as a code block: its lines are drawn
      +in a fixed-width font on a background, and coloured by the language the block names (keywords,
      +strings, numbers, comments, annotations). `RichText` and the editors both draw it. The colours
      +are presentation only, they are never written to HTML, Markdown or JSON.
       
      -Stay tuned for updates!
      +Code blocks are experimental API (`@ExperimentalRichTextApi`).
      +
      +### Basic usage
      +
      +```kotlin
      +val state = rememberRichTextState()
      +
      +LaunchedEffect(Unit) {
      +    state.setMarkdown(
      +        """
      +        Here is a function:
      +
      +        ```kotlin
      +        fun greet() = println("Hi")
      +        ```
      +        """.trimIndent()
      +    )
      +}
      +
      +RichText(state = state, modifier = Modifier.fillMaxWidth())
      +```
      +
      +The background is as wide as the composable, so give it the width the block should have
      +(`fillMaxWidth()` in most layouts).
      +
      +The same block in each format:
      +
      +| Format | Form |
      +|---|---|
      +| Markdown | A fence of three or more backticks with the language after it. Export uses a fence longer than any backtick run in the code |
      +| HTML | `
      ...
      `. A `
      ` without `` or without a class is a block with no language |
      +| JSON | One `"type": "code-block"` block per line, with `"language"` and `"start": true` on the first line of a block |
      +
      +The text inside a block is kept exactly as written: indentation, tabs, blank lines, and Markdown
      +or HTML that would otherwise be formatting.
      +
      +### Customizing
      +
      +| Property on `RichTextState.config` | Type | Default | Description |
      +|---|---|---|---|
      +| `codeBlockBackgroundColor` | `Color` | translucent grey | The background drawn behind a block |
      +| `codeBlockFontFamily` | `FontFamily` | `FontFamily.Monospace` | The font of the code |
      +| `codeBlockColors` | `CodeBlockColors` | `CodeBlockColors.Default` | The style of each kind of token |
      +
      +`CodeBlockColors` holds a `SpanStyle` per token kind, not just a colour, so a comment can be
      +italic:
      +
      +```kotlin
      +val scheme = MaterialTheme.colorScheme
      +
      +state.config.codeBlockBackgroundColor = scheme.surfaceVariant
      +state.config.codeBlockColors = CodeBlockColors(
      +    keyword = SpanStyle(color = scheme.primary),
      +    string = SpanStyle(color = scheme.tertiary),
      +    number = SpanStyle(color = scheme.secondary),
      +    comment = SpanStyle(color = scheme.outline, fontStyle = FontStyle.Italic),
      +    annotation = SpanStyle(color = scheme.secondary),
      +)
      +```
      +
      +`CodeBlockColors.Default` uses mid-tone colours that stay readable on light and dark backgrounds.
      +
      +### Turning code blocks off
      +
      +Code blocks are one of the [editor features](features.md). An editor whose feature set leaves out
      +`RichTextFeature.CodeBlock` loads and pastes a code block as plain paragraphs:
      +
      +```kotlin
      +state.config.features = RichTextFeature.All - RichTextFeature.CodeBlock
      +```
      +
      +## Showing Code Alone
      +
      +To show code that is not part of a rich text, such as a snippet or a whole file, use
      +`BasicCodeText`. It needs no `RichTextState`:
      +
      +```kotlin
      +BasicCodeText(
      +    code = "fun greet() = println(\"Hi\")",
      +    language = CodeLanguage.Kotlin,
      +    modifier = Modifier
      +        .fillMaxWidth()
      +        .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp))
      +        .padding(12.dp),
      +)
      +```
      +
      +| Parameter | Type | Default | Description |
      +|---|---|---|---|
      +| `code` | `String` | required | The code to show |
      +| `language` | `CodeLanguage?` | required | The language to colour by, or null to draw the code plain |
      +| `modifier` | `Modifier` | `Modifier` | Background, padding and shape come from here |
      +| `style` | `TextStyle` | monospace | The text style of the code |
      +| `colors` | `CodeBlockColors` | `CodeBlockColors.Default` | The style of each kind of token |
      +| `softWrap` | `Boolean` | `false` | When false, a long line scrolls sideways instead of wrapping |
      +| `onTextLayout` | `(TextLayoutResult) -> Unit` | `{}` | Called when the text is laid out |
      +
      +`BasicCodeText` draws the text and nothing else, so it fits any design system.
      +
      +For a `Text` of your own, `highlightCode` returns the coloured `AnnotatedString`:
      +
      +```kotlin
      +Text(text = highlightCode(code, CodeLanguage.fromName("python")))
      +```
      +
      +## Custom Layouts Such as a Diff View
      +
      +A view that draws its own rows, for example a diff with a gutter and added or removed
      +backgrounds, needs the tokens of each line. `CodeHighlighter.tokenizeLines` returns them with
      +offsets relative to each line. The lines are read as one piece of code, so a comment or string
      +that opens on one line is still coloured on the next:
      +
      +```kotlin
      +val language = CodeLanguage.fromFileName("src/main/kotlin/Greeter.kt") ?: return
      +val colors = CodeBlockColors.Default
      +val tokens = CodeHighlighter.tokenizeLines(lines, language)
      +
      +lines.forEachIndexed { index, line ->
      +    val text = buildAnnotatedString {
      +        append(line)
      +        tokens[index].forEach { token ->
      +            addStyle(colors.styleOf(token.kind), token.start, token.end)
      +        }
      +    }
      +    DiffRow(text)
      +}
      +```
      +
      +Lines that do not follow each other in the file, such as two hunks of a diff, are two calls.
      +A hunk that starts in the middle of a comment or string is coloured as code until that comment
      +or string ends, because the lines above it are not known.
      +
      +`CodeHighlighter.tokenize(code, language)` returns the tokens of a whole piece of code.
      +Tokenizing is linear in the length of the code and never throws, whatever the input.
      +
      +## Supported Languages
      +
      +| Language | `CodeLanguage` | Names it answers to | File endings |
      +|---|---|---|---|
      +| Kotlin | `Kotlin` | `kotlin`, `kt`, `kts` | `kt`, `kts` |
      +| Java | `Java` | `java` | `java` |
      +| JavaScript | `JavaScript` | `javascript`, `js`, `jsx`, `mjs`, `cjs`, `node` | `js`, `jsx`, `mjs`, `cjs` |
      +| TypeScript | `TypeScript` | `typescript`, `ts`, `tsx` | `ts`, `tsx` |
      +| Python | `Python` | `python`, `py`, `python3` | `py` |
      +| Swift | `Swift` | `swift` | `swift` |
      +| Go | `Go` | `go`, `golang` | `go` |
      +| Rust | `Rust` | `rust`, `rs` | `rs` |
      +| C | `C` | `c`, `h` | `c`, `h` |
      +| C++ | `Cpp` | `cpp`, `c++`, `cc`, `cxx`, `hpp` | `cpp`, `cc`, `cxx`, `hpp`, `hh` |
      +| C# | `CSharp` | `csharp`, `cs`, `c#` | `cs` |
      +| Dart | `Dart` | `dart` | `dart` |
      +| Shell | `Shell` | `shell`, `sh`, `bash`, `zsh`, `shellscript` | `sh`, `bash`, `zsh` |
      +| SQL | `Sql` | `sql` | `sql` |
      +| JSON | `Json` | `json` | `json` |
      +| YAML | `Yaml` | `yaml`, `yml` | `yaml`, `yml` |
      +
      +`CodeLanguage.fromName` takes the name of a fence or of a `language-x` class, ignoring case, and
      +`CodeLanguage.fromFileName` takes a file name or path. Both return null for a language the
      +library does not know. A code block with an unknown language is drawn as plain code and keeps
      +its language tag on export.
      +
      +## Limitations
      +
      +- A long line in a code block inside `RichText` or an editor wraps. Use `BasicCodeText` when the
      +  code should scroll sideways.
      +- There is no editor action yet to turn text into a code block or to leave one. A code block
      +  that was loaded can be edited, and Enter adds a line to it.
      +- Only fenced Markdown code is a code block. Code indented by four spaces is not.
      +- HTML, XML, CSS and diffs are not coloured yet.
      +- Markup inside an HTML `
      ` is read as plain code, so the colours of code copied from an IDE
      +  are replaced by the block's own.
      +- A code block inside a list item or a quote is moved to the top level.
      +- `ExpandableBasicRichText` colours the code but draws no background behind it.
      +
      +## Related
      +
      +- For the feature set that switches code blocks on and off, see [Editor features](features.md).
      +- For format details, see [HTML Import and Export](html_import_export.md),
      +  [Markdown Import and Export](markdown_import_export.md) and
      +  [JSON Import and Export](json_import_export.md).
      +- For the block model behind the JSON format, see [Rich Text Document](rich_text_document.md).
      diff --git a/docs/html_import_export.md b/docs/html_import_export.md
      index a3e33227..4a4c04c5 100644
      --- a/docs/html_import_export.md
      +++ b/docs/html_import_export.md
      @@ -60,6 +60,7 @@ The following HTML tags are supported:
       - `

      ` - Paragraphs - `

      ` - Divisions - `
      ` - Line breaks +- `
      ` - Code blocks, with the language from `` (see [Code Blocks](code_blocks.md))
       - `

      `..`

      ` - Headings (see [Headings](headings.md)) - `
        ` - Unordered lists. `style="list-style-type: ..."` sets the bullet (`disc`, `circle`, `square`) - `
          ` - Ordered lists. `start="N"` sets the first item's number; `style="list-style-type: ..."` sets the numbering (`decimal`, `lower-alpha`, `upper-alpha`, `lower-roman`, `upper-roman`, `arabic-indic`, `arabic-abjad`) diff --git a/docs/json_import_export.md b/docs/json_import_export.md index 9004a484..4477caca 100644 --- a/docs/json_import_export.md +++ b/docs/json_import_export.md @@ -55,10 +55,11 @@ Block fields: | Field | When present | Meaning | |---|---|---| | `id` | always | `"b" + index`; accepted and ignored on import | -| `type` | always | `paragraph`, `heading`, or `list-item` | +| `type` | always | `paragraph`, `heading`, `list-item`, or `code-block` | | `level` | headings | Heading level 1 to 6 | | `ordered`, `indent`, `start` | list items | Ordered flag, 0-based nesting, numbering restart | | `listStyle` | list items with a style of their own | CSS `list-style-type` keyword of the item's list (`lower-alpha`, `square`, ...) | +| `language`, `start` | code blocks | One block per line of code: the language tag as written, and `true` on the first line of a block (see [Code Blocks](code_blocks.md)). A library version from before code blocks rejects a document that contains one | | `align`, `dir`, `lineHeight`, `textIndent` | when set | Paragraph style | | `br` | line-break paragraphs | Paragraph created by `
          ` | | `text`, `spans` | always | Content and styling marks | diff --git a/docs/markdown_import_export.md b/docs/markdown_import_export.md index dc4fe64b..c8f36321 100644 --- a/docs/markdown_import_export.md +++ b/docs/markdown_import_export.md @@ -55,6 +55,7 @@ The following Markdown syntax elements are supported: - `*text*` or `_text_` - Italic text - `~~text~~` - Strikethrough text - `` `code` `` - Code spans +- Fenced code with a language after the opening fence - Code blocks (see [Code Blocks](code_blocks.md)) ### Headings - `# Title` through `###### Title` - ATX headings H1..H6 (see [Headings](headings.md)) diff --git a/docs/rich_text_document.md b/docs/rich_text_document.md index 8693517f..4ccb5c8f 100644 --- a/docs/rich_text_document.md +++ b/docs/rich_text_document.md @@ -29,7 +29,7 @@ A document is a list of blocks, one per paragraph: | `RichTextBlock` field | Type | Meaning | |---|---|---| | `text` | `String` | Flattened paragraph text. List prefixes are excluded. Each inline image occupies one U+FFFC placeholder character. | -| `type` | `RichTextBlockType` | `Paragraph` or `ListItem(ordered, indent, startNumber, listStyleType)` | +| `type` | `RichTextBlockType` | `Paragraph`, `ListItem(ordered, indent, startNumber, listStyleType)` or `CodeBlock(language, isBlockStart)`, one per line of code | | `spans` | `List` | Styling marks over inclusive character ranges of `text` | | `headingLevel` | `Int` | 0 for normal text, 1 to 6 for headings | | `textAlign` | `TextAlign` | Paragraph alignment, `Unspecified` when not set | diff --git a/richeditor-compose/api/desktop/richeditor-compose.api b/richeditor-compose/api/desktop/richeditor-compose.api index 24bd2da4..424adbc5 100644 --- a/richeditor-compose/api/desktop/richeditor-compose.api +++ b/richeditor-compose/api/desktop/richeditor-compose.api @@ -36,6 +36,22 @@ public final class com/mohamedrejeb/richeditor/document/RichTextBlock { public abstract interface class com/mohamedrejeb/richeditor/document/RichTextBlockType { } +public final class com/mohamedrejeb/richeditor/document/RichTextBlockType$CodeBlock : com/mohamedrejeb/richeditor/document/RichTextBlockType { + public static final field $stable I + public fun ()V + public fun (Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Z + public final fun copy (Ljava/lang/String;Z)Lcom/mohamedrejeb/richeditor/document/RichTextBlockType$CodeBlock; + public static synthetic fun copy$default (Lcom/mohamedrejeb/richeditor/document/RichTextBlockType$CodeBlock;Ljava/lang/String;ZILjava/lang/Object;)Lcom/mohamedrejeb/richeditor/document/RichTextBlockType$CodeBlock; + public fun equals (Ljava/lang/Object;)Z + public final fun getLanguage ()Ljava/lang/String; + public fun hashCode ()I + public final fun isBlockStart ()Z + public fun toString ()Ljava/lang/String; +} + public final class com/mohamedrejeb/richeditor/document/RichTextBlockType$ListItem : com/mohamedrejeb/richeditor/document/RichTextBlockType { public static final field $stable I public fun (ZILjava/lang/Integer;Ljava/lang/String;)V @@ -331,6 +347,87 @@ public final class com/mohamedrejeb/richeditor/document/RichTextSpanMark$Unknown public fun toString ()Ljava/lang/String; } +public final class com/mohamedrejeb/richeditor/highlight/CodeBlockColors { + public static final field $stable I + public static final field Companion Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors$Companion; + public fun (Landroidx/compose/ui/text/SpanStyle;Landroidx/compose/ui/text/SpanStyle;Landroidx/compose/ui/text/SpanStyle;Landroidx/compose/ui/text/SpanStyle;Landroidx/compose/ui/text/SpanStyle;)V + public fun equals (Ljava/lang/Object;)Z + public final fun getAnnotation ()Landroidx/compose/ui/text/SpanStyle; + public final fun getComment ()Landroidx/compose/ui/text/SpanStyle; + public final fun getKeyword ()Landroidx/compose/ui/text/SpanStyle; + public final fun getNumber ()Landroidx/compose/ui/text/SpanStyle; + public final fun getString ()Landroidx/compose/ui/text/SpanStyle; + public fun hashCode ()I + public final fun styleOf (Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind;)Landroidx/compose/ui/text/SpanStyle; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeBlockColors$Companion { + public final fun getDefault ()Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeHighlighter { + public static final field $stable I + public static final field INSTANCE Lcom/mohamedrejeb/richeditor/highlight/CodeHighlighter; + public final fun tokenize (Ljava/lang/String;Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage;)Ljava/util/List; + public final fun tokenizeLines (Ljava/util/List;Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage;)Ljava/util/List; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeLanguage { + public static final field $stable I + public static final field Companion Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage$Companion; + public final fun getName ()Ljava/lang/String; + public fun toString ()Ljava/lang/String; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeLanguage$Companion { + public final fun fromFileName (Ljava/lang/String;)Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun fromName (Ljava/lang/String;)Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getAll ()Ljava/util/List; + public final fun getC ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getCSharp ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getCpp ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getDart ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getGo ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getJava ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getJavaScript ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getJson ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getKotlin ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getPython ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getRust ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getShell ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getSql ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getSwift ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getTypeScript ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; + public final fun getYaml ()Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeToken { + public static final field $stable I + public fun (IILcom/mohamedrejeb/richeditor/highlight/CodeTokenKind;)V + public fun equals (Ljava/lang/Object;)Z + public final fun getEnd ()I + public final fun getKind ()Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public final fun getStart ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/mohamedrejeb/richeditor/highlight/CodeTokenKind : java/lang/Enum { + public static final field Annotation Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static final field Comment Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static final field Keyword Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static final field Number Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static final field String Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; + public static fun values ()[Lcom/mohamedrejeb/richeditor/highlight/CodeTokenKind; +} + +public final class com/mohamedrejeb/richeditor/highlight/HighlightCodeKt { + public static final fun highlightCode (Ljava/lang/String;Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage;Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors;)Landroidx/compose/ui/text/AnnotatedString; + public static synthetic fun highlightCode$default (Ljava/lang/String;Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage;Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors;ILjava/lang/Object;)Landroidx/compose/ui/text/AnnotatedString; +} + public final class com/mohamedrejeb/richeditor/model/DefaultImageLoader : com/mohamedrejeb/richeditor/model/ImageLoader { public static final field $stable I public static final field INSTANCE Lcom/mohamedrejeb/richeditor/model/DefaultImageLoader; @@ -493,6 +590,9 @@ public final class com/mohamedrejeb/richeditor/model/RichSpanStyleRegistry$Compa public final class com/mohamedrejeb/richeditor/model/RichTextConfig { public static final field $stable I public final fun getAutoLinkEnabled ()Z + public final fun getCodeBlockBackgroundColor-0d7_KjU ()J + public final fun getCodeBlockColors ()Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors; + public final fun getCodeBlockFontFamily ()Landroidx/compose/ui/text/font/FontFamily; public final fun getCodeSpanBackgroundColor-0d7_KjU ()J public final fun getCodeSpanColor-0d7_KjU ()J public final fun getCodeSpanCornerRadius-XSAIIZE ()J @@ -518,6 +618,9 @@ public final class com/mohamedrejeb/richeditor/model/RichTextConfig { public final fun getUnorderedListIndent ()I public final fun getUnorderedListStyleType ()Lcom/mohamedrejeb/richeditor/paragraph/type/UnorderedListStyleType; public final fun setAutoLinkEnabled (Z)V + public final fun setCodeBlockBackgroundColor-8_81llA (J)V + public final fun setCodeBlockColors (Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors;)V + public final fun setCodeBlockFontFamily (Landroidx/compose/ui/text/font/FontFamily;)V public final fun setCodeSpanBackgroundColor-8_81llA (J)V public final fun setCodeSpanColor-8_81llA (J)V public final fun setCodeSpanCornerRadius--R2X_6o (J)V @@ -547,6 +650,7 @@ public final class com/mohamedrejeb/richeditor/model/RichTextConfig { public final class com/mohamedrejeb/richeditor/model/RichTextFeature : java/lang/Enum { public static final field BaselineShift Lcom/mohamedrejeb/richeditor/model/RichTextFeature; public static final field Bold Lcom/mohamedrejeb/richeditor/model/RichTextFeature; + public static final field CodeBlock Lcom/mohamedrejeb/richeditor/model/RichTextFeature; public static final field CodeSpan Lcom/mohamedrejeb/richeditor/model/RichTextFeature; public static final field Companion Lcom/mohamedrejeb/richeditor/model/RichTextFeature$Companion; public static final field CustomSpanStyle Lcom/mohamedrejeb/richeditor/model/RichTextFeature; @@ -906,6 +1010,10 @@ public final class com/mohamedrejeb/richeditor/paragraph/type/UnorderedListStyle public final fun getSquare ()Lcom/mohamedrejeb/richeditor/paragraph/type/UnorderedListStyleType; } +public final class com/mohamedrejeb/richeditor/ui/BasicCodeTextKt { + public static final fun BasicCodeText (Ljava/lang/String;Lcom/mohamedrejeb/richeditor/highlight/CodeLanguage;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/highlight/CodeBlockColors;ZLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V +} + public final class com/mohamedrejeb/richeditor/ui/BasicRichTextEditorKt { public static final fun BasicRichTextEditor (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;ZZLandroidx/compose/ui/text/TextStyle;Landroidx/compose/foundation/text/KeyboardOptions;Landroidx/compose/foundation/text/KeyboardActions;ZIIILkotlin/jvm/functions/Function1;Landroidx/compose/foundation/interaction/MutableInteractionSource;Landroidx/compose/ui/graphics/Brush;Lcom/mohamedrejeb/richeditor/ui/UndoBehavior;Lkotlin/jvm/functions/Function3;Landroidx/compose/runtime/Composer;III)V public static final fun BasicRichTextEditor (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;ZZLandroidx/compose/ui/text/TextStyle;Landroidx/compose/foundation/text/KeyboardOptions;Landroidx/compose/foundation/text/KeyboardActions;ZZIIILkotlin/jvm/functions/Function1;Landroidx/compose/foundation/interaction/MutableInteractionSource;Landroidx/compose/ui/graphics/Brush;Lcom/mohamedrejeb/richeditor/ui/UndoBehavior;Lkotlin/jvm/functions/Function3;Landroidx/compose/foundation/layout/PaddingValues;Landroidx/compose/runtime/Composer;III)V diff --git a/richeditor-compose/api/richeditor-compose.klib.api b/richeditor-compose/api/richeditor-compose.klib.api index e849e432..db20d4a3 100644 --- a/richeditor-compose/api/richeditor-compose.klib.api +++ b/richeditor-compose/api/richeditor-compose.klib.api @@ -14,6 +14,20 @@ open annotation class com.mohamedrejeb.richeditor.annotation/InternalRichTextApi constructor () // com.mohamedrejeb.richeditor.annotation/InternalRichTextApi.|(){}[0] } +final enum class com.mohamedrejeb.richeditor.highlight/CodeTokenKind : kotlin/Enum { // com.mohamedrejeb.richeditor.highlight/CodeTokenKind|null[0] + enum entry Annotation // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.Annotation|null[0] + enum entry Comment // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.Comment|null[0] + enum entry Keyword // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.Keyword|null[0] + enum entry Number // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.Number|null[0] + enum entry String // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.String|null[0] + + final val entries // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.entries|#static{}entries[0] + final fun (): kotlin.enums/EnumEntries // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.entries.|#static(){}[0] + + final fun valueOf(kotlin/String): com.mohamedrejeb.richeditor.highlight/CodeTokenKind // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.valueOf|valueOf#static(kotlin.String){}[0] + final fun values(): kotlin/Array // com.mohamedrejeb.richeditor.highlight/CodeTokenKind.values|values#static(){}[0] +} + final enum class com.mohamedrejeb.richeditor.model/HeadingStyle : kotlin/Enum { // com.mohamedrejeb.richeditor.model/HeadingStyle|null[0] enum entry H1 // com.mohamedrejeb.richeditor.model/HeadingStyle.H1|null[0] enum entry H2 // com.mohamedrejeb.richeditor.model/HeadingStyle.H2|null[0] @@ -39,6 +53,7 @@ final enum class com.mohamedrejeb.richeditor.model/HeadingStyle : kotlin/Enum { // com.mohamedrejeb.richeditor.model/RichTextFeature|null[0] enum entry BaselineShift // com.mohamedrejeb.richeditor.model/RichTextFeature.BaselineShift|null[0] enum entry Bold // com.mohamedrejeb.richeditor.model/RichTextFeature.Bold|null[0] + enum entry CodeBlock // com.mohamedrejeb.richeditor.model/RichTextFeature.CodeBlock|null[0] enum entry CodeSpan // com.mohamedrejeb.richeditor.model/RichTextFeature.CodeSpan|null[0] enum entry CustomSpanStyle // com.mohamedrejeb.richeditor.model/RichTextFeature.CustomSpanStyle|null[0] enum entry FontSize // com.mohamedrejeb.richeditor.model/RichTextFeature.FontSize|null[0] @@ -264,6 +279,22 @@ abstract interface com.mohamedrejeb.richeditor.paragraph.type/OrderedListStyleTy } sealed interface com.mohamedrejeb.richeditor.document/RichTextBlockType { // com.mohamedrejeb.richeditor.document/RichTextBlockType|null[0] + final class CodeBlock : com.mohamedrejeb.richeditor.document/RichTextBlockType { // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock|null[0] + constructor (kotlin/String? = ..., kotlin/Boolean = ...) // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.|(kotlin.String?;kotlin.Boolean){}[0] + + final val isBlockStart // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.isBlockStart|{}isBlockStart[0] + final fun (): kotlin/Boolean // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.isBlockStart.|(){}[0] + final val language // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.language|{}language[0] + final fun (): kotlin/String? // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.language.|(){}[0] + + final fun component1(): kotlin/String? // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.component1|component1(){}[0] + final fun component2(): kotlin/Boolean // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.component2|component2(){}[0] + final fun copy(kotlin/String? = ..., kotlin/Boolean = ...): com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.copy|copy(kotlin.String?;kotlin.Boolean){}[0] + final fun equals(kotlin/Any?): kotlin/Boolean // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.hashCode|hashCode(){}[0] + final fun toString(): kotlin/String // com.mohamedrejeb.richeditor.document/RichTextBlockType.CodeBlock.toString|toString(){}[0] + } + final class ListItem : com.mohamedrejeb.richeditor.document/RichTextBlockType { // com.mohamedrejeb.richeditor.document/RichTextBlockType.ListItem|null[0] constructor (kotlin/Boolean, kotlin/Int = ..., kotlin/Int? = ..., kotlin/String? = ...) // com.mohamedrejeb.richeditor.document/RichTextBlockType.ListItem.|(kotlin.Boolean;kotlin.Int;kotlin.Int?;kotlin.String?){}[0] @@ -636,6 +667,92 @@ final class com.mohamedrejeb.richeditor.document/RichTextDocument { // com.moham } } +final class com.mohamedrejeb.richeditor.highlight/CodeBlockColors { // com.mohamedrejeb.richeditor.highlight/CodeBlockColors|null[0] + constructor (androidx.compose.ui.text/SpanStyle, androidx.compose.ui.text/SpanStyle, androidx.compose.ui.text/SpanStyle, androidx.compose.ui.text/SpanStyle, androidx.compose.ui.text/SpanStyle) // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.|(androidx.compose.ui.text.SpanStyle;androidx.compose.ui.text.SpanStyle;androidx.compose.ui.text.SpanStyle;androidx.compose.ui.text.SpanStyle;androidx.compose.ui.text.SpanStyle){}[0] + + final val annotation // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.annotation|{}annotation[0] + final fun (): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.annotation.|(){}[0] + final val comment // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.comment|{}comment[0] + final fun (): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.comment.|(){}[0] + final val keyword // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.keyword|{}keyword[0] + final fun (): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.keyword.|(){}[0] + final val number // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.number|{}number[0] + final fun (): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.number.|(){}[0] + final val string // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.string|{}string[0] + final fun (): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.string.|(){}[0] + + final fun equals(kotlin/Any?): kotlin/Boolean // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.hashCode|hashCode(){}[0] + final fun styleOf(com.mohamedrejeb.richeditor.highlight/CodeTokenKind): androidx.compose.ui.text/SpanStyle // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.styleOf|styleOf(com.mohamedrejeb.richeditor.highlight.CodeTokenKind){}[0] + + final object Companion { // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.Companion|null[0] + final val Default // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.Companion.Default|{}Default[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeBlockColors // com.mohamedrejeb.richeditor.highlight/CodeBlockColors.Companion.Default.|(){}[0] + } +} + +final class com.mohamedrejeb.richeditor.highlight/CodeLanguage { // com.mohamedrejeb.richeditor.highlight/CodeLanguage|null[0] + final val name // com.mohamedrejeb.richeditor.highlight/CodeLanguage.name|{}name[0] + final fun (): kotlin/String // com.mohamedrejeb.richeditor.highlight/CodeLanguage.name.|(){}[0] + + final fun toString(): kotlin/String // com.mohamedrejeb.richeditor.highlight/CodeLanguage.toString|toString(){}[0] + + final object Companion { // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion|null[0] + final val C // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.C|{}C[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.C.|(){}[0] + final val CSharp // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.CSharp|{}CSharp[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.CSharp.|(){}[0] + final val Cpp // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Cpp|{}Cpp[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Cpp.|(){}[0] + final val Dart // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Dart|{}Dart[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Dart.|(){}[0] + final val Go // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Go|{}Go[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Go.|(){}[0] + final val Java // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Java|{}Java[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Java.|(){}[0] + final val JavaScript // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.JavaScript|{}JavaScript[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.JavaScript.|(){}[0] + final val Json // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Json|{}Json[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Json.|(){}[0] + final val Kotlin // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Kotlin|{}Kotlin[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Kotlin.|(){}[0] + final val Python // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Python|{}Python[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Python.|(){}[0] + final val Rust // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Rust|{}Rust[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Rust.|(){}[0] + final val Shell // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Shell|{}Shell[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Shell.|(){}[0] + final val Sql // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Sql|{}Sql[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Sql.|(){}[0] + final val Swift // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Swift|{}Swift[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Swift.|(){}[0] + final val TypeScript // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.TypeScript|{}TypeScript[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.TypeScript.|(){}[0] + final val Yaml // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Yaml|{}Yaml[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeLanguage // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.Yaml.|(){}[0] + final val all // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.all|{}all[0] + final fun (): kotlin.collections/List // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.all.|(){}[0] + + final fun fromFileName(kotlin/String): com.mohamedrejeb.richeditor.highlight/CodeLanguage? // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.fromFileName|fromFileName(kotlin.String){}[0] + final fun fromName(kotlin/String): com.mohamedrejeb.richeditor.highlight/CodeLanguage? // com.mohamedrejeb.richeditor.highlight/CodeLanguage.Companion.fromName|fromName(kotlin.String){}[0] + } +} + +final class com.mohamedrejeb.richeditor.highlight/CodeToken { // com.mohamedrejeb.richeditor.highlight/CodeToken|null[0] + constructor (kotlin/Int, kotlin/Int, com.mohamedrejeb.richeditor.highlight/CodeTokenKind) // com.mohamedrejeb.richeditor.highlight/CodeToken.|(kotlin.Int;kotlin.Int;com.mohamedrejeb.richeditor.highlight.CodeTokenKind){}[0] + + final val end // com.mohamedrejeb.richeditor.highlight/CodeToken.end|{}end[0] + final fun (): kotlin/Int // com.mohamedrejeb.richeditor.highlight/CodeToken.end.|(){}[0] + final val kind // com.mohamedrejeb.richeditor.highlight/CodeToken.kind|{}kind[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeTokenKind // com.mohamedrejeb.richeditor.highlight/CodeToken.kind.|(){}[0] + final val start // com.mohamedrejeb.richeditor.highlight/CodeToken.start|{}start[0] + final fun (): kotlin/Int // com.mohamedrejeb.richeditor.highlight/CodeToken.start.|(){}[0] + + final fun equals(kotlin/Any?): kotlin/Boolean // com.mohamedrejeb.richeditor.highlight/CodeToken.equals|equals(kotlin.Any?){}[0] + final fun hashCode(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/CodeToken.hashCode|hashCode(){}[0] + final fun toString(): kotlin/String // com.mohamedrejeb.richeditor.highlight/CodeToken.toString|toString(){}[0] +} + final class com.mohamedrejeb.richeditor.model.history/RichTextHistory { // com.mohamedrejeb.richeditor.model.history/RichTextHistory|null[0] final val canRedo // com.mohamedrejeb.richeditor.model.history/RichTextHistory.canRedo|{}canRedo[0] final fun (): kotlin/Boolean // com.mohamedrejeb.richeditor.model.history/RichTextHistory.canRedo.|(){}[0] @@ -735,6 +852,15 @@ final class com.mohamedrejeb.richeditor.model/RichTextConfig { // com.mohamedrej final var autoLinkEnabled // com.mohamedrejeb.richeditor.model/RichTextConfig.autoLinkEnabled|{}autoLinkEnabled[0] final fun (): kotlin/Boolean // com.mohamedrejeb.richeditor.model/RichTextConfig.autoLinkEnabled.|(){}[0] final fun (kotlin/Boolean) // com.mohamedrejeb.richeditor.model/RichTextConfig.autoLinkEnabled.|(kotlin.Boolean){}[0] + final var codeBlockBackgroundColor // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockBackgroundColor|{}codeBlockBackgroundColor[0] + final fun (): androidx.compose.ui.graphics/Color // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockBackgroundColor.|(){}[0] + final fun (androidx.compose.ui.graphics/Color) // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockBackgroundColor.|(androidx.compose.ui.graphics.Color){}[0] + final var codeBlockColors // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockColors|{}codeBlockColors[0] + final fun (): com.mohamedrejeb.richeditor.highlight/CodeBlockColors // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockColors.|(){}[0] + final fun (com.mohamedrejeb.richeditor.highlight/CodeBlockColors) // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockColors.|(com.mohamedrejeb.richeditor.highlight.CodeBlockColors){}[0] + final var codeBlockFontFamily // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockFontFamily|{}codeBlockFontFamily[0] + final fun (): androidx.compose.ui.text.font/FontFamily // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockFontFamily.|(){}[0] + final fun (androidx.compose.ui.text.font/FontFamily) // com.mohamedrejeb.richeditor.model/RichTextConfig.codeBlockFontFamily.|(androidx.compose.ui.text.font.FontFamily){}[0] final var codeSpanBackgroundColor // com.mohamedrejeb.richeditor.model/RichTextConfig.codeSpanBackgroundColor|{}codeSpanBackgroundColor[0] final fun (): androidx.compose.ui.graphics/Color // com.mohamedrejeb.richeditor.model/RichTextConfig.codeSpanBackgroundColor.|(){}[0] final fun (androidx.compose.ui.graphics/Color) // com.mohamedrejeb.richeditor.model/RichTextConfig.codeSpanBackgroundColor.|(androidx.compose.ui.graphics.Color){}[0] @@ -1017,6 +1143,11 @@ final class com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors { // c final fun hashCode(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors.hashCode|hashCode(){}[0] } +final object com.mohamedrejeb.richeditor.highlight/CodeHighlighter { // com.mohamedrejeb.richeditor.highlight/CodeHighlighter|null[0] + final fun tokenize(kotlin/String, com.mohamedrejeb.richeditor.highlight/CodeLanguage): kotlin.collections/List // com.mohamedrejeb.richeditor.highlight/CodeHighlighter.tokenize|tokenize(kotlin.String;com.mohamedrejeb.richeditor.highlight.CodeLanguage){}[0] + final fun tokenizeLines(kotlin.collections/List, com.mohamedrejeb.richeditor.highlight/CodeLanguage): kotlin.collections/List> // com.mohamedrejeb.richeditor.highlight/CodeHighlighter.tokenizeLines|tokenizeLines(kotlin.collections.List;com.mohamedrejeb.richeditor.highlight.CodeLanguage){}[0] +} + final object com.mohamedrejeb.richeditor.model/DefaultImageLoader : com.mohamedrejeb.richeditor.model/ImageLoader { // com.mohamedrejeb.richeditor.model/DefaultImageLoader|null[0] final fun load(kotlin/Any, androidx.compose.runtime/Composer?, kotlin/Int): com.mohamedrejeb.richeditor.model/ImageData? // com.mohamedrejeb.richeditor.model/DefaultImageLoader.load|load(kotlin.Any;androidx.compose.runtime.Composer?;kotlin.Int){}[0] } @@ -1050,6 +1181,7 @@ final object com.mohamedrejeb.richeditor.ui.material3/RichTextEditorDefaults { / } final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop[0] +final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop[0] final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop[0] final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop[0] final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop[0] @@ -1070,6 +1202,10 @@ final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_docum final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop[0] final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop[0] final val com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop|#static{}com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop[0] +final val com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop|#static{}com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop[0] +final val com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop|#static{}com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop[0] +final val com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop|#static{}com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop[0] +final val com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop|#static{}com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop[0] final val com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop|#static{}com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop[0] final val com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop|#static{}com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop[0] final val com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop|#static{}com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop[0] @@ -1122,6 +1258,7 @@ final fun (androidx.compose.ui.text/TextLayoutResult).com.mohamedrejeb.richedito final fun (kotlin/Float).com.mohamedrejeb.richeditor.utils/maxDecimals(kotlin/Int): kotlin/Float // com.mohamedrejeb.richeditor.utils/maxDecimals|maxDecimals@kotlin.Float(kotlin.Int){}[0] final fun <#A: kotlin/Any?> com.mohamedrejeb.richeditor.ui.material3/TriggerSuggestions(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/String, kotlin/Function1>, kotlin/Function1<#A, com.mohamedrejeb.richeditor.model/RichSpanStyle.Token>, androidx.compose.ui/Modifier?, androidx.compose.ui.unit/Dp, androidx.compose.ui.graphics/Color, androidx.compose.ui.graphics/Color, androidx.compose.ui.graphics/Color, androidx.compose.ui.graphics/Shape?, kotlin/Int, kotlin/Function3<#A, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/TriggerSuggestions|TriggerSuggestions(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.String;kotlin.Function1>;kotlin.Function1<0:0,com.mohamedrejeb.richeditor.model.RichSpanStyle.Token>;androidx.compose.ui.Modifier?;androidx.compose.ui.unit.Dp;androidx.compose.ui.graphics.Color;androidx.compose.ui.graphics.Color;androidx.compose.ui.graphics.Color;androidx.compose.ui.graphics.Shape?;kotlin.Int;kotlin.Function3<0:0,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){0§}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextBlock$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextBlockType_CodeBlock$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextBlockType_ListItem$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextBlockType_Paragraph$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextDocument$stableprop_getter(){}[0] @@ -1142,6 +1279,11 @@ final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_docum final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextSpanMark_Token$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextSpanMark_Underline$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.document/com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop_getter|com_mohamedrejeb_richeditor_document_RichTextSpanMark_Unknown$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop_getter|com_mohamedrejeb_richeditor_highlight_CodeBlockColors$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop_getter|com_mohamedrejeb_richeditor_highlight_CodeHighlighter$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop_getter|com_mohamedrejeb_richeditor_highlight_CodeLanguage$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.highlight/com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop_getter|com_mohamedrejeb_richeditor_highlight_CodeToken$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.highlight/highlightCode(kotlin/String, com.mohamedrejeb.richeditor.highlight/CodeLanguage?, com.mohamedrejeb.richeditor.highlight/CodeBlockColors = ...): androidx.compose.ui.text/AnnotatedString // com.mohamedrejeb.richeditor.highlight/highlightCode|highlightCode(kotlin.String;com.mohamedrejeb.richeditor.highlight.CodeLanguage?;com.mohamedrejeb.richeditor.highlight.CodeBlockColors){}[0] final fun com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop_getter|com_mohamedrejeb_richeditor_model_history_CommitTrigger_Delete$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop_getter|com_mohamedrejeb_richeditor_model_history_CommitTrigger_Formatting$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.model.history/com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop_getter|com_mohamedrejeb_richeditor_model_history_CommitTrigger_LineBreak$stableprop_getter(){}[0] @@ -1188,6 +1330,7 @@ final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.ric final fun com.mohamedrejeb.richeditor.ui.material3/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(){}[0] +final fun com.mohamedrejeb.richeditor.ui/BasicCodeText(kotlin/String, com.mohamedrejeb.richeditor.highlight/CodeLanguage?, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.highlight/CodeBlockColors?, kotlin/Boolean, kotlin/Function1?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicCodeText|BasicCodeText(kotlin.String;com.mohamedrejeb.richeditor.highlight.CodeLanguage?;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.highlight.CodeBlockColors?;kotlin.Boolean;kotlin.Function1?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.foundation.layout/PaddingValues, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.foundation.layout.PaddingValues;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] diff --git a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt new file mode 100644 index 00000000..b03f0d52 --- /dev/null +++ b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt @@ -0,0 +1,219 @@ +package com.mohamedrejeb.richeditor.sample.common.codeblocks + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.highlight.CodeBlockColors +import com.mohamedrejeb.richeditor.highlight.CodeHighlighter +import com.mohamedrejeb.richeditor.highlight.CodeLanguage +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.sample.common.components.SampleScaffold +import com.mohamedrejeb.richeditor.ui.BasicCodeText +import com.mohamedrejeb.richeditor.ui.material3.RichText + +private val replyMarkdown = """ +Here is a small **Kotlin** function and the same idea in *Python*: + +```kotlin +/* Greets everyone + in the list. */ +@Composable +fun Greeting(names: List) { + for (name in names) { + Text("Hello, ${'$'}name!") // one line each + } +} +``` + +```python +def greet(names): + ${"\"\"\""}Greets everyone in the list.${"\"\"\""} + for name in names: + print(f"Hello, {name}!") # one line each +``` + +Both walk the list once. +""".trimIndent() + +private const val Snippet = + "val message = listOf(\"a fairly long line\", \"that does not fit\", \"and scrolls sideways\").joinToString(separator = \", \") { it.uppercase() }\n" + + "println(message)" + +private enum class DiffKind { Same, Added, Removed } + +private class DiffLine(val kind: DiffKind, val text: String) + +private const val DiffFileName = "Greeter.kt" + +private val diffLines = listOf( + DiffLine(DiffKind.Same, "class Greeter(private val names: List) {"), + DiffLine(DiffKind.Same, " /* Greets everyone"), + DiffLine(DiffKind.Same, " in the list. */"), + DiffLine(DiffKind.Removed, " fun greet() = names.forEach { println(\"Hi \$it\") }"), + DiffLine(DiffKind.Added, " fun greet(greeting: String = \"Hello\") ="), + DiffLine(DiffKind.Added, " names.forEach { println(\"\$greeting, \$it!\") }"), + DiffLine(DiffKind.Same, "}"), +) + +private val AddedBackground = Color(0x3322C55E) +private val RemovedBackground = Color(0x33EF4444) + +@OptIn(ExperimentalRichTextApi::class) +@Composable +fun CodeBlocksSampleScreen(navigateBack: () -> Unit) { + val scheme = MaterialTheme.colorScheme + val colors = remember(scheme) { + CodeBlockColors( + keyword = SpanStyle(color = scheme.primary), + string = SpanStyle(color = scheme.tertiary), + number = SpanStyle(color = scheme.secondary), + comment = SpanStyle(color = scheme.outline, fontStyle = FontStyle.Italic), + annotation = SpanStyle(color = scheme.secondary), + ) + } + + SampleScaffold( + title = "Code blocks", + navigateBack = navigateBack, + ) { paddingValues -> + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + .padding(horizontal = 20.dp) + .verticalScroll(rememberScrollState()), + ) { + Spacer(Modifier.height(8.dp)) + + SectionTitle("Markdown with code blocks", "RichText draws fenced code coloured by its language.") + val state = remember(scheme, colors) { + RichTextState().apply { + config.codeBlockBackgroundColor = scheme.surfaceVariant + config.codeBlockColors = colors + setMarkdown(replyMarkdown) + } + } + RichText(state = state, modifier = Modifier.fillMaxWidth()) + + SectionTitle("Code alone", "BasicCodeText needs no state. A long line scrolls sideways.") + BasicCodeText( + code = Snippet, + language = CodeLanguage.Kotlin, + colors = colors, + style = CodeStyle.copy(color = scheme.onSurface), + modifier = Modifier + .fillMaxWidth() + .background(scheme.surfaceVariant, RoundedCornerShape(8.dp)) + .padding(12.dp), + ) + + SectionTitle("A diff view", "Rows drawn by the app and coloured with CodeHighlighter.tokenizeLines.") + DiffView(colors) + + Spacer(Modifier.height(24.dp)) + } + } +} + +@Composable +private fun SectionTitle(title: String, description: String) { + Column(verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.padding(top = 12.dp)) { + Text(title, style = MaterialTheme.typography.titleMedium) + Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@OptIn(ExperimentalRichTextApi::class) +@Composable +private fun DiffView(colors: CodeBlockColors) { + val scheme = MaterialTheme.colorScheme + val rows = remember(colors) { diffRows(colors) } + + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(scheme.surfaceVariant), + ) { + diffLines.forEachIndexed { index, line -> + Row( + modifier = Modifier + .fillMaxWidth() + .background( + when (line.kind) { + DiffKind.Same -> Color.Transparent + DiffKind.Added -> AddedBackground + DiffKind.Removed -> RemovedBackground + } + ) + .padding(horizontal = 12.dp, vertical = 2.dp), + ) { + Text( + text = when (line.kind) { + DiffKind.Same -> " " + DiffKind.Added -> "+" + DiffKind.Removed -> "-" + }, + style = CodeStyle, + color = scheme.onSurfaceVariant, + modifier = Modifier.width(20.dp), + ) + Text(text = rows[index], style = CodeStyle, color = scheme.onSurface) + } + } + } +} + +/** + * The text of each diff row with its token styles. The old and the new side are tokenized apart, + * each as the continuous code it is, so a removed line never changes how an added one is read. + */ +@OptIn(ExperimentalRichTextApi::class) +private fun diffRows(colors: CodeBlockColors): List { + val language = CodeLanguage.fromFileName(DiffFileName) ?: return diffLines.map { AnnotatedString(it.text) } + val oldSide = diffLines.withIndex().filter { it.value.kind != DiffKind.Added } + val newSide = diffLines.withIndex().filter { it.value.kind != DiffKind.Removed } + val oldTokens = CodeHighlighter.tokenizeLines(oldSide.map { it.value.text }, language) + val newTokens = CodeHighlighter.tokenizeLines(newSide.map { it.value.text }, language) + val tokensByRow = + oldSide.mapIndexed { position, row -> row.index to oldTokens[position] }.toMap() + + newSide.mapIndexed { position, row -> row.index to newTokens[position] }.toMap() + + return diffLines.mapIndexed { index, line -> + buildAnnotatedString { + append(line.text) + tokensByRow[index].orEmpty().forEach { token -> + addStyle(colors.styleOf(token.kind), token.start, token.end) + } + } + } +} + +private val CodeStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp) diff --git a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/home/HomeScreen.kt b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/home/HomeScreen.kt index 501e2669..916e6ef5 100644 --- a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/home/HomeScreen.kt +++ b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/home/HomeScreen.kt @@ -22,6 +22,7 @@ import androidx.compose.material.icons.outlined.AlternateEmail import androidx.compose.material.icons.outlined.Apps import androidx.compose.material.icons.outlined.BugReport import androidx.compose.material.icons.outlined.Code +import androidx.compose.material.icons.outlined.DataObject import androidx.compose.material.icons.outlined.History import androidx.compose.material.icons.outlined.Image import androidx.compose.material.icons.outlined.Link @@ -66,6 +67,7 @@ fun HomeScreen( navigateToClaude: () -> Unit, navigateToExpandable: () -> Unit, navigateToEditorLab: () -> Unit, + navigateToCodeBlocks: () -> Unit, ) { SampleScaffold( title = "Compose Rich Editor", @@ -239,6 +241,16 @@ fun HomeScreen( ) } + item { + FeatureCard( + title = "Code blocks", + description = "Fenced code coloured by language, code on its own with BasicCodeText, and a diff view built on the tokenizer.", + icon = Icons.Outlined.DataObject, + accent = SampleAccents.Violet, + onClick = navigateToCodeBlocks, + ) + } + item { SectionSpacer() } item { diff --git a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/navigation/NavGraph.kt b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/navigation/NavGraph.kt index e726df90..6fcb4ebc 100644 --- a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/navigation/NavGraph.kt +++ b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/navigation/NavGraph.kt @@ -11,6 +11,7 @@ import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.mohamedrejeb.richeditor.sample.common.claude.ClaudeDemoScreen +import com.mohamedrejeb.richeditor.sample.common.codeblocks.CodeBlocksSampleScreen import com.mohamedrejeb.richeditor.sample.common.examples.RealExamplesScreen import com.mohamedrejeb.richeditor.sample.common.expandable.ExpandableTextSampleScreen import com.mohamedrejeb.richeditor.sample.common.github.GitHubDemoScreen @@ -45,6 +46,7 @@ private const val HEADINGS_ROUTE = "headings" private const val CLAUDE_ROUTE = "claude" private const val EXPANDABLE_ROUTE = "expandable" private const val EDITOR_LAB_ROUTE = "editorLab" +private const val CODE_BLOCKS_ROUTE = "codeBlocks" @Composable fun NavGraph() { @@ -82,6 +84,7 @@ fun NavGraph() { navigateToClaude = { navController.navigate(CLAUDE_ROUTE) }, navigateToExpandable = { navController.navigate(EXPANDABLE_ROUTE) }, navigateToEditorLab = { navController.navigate(EDITOR_LAB_ROUTE) }, + navigateToCodeBlocks = { navController.navigate(CODE_BLOCKS_ROUTE) }, ) } @@ -184,5 +187,11 @@ fun NavGraph() { navigateBack = { navController.popBackStack() } ) } + + composable(CODE_BLOCKS_ROUTE) { + CodeBlocksSampleScreen( + navigateBack = { navController.popBackStack() } + ) + } } } From afb0cea84ea08ccbc6d28b00dd60a3c89c0b2f26 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 23:26:44 +0100 Subject: [PATCH 12/16] fix: keep a pasted code block whole and paste into a block as plain code --- .../richeditor/model/RichTextState.kt | 48 ++++- .../richeditor/paragraph/CodeBlocks.kt | 9 + .../model/CodeBlockClipboardTest.kt | 199 ++++++++++++++++++ .../richeditor/clipboard/CodeBlockCopyTest.kt | 164 +++++++++++++++ 4 files changed, 409 insertions(+), 11 deletions(-) create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt create mode 100644 richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/clipboard/CodeBlockCopyTest.kt 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 0aa84218..68dcd055 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 @@ -46,6 +46,7 @@ import com.mohamedrejeb.richeditor.model.trigger.Trigger import com.mohamedrejeb.richeditor.model.trigger.TriggerQuery import com.mohamedrejeb.richeditor.model.trigger.detectActiveTrigger import com.mohamedrejeb.richeditor.paragraph.RichParagraph +import com.mohamedrejeb.richeditor.paragraph.asCodeLinesOf import com.mohamedrejeb.richeditor.paragraph.baseSpanStyle import com.mohamedrejeb.richeditor.paragraph.type.* import com.mohamedrejeb.richeditor.platform.currentPlatform @@ -6169,8 +6170,6 @@ public class RichTextState internal constructor( p.children.add(RichSpan(paragraph = p)) } - val firstNewParagraph = newParagraphs.first() - val richSpan = getRichSpanByTextIndex( textIndex = position - 1, ignoreCustomFiltering = true, @@ -6180,6 +6179,11 @@ public class RichTextState internal constructor( val targetParagraph = richSpan.paragraph val paragraphIndex = richParagraphList.indexOf(targetParagraph) + // Whatever lands inside a code block becomes plain lines of that block. + val targetCodeBlock = targetParagraph.type as? CodeBlock + val newParagraphs = if (targetCodeBlock == null) newParagraphs else newParagraphs.asCodeLinesOf(targetCodeBlock) + val firstNewParagraph = newParagraphs.first() + val sliceIndex = max(position, richSpan.textRange.min) val targetParagraphFirstHalf = targetParagraph @@ -6189,7 +6193,11 @@ public class RichTextState internal constructor( removeSliceIndex = false, ) - if (targetParagraphFirstHalf.isEmpty() && firstNewParagraph.isNotEmpty()) { + if ( + targetCodeBlock == null && + targetParagraphFirstHalf.isEmpty() && + (firstNewParagraph.isNotEmpty() || firstNewParagraph.type is CodeBlock) + ) { targetParagraphFirstHalf.paragraphStyle = firstNewParagraph.paragraphStyle targetParagraphFirstHalf.type = firstNewParagraph.type } @@ -6209,22 +6217,40 @@ public class RichTextState internal constructor( val lastNewParagraph = newParagraphs.last() + // A code block pasted into ordinary text stays whole: the text is split around it + // and never joins its first or last line. + val keepsFirstWhole = targetCodeBlock == null && + firstNewParagraph.type is CodeBlock && firstNewParagraph.type != targetParagraphFirstHalf.type + val keepsLastWhole = targetCodeBlock == null && + lastNewParagraph.type is CodeBlock && targetParagraphSecondHalf.isNotEmpty() + val firstIndex = if (keepsFirstWhole) paragraphIndex + 1 else paragraphIndex + // Before position + First pasted paragraph - firstNewParagraph.updateChildrenParagraph(targetParagraphFirstHalf) - targetParagraphFirstHalf.children.addAll(firstNewParagraph.children) - targetParagraphFirstHalf.removeEmptyChildren() + if (keepsFirstWhole) { + richParagraphList.add(firstIndex, firstNewParagraph) + } else { + firstNewParagraph.updateChildrenParagraph(targetParagraphFirstHalf) + targetParagraphFirstHalf.children.addAll(firstNewParagraph.children) + targetParagraphFirstHalf.removeEmptyChildren() + } // Pasted paragraphs between first and last if (newParagraphs.size >= 3) { val middleParagraphs = newParagraphs.subList(1, newParagraphs.size - 1) - richParagraphList.addAll(paragraphIndex + 1, middleParagraphs) + richParagraphList.addAll(firstIndex + 1, middleParagraphs) } // Last pasted paragraph + After position - targetParagraphSecondHalf.updateChildrenParagraph(lastNewParagraph) - lastNewParagraph.children.addAll(targetParagraphSecondHalf.children) - lastNewParagraph.removeEmptyChildren() - richParagraphList.add(paragraphIndex + newParagraphs.size - 1, lastNewParagraph) + val lastIndex = firstIndex + newParagraphs.size - 1 + if (keepsLastWhole) { + richParagraphList.add(lastIndex, lastNewParagraph) + richParagraphList.add(lastIndex + 1, targetParagraphSecondHalf) + } else { + targetParagraphSecondHalf.updateChildrenParagraph(lastNewParagraph) + lastNewParagraph.children.addAll(targetParagraphSecondHalf.children) + lastNewParagraph.removeEmptyChildren() + richParagraphList.add(lastIndex, lastNewParagraph) + } } // Update the state diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt index 613b864a..4480b311 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt @@ -43,6 +43,15 @@ internal fun codeBlockOf(language: String?, lines: List): List.asCodeLinesOf(type: CodeBlock): List = + map { source -> + RichParagraph(type = CodeBlock(language = type.language, isBlockStart = false)).also { paragraph -> + paragraph.children.add(RichSpan(paragraph = paragraph, text = source.plainText())) + } + } + /** The style every character of this paragraph starts from. */ @OptIn(ExperimentalRichTextApi::class) internal fun RichParagraph.baseSpanStyle(config: RichTextConfig): SpanStyle = diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt new file mode 100644 index 00000000..61d89c58 --- /dev/null +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt @@ -0,0 +1,199 @@ +package com.mohamedrejeb.richeditor.model + +import androidx.compose.foundation.text.input.toTextFieldBuffer +import androidx.compose.ui.text.TextRange +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.plainText +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Selecting, copying, pasting and deleting around code blocks. What a selection exports is what + * a copy writes to the clipboard, and a paste goes through the same pipeline the editor uses. + * + * A code block is kept whole when it is pasted into ordinary text, and whatever is pasted into + * a code block becomes plain code lines of that block. + */ +@OptIn(ExperimentalRichTextApi::class) +class CodeBlockClipboardTest { + + private val markdown = "Before text\n\n```kotlin\nval a = 1\n val b = 2\nval c = 3\n```\n\nAfter text" + private val pythonBlockHtml = "
          p = 1\nq = 2
          " + + private fun state(source: String = markdown) = RichTextState().apply { setMarkdown(source) } + + private fun RichTextState.offsetOf(text: String): Int = annotatedString.text.indexOf(text) + + /** Each paragraph as `P:text` or `C:text`, with `C*` on the first line of a code block. */ + private fun RichTextState.shape(): List = richParagraphList.map { paragraph -> + val type = paragraph.type as? CodeBlock + val mark = if (type == null) "P" else if (type.isBlockStart) "C*" else "C" + "$mark:${paragraph.plainText()}" + } + + private fun RichTextState.paste(at: TextRange, plain: String, html: String? = null) { + selection = at + pendingClipboardHtml = html + pendingClipboardPlainText = plain + val buffer = textFieldState.toTextFieldBuffer() + buffer.replace(at.min, at.max, plain) + applyChangeList(buffer) + } + + private fun RichTextState.delete(from: Int, to: Int) { + val buffer = textFieldState.toTextFieldBuffer() + buffer.replace(from, to, "") + applyChangeList(buffer) + } + + @Test + fun `a whole block copies as code with its lines and indentation`() { + val state = state() + val range = TextRange(state.offsetOf("val a"), state.offsetOf("val c = 3") + 9) + assertEquals("val a = 1\n val b = 2\nval c = 3", state.toText(range)) + assertEquals( + "
          val a = 1\n    val b = 2\nval c = 3
          ", + state.toHtml(range), + ) + assertEquals("```kotlin\nval a = 1\n val b = 2\nval c = 3\n```", state.toMarkdown(range)) + } + + @Test + fun `part of a block copies as a block of the selected text`() { + val state = state() + val range = TextRange(state.offsetOf("val a") + 4, state.offsetOf("val c") + 3) + assertEquals("a = 1\n val b = 2\nval", state.toText(range)) + assertEquals("
          a = 1\n    val b = 2\nval
          ", state.toHtml(range)) + } + + @Test + fun `a selection across text and code copies both`() { + val state = state() + val range = TextRange(state.offsetOf("text"), state.offsetOf("val b") + 5) + assertEquals("text\nval a = 1\n val b", state.toText(range)) + assertEquals( + "

          text

          val a = 1\n    val b
          ", + state.toHtml(range), + ) + assertEquals("text\n\n```kotlin\nval a = 1\n val b\n```", state.toMarkdown(range)) + } + + @Test + fun `plain lines pasted into a block become lines of that block`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "x = 1\ny = 2") + assertEquals( + listOf("P:Before text", "C*:val a = 1", "C: x = 1", "C:y = 2val b = 2", "C:val c = 3", "P:After text"), + state.shape(), + ) + } + + @Test + fun `a block pasted in the middle of text splits the text around it`() { + val state = state("Hello world") + state.paste(TextRange(5), "p = 1\nq = 2", pythonBlockHtml) + assertEquals(listOf("P:Hello", "C*:p = 1", "C:q = 2", "P: world"), state.shape()) + assertEquals("Hello\n\n```python\np = 1\nq = 2\n```\n\n world", state.toMarkdown()) + } + + @Test + fun `a block pasted at the end of text follows it`() { + val state = state("Hello") + state.paste(TextRange(5), "p = 1\nq = 2", pythonBlockHtml) + assertEquals(listOf("P:Hello", "C*:p = 1", "C:q = 2"), state.shape()) + } + + @Test + fun `a block pasted at the start of text comes before it`() { + val state = state("Hello") + state.paste(TextRange(0), "p = 1\nq = 2", pythonBlockHtml) + assertEquals(listOf("C*:p = 1", "C:q = 2", "P:Hello"), state.shape()) + } + + @Test + fun `a block pasted next to another block stays a block of its own`() { + val state = state() + state.paste(TextRange(state.offsetOf("fore")), "p = 1\nq = 2", pythonBlockHtml) + assertEquals( + listOf("P:Be", "C*:p = 1", "C:q = 2", "P:fore text", "C*:val a = 1", "C: val b = 2", "C:val c = 3", "P:After text"), + state.shape(), + ) + assertEquals(2, state.richParagraphList.toList().codeBlockGroups().size) + } + + @Test + fun `one line of code pasted into text joins the text`() { + val state = state("Hello world") + state.paste(TextRange(5), "a = 1", "
          a = 1
          ") + assertEquals(listOf("P:Helloa = 1 world"), state.shape()) + } + + @Test + fun `part of a block copied from one editor pastes as a block into another`() { + val source = state() + val range = TextRange(source.offsetOf("val a") + 4, source.offsetOf("val c") + 3) + val target = state("Hello world") + target.paste(TextRange(5), source.toText(range), source.toHtml(range)) + assertEquals(listOf("P:Hello", "C*:a = 1", "C: val b = 2", "C:val", "P: world"), target.shape()) + } + + @Test + fun `formatted text pasted into a block becomes plain code`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "bold", "bold") + assertEquals( + listOf("P:Before text", "C*:val a = 1", "C: boldval b = 2", "C:val c = 3", "P:After text"), + state.shape(), + ) + assertTrue(state.toRichTextDocument().blocks[2].spans.isEmpty(), "no formatting inside the code line") + } + + @Test + fun `paragraphs pasted into a block become lines of that block`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "x\ny\nz", "

          x

          • y

          z

          ") + assertEquals( + listOf("P:Before text", "C*:val a = 1", "C: x", "C:y", "C:zval b = 2", "C:val c = 3", "P:After text"), + state.shape(), + ) + assertEquals(1, state.richParagraphList.toList().codeBlockGroups().size) + } + + @Test + fun `a block pasted into a block joins it`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "p = 1\nq = 2", pythonBlockHtml) + assertEquals( + "Before text\n\n```kotlin\nval a = 1\n p = 1\nq = 2val b = 2\nval c = 3\n```\n\nAfter text", + state.toMarkdown(), + ) + assertEquals(1, state.richParagraphList.toList().codeBlockGroups().size) + } + + @Test + fun `deleting from text into a block keeps the rest of the block`() { + val state = state() + state.delete(state.offsetOf("text"), state.offsetOf("val b") + 5) + assertEquals(listOf("P:Before = 2", "C:val c = 3", "P:After text"), state.shape()) + assertEquals("Before = 2\n\n```kotlin\nval c = 3\n```\n\nAfter text", state.toMarkdown()) + assertEquals(1, state.renderedCodeBlocks.size) + } + + @Test + fun `deleting the first line of a block keeps the block and its language`() { + val state = state() + state.delete(state.offsetOf("val a"), state.offsetOf(" val b")) + assertEquals("Before text\n\n```kotlin\n val b = 2\nval c = 3\n```\n\nAfter text", state.toMarkdown()) + } + + @Test + fun `deleting everything leaves an empty paragraph and no block`() { + val state = state() + state.delete(0, state.annotatedString.text.length) + assertEquals(listOf("P:"), state.shape()) + assertEquals(emptyList(), state.renderedCodeBlocks) + } +} diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/clipboard/CodeBlockCopyTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/clipboard/CodeBlockCopyTest.kt new file mode 100644 index 00000000..972bc86e --- /dev/null +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/clipboard/CodeBlockCopyTest.kt @@ -0,0 +1,164 @@ +package com.mohamedrejeb.richeditor.clipboard + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.Clipboard +import androidx.compose.ui.platform.LocalClipboard +import androidx.compose.ui.platform.NativeClipboard +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.DesktopComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.compose.ui.text.TextRange +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.ui.BasicRichTextEditor +import java.awt.datatransfer.DataFlavor +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalComposeUiApi::class) +private class CodeBlockTestClipboard : Clipboard { + val awt = java.awt.datatransfer.Clipboard("test") + + override val nativeClipboard: NativeClipboard get() = awt + + override suspend fun getClipEntry(): ClipEntry? = null + + override suspend fun setClipEntry(clipEntry: ClipEntry?) { + awt.setContents(clipEntry?.nativeClipEntry as? java.awt.datatransfer.Transferable, null) + } +} + +/** + * Copy, cut and keyboard selection of code through the real editor: the clipboard gets the + * code line by line, with its indentation. + */ +@OptIn(ExperimentalTestApi::class) +class CodeBlockCopyTest { + + private val markdown = "Before\n\n```kotlin\nval a = 1\n val b = 2\n```\n\nAfter" + + @Test + fun `copying a selection inside a block puts the code on the clipboard`() = runEditorTest { state, clipboard -> + val text = state.annotatedString.text + select(state, TextRange(text.indexOf("val a"), text.indexOf("val b = 2") + 9)) + + pressShortcut(Key.C) + + assertEquals("val a = 1\n val b = 2", clipboard.plainText()) + assertEquals( + "
          val a = 1\n    val b = 2
          ", + clipboard.html(), + ) + assertEquals(markdown, state.toMarkdown()) + } + + @Test + fun `copying across text and code puts both on the clipboard`() = runEditorTest { state, clipboard -> + select(state, TextRange(0, state.annotatedString.text.length)) + + pressShortcut(Key.C) + + assertEquals("Before\nval a = 1\n val b = 2\nAfter", clipboard.plainText()) + assertEquals( + "

          Before

          val a = 1\n    val b = 2

          After

          ", + clipboard.html(), + ) + } + + @Test + fun `cutting a line of a block removes it and keeps the block`() = runEditorTest { state, clipboard -> + val text = state.annotatedString.text + select(state, TextRange(text.indexOf("val a"), text.indexOf("val b") - INDENT)) + + pressShortcut(Key.X) + + assertEquals("val a = 1", clipboard.plainText()) + assertEquals("Before\n\n```kotlin\n val b = 2\n```\n\nAfter", state.toMarkdown()) + } + + @Test + fun `keyboard selection extends across the lines of a block`() = runEditorTest { state, _ -> + val text = state.annotatedString.text + select(state, TextRange(text.indexOf("val a"))) + + onNodeWithTag(TAG).performKeyInput { + keyDown(Key.ShiftLeft) + pressKey(Key.DirectionDown) + keyUp(Key.ShiftLeft) + } + waitForIdle() + + assertEquals(TextRange(text.indexOf("val a"), text.indexOf("val b") - INDENT), state.selection) + assertEquals("val a = 1", state.toText(state.selection)) + } + + private fun runEditorTest( + block: DesktopComposeUiTest.(state: RichTextState, clipboard: CodeBlockTestClipboard) -> Unit, + ) = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + val clipboard = CodeBlockTestClipboard() + setContent { + val focusRequester = remember { FocusRequester() } + CompositionLocalProvider(LocalClipboard provides clipboard) { + Box { + BasicRichTextEditor( + state = state, + modifier = Modifier.focusRequester(focusRequester).testTag(TAG), + ) + } + } + LaunchedEffect(Unit) { focusRequester.requestFocus() } + } + waitForIdle() + block(state, clipboard) + } + + private fun DesktopComposeUiTest.select(state: RichTextState, range: TextRange) { + state.textFieldState.edit { selection = range } + waitForIdle() + } + + private fun DesktopComposeUiTest.pressShortcut(key: Key) { + onNodeWithTag(TAG).performKeyInput { + keyDown(shortcutModifierKey) + pressKey(key) + keyUp(shortcutModifierKey) + } + waitForIdle() + } + + private fun CodeBlockTestClipboard.plainText(): String { + val contents = assertNotNull(awt.getContents(null), "Expected clipboard contents") + assertTrue(contents.isDataFlavorSupported(DataFlavor.stringFlavor), "Expected plain text") + return contents.getTransferData(DataFlavor.stringFlavor) as String + } + + private fun CodeBlockTestClipboard.html(): String { + val contents = assertNotNull(awt.getContents(null), "Expected clipboard contents") + assertTrue(contents.isDataFlavorSupported(DataFlavor.fragmentHtmlFlavor), "Expected html on the clipboard") + return contents.getTransferData(DataFlavor.fragmentHtmlFlavor) as String + } + + private companion object { + const val TAG = "editor" + const val INDENT = 4 + + // The framework maps clipboard shortcuts to Meta on macOS and to Ctrl elsewhere. + val shortcutModifierKey: Key = + if (System.getProperty("os.name") == "Mac OS X") Key.MetaLeft else Key.CtrlLeft + } +} From 36530df3066d167eb25adc9a46eaf108a46ee5f0 Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 23:31:08 +0100 Subject: [PATCH 13/16] fix: draw a cut off code block safely and leave typing shortcuts out of code --- docs/code_blocks.md | 21 ++++- .../richeditor/model/CodeBlockRendering.kt | 9 +- .../richeditor/model/TypingShortcuts.kt | 3 + .../mohamedrejeb/richeditor/ui/ModifierExt.kt | 16 +++- .../richeditor/model/CodeBlockTypingTest.kt | 55 ++++++++++++ .../richeditor/ui/BasicCodeTextTest.kt | 6 +- .../richeditor/ui/CodeBlockRenderTest.kt | 89 +++++++++++++++++++ 7 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt diff --git a/docs/code_blocks.md b/docs/code_blocks.md index 417ba268..e45e3769 100644 --- a/docs/code_blocks.md +++ b/docs/code_blocks.md @@ -68,6 +68,18 @@ The same block in each format: The text inside a block is kept exactly as written: indentation, tabs, blank lines, and Markdown or HTML that would otherwise be formatting. +### Copy and paste + +Copying or cutting a selection that covers code writes the code line by line, with its +indentation, as plain text and as a `
          ` block in HTML.
          +
          +A code block pasted into ordinary text stays whole: the text is split around it. A single line
          +of code pasted into a sentence joins the sentence as text. Whatever is pasted into a code block,
          +formatted or not, becomes plain lines of that block.
          +
          +Typing shortcuts (`**bold**`, `__bold__`, `` `code` `` and the others) do nothing inside a code
          +block, where those marks are code.
          +
           ### Customizing
           
           | Property on `RichTextState.config` | Type | Default | Description |
          @@ -201,9 +213,14 @@ its language tag on export.
             that was loaded can be edited, and Enter adds a line to it.
           - Only fenced Markdown code is a code block. Code indented by four spaces is not.
           - HTML, XML, CSS and diffs are not coloured yet.
          -- Markup inside an HTML `
          ` is read as plain code, so the colours of code copied from an IDE
          -  are replaced by the block's own.
          +- Markup inside an HTML `
          ` is read as plain code. Code copied from an IDE arrives as a
          +  `
          ` with coloured spans and no language, so it is pasted as a code block without colours.
           - A code block inside a list item or a quote is moved to the top level.
          +- A block has no space of its own above or below it, and two blocks in a row touch.
          +- In Markdown, an empty paragraph directly after a block is not kept on a round trip.
          +- Text selected in a read-only `RichText` inside a `SelectionContainer` is copied with a space
          +  between paragraphs, so code selected that way loses its line ends. Copy and cut in the editors
          +  keep them.
           - `ExpandableBasicRichText` colours the code but draws no background behind it.
           
           ## Related
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt
          index b3e74ec3..1c5663c3 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt
          @@ -12,9 +12,14 @@ import com.mohamedrejeb.richeditor.paragraph.RichParagraph
           import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups
           import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock
           
          -/** A code block as it sits in the rendered text: where it is and the token styles drawn over it. */
          +/**
          + * A code block as it sits in the rendered text: where it is and the token styles drawn over it.
          + * [lastLineOffset] is an offset on the last line of the block, which [range] cannot give: its
          + * end is the start of whatever follows, and an empty last line has no character of its own.
          + */
           internal data class RenderedCodeBlock(
               val range: TextRange,
          +    val lastLineOffset: Int,
               val styles: List>,
           )
           
          @@ -65,8 +70,10 @@ internal fun renderCodeBlocks(
                       if (separator in chars.indices && chars[separator] == ' ') chars[separator] = '\n'
                   }
                   val language = (paragraphs[group.first].type as? CodeBlock)?.language
          +        val lastLine = ranges[group.last]
                   RenderedCodeBlock(
                       range = TextRange(start, end),
          +            lastLineOffset = if (lastLine.start == lastLine.end) lastLine.start else lastLine.end - 1,
                       styles = cache.tokens(chars.concatToString(), language).map { token ->
                           AnnotatedString.Range(colors.styleOf(token.kind), start + token.start, start + token.end)
                       },
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/TypingShortcuts.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/TypingShortcuts.kt
          index a56d82d5..78b87b09 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/TypingShortcuts.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/TypingShortcuts.kt
          @@ -8,6 +8,7 @@ import androidx.compose.ui.text.style.TextDecoration
           import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
           import com.mohamedrejeb.richeditor.model.history.CommitTrigger
           import com.mohamedrejeb.richeditor.paragraph.RichParagraph
          +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock
           import com.mohamedrejeb.richeditor.paragraph.type.DefaultParagraph
           
           /** An inline Markdown mark and the formatting it stands for. Double marks come first so `**` wins over `*`. */
          @@ -74,6 +75,8 @@ internal fun RichTextState.applyTypingShortcuts(inserted: String) {
               if (at < 0 || !text.startsWith(inserted, at)) return
           
               val (paragraph, paragraphRange) = paragraphAt(caret) ?: return
          +    // Markdown marks are code inside a code block.
          +    if (paragraph.type is CodeBlock) return
               val contentStart = paragraphRange.min + paragraph.type.startRichSpan.text.length
               if (caret <= contentStart) return
           
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          index 467a6d4c..7a24787f 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          @@ -43,10 +43,20 @@ internal fun Modifier.drawRichSpanStyle(
                       translate(top = -richTextState.scrollState.value.toFloat()) {
                           richTextState.textLayoutResult?.let { textLayoutResult ->
                               val textLength = textLayoutResult.layoutInput.text.length
          -                    if (textLength > 0 && textLayoutResult.isForModelText(richTextState.annotatedString.length)) {
          +                    if (
          +                        textLength > 0 &&
          +                        textLayoutResult.lineCount > 0 &&
          +                        textLayoutResult.isForModelText(richTextState.annotatedString.length)
          +                    ) {
          +                        // maxLines and overflow stop the layout early, and asking it for a line
          +                        // past what it laid out throws.
          +                        val laidOutEnd = textLayoutResult.getLineEnd(textLayoutResult.lineCount - 1)
          +                        val isCutOff = laidOutEnd < textLength
          +                        val lastOffset = if (isCutOff) laidOutEnd - 1 else laidOutEnd
                                   richTextState.renderedCodeBlocks.fastForEach { block ->
          -                            val firstLine = textLayoutResult.getLineForOffset(block.range.min.coerceIn(0, textLength))
          -                            val lastLine = textLayoutResult.getLineForOffset((block.range.max - 1).coerceIn(0, textLength))
          +                            if (block.range.min > lastOffset) return@fastForEach
          +                            val firstLine = textLayoutResult.getLineForOffset(block.range.min.coerceIn(0, lastOffset))
          +                            val lastLine = textLayoutResult.getLineForOffset(block.lastLineOffset.coerceIn(0, lastOffset))
                                       val top = textLayoutResult.getLineTop(firstLine)
                                       drawRoundRect(
                                           color = richTextState.config.codeBlockBackgroundColor,
          diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt
          new file mode 100644
          index 00000000..e029f36e
          --- /dev/null
          +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt
          @@ -0,0 +1,55 @@
          +package com.mohamedrejeb.richeditor.model
          +
          +import androidx.compose.ui.text.TextRange
          +import androidx.compose.ui.text.input.TextFieldValue
          +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
          +import kotlin.test.Test
          +import kotlin.test.assertEquals
          +
          +/**
          + * Typing inside a code block: Markdown marks are code there, so the typing shortcuts that
          + * format ordinary text must leave them alone.
          + */
          +@OptIn(ExperimentalRichTextApi::class)
          +class CodeBlockTypingTest {
          +
          +    private fun codeState(): RichTextState = RichTextState().apply {
          +        config.inlineTypingShortcutsEnabled = true
          +        config.headingTypingShortcutsEnabled = true
          +        setMarkdown("```python\nx\n```")
          +        selection = TextRange(annotatedString.text.length)
          +    }
          +
          +    /** Types [text] one character at a time at the caret, as a keyboard does. */
          +    private fun RichTextState.type(text: String) {
          +        text.forEach { char ->
          +            val caret = selection.min
          +            val current = annotatedString.text
          +            val newText = current.substring(0, caret) + char + current.substring(caret)
          +            onTextFieldValueChange(TextFieldValue(newText, TextRange(caret + 1)))
          +        }
          +    }
          +
          +    @Test
          +    fun `underscores typed in a block stay as typed`() {
          +        val state = codeState()
          +        state.type(" = __init__")
          +        assertEquals("```python\nx = __init__\n```", state.toMarkdown())
          +        assertEquals(true, state.toRichTextDocument().blocks.single().spans.isEmpty())
          +    }
          +
          +    @Test
          +    fun `stars and backticks typed in a block stay as typed`() {
          +        val state = codeState()
          +        state.type(" = *a* + **b** + `c` + ~~d~~")
          +        assertEquals("x = *a* + **b** + `c` + ~~d~~", state.annotatedString.text)
          +        assertEquals(true, state.toRichTextDocument().blocks.single().spans.isEmpty())
          +    }
          +
          +    @Test
          +    fun `the same marks still format ordinary text`() {
          +        val state = RichTextState().apply { config.inlineTypingShortcutsEnabled = true }
          +        state.type("**bold**")
          +        assertEquals("

          bold

          ", state.toHtml()) + } +} diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt index 945ea93c..34228e45 100644 --- a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/BasicCodeTextTest.kt @@ -50,7 +50,11 @@ class BasicCodeTextTest { } waitForIdle() - assertEquals(1, assertNotNull(layout).lineCount) + val result = assertNotNull(layout) + assertEquals(1, result.lineCount) + // Laid out wider than the 120.dp parent and not clipped: the line scrolls sideways. + assertTrue(result.size.width > 120, "the line keeps its full width, was ${result.size.width}") + assertTrue(!result.didOverflowWidth, "the line is not cut off") } @Test diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt index 74ed7ad2..6df4d8bf 100644 --- a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt @@ -9,6 +9,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PixelMap import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.input.key.Key import androidx.compose.ui.platform.testTag @@ -133,6 +134,94 @@ class CodeBlockRenderTest { assertTrue(!isRedAtLine(0), "the plain line has no block background") } + @Test + fun `a block cut off by maxLines is drawn without crashing`() = runDesktopComposeUiTest { + val state = RichTextState().apply { + config.codeBlockBackgroundColor = Color.Red + setMarkdown("```\none\ntwo\nthree\n```") + } + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(200.dp)) { + BasicRichText( + state = state, + modifier = Modifier.testTag(EDITOR_TAG).fillMaxWidth(), + maxLines = 2, + onTextLayout = { layout = it }, + ) + } + } + waitForIdle() + + val lines = assertNotNull(layout) + assertEquals(2, lines.lineCount) + val pixels = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap() + assertTrue(pixels.isRedAt(pixels.width - 12, lines.lineMiddle(0)), "the first visible line has the background") + assertTrue(pixels.isRedAt(pixels.width - 12, lines.lineMiddle(1)), "the last visible line has the background") + } + + @Test + fun `a block that lies past maxLines is skipped without crashing`() = runDesktopComposeUiTest { + val state = RichTextState().apply { + config.codeBlockBackgroundColor = Color.Red + setMarkdown("text\n\n```\ncode\n```") + } + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(200.dp)) { + BasicRichText( + state = state, + modifier = Modifier.testTag(EDITOR_TAG).fillMaxWidth(), + maxLines = 1, + onTextLayout = { layout = it }, + ) + } + } + waitForIdle() + + val lines = assertNotNull(layout) + assertEquals(1, lines.lineCount) + val pixels = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap() + assertTrue(!pixels.isRedAt(pixels.width - 12, lines.lineMiddle(0)), "the plain line has no background") + } + + @Test + fun `an empty last line of a block has the background`() = runDesktopComposeUiTest { + val state = RichTextState().apply { + config.codeBlockBackgroundColor = Color.Red + setMarkdown("```\ncode\n```") + } + setContent { + val focusRequester = remember { FocusRequester() } + Box(Modifier.width(200.dp)) { + BasicRichTextEditor( + state = state, + modifier = Modifier.focusRequester(focusRequester).testTag(EDITOR_TAG).fillMaxWidth(), + ) + } + LaunchedEffect(Unit) { focusRequester.requestFocus() } + } + waitForIdle() + state.textFieldState.edit { selection = TextRange(length) } + waitForIdle() + + onNodeWithTag(EDITOR_TAG).performKeyInput { pressKey(Key.Enter) } + waitForIdle() + + val lines = editorLayout(state) + assertEquals(2, lines.lineCount) + val pixels = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap() + assertTrue(pixels.isRedAt(pixels.width - 12, lines.lineMiddle(0)), "the code line has the background") + assertTrue(pixels.isRedAt(pixels.width - 12, lines.lineMiddle(1)), "the new empty line has the background") + } + + private fun TextLayoutResult.lineMiddle(line: Int): Int = ((getLineTop(line) + getLineBottom(line)) / 2).toInt() + + private fun PixelMap.isRedAt(x: Int, y: Int): Boolean { + val color = this[x, y] + return color.red > 0.8f && color.green < 0.3f && color.blue < 0.3f + } + private fun runEditorTest(block: DesktopComposeUiTest.(state: RichTextState) -> Unit) = runDesktopComposeUiTest { val state = RichTextState().apply { setMarkdown(markdown) } setContent { From 3eeb1bf057ccb53725bebb5bc78405088f5f06fe Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Thu, 8 Oct 2026 23:43:52 +0100 Subject: [PATCH 14/16] feat: add a copy button and an action slot on code blocks in RichText --- docs/code_blocks.md | 31 +++ .../api/desktop/richeditor-compose.api | 6 +- .../api/richeditor-compose.klib.api | 12 +- .../richeditor/model/CodeBlockRendering.kt | 20 ++ .../richeditor/ui/BasicRichText.kt | 151 +++++++------- .../richeditor/ui/CodeBlockActionLayout.kt | 60 ++++++ .../richeditor/ui/CodeBlockCopyButton.kt | 63 ++++++ .../mohamedrejeb/richeditor/ui/ModifierExt.kt | 21 +- .../richeditor/ui/material/RichText.kt | 7 + .../richeditor/ui/material3/RichText.kt | 7 + .../richeditor/ui/CodeBlockActionTest.kt | 185 ++++++++++++++++++ .../codeblocks/CodeBlocksSampleScreen.kt | 4 +- 12 files changed, 466 insertions(+), 101 deletions(-) create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt create mode 100644 richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt create mode 100644 richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt diff --git a/docs/code_blocks.md b/docs/code_blocks.md index e45e3769..43c7472a 100644 --- a/docs/code_blocks.md +++ b/docs/code_blocks.md @@ -80,6 +80,37 @@ formatted or not, becomes plain lines of that block. Typing shortcuts (`**bold**`, `__bold__`, `` `code` `` and the others) do nothing inside a code block, where those marks are code. +### Copy button + +A read-only `RichText` can show a copy button at the top end corner of each code block. It copies +the block's code exactly, line ends and indentation included: + +```kotlin +RichText( + state = state, + modifier = Modifier.fillMaxWidth(), + showCodeBlockCopyButton = true, +) +``` + +The Material and Material3 `RichText` both have the option, and it is off by default. For a +button of your own, or any other action, `BasicRichText` takes a slot that is given the code and +the language of each block: + +```kotlin +BasicRichText( + state = state, + modifier = Modifier.fillMaxWidth(), + codeBlockAction = { code, language -> + MyCopyButton(onClick = { copyToClipboard(code) }) + }, +) +``` + +The action is drawn over the corner of the block and takes no room of its own, so keep it about +one line tall: on a block with a long first line it covers the end of that line. The editors do +not have this option. + ### Customizing | Property on `RichTextState.config` | Type | Default | Description | diff --git a/richeditor-compose/api/desktop/richeditor-compose.api b/richeditor-compose/api/desktop/richeditor-compose.api index 424adbc5..501e238c 100644 --- a/richeditor-compose/api/desktop/richeditor-compose.api +++ b/richeditor-compose/api/desktop/richeditor-compose.api @@ -1020,7 +1020,7 @@ public final class com/mohamedrejeb/richeditor/ui/BasicRichTextEditorKt { } public final class com/mohamedrejeb/richeditor/ui/BasicRichTextKt { - public static final fun BasicRichText-Jzo1Dmk (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lkotlin/jvm/functions/Function1;IZIILjava/util/Map;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;III)V + public static final fun BasicRichText-Kj_y3YE (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lkotlin/jvm/functions/Function1;IZIILjava/util/Map;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;III)V } public final class com/mohamedrejeb/richeditor/ui/ComposableSingletons$BasicRichTextEditorKt { @@ -1051,7 +1051,7 @@ public final class com/mohamedrejeb/richeditor/ui/material/RichTextEditorKt { } public final class com/mohamedrejeb/richeditor/ui/material/RichTextKt { - public static final fun RichText-mQfddtU (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;IIII)V + public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;ZLandroidx/compose/runtime/Composer;IIII)V } public final class com/mohamedrejeb/richeditor/ui/material3/ExpandableRichTextKt { @@ -1100,7 +1100,7 @@ public final class com/mohamedrejeb/richeditor/ui/material3/RichTextEditorKt { } public final class com/mohamedrejeb/richeditor/ui/material3/RichTextKt { - public static final fun RichText-mQfddtU (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;IIII)V + public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;ZLandroidx/compose/runtime/Composer;IIII)V } public final class com/mohamedrejeb/richeditor/ui/material3/TriggerSuggestionsKt { diff --git a/richeditor-compose/api/richeditor-compose.klib.api b/richeditor-compose/api/richeditor-compose.klib.api index db20d4a3..86671369 100644 --- a/richeditor-compose/api/richeditor-compose.klib.api +++ b/richeditor-compose/api/richeditor-compose.klib.api @@ -1320,19 +1320,19 @@ final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter|com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter|com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/Boolean, kotlin/Function1, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, androidx.compose.ui.graphics/Color, kotlin/Int, kotlin/String?, kotlin/String?, androidx.compose.ui.graphics/Color, kotlin/Boolean, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText|ExpandableRichText(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.Boolean;kotlin.Function1;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;androidx.compose.ui.graphics.Color;kotlin.Int;kotlin.String?;kotlin.String?;androidx.compose.ui.graphics.Color;kotlin.Boolean;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicCodeText(kotlin/String, com.mohamedrejeb.richeditor.highlight/CodeLanguage?, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.highlight/CodeBlockColors?, kotlin/Boolean, kotlin/Function1?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicCodeText|BasicCodeText(kotlin.String;com.mohamedrejeb.richeditor.highlight.CodeLanguage?;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.highlight.CodeBlockColors?;kotlin.Boolean;kotlin.Function1?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] -final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] +final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.foundation.layout/PaddingValues, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.foundation.layout.PaddingValues;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] final fun com.mohamedrejeb.richeditor.ui/ExpandableBasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/Boolean, kotlin/Function1, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Int, kotlin/String?, kotlin/String?, androidx.compose.ui.text/SpanStyle?, kotlin/Boolean, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/ExpandableBasicRichText|ExpandableBasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.Boolean;kotlin.Function1;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Int;kotlin.String?;kotlin.String?;androidx.compose.ui.text.SpanStyle?;kotlin.Boolean;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0] diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt index 1c5663c3..adf925f3 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockRendering.kt @@ -2,6 +2,7 @@ package com.mohamedrejeb.richeditor.model import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextRange import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi import com.mohamedrejeb.richeditor.highlight.CodeBlockColors @@ -10,6 +11,7 @@ import com.mohamedrejeb.richeditor.highlight.CodeLanguage import com.mohamedrejeb.richeditor.highlight.CodeToken import com.mohamedrejeb.richeditor.paragraph.RichParagraph import com.mohamedrejeb.richeditor.paragraph.codeBlockGroups +import com.mohamedrejeb.richeditor.paragraph.plainText import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock /** @@ -21,8 +23,24 @@ internal data class RenderedCodeBlock( val range: TextRange, val lastLineOffset: Int, val styles: List>, + val code: String, + val language: String?, ) +/** + * The first and last line of [block] in this layout, or null when none of it was laid out. + * maxLines and overflow stop a layout early, and asking it for a line past that point throws. + */ +internal fun TextLayoutResult.linesOf(block: RenderedCodeBlock): IntRange? { + val textLength = layoutInput.text.length + if (textLength == 0 || lineCount == 0) return null + val laidOutEnd = getLineEnd(lineCount - 1) + val lastOffset = if (laidOutEnd < textLength) laidOutEnd - 1 else laidOutEnd + if (block.range.min > lastOffset) return null + return getLineForOffset(block.range.min.coerceIn(0, lastOffset)).. + getLineForOffset(block.lastLineOffset.coerceIn(0, lastOffset)) +} + /** * Tokens of the blocks rendered last, so a rebuild that leaves a block's text alone (typing * elsewhere, a style change) does not tokenize it again. @@ -77,6 +95,8 @@ internal fun renderCodeBlocks( styles = cache.tokens(chars.concatToString(), language).map { token -> AnnotatedString.Range(colors.styleOf(token.kind), start + token.start, start + token.end) }, + code = group.joinToString("\n") { paragraphs[it].plainText() }, + language = language, ) } cache.keepOnlyUsed() diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt index 11a58c7b..08e97a4b 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt @@ -51,6 +51,7 @@ public fun BasicRichText( imageLoader: ImageLoader = LocalImageLoader.current, onTokenClick: TokenClickHandler? = null, onTokenHover: TokenHoverHandler? = null, + codeBlockAction: (@Composable (code: String, language: String?) -> Unit)? = null, ) { val density = LocalDensity.current val uriHandler = LocalUriHandler.current @@ -68,88 +69,90 @@ public fun BasicRichText( state.annotatedString.withCodeBlockStyles(state.renderedCodeBlocks).withHighlights(state.highlights) } - CompositionLocalProvider( - LocalImageLoader provides imageLoader, - LocalRichTextMaxImageWidthProvider provides maxImageWidthProvider, - ) { - BasicText( - text = text, - modifier = modifier - .drawRichSpanStyle(state) - .pointerHoverIcon(pointerIcon.value) - .pointerInput(state, effectiveTokenClick != null, effectiveTokenHover) { - var lastHoveredToken: RichSpanStyle.Token? = null - try { - awaitEachGesture { - val event = awaitPointerEvent() - val position = event.changes.first().position - val exited = event.type == PointerEventType.Exit + CodeBlockActionLayout(state = state, modifier = modifier, action = codeBlockAction) { textModifier -> + CompositionLocalProvider( + LocalImageLoader provides imageLoader, + LocalRichTextMaxImageWidthProvider provides maxImageWidthProvider, + ) { + BasicText( + text = text, + modifier = textModifier + .drawRichSpanStyle(state) + .pointerHoverIcon(pointerIcon.value) + .pointerInput(state, effectiveTokenClick != null, effectiveTokenHover) { + var lastHoveredToken: RichSpanStyle.Token? = null + try { + awaitEachGesture { + val event = awaitPointerEvent() + val position = event.changes.first().position + val exited = event.type == PointerEventType.Exit - val tokenUnderPointer = - if (exited) null else state.getTokenByOffset(position) - val isInteractive = !exited && ( - state.isLink(position) || - (effectiveTokenClick != null && tokenUnderPointer != null) - ) + val tokenUnderPointer = + if (exited) null else state.getTokenByOffset(position) + val isInteractive = !exited && ( + state.isLink(position) || + (effectiveTokenClick != null && tokenUnderPointer != null) + ) - pointerIcon.value = - if (isInteractive) - PointerIcon.Hand - else - PointerIcon.Default + pointerIcon.value = + if (isInteractive) + PointerIcon.Hand + else + PointerIcon.Default - if (effectiveTokenHover != null && tokenUnderPointer != lastHoveredToken) { - lastHoveredToken = tokenUnderPointer - effectiveTokenHover.invoke(tokenUnderPointer, position) + if (effectiveTokenHover != null && tokenUnderPointer != lastHoveredToken) { + lastHoveredToken = tokenUnderPointer + effectiveTokenHover.invoke(tokenUnderPointer, position) + } } - } - } catch (_: Exception) { + } catch (_: Exception) { + } } - } - .pointerInput(state, effectiveTokenClick) { - detectTapGestures( - onTap = { offset -> - val token = state.getTokenByOffset(offset) - if (token != null && effectiveTokenClick != null) { - effectiveTokenClick.invoke(token, offset) - return@detectTapGestures - } - state.getLinkByOffset(offset)?.let { url -> - try { - uriHandler.openUri(url) - } catch (e: Exception) { - e.printStackTrace() + .pointerInput(state, effectiveTokenClick) { + detectTapGestures( + onTap = { offset -> + val token = state.getTokenByOffset(offset) + if (token != null && effectiveTokenClick != null) { + effectiveTokenClick.invoke(token, offset) + return@detectTapGestures } - } - }, - consumeDown = { offset -> - state.isLink(offset) || - (effectiveTokenClick != null && state.isToken(offset)) - }, - ) - } - .onSizeChanged { size -> - val newWidth = with(density) { size.width.toSp() } - if (newWidth != maxImageWidthProvider.maxWidth) { - maxImageWidthProvider.maxWidth = newWidth + state.getLinkByOffset(offset)?.let { url -> + try { + uriHandler.openUri(url) + } catch (e: Exception) { + e.printStackTrace() + } + } + }, + consumeDown = { offset -> + state.isLink(offset) || + (effectiveTokenClick != null && state.isToken(offset)) + }, + ) } + .onSizeChanged { size -> + val newWidth = with(density) { size.width.toSp() } + if (newWidth != maxImageWidthProvider.maxWidth) { + maxImageWidthProvider.maxWidth = newWidth + } + }, + style = style, + onTextLayout = { + state.onTextLayout( + textLayoutResult = it, + density = density, + ) + onTextLayout(it) }, - style = style, - onTextLayout = { - state.onTextLayout( - textLayoutResult = it, - density = density, - ) - onTextLayout(it) - }, - overflow = overflow, - softWrap = softWrap, - maxLines = maxLines, - minLines = minLines, - inlineContent = remember(inlineContent, state.inlineContentMap.toMap()) { - inlineContent + state.inlineContentMap - } - ) + overflow = overflow, + softWrap = softWrap, + maxLines = maxLines, + minLines = minLines, + inlineContent = remember(inlineContent, state.inlineContentMap.toMap()) { + inlineContent + state.inlineContentMap + } + ) + } } } diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt new file mode 100644 index 00000000..5da46bb9 --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt @@ -0,0 +1,60 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.key +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.unit.Constraints +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.model.isForModelText +import com.mohamedrejeb.richeditor.model.linesOf +import kotlin.math.roundToInt + +/** + * Lays [text] out and puts [action] over the top end corner of each code block in it. A code + * block shares one text layout with the text around it, so the action is drawn over the block + * and takes no room of its own. Without an [action], [text] is emitted as it is. + */ +@Composable +internal fun CodeBlockActionLayout( + state: RichTextState, + modifier: Modifier, + action: (@Composable (code: String, language: String?) -> Unit)?, + text: @Composable (Modifier) -> Unit, +) { + if (action == null) { + text(modifier) + return + } + + val blocks = state.renderedCodeBlocks + Layout( + content = { + text(Modifier) + blocks.forEachIndexed { index, block -> + key(index) { Box { action(block.code, block.language) } } + } + }, + modifier = modifier, + ) { measurables, constraints -> + val textPlaceable = measurables.first().measure(constraints) + val actionConstraints = Constraints(maxWidth = textPlaceable.width, maxHeight = textPlaceable.height) + val actionPlaceables = measurables.drop(1).map { it.measure(actionConstraints) } + + layout(textPlaceable.width, textPlaceable.height) { + textPlaceable.placeRelative(0, 0) + val layoutResult = state.textLayoutResult + ?.takeIf { it.isForModelText(state.annotatedString.length) } + ?: return@layout + actionPlaceables.forEachIndexed { index, placeable -> + // A block that maxLines or overflow left out has no line to sit on and is not placed. + val lines = blocks.getOrNull(index)?.let { layoutResult.linesOf(it) } ?: return@forEachIndexed + placeable.placeRelative( + x = textPlaceable.width - placeable.width, + y = layoutResult.getLineTop(lines.first).roundToInt(), + ) + } + } + } +} diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt new file mode 100644 index 00000000..ec6066bf --- /dev/null +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt @@ -0,0 +1,63 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.graphics.vector.rememberVectorPainter +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.unit.dp + +internal const val CopyCodeDescription: String = "Copy code" + +/** A small button that copies [code] to the clipboard exactly as it is, line ends included. */ +@Composable +internal fun CodeBlockCopyButton(code: String, tint: Color) { + // The suspending LocalClipboard needs a ClipEntry, which has no common constructor. + @Suppress("DEPRECATION") + val clipboard = LocalClipboardManager.current + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .padding(2.dp) + .size(20.dp) + .clip(RoundedCornerShape(4.dp)) + .clickable(onClickLabel = CopyCodeDescription, role = Role.Button) { + clipboard.setText(AnnotatedString(code)) + }, + ) { + Image( + painter = rememberVectorPainter(CopyIcon), + contentDescription = CopyCodeDescription, + colorFilter = ColorFilter.tint(tint), + modifier = Modifier.size(14.dp), + ) + } +} + +private val CopyIcon: ImageVector = ImageVector.Builder( + name = "CopyCode", + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, +).addPath( + pathData = addPathNodes( + "M16,1L4,1c-1.1,0 -2,0.9 -2,2v14h2L4,3h12L16,1zM19,5L8,5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h11" + + "c1.1,0 2,-0.9 2,-2L21,7c0,-1.1 -0.9,-2 -2,-2zM19,21L8,21L8,7h11v14z" + ), + fill = SolidColor(Color.Black), +).build() diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt index 7a24787f..2b98f21e 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt @@ -12,6 +12,7 @@ import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi import com.mohamedrejeb.richeditor.model.RichSpanStyle import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.model.isForModelText +import com.mohamedrejeb.richeditor.model.linesOf import androidx.compose.ui.util.fastForEach @OptIn(ExperimentalRichTextApi::class) @@ -42,26 +43,14 @@ internal fun Modifier.drawRichSpanStyle( translate(top = -richTextState.scrollState.value.toFloat()) { richTextState.textLayoutResult?.let { textLayoutResult -> - val textLength = textLayoutResult.layoutInput.text.length - if ( - textLength > 0 && - textLayoutResult.lineCount > 0 && - textLayoutResult.isForModelText(richTextState.annotatedString.length) - ) { - // maxLines and overflow stop the layout early, and asking it for a line - // past what it laid out throws. - val laidOutEnd = textLayoutResult.getLineEnd(textLayoutResult.lineCount - 1) - val isCutOff = laidOutEnd < textLength - val lastOffset = if (isCutOff) laidOutEnd - 1 else laidOutEnd + if (textLayoutResult.isForModelText(richTextState.annotatedString.length)) { richTextState.renderedCodeBlocks.fastForEach { block -> - if (block.range.min > lastOffset) return@fastForEach - val firstLine = textLayoutResult.getLineForOffset(block.range.min.coerceIn(0, lastOffset)) - val lastLine = textLayoutResult.getLineForOffset(block.lastLineOffset.coerceIn(0, lastOffset)) - val top = textLayoutResult.getLineTop(firstLine) + val lines = textLayoutResult.linesOf(block) ?: return@fastForEach + val top = textLayoutResult.getLineTop(lines.first) drawRoundRect( color = richTextState.config.codeBlockBackgroundColor, topLeft = Offset(0f, top + topPadding), - size = Size(size.width, textLayoutResult.getLineBottom(lastLine) - top), + size = Size(size.width, textLayoutResult.getLineBottom(lines.last) - top), cornerRadius = CornerRadius(CodeBlockCornerRadius.toPx()), ) } diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt index 01d8b628..51b5bc7d 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt @@ -26,6 +26,7 @@ import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.model.TokenClickHandler import com.mohamedrejeb.richeditor.model.TokenHoverHandler import com.mohamedrejeb.richeditor.ui.BasicRichText +import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton /** * High-level element that displays rich text and provides semantics / accessibility information. @@ -64,6 +65,8 @@ import com.mohamedrejeb.richeditor.ui.BasicRichText * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw selection around the text. * @param style Style configuration for the text such as color, font, line height etc. + * @param showCodeBlockCopyButton when true, each code block has a button at its top end corner that + * copies its code to the clipboard. */ @OptIn(ExperimentalRichTextApi::class) @Composable @@ -89,6 +92,7 @@ public fun RichText( imageLoader: ImageLoader = LocalImageLoader.current, onTokenClick: TokenClickHandler? = null, onTokenHover: TokenHoverHandler? = null, + showCodeBlockCopyButton: Boolean = false, ) { val textColor = color.takeOrElse { style.color.takeOrElse { @@ -123,5 +127,8 @@ public fun RichText( imageLoader = imageLoader, onTokenClick = onTokenClick, onTokenHover = onTokenHover, + codeBlockAction = + if (showCodeBlockCopyButton) { code, _ -> CodeBlockCopyButton(code = code, tint = textColor) } + else null, ) } \ No newline at end of file diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt index ee129d81..8343ad98 100644 --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt @@ -25,6 +25,7 @@ import com.mohamedrejeb.richeditor.model.RichTextState import com.mohamedrejeb.richeditor.model.TokenClickHandler import com.mohamedrejeb.richeditor.model.TokenHoverHandler import com.mohamedrejeb.richeditor.ui.BasicRichText +import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton /** * High-level element that displays rich text and provides semantics / accessibility information. @@ -63,6 +64,8 @@ import com.mohamedrejeb.richeditor.ui.BasicRichText * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw selection around the text. * @param style style configuration for the text such as color, font, line height etc. + * @param showCodeBlockCopyButton when true, each code block has a button at its top end corner that + * copies its code to the clipboard. */ @OptIn(ExperimentalRichTextApi::class) @Composable @@ -88,6 +91,7 @@ public fun RichText( imageLoader: ImageLoader = LocalImageLoader.current, onTokenClick: TokenClickHandler? = null, onTokenHover: TokenHoverHandler? = null, + showCodeBlockCopyButton: Boolean = false, ) { val textColor = color.takeOrElse { style.color.takeOrElse { @@ -122,5 +126,8 @@ public fun RichText( imageLoader = imageLoader, onTokenClick = onTokenClick, onTokenHover = onTokenHover, + codeBlockAction = + if (showCodeBlockCopyButton) { code, _ -> CodeBlockCopyButton(code = code, tint = textColor) } + else null, ) } \ No newline at end of file diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt new file mode 100644 index 00000000..604c2d7f --- /dev/null +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt @@ -0,0 +1,185 @@ +package com.mohamedrejeb.richeditor.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ClipboardManager +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotDisplayed +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.unit.dp +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi +import com.mohamedrejeb.richeditor.model.RichTextState +import com.mohamedrejeb.richeditor.ui.material3.RichText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +/** + * The action drawn at the top end corner of each code block in the read-only text, and the copy + * button the Material text puts there. + */ +@OptIn(ExperimentalTestApi::class, ExperimentalRichTextApi::class) +class CodeBlockActionTest { + + private val markdown = "Intro\n\n```kotlin\nval a = 1\n val b = 2\n```\n\nBetween\n\n```\nplain\n```" + + private class FakeClipboardManager : ClipboardManager { + var copied: AnnotatedString? = null + + override fun getText(): AnnotatedString? = copied + + override fun setText(annotatedString: AnnotatedString) { + copied = annotatedString + } + } + + @Test + fun `the action is given the code and language of each block`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + val seen = mutableListOf>() + setContent { + BasicRichText( + state = state, + modifier = Modifier.fillMaxWidth(), + codeBlockAction = { code, language -> + seen += code to language + Box(Modifier.size(20.dp).testTag(ACTION_TAG)) + }, + ) + } + waitForIdle() + + assertEquals( + setOf("val a = 1\n val b = 2" to "kotlin", "plain" to null), + seen.toSet(), + ) + onAllNodesWithTag(ACTION_TAG).assertCountEquals(2) + } + + @Test + fun `each action sits at the top end corner of its block`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + var layout: TextLayoutResult? = null + setContent { + Box(Modifier.width(300.dp)) { + BasicRichText( + state = state, + modifier = Modifier.fillMaxWidth().testTag(TEXT_TAG), + onTextLayout = { layout = it }, + codeBlockAction = { _, _ -> Box(Modifier.size(20.dp).testTag(ACTION_TAG)) }, + ) + } + } + waitForIdle() + + val lines = assertNotNull(layout) + val text = onNodeWithTag(TEXT_TAG).getUnclippedBoundsInRoot() + val actions = onAllNodesWithTag(ACTION_TAG) + // Line 0 is the intro, lines 1 and 2 the first block, line 3 the text between, line 4 the second block. + listOf(0 to 1, 1 to 4).forEach { (index, line) -> + val bounds = actions[index].getUnclippedBoundsInRoot() + assertEquals(text.right, bounds.right, "action $index ends at the end edge") + assertEquals(text.top.value + lines.getLineTop(line), bounds.top.value, 1f, "action $index starts at its block's first line") + } + } + + @Test + fun `text without a block has no action`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown("just text") } + setContent { + BasicRichText(state = state, codeBlockAction = { _, _ -> Box(Modifier.size(20.dp).testTag(ACTION_TAG)) }) + } + waitForIdle() + + onAllNodesWithTag(ACTION_TAG).assertCountEquals(0) + } + + @Test + fun `a block left out by maxLines shows no action`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + setContent { + BasicRichText( + state = state, + modifier = Modifier.fillMaxWidth(), + maxLines = 3, + codeBlockAction = { _, _ -> Box(Modifier.size(20.dp).testTag(ACTION_TAG)) }, + ) + } + waitForIdle() + + // The second block is past the third line: its action is composed but never placed. + val actions = onAllNodesWithTag(ACTION_TAG) + actions[0].assertIsDisplayed() + actions[1].assertIsNotDisplayed() + } + + @Test + fun `the action follows the blocks when the text changes`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown("just text") } + setContent { + BasicRichText(state = state, codeBlockAction = { _, _ -> Box(Modifier.size(20.dp).testTag(ACTION_TAG)) }) + } + waitForIdle() + + state.setMarkdown(markdown) + waitForIdle() + onAllNodesWithTag(ACTION_TAG).assertCountEquals(2) + + state.setMarkdown("```\nonly\n```") + waitForIdle() + onAllNodesWithTag(ACTION_TAG).assertCountEquals(1) + } + + @Test + fun `the copy button copies the exact code of its block`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown + "\n\nEnd") } + val clipboard = FakeClipboardManager() + setContent { + CompositionLocalProvider(LocalClipboardManager provides clipboard) { + RichText(state = state, modifier = Modifier.fillMaxWidth(), showCodeBlockCopyButton = true) + } + } + waitForIdle() + + val buttons = onAllNodesWithContentDescription(COPY_DESCRIPTION) + buttons.assertCountEquals(2) + + buttons[0].performClick() + waitForIdle() + assertEquals("val a = 1\n val b = 2", clipboard.copied?.text) + + buttons[1].performClick() + waitForIdle() + assertEquals("plain", clipboard.copied?.text) + } + + @Test + fun `the copy button is off by default`() = runDesktopComposeUiTest { + val state = RichTextState().apply { setMarkdown(markdown) } + setContent { RichText(state = state) } + waitForIdle() + + onAllNodesWithContentDescription(COPY_DESCRIPTION).assertCountEquals(0) + } + + private companion object { + const val ACTION_TAG = "action" + const val TEXT_TAG = "text" + const val COPY_DESCRIPTION = "Copy code" + } +} diff --git a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt index b03f0d52..4be01584 100644 --- a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt +++ b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt @@ -112,7 +112,7 @@ fun CodeBlocksSampleScreen(navigateBack: () -> Unit) { ) { Spacer(Modifier.height(8.dp)) - SectionTitle("Markdown with code blocks", "RichText draws fenced code coloured by its language.") + SectionTitle("Markdown with code blocks", "RichText draws fenced code coloured by its language, with a copy button on each block.") val state = remember(scheme, colors) { RichTextState().apply { config.codeBlockBackgroundColor = scheme.surfaceVariant @@ -120,7 +120,7 @@ fun CodeBlocksSampleScreen(navigateBack: () -> Unit) { setMarkdown(replyMarkdown) } } - RichText(state = state, modifier = Modifier.fillMaxWidth()) + RichText(state = state, modifier = Modifier.fillMaxWidth(), showCodeBlockCopyButton = true) SectionTitle("Code alone", "BasicCodeText needs no state. A long line scrolls sideways.") BasicCodeText( From a5635095e3e0771a1c8ffa3b8c692c04672652fb Mon Sep 17 00:00:00 2001 From: MohamedRejeb Date: Fri, 9 Oct 2026 11:59:21 +0100 Subject: [PATCH 15/16] feat: customizable code block copy button, block spacing and editor background fixes --- docs/code_blocks.md | 48 +++++--- .../api/desktop/richeditor-compose.api | 8 +- .../api/richeditor-compose.klib.api | 9 +- .../richeditor/model/RichTextState.kt | 11 +- .../richeditor/paragraph/CodeBlocks.kt | 39 ++++++ .../richeditor/ui/BasicRichTextEditor.kt | 3 + .../richeditor/ui/CodeBlockActionLayout.kt | 2 +- .../richeditor/ui/CodeBlockCopyButton.kt | 33 ++++- .../mohamedrejeb/richeditor/ui/ModifierExt.kt | 46 +++++-- .../richeditor/ui/material/RichText.kt | 11 +- .../richeditor/ui/material3/RichText.kt | 11 +- .../richeditor/ui/CodeBlockActionTest.kt | 62 +++++++++- .../richeditor/ui/CodeBlockRenderTest.kt | 115 ++++++++++++++++++ .../codeblocks/CodeBlocksSampleScreen.kt | 7 +- 14 files changed, 344 insertions(+), 61 deletions(-) diff --git a/docs/code_blocks.md b/docs/code_blocks.md index 43c7472a..d6c95ff8 100644 --- a/docs/code_blocks.md +++ b/docs/code_blocks.md @@ -82,34 +82,49 @@ block, where those marks are code. ### Copy button -A read-only `RichText` can show a copy button at the top end corner of each code block. It copies -the block's code exactly, line ends and indentation included: +A read-only `RichText` can draw an action at the top end corner of each code block. Pass +`CodeBlockCopyButton` to get a button that copies the block's code exactly, line ends and +indentation included: ```kotlin RichText( state = state, modifier = Modifier.fillMaxWidth(), - showCodeBlockCopyButton = true, + codeBlockAction = { code, language -> CodeBlockCopyButton(code) }, ) ``` -The Material and Material3 `RichText` both have the option, and it is off by default. For a -button of your own, or any other action, `BasicRichText` takes a slot that is given the code and -the language of each block: +`BasicRichText` and the Material and Material3 `RichText` all take `codeBlockAction`. It is given +the code and the language of the block, and nothing is drawn when it is null, which is the +default. + +`CodeBlockCopyButton` can be adjusted: + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `code` | `String` | required | The code to copy | +| `modifier` | `Modifier` | `Modifier` | Applied to the button | +| `tint` | `Color` | mid-tone grey | The colour of the icon | +| `contentDescription` | `String` | `"Copy code"` | What accessibility services call the button. Pass a translated string for other languages | +| `onCopied` | `() -> Unit` | `{}` | Called after the copy, for example to show a "Copied" message | ```kotlin -BasicRichText( - state = state, - modifier = Modifier.fillMaxWidth(), - codeBlockAction = { code, language -> - MyCopyButton(onClick = { copyToClipboard(code) }) - }, -) +codeBlockAction = { code, _ -> + CodeBlockCopyButton( + code = code, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + contentDescription = stringResource(Res.string.copy_code), + onCopied = { showCopiedMessage() }, + ) +} ``` +The slot takes any composable, so the action can also be a button of your own, a language label, +or both in a `Row`. + The action is drawn over the corner of the block and takes no room of its own, so keep it about one line tall: on a block with a long first line it covers the end of that line. The editors do -not have this option. +not draw it. ### Customizing @@ -247,7 +262,10 @@ its language tag on export. - Markup inside an HTML `
          ` is read as plain code. Code copied from an IDE arrives as a
             `
          ` with coloured spans and no language, so it is pasted as a code block without colours.
           - A code block inside a list item or a quote is moved to the top level.
          -- A block has no space of its own above or below it, and two blocks in a row touch.
          +- The room above and below a block comes from a taller first and last line, because a text
          +  layout has no space between paragraphs. When the first or last line of a block is long enough
          +  to wrap, its wrapped lines are spaced a little wider than the rest. A one-line block that wraps
          +  shows this most.
           - In Markdown, an empty paragraph directly after a block is not kept on a round trip.
           - Text selected in a read-only `RichText` inside a `SelectionContainer` is copied with a space
             between paragraphs, so code selected that way loses its line ends. Copy and cut in the editors
          diff --git a/richeditor-compose/api/desktop/richeditor-compose.api b/richeditor-compose/api/desktop/richeditor-compose.api
          index e49645e8..e661999e 100644
          --- a/richeditor-compose/api/desktop/richeditor-compose.api
          +++ b/richeditor-compose/api/desktop/richeditor-compose.api
          @@ -1025,6 +1025,10 @@ public final class com/mohamedrejeb/richeditor/ui/BasicRichTextKt {
           	public static final fun BasicRichText-Kj_y3YE (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lkotlin/jvm/functions/Function1;IZIILjava/util/Map;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;III)V
           }
           
          +public final class com/mohamedrejeb/richeditor/ui/CodeBlockCopyButtonKt {
          +	public static final fun CodeBlockCopyButton-T042LqI (Ljava/lang/String;Landroidx/compose/ui/Modifier;JLjava/lang/String;Lkotlin/jvm/functions/Function0;Landroidx/compose/runtime/Composer;II)V
          +}
          +
           public final class com/mohamedrejeb/richeditor/ui/ComposableSingletons$BasicRichTextEditorKt {
           	public static final field INSTANCE Lcom/mohamedrejeb/richeditor/ui/ComposableSingletons$BasicRichTextEditorKt;
           	public fun  ()V
          @@ -1053,7 +1057,7 @@ public final class com/mohamedrejeb/richeditor/ui/material/RichTextEditorKt {
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material/RichTextKt {
          -	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;ZLandroidx/compose/runtime/Composer;IIII)V
          +	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;IIII)V
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material3/ExpandableRichTextKt {
          @@ -1102,7 +1106,7 @@ public final class com/mohamedrejeb/richeditor/ui/material3/RichTextEditorKt {
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material3/RichTextKt {
          -	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;ZLandroidx/compose/runtime/Composer;IIII)V
          +	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;IIII)V
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material3/TriggerSuggestionsKt {
          diff --git a/richeditor-compose/api/richeditor-compose.klib.api b/richeditor-compose/api/richeditor-compose.klib.api
          index 73d25e38..cd31b157 100644
          --- a/richeditor-compose/api/richeditor-compose.klib.api
          +++ b/richeditor-compose/api/richeditor-compose.klib.api
          @@ -1323,13 +1323,13 @@ final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor
           final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter|com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter|com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          -final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          -final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/Boolean, kotlin/Function1, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, androidx.compose.ui.graphics/Color, kotlin/Int, kotlin/String?, kotlin/String?, androidx.compose.ui.graphics/Color, kotlin/Boolean, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText|ExpandableRichText(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.Boolean;kotlin.Function1;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;androidx.compose.ui.graphics.Color;kotlin.Int;kotlin.String?;kotlin.String?;androidx.compose.ui.graphics.Color;kotlin.Boolean;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          -final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          -final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Boolean, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Boolean;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(){}[0]
          @@ -1338,6 +1338,7 @@ final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richedit
           final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.foundation.layout/PaddingValues, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.foundation.layout.PaddingValues;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui/CodeBlockCopyButton(kotlin/String, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, kotlin/String?, kotlin/Function0?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/CodeBlockCopyButton|CodeBlockCopyButton(kotlin.String;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;kotlin.String?;kotlin.Function0?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/ExpandableBasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/Boolean, kotlin/Function1, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Int, kotlin/String?, kotlin/String?, androidx.compose.ui.text/SpanStyle?, kotlin/Boolean, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/ExpandableBasicRichText|ExpandableBasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.Boolean;kotlin.Function1;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Int;kotlin.String?;kotlin.String?;androidx.compose.ui.text.SpanStyle?;kotlin.Boolean;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/com_mohamedrejeb_richeditor_ui_TruncationPhase_Fits$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui/com_mohamedrejeb_richeditor_ui_TruncationPhase_Fits$stableprop_getter|com_mohamedrejeb_richeditor_ui_TruncationPhase_Fits$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui/com_mohamedrejeb_richeditor_ui_TruncationPhase_NeedsMeasure$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui/com_mohamedrejeb_richeditor_ui_TruncationPhase_NeedsMeasure$stableprop_getter|com_mohamedrejeb_richeditor_ui_TruncationPhase_NeedsMeasure$stableprop_getter(){}[0]
          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 aa0eee9a..161410d5 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
          @@ -48,6 +48,7 @@ import com.mohamedrejeb.richeditor.model.trigger.detectActiveTrigger
           import com.mohamedrejeb.richeditor.paragraph.RichParagraph
           import com.mohamedrejeb.richeditor.paragraph.asCodeLinesOf
           import com.mohamedrejeb.richeditor.paragraph.baseSpanStyle
          +import com.mohamedrejeb.richeditor.paragraph.codeBlockEdgeStyle
           import com.mohamedrejeb.richeditor.paragraph.type.*
           import com.mohamedrejeb.richeditor.platform.currentPlatform
           import com.mohamedrejeb.richeditor.paragraph.type.ParagraphType.Companion.startText
          @@ -3391,14 +3392,16 @@ public class RichTextState internal constructor(
                * [RichTextConfig.headingTextStyles] takes the paragraph part of that style underneath
                * its own, so an alignment set on the heading itself still wins.
                */
          -    private fun renderedParagraphStyle(richParagraph: RichParagraph): ParagraphStyle {
          +    private fun renderedParagraphStyle(richParagraph: RichParagraph, index: Int): ParagraphStyle {
                   val headingTextStyle = config.headingTextStyleFor(richParagraph.headingStyle)
                   val paragraphStyle =
                       if (headingTextStyle == null)
                           richParagraph.paragraphStyle
                       else
                           headingTextStyle.toParagraphStyle().merge(richParagraph.paragraphStyle)
          -        return paragraphStyle.merge(richParagraph.type.getStyle(config))
          +        return paragraphStyle
          +            .merge(richParagraph.type.getStyle(config))
          +            .merge(richParagraphList.codeBlockEdgeStyle(index))
               }
           
               private inner class HistoryHostImpl : RichTextHistoryHost {
          @@ -3599,7 +3602,7 @@ public class RichTextState internal constructor(
                           }
           
                           val headingSpanStyle = config.headingSpanStyleFor(richParagraph.headingStyle)
          -                withStyle(renderedParagraphStyle(richParagraph)) {
          +                withStyle(renderedParagraphStyle(richParagraph, i)) {
                               withStyle(
                                   richParagraph.getListMarkerSpanStyle(
                                       config.listMarkerStyleBehavior,
          @@ -6332,7 +6335,7 @@ public class RichTextState internal constructor(
                       var index = 0
                       richParagraphList.fastForEachIndexed { i, richParagraph ->
                           val headingSpanStyle = config.headingSpanStyleFor(richParagraph.headingStyle)
          -                withStyle(renderedParagraphStyle(richParagraph)) {
          +                withStyle(renderedParagraphStyle(richParagraph, i)) {
                               withStyle(
                                   richParagraph.getListMarkerSpanStyle(
                                       config.listMarkerStyleBehavior,
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt
          index 4480b311..7fec779a 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/paragraph/CodeBlocks.kt
          @@ -1,6 +1,9 @@
           package com.mohamedrejeb.richeditor.paragraph
           
          +import androidx.compose.ui.text.ParagraphStyle
           import androidx.compose.ui.text.SpanStyle
          +import androidx.compose.ui.text.style.LineHeightStyle
          +import androidx.compose.ui.unit.em
           import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
           import com.mohamedrejeb.richeditor.model.RichSpan
           import com.mohamedrejeb.richeditor.model.RichSpanStyle
          @@ -57,3 +60,39 @@ internal fun List.asCodeLinesOf(type: CodeBlock): List.codeBlockEdgeStyle(index: Int): ParagraphStyle? {
          +    val type = getOrNull(index)?.type as? CodeBlock ?: return null
          +    val isFirst = type.isBlockStart || getOrNull(index - 1)?.type !is CodeBlock
          +    val next = getOrNull(index + 1)?.type as? CodeBlock
          +    val isLast = next == null || next.isBlockStart
          +    return when {
          +        isFirst && isLast -> CodeBlockOnlyLineStyle
          +        isFirst -> CodeBlockFirstLineStyle
          +        isLast -> CodeBlockLastLineStyle
          +        else -> null
          +    }
          +}
          +
          +private val CodeBlockEdgeLineHeight = 1.75.em
          +private val CodeBlockOnlyLineHeight = 2.1.em
          +
          +private val CodeBlockFirstLineStyle = ParagraphStyle(
          +    lineHeight = CodeBlockEdgeLineHeight,
          +    lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Bottom, LineHeightStyle.Trim.None),
          +)
          +
          +private val CodeBlockLastLineStyle = ParagraphStyle(
          +    lineHeight = CodeBlockEdgeLineHeight,
          +    lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Top, LineHeightStyle.Trim.None),
          +)
          +
          +private val CodeBlockOnlyLineStyle = ParagraphStyle(
          +    lineHeight = CodeBlockOnlyLineHeight,
          +    lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.None),
          +)
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichTextEditor.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichTextEditor.kt
          index 869a3f3c..dd87b51a 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichTextEditor.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichTextEditor.kt
          @@ -5,6 +5,7 @@ import androidx.compose.foundation.interaction.Interaction
           import androidx.compose.foundation.interaction.MutableInteractionSource
           import androidx.compose.foundation.interaction.PressInteraction
           import androidx.compose.foundation.layout.PaddingValues
          +import androidx.compose.foundation.layout.calculateEndPadding
           import androidx.compose.foundation.layout.calculateStartPadding
           import androidx.compose.foundation.text.BasicTextField
           import androidx.compose.foundation.text.KeyboardActionScope
          @@ -384,6 +385,8 @@ public fun BasicRichTextEditor(
                               richTextState = state,
                               topPadding = with(density) { contentPadding.calculateTopPadding().toPx() },
                               startPadding = with(density) { contentPadding.calculateStartPadding(layoutDirection).toPx() },
          +                    endPadding = with(density) { contentPadding.calculateEndPadding(layoutDirection).toPx() },
          +                    bottomPadding = with(density) { contentPadding.calculateBottomPadding().toPx() },
                           )
                           .then(
                               if (singleParagraph)
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt
          index 5da46bb9..2ca7964c 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionLayout.kt
          @@ -52,7 +52,7 @@ internal fun CodeBlockActionLayout(
                           val lines = blocks.getOrNull(index)?.let { layoutResult.linesOf(it) } ?: return@forEachIndexed
                           placeable.placeRelative(
                               x = textPlaceable.width - placeable.width,
          -                    y = layoutResult.getLineTop(lines.first).roundToInt(),
          +                    y = (layoutResult.getLineTop(lines.first) + CodeBlockVerticalGap.toPx()).roundToInt(),
                           )
                       }
                   }
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt
          index ec6066bf..b5895a43 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockCopyButton.kt
          @@ -20,28 +20,49 @@ import androidx.compose.ui.platform.LocalClipboardManager
           import androidx.compose.ui.semantics.Role
           import androidx.compose.ui.text.AnnotatedString
           import androidx.compose.ui.unit.dp
          +import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
           
          -internal const val CopyCodeDescription: String = "Copy code"
          +private const val CopyCodeDescription: String = "Copy code"
           
          -/** A small button that copies [code] to the clipboard exactly as it is, line ends included. */
          +/** A mid-tone grey that stays visible on light and dark backgrounds. */
          +private val DefaultTint: Color = Color(0xFF8A8F98)
          +
          +/**
          + * A small button that copies [code] to the clipboard exactly as it is, line ends and
          + * indentation included. It is about one line of code tall, so it fits the corner of a code
          + * block: pass it as the `codeBlockAction` of [BasicRichText] or of the Material `RichText`.
          + *
          + * @param tint the colour of the icon.
          + * @param contentDescription what accessibility services call the button. Pass a translated
          + * string for other languages.
          + * @param onCopied called after the code was copied, to show feedback.
          + */
          +@ExperimentalRichTextApi
           @Composable
          -internal fun CodeBlockCopyButton(code: String, tint: Color) {
          +public fun CodeBlockCopyButton(
          +    code: String,
          +    modifier: Modifier = Modifier,
          +    tint: Color = DefaultTint,
          +    contentDescription: String = CopyCodeDescription,
          +    onCopied: () -> Unit = {},
          +) {
               // The suspending LocalClipboard needs a ClipEntry, which has no common constructor.
               @Suppress("DEPRECATION")
               val clipboard = LocalClipboardManager.current
               Box(
                   contentAlignment = Alignment.Center,
          -        modifier = Modifier
          +        modifier = modifier
                       .padding(2.dp)
                       .size(20.dp)
                       .clip(RoundedCornerShape(4.dp))
          -            .clickable(onClickLabel = CopyCodeDescription, role = Role.Button) {
          +            .clickable(onClickLabel = contentDescription, role = Role.Button) {
                           clipboard.setText(AnnotatedString(code))
          +                onCopied()
                       },
               ) {
                   Image(
                       painter = rememberVectorPainter(CopyIcon),
          -            contentDescription = CopyCodeDescription,
          +            contentDescription = contentDescription,
                       colorFilter = ColorFilter.tint(tint),
                       modifier = Modifier.size(14.dp),
                   )
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          index 2b98f21e..bc9e9549 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          @@ -5,6 +5,7 @@ import androidx.compose.ui.draw.drawBehind
           import androidx.compose.ui.geometry.CornerRadius
           import androidx.compose.ui.geometry.Offset
           import androidx.compose.ui.geometry.Size
          +import androidx.compose.ui.graphics.drawscope.clipRect
           import androidx.compose.ui.graphics.drawscope.translate
           import androidx.compose.ui.text.TextRange
           import androidx.compose.ui.unit.dp
          @@ -20,6 +21,8 @@ internal fun Modifier.drawRichSpanStyle(
               richTextState: RichTextState,
               topPadding: Float = 0f,
               startPadding: Float = 0f,
          +    endPadding: Float = 0f,
          +    bottomPadding: Float = 0f,
           ): Modifier {
               return this
                   .drawBehind {
          @@ -41,21 +44,37 @@ internal fun Modifier.drawRichSpanStyle(
                               styledRichSpanList.add(richSpan.richSpanStyle to TextRange(richSpan.textRange.start, end))
                       }
           
          -            translate(top = -richTextState.scrollState.value.toFloat()) {
          -                richTextState.textLayoutResult?.let { textLayoutResult ->
          -                    if (textLayoutResult.isForModelText(richTextState.annotatedString.length)) {
          -                        richTextState.renderedCodeBlocks.fastForEach { block ->
          -                            val lines = textLayoutResult.linesOf(block) ?: return@fastForEach
          -                            val top = textLayoutResult.getLineTop(lines.first)
          -                            drawRoundRect(
          -                                color = richTextState.config.codeBlockBackgroundColor,
          -                                topLeft = Offset(0f, top + topPadding),
          -                                size = Size(size.width, textLayoutResult.getLineBottom(lines.last) - top),
          -                                cornerRadius = CornerRadius(CodeBlockCornerRadius.toPx()),
          -                            )
          +            // A block is as wide as the text area, and one scrolled partly out of an editor
          +            // must not paint over the padding around that area.
          +            clipRect(
          +                left = startPadding,
          +                top = topPadding,
          +                right = size.width - endPadding,
          +                bottom = size.height - bottomPadding,
          +            ) {
          +                translate(top = -richTextState.scrollState.value.toFloat()) {
          +                    richTextState.textLayoutResult?.let { textLayoutResult ->
          +                        if (textLayoutResult.isForModelText(richTextState.annotatedString.length)) {
          +                            richTextState.renderedCodeBlocks.fastForEach { block ->
          +                                val lines = textLayoutResult.linesOf(block) ?: return@fastForEach
          +                                val gap = CodeBlockVerticalGap.toPx()
          +                                val top = textLayoutResult.getLineTop(lines.first) + gap
          +                                drawRoundRect(
          +                                    color = richTextState.config.codeBlockBackgroundColor,
          +                                    topLeft = Offset(startPadding, top + topPadding),
          +                                    size = Size(
          +                                        width = size.width - startPadding - endPadding,
          +                                        height = textLayoutResult.getLineBottom(lines.last) - gap - top,
          +                                    ),
          +                                    cornerRadius = CornerRadius(CodeBlockCornerRadius.toPx()),
          +                                )
          +                            }
                                   }
                               }
                           }
          +            }
          +
          +            translate(top = -richTextState.scrollState.value.toFloat()) {
                           styledRichSpanList.fastForEach { (style, textRange) ->
                               richTextState.textLayoutResult?.let { textLayoutResult ->
                                   with(style) {
          @@ -76,3 +95,6 @@ internal fun Modifier.drawRichSpanStyle(
           }
           
           private val CodeBlockCornerRadius = 8.dp
          +
          +/** Left clear above and below a block's background, inside the room its first and last line make. */
          +internal val CodeBlockVerticalGap = 2.dp
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          index 51b5bc7d..c52a889a 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          @@ -26,7 +26,6 @@ import com.mohamedrejeb.richeditor.model.RichTextState
           import com.mohamedrejeb.richeditor.model.TokenClickHandler
           import com.mohamedrejeb.richeditor.model.TokenHoverHandler
           import com.mohamedrejeb.richeditor.ui.BasicRichText
          -import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton
           
           /**
            * High-level element that displays rich text and provides semantics / accessibility information.
          @@ -65,8 +64,8 @@ import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton
            * text, baselines and other details. The callback can be used to add additional decoration or
            * functionality to the text. For example, to draw selection around the text.
            * @param style Style configuration for the text such as color, font, line height etc.
          - * @param showCodeBlockCopyButton when true, each code block has a button at its top end corner that
          - * copies its code to the clipboard.
          + * @param codeBlockAction drawn over the top end corner of each code block and given its code and
          + * language, for example a `CodeBlockCopyButton`. Null draws nothing.
            */
           @OptIn(ExperimentalRichTextApi::class)
           @Composable
          @@ -92,7 +91,7 @@ public fun RichText(
               imageLoader: ImageLoader = LocalImageLoader.current,
               onTokenClick: TokenClickHandler? = null,
               onTokenHover: TokenHoverHandler? = null,
          -    showCodeBlockCopyButton: Boolean = false,
          +    codeBlockAction: (@Composable (code: String, language: String?) -> Unit)? = null,
           ) {
               val textColor = color.takeOrElse {
                   style.color.takeOrElse {
          @@ -127,8 +126,6 @@ public fun RichText(
                   imageLoader = imageLoader,
                   onTokenClick = onTokenClick,
                   onTokenHover = onTokenHover,
          -        codeBlockAction =
          -            if (showCodeBlockCopyButton) { code, _ -> CodeBlockCopyButton(code = code, tint = textColor) }
          -            else null,
          +        codeBlockAction = codeBlockAction,
               )
           }
          \ No newline at end of file
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          index 8343ad98..2c95fe02 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          @@ -25,7 +25,6 @@ import com.mohamedrejeb.richeditor.model.RichTextState
           import com.mohamedrejeb.richeditor.model.TokenClickHandler
           import com.mohamedrejeb.richeditor.model.TokenHoverHandler
           import com.mohamedrejeb.richeditor.ui.BasicRichText
          -import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton
           
           /**
            * High-level element that displays rich text and provides semantics / accessibility information.
          @@ -64,8 +63,8 @@ import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton
            * text, baselines and other details. The callback can be used to add additional decoration or
            * functionality to the text. For example, to draw selection around the text.
            * @param style style configuration for the text such as color, font, line height etc.
          - * @param showCodeBlockCopyButton when true, each code block has a button at its top end corner that
          - * copies its code to the clipboard.
          + * @param codeBlockAction drawn over the top end corner of each code block and given its code and
          + * language, for example a `CodeBlockCopyButton`. Null draws nothing.
            */
           @OptIn(ExperimentalRichTextApi::class)
           @Composable
          @@ -91,7 +90,7 @@ public fun RichText(
               imageLoader: ImageLoader = LocalImageLoader.current,
               onTokenClick: TokenClickHandler? = null,
               onTokenHover: TokenHoverHandler? = null,
          -    showCodeBlockCopyButton: Boolean = false,
          +    codeBlockAction: (@Composable (code: String, language: String?) -> Unit)? = null,
           ) {
               val textColor = color.takeOrElse {
                   style.color.takeOrElse {
          @@ -126,8 +125,6 @@ public fun RichText(
                   imageLoader = imageLoader,
                   onTokenClick = onTokenClick,
                   onTokenHover = onTokenHover,
          -        codeBlockAction =
          -            if (showCodeBlockCopyButton) { code, _ -> CodeBlockCopyButton(code = code, tint = textColor) }
          -            else null,
          +        codeBlockAction = codeBlockAction,
               )
           }
          \ No newline at end of file
          diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt
          index 604c2d7f..4d533022 100644
          --- a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt
          +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockActionTest.kt
          @@ -1,6 +1,7 @@
           package com.mohamedrejeb.richeditor.ui
           
           import androidx.compose.foundation.layout.Box
          +import androidx.compose.foundation.layout.Column
           import androidx.compose.foundation.layout.fillMaxWidth
           import androidx.compose.foundation.layout.size
           import androidx.compose.foundation.layout.width
          @@ -28,6 +29,7 @@ import com.mohamedrejeb.richeditor.ui.material3.RichText
           import kotlin.test.Test
           import kotlin.test.assertEquals
           import kotlin.test.assertNotNull
          +import kotlin.test.assertTrue
           
           /**
            * The action drawn at the top end corner of each code block in the read-only text, and the copy
          @@ -94,7 +96,9 @@ class CodeBlockActionTest {
                   listOf(0 to 1, 1 to 4).forEach { (index, line) ->
                       val bounds = actions[index].getUnclippedBoundsInRoot()
                       assertEquals(text.right, bounds.right, "action $index ends at the end edge")
          -            assertEquals(text.top.value + lines.getLineTop(line), bounds.top.value, 1f, "action $index starts at its block's first line")
          +            // The background, and the action with it, starts a little below the top of the line.
          +            val top = bounds.top.value - (text.top.value + lines.getLineTop(line))
          +            assertTrue(top in 0f..4f, "action $index starts at the top of its block, was $top below the line top")
                   }
               }
           
          @@ -151,7 +155,11 @@ class CodeBlockActionTest {
                   val clipboard = FakeClipboardManager()
                   setContent {
                       CompositionLocalProvider(LocalClipboardManager provides clipboard) {
          -                RichText(state = state, modifier = Modifier.fillMaxWidth(), showCodeBlockCopyButton = true)
          +                RichText(
          +                    state = state,
          +                    modifier = Modifier.fillMaxWidth(),
          +                    codeBlockAction = { code, _ -> CodeBlockCopyButton(code) },
          +                )
                       }
                   }
                   waitForIdle()
          @@ -168,6 +176,56 @@ class CodeBlockActionTest {
                   assertEquals("plain", clipboard.copied?.text)
               }
           
          +    @Test
          +    fun `the copy button takes a label of its own and reports the copy`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply { setMarkdown("```\nonly\n```\n\nEnd") }
          +        val clipboard = FakeClipboardManager()
          +        var copies = 0
          +        setContent {
          +            CompositionLocalProvider(LocalClipboardManager provides clipboard) {
          +                RichText(
          +                    state = state,
          +                    modifier = Modifier.fillMaxWidth(),
          +                    codeBlockAction = { code, _ ->
          +                        CodeBlockCopyButton(code = code, contentDescription = "Copier", onCopied = { copies++ })
          +                    },
          +                )
          +            }
          +        }
          +        waitForIdle()
          +
          +        onAllNodesWithContentDescription(COPY_DESCRIPTION).assertCountEquals(0)
          +        onAllNodesWithContentDescription("Copier")[0].performClick()
          +        waitForIdle()
          +
          +        assertEquals("only", clipboard.copied?.text)
          +        assertEquals(1, copies)
          +    }
          +
          +    @Test
          +    fun `the material texts take any action`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply { setMarkdown(markdown) }
          +        setContent {
          +            Column {
          +                RichText(
          +                    state = state,
          +                    modifier = Modifier.fillMaxWidth(),
          +                    codeBlockAction = { _, language -> Box(Modifier.size(20.dp).testTag("m3-" + language)) },
          +                )
          +                com.mohamedrejeb.richeditor.ui.material.RichText(
          +                    state = state,
          +                    modifier = Modifier.fillMaxWidth(),
          +                    codeBlockAction = { _, language -> Box(Modifier.size(20.dp).testTag("m2-" + language)) },
          +                )
          +            }
          +        }
          +        waitForIdle()
          +
          +        listOf("m3-kotlin", "m3-null", "m2-kotlin", "m2-null").forEach { tag ->
          +            onAllNodesWithTag(tag).assertCountEquals(1)
          +        }
          +    }
          +
               @Test
               fun `the copy button is off by default`() = runDesktopComposeUiTest {
                   val state = RichTextState().apply { setMarkdown(markdown) }
          diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt
          index 6df4d8bf..2c4cb85d 100644
          --- a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt
          +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt
          @@ -1,6 +1,9 @@
           package com.mohamedrejeb.richeditor.ui
           
           import androidx.compose.foundation.layout.Box
          +import androidx.compose.foundation.layout.PaddingValues
          +import androidx.compose.foundation.layout.height
          +import androidx.compose.foundation.layout.padding
           import androidx.compose.foundation.layout.fillMaxWidth
           import androidx.compose.foundation.layout.width
           import androidx.compose.runtime.LaunchedEffect
          @@ -26,6 +29,7 @@ import androidx.compose.ui.text.SpanStyle
           import androidx.compose.ui.text.TextLayoutResult
           import androidx.compose.ui.text.TextRange
           import androidx.compose.ui.text.font.FontFamily
          +import androidx.compose.ui.unit.IntRect
           import androidx.compose.ui.unit.dp
           import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
           import com.mohamedrejeb.richeditor.highlight.CodeBlockColors
          @@ -215,6 +219,117 @@ class CodeBlockRenderTest {
                   assertTrue(pixels.isRedAt(pixels.width - 12, lines.lineMiddle(1)), "the new empty line has the background")
               }
           
          +    @Test
          +    fun `a block has room above its first line and below its last`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply { setMarkdown("```\none\ntwo\nthree\n```") }
          +        var layout: TextLayoutResult? = null
          +        setContent { BasicRichText(state = state, onTextLayout = { layout = it }) }
          +        waitForIdle()
          +
          +        val lines = assertNotNull(layout)
          +        fun height(line: Int) = lines.getLineBottom(line) - lines.getLineTop(line)
          +        assertTrue(height(0) > height(1), "the first line is taller than a middle line")
          +        assertTrue(height(2) > height(1), "the last line is taller than a middle line")
          +        // The room is above the first line's text and below the last line's.
          +        assertTrue(lines.getLineBaseline(0) - lines.getLineTop(0) > lines.getLineBaseline(1) - lines.getLineTop(1))
          +        assertTrue(lines.getLineBottom(2) - lines.getLineBaseline(2) > lines.getLineBottom(1) - lines.getLineBaseline(1))
          +    }
          +
          +    @Test
          +    fun `two blocks in a row do not touch`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply {
          +            config.codeBlockBackgroundColor = Color.Red
          +            setMarkdown("```\none\n```\n```\ntwo\n```")
          +        }
          +        var layout: TextLayoutResult? = null
          +        setContent {
          +            Box(Modifier.width(200.dp)) {
          +                BasicRichText(
          +                    state = state,
          +                    modifier = Modifier.testTag(EDITOR_TAG).fillMaxWidth(),
          +                    onTextLayout = { layout = it },
          +                )
          +            }
          +        }
          +        waitForIdle()
          +
          +        val lines = assertNotNull(layout)
          +        val pixels = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap()
          +        val x = pixels.width / 2
          +        assertTrue(pixels.isRedAt(x, lines.lineMiddle(0)), "the first block is drawn")
          +        assertTrue(pixels.isRedAt(x, lines.lineMiddle(1)), "the second block is drawn")
          +        assertTrue(!pixels.isRedAt(x, lines.getLineBottom(0).toInt()), "there is a gap where the two blocks meet")
          +    }
          +
          +    @Test
          +    fun `the background stays inside the content padding of an editor`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply {
          +            config.codeBlockBackgroundColor = Color.Red
          +            setMarkdown("```\ncode\n```")
          +        }
          +        val horizontalPadding = PaddingValues(start = 16.dp, top = 12.dp, end = 24.dp, bottom = 12.dp)
          +        setContent {
          +            BasicRichTextEditor(
          +                state = state,
          +                modifier = Modifier.width(200.dp).testTag(EDITOR_TAG),
          +                decorationBox = { innerTextField -> Box(Modifier.padding(horizontalPadding)) { innerTextField() } },
          +                contentPadding = horizontalPadding,
          +            )
          +        }
          +        waitForIdle()
          +
          +        val red = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap().redBounds()
          +        assertEquals(16, red.left, "the background starts after the start padding")
          +        assertEquals(200 - 24, red.right, "the background ends before the end padding")
          +    }
          +
          +    @Test
          +    fun `a scrolled block is not drawn over the padding of an editor`() = runDesktopComposeUiTest {
          +        val state = RichTextState().apply {
          +            config.codeBlockBackgroundColor = Color.Red
          +            setMarkdown("```\n" + (1..30).joinToString("\n") { "line " + it } + "\n```")
          +        }
          +        setContent {
          +            val focusRequester = remember { FocusRequester() }
          +            BasicRichTextEditor(
          +                state = state,
          +                modifier = Modifier.width(200.dp).height(120.dp).focusRequester(focusRequester).testTag(EDITOR_TAG),
          +                decorationBox = { innerTextField -> Box(Modifier.padding(12.dp)) { innerTextField() } },
          +                contentPadding = PaddingValues(12.dp),
          +            )
          +            LaunchedEffect(Unit) { focusRequester.requestFocus() }
          +        }
          +        waitForIdle()
          +        state.textFieldState.edit { selection = TextRange(length / 2) }
          +        waitForIdle()
          +        onNodeWithTag(EDITOR_TAG).performTextInput("x")
          +        waitForIdle()
          +
          +        assertTrue(state.scrollState.value > 0, "the editor is scrolled")
          +        val red = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap().redBounds()
          +        assertEquals(12, red.top, "nothing is drawn over the top padding")
          +        assertEquals(120 - 12, red.bottom, "nothing is drawn over the bottom padding")
          +    }
          +
          +    /** The smallest rectangle holding every red pixel, right and bottom exclusive. */
          +    private fun PixelMap.redBounds(): IntRect {
          +        var left = width
          +        var top = height
          +        var right = 0
          +        var bottom = 0
          +        for (y in 0 until height) {
          +            for (x in 0 until width) {
          +                if (isRedAt(x, y)) {
          +                    left = minOf(left, x)
          +                    top = minOf(top, y)
          +                    right = maxOf(right, x + 1)
          +                    bottom = maxOf(bottom, y + 1)
          +                }
          +            }
          +        }
          +        return IntRect(left, top, right, bottom)
          +    }
          +
               private fun TextLayoutResult.lineMiddle(line: Int): Int = ((getLineTop(line) + getLineBottom(line)) / 2).toInt()
           
               private fun PixelMap.isRedAt(x: Int, y: Int): Boolean {
          diff --git a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt
          index 4be01584..55918285 100644
          --- a/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt
          +++ b/sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/codeblocks/CodeBlocksSampleScreen.kt
          @@ -35,6 +35,7 @@ import com.mohamedrejeb.richeditor.highlight.CodeLanguage
           import com.mohamedrejeb.richeditor.model.RichTextState
           import com.mohamedrejeb.richeditor.sample.common.components.SampleScaffold
           import com.mohamedrejeb.richeditor.ui.BasicCodeText
          +import com.mohamedrejeb.richeditor.ui.CodeBlockCopyButton
           import com.mohamedrejeb.richeditor.ui.material3.RichText
           
           private val replyMarkdown = """
          @@ -120,7 +121,11 @@ fun CodeBlocksSampleScreen(navigateBack: () -> Unit) {
                               setMarkdown(replyMarkdown)
                           }
                       }
          -            RichText(state = state, modifier = Modifier.fillMaxWidth(), showCodeBlockCopyButton = true)
          +            RichText(
          +                state = state,
          +                modifier = Modifier.fillMaxWidth(),
          +                codeBlockAction = { code, _ -> CodeBlockCopyButton(code = code, tint = scheme.onSurfaceVariant) },
          +            )
           
                       SectionTitle("Code alone", "BasicCodeText needs no state. A long line scrolls sideways.")
                       BasicCodeText(
          
          From 75992a3f356a2ea698ca88680ba95ffa2d9a09c3 Mon Sep 17 00:00:00 2001
          From: MohamedRejeb 
          Date: Wed, 11 Nov 2026 14:43:51 +0100
          Subject: [PATCH 16/16] fix: code blocks keep URLs as code, one pasted line
           joins the text it precedes, right to left padding, and the old RichText
           signatures stay callable
          
          ---
           docs/code_blocks.md                           |  2 +-
           .../api/desktop/richeditor-compose.api        |  3 ++
           .../api/richeditor-compose.klib.api           |  6 +++
           .../mohamedrejeb/richeditor/model/AutoLink.kt |  3 ++
           .../richeditor/model/RichTextState.kt         |  5 ++
           .../richeditor/ui/BasicRichText.kt            | 33 ++++++++++++
           .../mohamedrejeb/richeditor/ui/ModifierExt.kt | 12 +++--
           .../richeditor/ui/material/RichText.kt        | 53 ++++++++++++++++++-
           .../richeditor/ui/material3/RichText.kt       | 53 ++++++++++++++++++-
           .../model/CodeBlockClipboardTest.kt           | 28 ++++++++++
           .../richeditor/model/CodeBlockTypingTest.kt   | 22 ++++++++
           .../richeditor/ui/CodeBlockRenderTest.kt      | 27 ++++++++++
           12 files changed, 240 insertions(+), 7 deletions(-)
          
          diff --git a/docs/code_blocks.md b/docs/code_blocks.md
          index d6c95ff8..6c6501c4 100644
          --- a/docs/code_blocks.md
          +++ b/docs/code_blocks.md
          @@ -78,7 +78,7 @@ of code pasted into a sentence joins the sentence as text. Whatever is pasted in
           formatted or not, becomes plain lines of that block.
           
           Typing shortcuts (`**bold**`, `__bold__`, `` `code` `` and the others) do nothing inside a code
          -block, where those marks are code.
          +block, where those marks are code. A URL typed or pasted there is not turned into a link either.
           
           ### Copy button
           
          diff --git a/richeditor-compose/api/desktop/richeditor-compose.api b/richeditor-compose/api/desktop/richeditor-compose.api
          index e661999e..5513aa63 100644
          --- a/richeditor-compose/api/desktop/richeditor-compose.api
          +++ b/richeditor-compose/api/desktop/richeditor-compose.api
          @@ -1022,6 +1022,7 @@ public final class com/mohamedrejeb/richeditor/ui/BasicRichTextEditorKt {
           }
           
           public final class com/mohamedrejeb/richeditor/ui/BasicRichTextKt {
          +	public static final synthetic fun BasicRichText-Jzo1Dmk (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lkotlin/jvm/functions/Function1;IZIILjava/util/Map;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;III)V
           	public static final fun BasicRichText-Kj_y3YE (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;Lkotlin/jvm/functions/Function1;IZIILjava/util/Map;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;III)V
           }
           
          @@ -1058,6 +1059,7 @@ public final class com/mohamedrejeb/richeditor/ui/material/RichTextEditorKt {
           
           public final class com/mohamedrejeb/richeditor/ui/material/RichTextKt {
           	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;IIII)V
          +	public static final synthetic fun RichText-mQfddtU (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;IIII)V
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material3/ExpandableRichTextKt {
          @@ -1107,6 +1109,7 @@ public final class com/mohamedrejeb/richeditor/ui/material3/RichTextEditorKt {
           
           public final class com/mohamedrejeb/richeditor/ui/material3/RichTextKt {
           	public static final fun RichText-KrekslA (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;IIII)V
          +	public static final synthetic fun RichText-mQfddtU (Lcom/mohamedrejeb/richeditor/model/RichTextState;Landroidx/compose/ui/Modifier;JJLandroidx/compose/ui/text/font/FontStyle;Landroidx/compose/ui/text/font/FontWeight;Landroidx/compose/ui/text/font/FontFamily;JLandroidx/compose/ui/text/style/TextDecoration;IJIZIILjava/util/Map;Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/text/TextStyle;Lcom/mohamedrejeb/richeditor/model/ImageLoader;Lcom/mohamedrejeb/richeditor/model/TokenClickHandler;Lcom/mohamedrejeb/richeditor/model/TokenHoverHandler;Landroidx/compose/runtime/Composer;IIII)V
           }
           
           public final class com/mohamedrejeb/richeditor/ui/material3/TriggerSuggestionsKt {
          diff --git a/richeditor-compose/api/richeditor-compose.klib.api b/richeditor-compose/api/richeditor-compose.klib.api
          index cd31b157..79f9d373 100644
          --- a/richeditor-compose/api/richeditor-compose.klib.api
          +++ b/richeditor-compose/api/richeditor-compose.klib.api
          @@ -1323,18 +1323,24 @@ final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor
           final fun com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.paragraph.type/com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter|com_mohamedrejeb_richeditor_paragraph_type_UnorderedListStyleType$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.parser.html/com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter|com_mohamedrejeb_richeditor_parser_html_CssDecoder_HtmlStylingFormat$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, androidx.compose.material/TextFieldColors?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;androidx.compose.material.TextFieldColors?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText(com.mohamedrejeb.richeditor.model/RichTextState, kotlin/Boolean, kotlin/Function1, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, androidx.compose.ui.graphics/Color, kotlin/Int, kotlin/String?, kotlin/String?, androidx.compose.ui.graphics/Color, kotlin/Boolean, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/ExpandableRichText|ExpandableRichText(com.mohamedrejeb.richeditor.model.RichTextState;kotlin.Boolean;kotlin.Function1;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;androidx.compose.ui.graphics.Color;kotlin.Int;kotlin.String?;kotlin.String?;androidx.compose.ui.graphics.Color;kotlin.Boolean;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/OutlinedRichTextEditor|OutlinedRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign, androidx.compose.ui.unit/TextUnit, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign;androidx.compose.ui.unit.TextUnit;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/RichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.graphics/Color, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.font/FontStyle?, androidx.compose.ui.text.font/FontWeight?, androidx.compose.ui.text.font/FontFamily?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextDecoration?, androidx.compose.ui.text.style/TextAlign?, androidx.compose.ui.unit/TextUnit?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, kotlin/Function1?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichText|RichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.graphics.Color;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.font.FontStyle?;androidx.compose.ui.text.font.FontWeight?;androidx.compose.ui.text.font.FontFamily?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextDecoration?;androidx.compose.ui.text.style.TextAlign?;androidx.compose.ui.unit.TextUnit?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;kotlin.Function1?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/RichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Function2?, kotlin/Boolean, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Shape?, com.mohamedrejeb.richeditor.ui.material3/RichTextEditorColors?, androidx.compose.foundation.layout/PaddingValues?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui.material3/RichTextEditor|RichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Function2?;kotlin.Boolean;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Shape?;com.mohamedrejeb.richeditor.ui.material3.RichTextEditorColors?;androidx.compose.foundation.layout.PaddingValues?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorColors$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(): kotlin/Int // com.mohamedrejeb.richeditor.ui.material3/com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter|com_mohamedrejeb_richeditor_ui_material3_RichTextEditorDefaults$stableprop_getter(){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicCodeText(kotlin/String, com.mohamedrejeb.richeditor.highlight/CodeLanguage?, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, com.mohamedrejeb.richeditor.highlight/CodeBlockColors?, kotlin/Boolean, kotlin/Function1?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicCodeText|BasicCodeText(kotlin.String;com.mohamedrejeb.richeditor.highlight.CodeLanguage?;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;com.mohamedrejeb.richeditor.highlight.CodeBlockColors?;kotlin.Boolean;kotlin.Function1?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          +final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichText(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, androidx.compose.ui.text/TextStyle?, kotlin/Function1?, androidx.compose.ui.text.style/TextOverflow?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin.collections/Map?, com.mohamedrejeb.richeditor.model/ImageLoader?, com.mohamedrejeb.richeditor.model/TokenClickHandler?, com.mohamedrejeb.richeditor.model/TokenHoverHandler?, kotlin/Function4?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichText|BasicRichText(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;androidx.compose.ui.text.TextStyle?;kotlin.Function1?;androidx.compose.ui.text.style.TextOverflow?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.collections.Map?;com.mohamedrejeb.richeditor.model.ImageLoader?;com.mohamedrejeb.richeditor.model.TokenClickHandler?;com.mohamedrejeb.richeditor.model.TokenHoverHandler?;kotlin.Function4?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.foundation.layout/PaddingValues, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.foundation.layout.PaddingValues;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
           final fun com.mohamedrejeb.richeditor.ui/BasicRichTextEditor(com.mohamedrejeb.richeditor.model/RichTextState, androidx.compose.ui/Modifier?, kotlin/Boolean, kotlin/Boolean, androidx.compose.ui.text/TextStyle?, androidx.compose.foundation.text/KeyboardOptions?, androidx.compose.foundation.text/KeyboardActions?, kotlin/Boolean, kotlin/Int, kotlin/Int, kotlin/Int, kotlin/Function1?, androidx.compose.foundation.interaction/MutableInteractionSource?, androidx.compose.ui.graphics/Brush?, com.mohamedrejeb.richeditor.ui/UndoBehavior?, kotlin/Function3, androidx.compose.runtime/Composer, kotlin/Int, kotlin/Unit>?, androidx.compose.runtime/Composer?, kotlin/Int, kotlin/Int, kotlin/Int) // com.mohamedrejeb.richeditor.ui/BasicRichTextEditor|BasicRichTextEditor(com.mohamedrejeb.richeditor.model.RichTextState;androidx.compose.ui.Modifier?;kotlin.Boolean;kotlin.Boolean;androidx.compose.ui.text.TextStyle?;androidx.compose.foundation.text.KeyboardOptions?;androidx.compose.foundation.text.KeyboardActions?;kotlin.Boolean;kotlin.Int;kotlin.Int;kotlin.Int;kotlin.Function1?;androidx.compose.foundation.interaction.MutableInteractionSource?;androidx.compose.ui.graphics.Brush?;com.mohamedrejeb.richeditor.ui.UndoBehavior?;kotlin.Function3,androidx.compose.runtime.Composer,kotlin.Int,kotlin.Unit>?;androidx.compose.runtime.Composer?;kotlin.Int;kotlin.Int;kotlin.Int){}[0]
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/AutoLink.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/AutoLink.kt
          index 2e845e84..d4b35526 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/AutoLink.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/AutoLink.kt
          @@ -2,6 +2,7 @@ package com.mohamedrejeb.richeditor.model
           
           import androidx.compose.ui.text.TextRange
           import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
          +import com.mohamedrejeb.richeditor.paragraph.type.CodeBlock
           
           /** The part of a word, from [start] to [end], that is a URL, and the [url] it links to. */
           internal class AutoLinkMatch(val start: Int, val end: Int, val url: String)
          @@ -73,6 +74,8 @@ internal fun RichTextState.autoLinkInsertedText(at: Int, inserted: String) {
               }
           
               val range = TextRange(wordStart + match.start, wordStart + match.end)
          +    // A URL inside a code block is code.
          +    if (getRichSpanByTextIndex(range.min, ignoreCustomFiltering = true)?.paragraph?.type is CodeBlock) return
               val isPlainText = (range.min until range.max).all {
                   getRichSpanByTextIndex(it, ignoreCustomFiltering = true)?.fullStyle is RichSpanStyle.Default
               }
          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 161410d5..5a619f1e 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
          @@ -6220,8 +6220,13 @@ public class RichTextState internal constructor(
                       removeSliceIndex = false,
                   )
           
          +        // One line of code pasted in front of text joins it, as it does in the middle of text.
          +        val joinsFollowingText = newParagraphs.size == 1 &&
          +            firstNewParagraph.type is CodeBlock && targetParagraphSecondHalf.isNotEmpty()
          +
                   if (
                       targetCodeBlock == null &&
          +            !joinsFollowingText &&
                       targetParagraphFirstHalf.isEmpty() &&
                       (firstNewParagraph.isNotEmpty() || firstNewParagraph.type is CodeBlock)
                   ) {
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt
          index 08e97a4b..2489908b 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/BasicRichText.kt
          @@ -156,3 +156,36 @@ public fun BasicRichText(
                   }
               }
           }
          +
          +@Deprecated("Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
          +@Composable
          +public fun BasicRichText(
          +    state: RichTextState,
          +    modifier: Modifier = Modifier,
          +    style: TextStyle = TextStyle.Default,
          +    onTextLayout: (TextLayoutResult) -> Unit = {},
          +    overflow: TextOverflow = TextOverflow.Clip,
          +    softWrap: Boolean = true,
          +    maxLines: Int = Int.MAX_VALUE,
          +    minLines: Int = 1,
          +    inlineContent: Map = mapOf(),
          +    imageLoader: ImageLoader = LocalImageLoader.current,
          +    onTokenClick: TokenClickHandler? = null,
          +    onTokenHover: TokenHoverHandler? = null,
          +) {
          +    BasicRichText(
          +        state = state,
          +        modifier = modifier,
          +        style = style,
          +        onTextLayout = onTextLayout,
          +        overflow = overflow,
          +        softWrap = softWrap,
          +        maxLines = maxLines,
          +        minLines = minLines,
          +        inlineContent = inlineContent,
          +        imageLoader = imageLoader,
          +        onTokenClick = onTokenClick,
          +        onTokenHover = onTokenHover,
          +        codeBlockAction = null,
          +    )
          +}
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          index bc9e9549..318f6a26 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/ModifierExt.kt
          @@ -8,6 +8,7 @@ import androidx.compose.ui.geometry.Size
           import androidx.compose.ui.graphics.drawscope.clipRect
           import androidx.compose.ui.graphics.drawscope.translate
           import androidx.compose.ui.text.TextRange
          +import androidx.compose.ui.unit.LayoutDirection
           import androidx.compose.ui.unit.dp
           import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
           import com.mohamedrejeb.richeditor.model.RichSpanStyle
          @@ -46,10 +47,13 @@ internal fun Modifier.drawRichSpanStyle(
           
                       // A block is as wide as the text area, and one scrolled partly out of an editor
                       // must not paint over the padding around that area.
          +            val isRtl = layoutDirection == LayoutDirection.Rtl
          +            val leftPadding = if (isRtl) endPadding else startPadding
          +            val rightPadding = if (isRtl) startPadding else endPadding
                       clipRect(
          -                left = startPadding,
          +                left = leftPadding,
                           top = topPadding,
          -                right = size.width - endPadding,
          +                right = size.width - rightPadding,
                           bottom = size.height - bottomPadding,
                       ) {
                           translate(top = -richTextState.scrollState.value.toFloat()) {
          @@ -61,9 +65,9 @@ internal fun Modifier.drawRichSpanStyle(
                                           val top = textLayoutResult.getLineTop(lines.first) + gap
                                           drawRoundRect(
                                               color = richTextState.config.codeBlockBackgroundColor,
          -                                    topLeft = Offset(startPadding, top + topPadding),
          +                                    topLeft = Offset(leftPadding, top + topPadding),
                                               size = Size(
          -                                        width = size.width - startPadding - endPadding,
          +                                        width = size.width - leftPadding - rightPadding,
                                                   height = textLayoutResult.getLineBottom(lines.last) - gap - top,
                                               ),
                                               cornerRadius = CornerRadius(CodeBlockCornerRadius.toPx()),
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          index c52a889a..cb9aac18 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material/RichText.kt
          @@ -128,4 +128,55 @@ public fun RichText(
                   onTokenHover = onTokenHover,
                   codeBlockAction = codeBlockAction,
               )
          -}
          \ No newline at end of file
          +}
          +
          +@Deprecated("Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
          +@Composable
          +public fun RichText(
          +    state: RichTextState,
          +    modifier: Modifier = Modifier,
          +    color: Color = Color.Unspecified,
          +    fontSize: TextUnit = TextUnit.Unspecified,
          +    fontStyle: FontStyle? = null,
          +    fontWeight: FontWeight? = null,
          +    fontFamily: FontFamily? = null,
          +    letterSpacing: TextUnit = TextUnit.Unspecified,
          +    textDecoration: TextDecoration? = null,
          +    textAlign: TextAlign = TextAlign.Unspecified,
          +    lineHeight: TextUnit = TextUnit.Unspecified,
          +    overflow: TextOverflow = TextOverflow.Clip,
          +    softWrap: Boolean = true,
          +    maxLines: Int = Int.MAX_VALUE,
          +    minLines: Int = 1,
          +    inlineContent: Map = mapOf(),
          +    onTextLayout: (TextLayoutResult) -> Unit = {},
          +    style: TextStyle = LocalTextStyle.current,
          +    imageLoader: ImageLoader = LocalImageLoader.current,
          +    onTokenClick: TokenClickHandler? = null,
          +    onTokenHover: TokenHoverHandler? = null,
          +) {
          +    RichText(
          +        state = state,
          +        modifier = modifier,
          +        color = color,
          +        fontSize = fontSize,
          +        fontStyle = fontStyle,
          +        fontWeight = fontWeight,
          +        fontFamily = fontFamily,
          +        letterSpacing = letterSpacing,
          +        textDecoration = textDecoration,
          +        textAlign = textAlign,
          +        lineHeight = lineHeight,
          +        overflow = overflow,
          +        softWrap = softWrap,
          +        maxLines = maxLines,
          +        minLines = minLines,
          +        inlineContent = inlineContent,
          +        onTextLayout = onTextLayout,
          +        style = style,
          +        imageLoader = imageLoader,
          +        onTokenClick = onTokenClick,
          +        onTokenHover = onTokenHover,
          +        codeBlockAction = null,
          +    )
          +}
          diff --git a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          index 2c95fe02..c2ec5ee7 100644
          --- a/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          +++ b/richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/ui/material3/RichText.kt
          @@ -127,4 +127,55 @@ public fun RichText(
                   onTokenHover = onTokenHover,
                   codeBlockAction = codeBlockAction,
               )
          -}
          \ No newline at end of file
          +}
          +
          +@Deprecated("Kept for binary compatibility.", level = DeprecationLevel.HIDDEN)
          +@Composable
          +public fun RichText(
          +    state: RichTextState,
          +    modifier: Modifier = Modifier,
          +    color: Color = Color.Unspecified,
          +    fontSize: TextUnit = TextUnit.Unspecified,
          +    fontStyle: FontStyle? = null,
          +    fontWeight: FontWeight? = null,
          +    fontFamily: FontFamily? = null,
          +    letterSpacing: TextUnit = TextUnit.Unspecified,
          +    textDecoration: TextDecoration? = null,
          +    textAlign: TextAlign = TextAlign.Unspecified,
          +    lineHeight: TextUnit = TextUnit.Unspecified,
          +    overflow: TextOverflow = TextOverflow.Clip,
          +    softWrap: Boolean = true,
          +    maxLines: Int = Int.MAX_VALUE,
          +    minLines: Int = 1,
          +    inlineContent: Map = mapOf(),
          +    onTextLayout: (TextLayoutResult) -> Unit = {},
          +    style: TextStyle = LocalTextStyle.current,
          +    imageLoader: ImageLoader = LocalImageLoader.current,
          +    onTokenClick: TokenClickHandler? = null,
          +    onTokenHover: TokenHoverHandler? = null,
          +) {
          +    RichText(
          +        state = state,
          +        modifier = modifier,
          +        color = color,
          +        fontSize = fontSize,
          +        fontStyle = fontStyle,
          +        fontWeight = fontWeight,
          +        fontFamily = fontFamily,
          +        letterSpacing = letterSpacing,
          +        textDecoration = textDecoration,
          +        textAlign = textAlign,
          +        lineHeight = lineHeight,
          +        overflow = overflow,
          +        softWrap = softWrap,
          +        maxLines = maxLines,
          +        minLines = minLines,
          +        inlineContent = inlineContent,
          +        onTextLayout = onTextLayout,
          +        style = style,
          +        imageLoader = imageLoader,
          +        onTokenClick = onTokenClick,
          +        onTokenHover = onTokenHover,
          +        codeBlockAction = null,
          +    )
          +}
          diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt
          index 61d89c58..3beb724d 100644
          --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt
          +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockClipboardTest.kt
          @@ -131,6 +131,34 @@ class CodeBlockClipboardTest {
                   assertEquals(listOf("P:Helloa = 1 world"), state.shape())
               }
           
          +    @Test
          +    fun `one line of code pasted at the start of text joins the text`() {
          +        val state = state("Hello world")
          +        state.paste(TextRange(0), "a = 1", "
          a = 1
          ") + assertEquals(listOf("P:a = 1Hello world"), state.shape()) + } + + @Test + fun `one line of code pasted into an empty paragraph is a block`() { + val state = state("") + state.paste(TextRange(0), "a = 1", "
          a = 1
          ") + assertEquals(listOf("C*:a = 1"), state.shape()) + } + + @Test + fun `a URL pasted into a block stays plain code`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "https://example.com") + assertTrue(state.toRichTextDocument().blocks.all { it.spans.isEmpty() }) + } + + @Test + fun `a URL pasted as rich text into a block stays plain code`() { + val state = state() + state.paste(TextRange(state.offsetOf("val b")), "https://example.com", "

          https://example.com

          ") + assertTrue(state.toRichTextDocument().blocks.all { it.spans.isEmpty() }) + } + @Test fun `part of a block copied from one editor pastes as a block into another`() { val source = state() diff --git a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt index e029f36e..09a41578 100644 --- a/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt +++ b/richeditor-compose/src/commonTest/kotlin/com/mohamedrejeb/richeditor/model/CodeBlockTypingTest.kt @@ -1,5 +1,6 @@ package com.mohamedrejeb.richeditor.model +import androidx.compose.foundation.text.input.toTextFieldBuffer import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi @@ -30,6 +31,18 @@ class CodeBlockTypingTest { } } + /** Commits [text] at the caret as one edit of the text field, the path automatic links run on. */ + private fun RichTextState.commit(text: String) { + val caret = selection.min + val buffer = textFieldState.toTextFieldBuffer() + buffer.replace(caret, caret, text) + buffer.selection = TextRange(caret + text.length) + applyChangeList(buffer) + val newCaret = pendingSelectionDuringSync ?: buffer.selection + pendingSelectionDuringSync = null + setTextFieldStateFromValue(text = annotatedString.text, selection = newCaret) + } + @Test fun `underscores typed in a block stay as typed`() { val state = codeState() @@ -46,6 +59,15 @@ class CodeBlockTypingTest { assertEquals(true, state.toRichTextDocument().blocks.single().spans.isEmpty()) } + @Test + fun `a URL typed in a block stays as typed`() { + val state = codeState() + state.commit(" = https://example.com") + state.commit(" ") + assertEquals("x = https://example.com ", state.annotatedString.text) + assertEquals(true, state.toRichTextDocument().blocks.single().spans.isEmpty()) + } + @Test fun `the same marks still format ordinary text`() { val state = RichTextState().apply { config.inlineTypingShortcutsEnabled = true } diff --git a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt index 2c4cb85d..5b1f30df 100644 --- a/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt +++ b/richeditor-compose/src/desktopTest/kotlin/com/mohamedrejeb/richeditor/ui/CodeBlockRenderTest.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier @@ -15,6 +16,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PixelMap import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.DesktopComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi @@ -30,6 +32,7 @@ import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi import com.mohamedrejeb.richeditor.highlight.CodeBlockColors @@ -283,6 +286,30 @@ class CodeBlockRenderTest { assertEquals(200 - 24, red.right, "the background ends before the end padding") } + @Test + fun `the background stays inside the content padding of a right to left editor`() = runDesktopComposeUiTest { + val state = RichTextState().apply { + config.codeBlockBackgroundColor = Color.Red + setMarkdown("```\ncode\n```") + } + val horizontalPadding = PaddingValues(start = 16.dp, top = 12.dp, end = 24.dp, bottom = 12.dp) + setContent { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { + BasicRichTextEditor( + state = state, + modifier = Modifier.width(200.dp).testTag(EDITOR_TAG), + decorationBox = { innerTextField -> Box(Modifier.padding(horizontalPadding)) { innerTextField() } }, + contentPadding = horizontalPadding, + ) + } + } + waitForIdle() + + val red = onNodeWithTag(EDITOR_TAG).captureToImage().toPixelMap().redBounds() + assertEquals(24, red.left, "the background starts after the end padding") + assertEquals(200 - 16, red.right, "the background ends before the start padding") + } + @Test fun `a scrolled block is not drawn over the padding of an editor`() = runDesktopComposeUiTest { val state = RichTextState().apply {