### Register math-showcase example in SampleChatDefaults Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a SampleScriptDefinition entry for the math-showcase example, making it available in the demo. ```kotlin SampleScriptDefinition( id = "math-showcase", title = "Math Showcase", summary = "Inline and block LaTeX with dollar and bracket delimiters, plus currency that must stay text.", resourcePath = "markdown-examples/math-showcase.md", ), ``` -------------------------------- ### Create math-showcase.md example file Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Markdown example demonstrating inline and display math with dollar and bracket delimiters, plus currency that must remain text. ```markdown # Math Showcase Inline dollar math like $E = mc^2$ flows within the sentence, and so does paren math \(a^2 + b^2 = c^2\). Currency is left alone: it costs $5 and $6 total. Display math with dollars: $$ \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$ And a bracket block: \[ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} \] ``` -------------------------------- ### Launch desktop demo Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Starts the sample-chat desktop application. Expected output: the window opens. ```bash ./gradlew :sample-chat:run ``` -------------------------------- ### Run sample-chat desktop and Android targets Source: https://github.com/adamglin0/compose-markdown/blob/main/sample-chat/README.md Use these Gradle commands to run the desktop app and install the Android app. The Android app is a separate module because AGP 9 keeps application modules out of Kotlin Multiplatform. ```bash ./gradlew :sample-chat:run # desktop ./gradlew :sample-chat-android:installDebug # Android ``` -------------------------------- ### C# code example Source: https://github.com/adamglin0/compose-markdown/blob/main/sample-chat/markdown-examples/full-markdown.md A C# code block demonstrating a class with a method that prints a message and returns a list of integers. ```csharp using System.IO.Compression; namespace MyApplication { class Program { public static List JustDoIt(int count) { Console.WriteLine($"Hello {count}!"); return new List(new int[] { 1, 2, 3 }); } } } ``` -------------------------------- ### Markdown Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Composable function that renders markdown content. It accepts a string content and optional components and other parameters. ```APIDOC ## Markdown ### Description Composable function that renders markdown content. It accepts a string content and optional components and other parameters. ### Parameters - `content` (String) - Required - The markdown string to render. - `components` (MarkdownComponents) - Optional - Custom components to override default rendering. - `onLinkClick` (callback) - Optional - Handler for link clicks. - `codeHighlighter` (CodeHighlighter) - Optional - Colors closed fenced code blocks. Defaults to DefaultCodeHighlighter; pass null to turn off. - `mathRenderer` (MathRenderer) - Optional - Renders math blocks. ### Example ```kotlin @Composable fun Message(content: String) { Markdown(content, components = ChatComponents) } ``` ``` -------------------------------- ### MarkdownTheme Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Styles every renderer inside it. Without it, the renderer uses MarkdownColors.Light, MarkdownTypography.Default and 12.dp block spacing. ```APIDOC ## MarkdownTheme ### Description Styles every renderer inside it. Without it, the renderer uses MarkdownColors.Light, MarkdownTypography.Default and 12.dp block spacing. ### Parameters - `colors` (MarkdownColors) - Optional - Color scheme for the markdown elements. - `typography` (MarkdownTypography) - Optional - Typography styles for the markdown elements. - `blockSpacing` (Dp) - Optional - Spacing between blocks, defaults to 12.dp. ``` -------------------------------- ### Implement MathRenderer and use GfmMath dialect Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Define a MathRenderer to render LaTeX math blocks and spans, then pass it to Markdown with the GfmMath dialect. Without a renderer, math shows its LaTeX source; unclosed math blocks also show source and are never passed to the renderer. ```kotlin import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import com.adamglin.compose.markdown.compose.Markdown import com.adamglin.compose.markdown.compose.MathRenderer import com.adamglin.compose.markdown.core.dialect.MarkdownDialect object MyMathRenderer : MathRenderer { @Composable override fun BlockMath(latex: String, modifier: Modifier) { // A display formula: `$$…$$` or `\[…\]`. } @Composable override fun InlineMath(latex: String, style: TextStyle) { // An inline formula: `$…$` or `\(…\)`. It is drawn at its natural size, in the surrounding text style. } } @Composable fun MathMessage(content: String) { Markdown(content, dialect = MarkdownDialect.GfmMath, mathRenderer = MyMathRenderer) } ``` -------------------------------- ### Stream Markdown chunks with rememberMarkdownState and MarkdownState Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Use MarkdownState to own the parser and stream chunks from a Flow. Each append publishes the new document immediately and only touched blocks recompose. The first example shows a simple streaming reply; the second shows a long document rendered as one lazy item per top-level block, keyed by 'key' plus the block's stable id. MarkdownState is plain observable state and can live in a view model. ```kotlin import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import com.adamglin.compose.markdown.compose.Markdown import com.adamglin.compose.markdown.compose.markdown import com.adamglin.compose.markdown.compose.rememberMarkdownState import kotlinx.coroutines.flow.Flow @Composable fun StreamingReply(chunks: Flow) { val state = rememberMarkdownState() LaunchedEffect(chunks) { state.reset() chunks.collect { state.append(it) } state.finish() } Markdown(state.document) } // Long documents: one lazy item per top-level block, keyed by `key` plus the block's stable id. @Composable fun LongReply(chunks: Flow) { val state = rememberMarkdownState() LaunchedEffect(chunks) { state.reset() chunks.collect { state.append(it) } state.finish() } LazyColumn { markdown(state.document, key = "reply") } } ``` -------------------------------- ### LazyListScope.markdown Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Extension function on LazyListScope that takes the same components as Markdown, for use in lazy lists. ```APIDOC ## LazyListScope.markdown ### Description Extension function on LazyListScope that takes the same components as Markdown, for use in lazy lists. ### Parameters - `components` (MarkdownComponents) - Optional - Custom components to override default rendering. - Other parameters same as Markdown. ``` -------------------------------- ### Render a Markdown string with MarkdownTheme and SelectionContainer Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Use this composable to render a Markdown string with theme colors based on the system dark mode. Wrap the Markdown composable in a SelectionContainer to make the text selectable. Markdown(text) parses once per distinct text and dialect. ```kotlin import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.runtime.Composable import com.adamglin.compose.markdown.compose.Markdown import com.adamglin.compose.markdown.compose.MarkdownColors import com.adamglin.compose.markdown.compose.MarkdownTheme @Composable fun Message(content: String) { MarkdownTheme(colors = if (isSystemInDarkTheme()) MarkdownColors.Dark else MarkdownColors.Light) { SelectionContainer { Markdown(content) } } } ``` -------------------------------- ### Parse without Compose: MarkdownEngine usage Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Shows how to use MarkdownEngine with MarkdownDialect.GfmCompat to append markdown chunks and inspect changed blocks or the final document. The engine only supports appending; edits in the middle of the source are not supported. ```kotlin import com.adamglin.compose.markdown.core.api.MarkdownEngine import com.adamglin.compose.markdown.core.dialect.MarkdownDialect fun main() { val engine = MarkdownEngine(MarkdownDialect.GfmCompat) engine.append("# Title\n\nSome *streamed") val delta = engine.append(" text*\n") println(delta.changedBlocks) // the top-level blocks this chunk added or changed val document = engine.finish().snapshot.document println(document.blocks) } ``` -------------------------------- ### Custom MarkdownComponents with codeBlock and heading slots Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Defines ChatComponents using MarkdownComponents to customize codeBlock and heading rendering. The codeBlock slot adds a header with language and copy button around the built-in highlighted code; heading adds a divider for levels <= 2. Use with Markdown(content, components = ChatComponents). Each slot should emit one layout node; wrap multiple in a Column or Box. copyToClipboard and Divider are placeholders; see sample-chat's SampleMarkdownComponents.kt for a working version. ```kotlin import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.adamglin.compose.markdown.compose.Markdown import com.adamglin.compose.markdown.compose.MarkdownComponents val ChatComponents = MarkdownComponents( codeBlock = { Column { Row(Modifier.padding(horizontal = 14.dp, vertical = 6.dp)) { BasicText(language ?: "text") // `isClosed` is false while the fence is still streaming. if (isClosed) BasicText("Copy", Modifier.clickable { copyToClipboard(code) }) } HighlightedCode(contentPadding = PaddingValues(14.dp)) } }, heading = { Column { DefaultContent() if (block.level <= 2) Divider() } }, ) @Composable fun Message(content: String) { Markdown(content, components = ChatComponents) } ``` -------------------------------- ### Add Compose Markdown dependency with version catalog Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Declares the compose-markdown version and library in a Gradle version catalog (libs.versions.toml). The module is com.adamglin.compose.markdown:markdown-compose. ```toml [versions] compose-markdown = "2.1.0" [libraries] compose-markdown = { module = "com.adamglin.compose.markdown:markdown-compose", version.ref = "compose-markdown" } ``` -------------------------------- ### JavaScript code example Source: https://github.com/adamglin0/compose-markdown/blob/main/sample-chat/markdown-examples/full-markdown.md A JavaScript code block defining a function that processes blocks and logs errors or undefined conditions. ```javascript function initHighlight(block, cls) { try { if (cls.search(/\bno\-highlight\b/) !== -1) { return process(block, true, 0x0F); } } catch (error) { console.log(error); } for (let i = 0; i < classes.length; i += 1) { if (checkCondition(classes[i]) === undefined) { console.log('undefined'); } } } export default initHighlight; ``` -------------------------------- ### MarkdownComponents Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Replaces or decorates how elements render. It has one slot per element: paragraph, heading, codeBlock, mathBlock, blockQuote, list, listItem, listMarker, taskCheckbox, table, thematicBreak and image. A slot runs with a scope as receiver, holding the element's data and DefaultContent() for built-in rendering. ```APIDOC ## MarkdownComponents ### Description Replaces or decorates how elements render. It has one slot per element: paragraph, heading, codeBlock, mathBlock, blockQuote, list, listItem, listMarker, taskCheckbox, table, thematicBreak and image. A slot runs with a scope as receiver, holding the element's data and DefaultContent() for built-in rendering. ### Parameters - `paragraph` (slot) - Optional - Slot for paragraph elements. - `heading` (slot) - Optional - Slot for heading elements. - `codeBlock` (slot) - Optional - Slot for code block elements. - `mathBlock` (slot) - Optional - Slot for math block elements. - `blockQuote` (slot) - Optional - Slot for block quote elements. - `list` (slot) - Optional - Slot for list elements. - `listItem` (slot) - Optional - Slot for list item elements. - `listMarker` (slot) - Optional - Slot for list marker elements. - `taskCheckbox` (slot) - Optional - Slot for task checkbox elements. - `table` (slot) - Optional - Slot for table elements. - `thematicBreak` (slot) - Optional - Slot for thematic break elements. - `image` (slot) - Optional - Slot for image elements. ### Example ```kotlin val ChatComponents = MarkdownComponents( codeBlock = { Column { Row(Modifier.padding(horizontal = 14.dp, vertical = 6.dp)) { BasicText(language ?: "text") if (isClosed) BasicText("Copy", Modifier.clickable { copyToClipboard(code) }) } HighlightedCode(contentPadding = PaddingValues(14.dp)) } }, heading = { Column { DefaultContent() if (block.level <= 2) Divider() } }, ) ``` ``` -------------------------------- ### Add Compose Markdown dependency in Kotlin DSL Source: https://github.com/adamglin0/compose-markdown/blob/main/README.md Adds the compose-markdown library to the commonMain dependencies block of a Kotlin Multiplatform module. Requires the version catalog entry defined in the previous snippet. ```kotlin commonMain.dependencies { implementation(libs.compose.markdown) } ``` -------------------------------- ### Parse inline math with dollar delimiter Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Parses inline math delimited by `$...$`. Returns null if the content starts with whitespace or `$`, or if the closing `$` is preceded by whitespace. Handles escaped backslashes by skipping two characters. ```kotlin private fun parseInlineMathDollar(index: Int, endExclusive: Int): ParsedInlineNode? { val contentStart = index + 1 if (contentStart >= endExclusive) { return null } val firstChar = text[contentStart] if (firstChar.isWhitespace() || firstChar == '$') { return null } var cursor = contentStart while (cursor < endExclusive) { val current = text[cursor] if (current == '\\') { cursor += 2 continue } if (current == '$' && !text[cursor - 1].isWhitespace()) { val latex = text.substring(contentStart, cursor) if (latex.isEmpty()) { return null } val range = toRange(index, cursor + 1) return ParsedInlineNode( node = InlineNode.MathSpan( id = inlineId(kind = "math", range = range, salt = latex.hashCode().toLong()), range = range, latex = latex, delimiter = MathInlineDelimiter.Dollar, ), nextIndex = cursor + 1, ) } cursor += 1 } return null } ``` -------------------------------- ### Export Gradle project properties for Maven Central credentials and signing Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/maven-central-publishing.md Set these environment variables before running any publish command. The signingInMemoryKey must be the raw ASCII-armored private key (starting with -----BEGIN PGP PRIVATE KEY BLOCK-----), not a base64-encoded copy. ```bash export ORG_GRADLE_PROJECT_mavenCentralUsername="your-central-portal-token-username" export ORG_GRADLE_PROJECT_mavenCentralPassword="your-central-portal-token-password" export ORG_GRADLE_PROJECT_signingInMemoryKey="$(gpg --export-secret-keys --armor )" export ORG_GRADLE_PROJECT_signingInMemoryKeyPassword="your-gpg-password" ``` -------------------------------- ### Compile the demo with Gradle Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the Gradle task to compile the sample-chat module for the JVM target. Expected to succeed; unresolved imports should be fixed per the API verification note. ```bash ./gradlew :sample-chat:compileKotlinJvm ``` -------------------------------- ### Switch demo engine to GfmMath in createMarkdownEngine Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Changes the sample chat's MarkdownEngine to use MarkdownDialect.GfmMath, enabling math rendering in the demo. ```kotlin fun createMarkdownEngine(): MarkdownEngine = MarkdownEngine( dialect = MarkdownDialect.GfmMath, ) ``` -------------------------------- ### Run full test suite Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Executes the JVM tests for markdown-core and markdown-compose modules. Expected output: all tests pass. ```bash ./gradlew :markdown-core:jvmTest :markdown-compose:jvmTest ``` -------------------------------- ### Add math renderer state and pass renderer in SampleChatApp Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds state for the math renderer option and creates renderer instances, then passes the selected renderer to Markdown. ```kotlin var mathRendererOption by remember { mutableStateOf(MathRendererOption.Huarangmeng) } val huarangmengRenderer = remember { HuarangmengMathRenderer() } val ratexRenderer = remember { RaTeXMathRenderer() } val mathRenderer = when (mathRendererOption) { MathRendererOption.Huarangmeng -> huarangmengRenderer MathRendererOption.RaTeX -> ratexRenderer MathRendererOption.Placeholder -> null } ``` ```kotlin Markdown( state = rendererState, modifier = Modifier.fillMaxWidth(), mathRenderer = mathRenderer, onLinkClick = onLinkClick, ) ``` -------------------------------- ### HighlightToken data class Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/api.md Data class representing a highlighted token with start and end indices and a color. ```APIDOC ## data class HighlightToken(val start: Int, val endExclusive: Int, val color: Color) ### Description Represents a highlighted token in code. ### Properties - **start** (Int) - Start index of the token. - **endExclusive** (Int) - End index (exclusive) of the token. - **color** (Color) - Color of the token. ``` -------------------------------- ### Run whole compose test suite Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the entire markdown-compose JVM test suite. Expected to pass. ```bash ./gradlew :markdown-compose:jvmTest ``` -------------------------------- ### Shell: Run full core test suite Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the entire core test suite to check for regressions; existing dialects should remain unchanged. ```shell ./gradlew :markdown-core:jvmTest ``` -------------------------------- ### Compile core module Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the Gradle command to compile the markdown-core module, which will surface exhaustive when expression errors that need to be resolved. ```bash ./gradlew :markdown-core:compileKotlinJvm ``` -------------------------------- ### Gradle command to run the failing test Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the specific JVM test for inline math rendering. Expected to fail because inline math has no rendering path yet. ```bash ./gradlew :markdown-compose:jvmTest --tests "com.adamglin.compose.markdown.compose.MathBlockRenderingTest.inlineMathUsesTheSlot" ``` -------------------------------- ### Imports for inline math rendering Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the necessary Compose imports for inline text content and key-based composition. ```kotlin import androidx.compose.foundation.text.InlineTextContent import androidx.compose.foundation.text.appendInlineContent import androidx.compose.runtime.key ``` -------------------------------- ### Commit sizing tweaks Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits changes to MathRenderers.kt with a message about tuning inline math placeholder sizing. ```bash git add sample-chat/src/commonMain/kotlin/com/adamglin/compose/markdown/sample/chat/MathRenderers.kt git commit -m "fix(sample): tune inline math placeholder sizing" ``` -------------------------------- ### Run failing test with Gradle Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Command to run the MathBlockParserTest in the markdown-core module. Expected to fail initially because math blocks are parsed as paragraphs, causing assertIs to throw. ```bash ./gradlew :markdown-core:jvmTest --tests "com.adamglin.compose.markdown.core.block.MathBlockParserTest" ``` -------------------------------- ### Run failing test Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Run this Gradle command to verify the test fails with a compile error because mathBlocks and GfmMath are unresolved. ```bash ./gradlew :markdown-core:jvmTest --tests "com.adamglin.compose.markdown.core.api.DialectExtensionTest" ``` -------------------------------- ### Add feature set additions Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Add these lines inside MarkdownPreset.featureSet buildSet after the existing block/inline lines. ```kotlin if (blockFeatures.mathBlocks) add(MarkdownFeature.MathBlock) if (inlineFeatures.inlineMath) add(MarkdownFeature.InlineMath) ``` -------------------------------- ### Run the failing test Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Command to run the MathBlockRenderingTest on the JVM target. Expected to fail because the mathRenderer parameter does not exist and MathBlock is not rendered yet. ```bash ./gradlew :markdown-compose:jvmTest --tests "com.adamglin.compose.markdown.compose.MathBlockRenderingTest" ``` -------------------------------- ### Add GfmMath preset Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Add this new preset after GfmCompat in sealed class MarkdownPreset. ```kotlin data object GfmMath : MarkdownPreset( id = "gfm-math", blockFeatures = MarkdownBlockFeatures( atxHeadings = true, setextHeadings = true, fencedCodeBlocks = true, blockQuotes = true, lists = true, taskListItems = true, tables = true, rawHtml = false, mathBlocks = true, ), inlineFeatures = MarkdownInlineFeatures( inlineCode = true, emphasis = true, strong = true, strikethrough = true, inlineLinks = true, referenceLinks = true, autolinks = true, bareAutolinks = true, images = true, softBreaks = true, hardBreaks = true, inlineMath = true, ), ) ``` -------------------------------- ### Commit dependency changes Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits the modified Gradle files with a descriptive message. ```bash git add gradle/libs.versions.toml sample-chat/build.gradle.kts settings.gradle.kts git commit -m "build(sample): add huarangmeng/latex and RaTeX-CMP dependencies" ``` -------------------------------- ### Add dependencies to sample-chat commonMain Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the huarangmeng/latex and ratex dependencies to the commonMain source set in sample-chat/build.gradle.kts. ```kotlin implementation(libs.huarangmeng.latex.base) implementation(libs.huarangmeng.latex.parser) implementation(libs.huarangmeng.latex.renderer) implementation(libs.ratex) ``` -------------------------------- ### Commit MathRenderers.kt Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits the new MathRenderers.kt file with a descriptive commit message. ```bash git add sample-chat/src/commonMain/kotlin/com/adamglin/compose/markdown/sample/chat/MathRenderers.kt git commit -m "feat(sample): implement huarangmeng and RaTeX MathRenderers" ``` -------------------------------- ### Add versions to gradle/libs.versions.toml [versions] Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the huarangmeng-latex and ratex version numbers to the version catalog. ```toml huarangmeng-latex = "1.4.7" ratex = "0.1.11" ``` -------------------------------- ### Import fillMaxWidth in MarkdownRenderer.kt Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the fillMaxWidth import to MarkdownRenderer.kt. The source notes that fillMaxWidth is already imported and should be skipped if present. ```kotlin import androidx.compose.foundation.layout.fillMaxWidth ``` -------------------------------- ### Add runtimeOnly dependency to sample-chat jvmMain Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the ratex native Darwin aarch64 runtime dependency to the jvmMain source set for Apple Silicon hosts. ```kotlin runtimeOnly(libs.ratex.native.darwin.aarch64) ``` -------------------------------- ### Add libraries to gradle/libs.versions.toml [libraries] Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Defines the huarangmeng-latex and ratex library coordinates in the version catalog. ```toml huarangmeng-latex-base = { module = "io.github.huarangmeng:latex-base", version.ref = "huarangmeng-latex" } huarangmeng-latex-parser = { module = "io.github.huarangmeng:latex-parser", version.ref = "huarangmeng-latex" } huarangmeng-latex-renderer = { module = "io.github.huarangmeng:latex-renderer", version.ref = "huarangmeng-latex" } ratex = { module = "io.github.darriousliu:ratex", version.ref = "ratex" } ratex-native-darwin-aarch64 = { module = "io.github.darriousliu:ratex-native-darwin-aarch64", version.ref = "ratex" } ``` -------------------------------- ### Composable for inline math rendering Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Renders an InlineRenderModel with BasicText, building an inlineContent map from math span references. Falls back to raw latex when mathRenderer is null. ```kotlin @Composable private fun MarkdownInlineText( model: InlineRenderModel, style: TextStyle, mathRenderer: MathRenderer?, modifier: Modifier = Modifier, ) { val inlineContent = if (model.mathSpans.isEmpty() || mathRenderer == null) { emptyMap() } else { buildMap { model.mathSpans.forEach { ref -> key(ref.key) { put(ref.key, mathRenderer.inlineMathContent(ref.latex, style.fontSize)) } } } } BasicText( text = model.text, style = style, inlineContent = inlineContent, modifier = modifier.fillMaxWidth(), ) } ``` -------------------------------- ### MathBlockParserTest.kt - failing tests for block math parsing Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Creates MathBlockParserTest.kt with tests for multi-line and single-line dollar blocks, bracket blocks, unclosed dollar blocks while streaming, and disabled dialect behavior. Uses MarkdownEngine with MarkdownDialect.GfmMath and GfmCompat. Expected to fail initially because math blocks parse as paragraphs. ```kotlin package com.adamglin.compose.markdown.core.block import com.adamglin.compose.markdown.core.api.MarkdownEngine import com.adamglin.compose.markdown.core.dialect.MarkdownDialect import com.adamglin.compose.markdown.core.model.BlockNode import com.adamglin.compose.markdown.core.model.MathBlockDelimiter import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue class MathBlockParserTest { private fun firstBlock(markdown: String): BlockNode { val engine = MarkdownEngine(dialect = MarkdownDialect.GfmMath) return engine.append(markdown).snapshot.document.blocks.first() } @Test fun parsesMultiLineDollarBlock() { val block = assertIs(firstBlock("$$\n\\frac{a}{b}\n$$\n")) assertEquals("\\frac{a}{b}", block.latex) assertEquals(MathBlockDelimiter.Dollar, block.delimiter) assertTrue(block.isClosed) } @Test fun parsesSingleLineDollarBlock() { val block = assertIs(firstBlock("$$x^2 + y^2$$\n")) assertEquals("x^2 + y^2", block.latex) assertTrue(block.isClosed) } @Test fun parsesBracketBlock() { val block = assertIs(firstBlock("\\[\n\\sum_{i=0}^n i\n\\]\n")) assertEquals("\\sum_{i=0}^n i", block.latex) assertEquals(MathBlockDelimiter.Bracket, block.delimiter) assertTrue(block.isClosed) } @Test fun unclosedDollarBlockStaysOpenWhileStreaming() { val engine = MarkdownEngine(dialect = MarkdownDialect.GfmMath) val block = assertIs( engine.append("$$\n\\frac{a}{b}\n").snapshot.document.blocks.first(), ) assertFalse(block.isClosed) } @Test fun disabledDialectDoesNotParseMath() { val engine = MarkdownEngine(dialect = MarkdownDialect.GfmCompat) val block = engine.append("$$\nx\n$$\n").snapshot.document.blocks.first() assertFalse(block is BlockNode.MathBlock) } } ``` -------------------------------- ### Inline render model and builder Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Defines data classes for math span references and the inline render model, plus a builder that converts a list of inline nodes into an annotated string and collects math span references. ```kotlin @Stable internal data class MathSpanRef(val key: String, val latex: String) @Stable internal data class InlineRenderModel( val text: AnnotatedString, val mathSpans: List, ) internal fun List.toInlineRenderModel( styles: MarkdownInlineStyles, onLinkClick: (String) -> Unit, ): InlineRenderModel { val mathSpans = mutableListOf() val text = buildAnnotatedString { appendInlineNodes( nodes = this@toInlineRenderModel, styles = styles, onLinkClick = onLinkClick, mathSpans = mathSpans, ) } return InlineRenderModel(text = text, mathSpans = mathSpans) } ``` -------------------------------- ### Add MathBlock branch to MarkdownBlock when Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a branch for BlockNode.MathBlock in MarkdownBlock's when, rendering MathBlockView. ```kotlin is BlockNode.MathBlock -> MathBlockView( block = block, styles = styles, mathRenderer = mathRenderer, modifier = modifier, ) ``` -------------------------------- ### Add math renderer toggle in Toolbar Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a row of buttons to select the math renderer option, using MathRendererOption.entries (requires Kotlin 1.9+). ```kotlin Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { AppText( text = "Math renderer:", style = SampleChatTheme.typography.bodyMedium, color = SampleChatTheme.colors.textSecondary, ) MathRendererOption.entries.forEach { option -> AppButton( text = option.label, onClick = { onMathRendererChange(option) }, filled = option == mathRendererOption, ) } } ``` -------------------------------- ### Bash: Commit block math parsing changes Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits the modified BlockParser.kt and new MathBlockParserTest.kt with a descriptive commit message. ```bash git add markdown-core/src/commonMain/kotlin/com/adamglin/compose/markdown/core/block/BlockParser.kt \ markdown-core/src/commonTest/kotlin/com/adamglin/compose/markdown/core/block/MathBlockParserTest.kt git commit -m "feat(core): parse block math ($$ and \\[ \\])" ``` -------------------------------- ### Commit changes for math renderer toggle Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Git commands to stage and commit the modified and new files for the math renderer toggle feature. ```bash git add sample-chat/src/commonMain/kotlin/com/adamglin/compose/markdown/sample/chat/SampleChatApp.kt \ sample-chat/src/commonMain/kotlin/com/adamglin/compose/markdown/sample/chat/SampleChatDefaults.kt \ sample-chat/src/commonMain/kotlin/com/adamglin/compose/markdown/sample/chat/BlockSnapshotDebugText.kt \ sample-chat/markdown-examples/math-showcase.md git commit -m "feat(sample): runtime math-renderer toggle, GfmMath engine, math example" ``` -------------------------------- ### Commit changes Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits the modified files for adding MathBlock and MathSpan AST nodes. ```bash git add markdown-core/src/commonMain/kotlin/com/adamglin/compose/markdown/core/model/BlockNode.kt \ markdown-core/src/commonMain/kotlin/com/adamglin/compose/markdown/core/model/InlineNode.kt \ markdown-core/src/commonMain/kotlin/com/adamglin/compose/markdown/core/engine/IncrementalMarkdownEngine.kt git commit -m "feat(core): add MathBlock and MathSpan AST nodes" ``` -------------------------------- ### Delegating toAnnotatedString extension Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Keeps the existing toAnnotatedString extension for plain joined text but delegates to the new inline render model builder. ```kotlin internal fun List.toAnnotatedString( styles: MarkdownInlineStyles = MarkdownInlineStyles( emphasis = SpanStyle(fontStyle = FontStyle.Italic), strong = SpanStyle(fontWeight = FontWeight.Bold), strike = SpanStyle(textDecoration = TextDecoration.LineThrough), code = SpanStyle(fontFamily = FontFamily.Monospace), link = TextLinkStyles(style = SpanStyle(textDecoration = TextDecoration.Underline)), ), onLinkClick: (String) -> Unit = {}, ): AnnotatedString = toInlineRenderModel(styles, onLinkClick).text ``` -------------------------------- ### InlineMathParserTest.kt - failing tests for inline math parsing Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Test class covering dollar and paren inline math, currency not treated as math, escaped dollar, and disabled dialect. Uses MarkdownEngine with MarkdownDialect.GfmMath and GfmCompat. Run with ./gradlew :markdown-core:jvmTest --tests "com.adamglin.compose.markdown.core.inline.InlineMathParserTest" to verify failure before implementation. ```kotlin package com.adamglin.compose.markdown.core.inline import com.adamglin.compose.markdown.core.api.MarkdownEngine import com.adamglin.compose.markdown.core.dialect.MarkdownDialect import com.adamglin.compose.markdown.core.model.BlockNode import com.adamglin.compose.markdown.core.model.InlineNode import com.adamglin.compose.markdown.core.model.MathInlineDelimiter import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue class InlineMathParserTest { private fun paragraph(markdown: String): BlockNode.Paragraph { val engine = MarkdownEngine(dialect = MarkdownDialect.GfmMath) return assertIs(engine.append(markdown).snapshot.document.blocks.first()) } @Test fun parsesDollarInlineMath() { val math = paragraph("energy is \$E = mc^2\$ today") .children.filterIsInstance().single() assertEquals("E = mc^2", math.latex) assertEquals(MathInlineDelimiter.Dollar, math.delimiter) } @Test fun parsesParenInlineMath() { val math = paragraph("value \\(a+b\\) end") .children.filterIsInstance().single() assertEquals("a+b", math.latex) assertEquals(MathInlineDelimiter.Paren, math.delimiter) } @Test fun currencyIsNotTreatedAsMath() { val children = paragraph("it costs \$5 and \$6 total").children assertTrue(children.none { it is InlineNode.MathSpan }) } @Test fun escapedDollarIsLiteral() { val children = paragraph("price \\\$5").children assertTrue(children.none { it is InlineNode.MathSpan }) } @Test fun disabledDialectDoesNotParseInlineMath() { val engine = MarkdownEngine(dialect = MarkdownDialect.GfmCompat) val paragraph = assertIs( engine.append("a \$E=mc^2\$ b").snapshot.document.blocks.first(), ) assertTrue(paragraph.children.none { it is InlineNode.MathSpan }) } } ``` -------------------------------- ### Add GfmMath dialect Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Add this new dialect after GfmCompat in sealed interface MarkdownDialect. ```kotlin data object GfmMath : MarkdownDialect { override val id: String = "gfm-math" override val preset: MarkdownPreset = MarkdownPreset.GfmMath override val blockFeatures: MarkdownBlockFeatures = preset.blockFeatures override val inlineFeatures: MarkdownInlineFeatures = preset.inlineFeatures } ``` -------------------------------- ### Forward mathRenderer in private Markdown composable Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Updates the private Markdown composable to accept and forward mathRenderer to MarkdownBlock. ```kotlin @Composable private fun Markdown( blocks: List, modifier: Modifier, style: MarkdownStyle, codeHighlighter: CodeHighlighter?, mathRenderer: MathRenderer?, onLinkClick: (String) -> Unit, ) { // …unchanged up to the forEach… MarkdownBlock( block = renderedBlock.block, styles = styles, codeHighlighter = codeHighlighter ?: defaultCodeHighlighter!!, mathRenderer = mathRenderer, onLinkClick = { currentOnLinkClick.value(it) }, ) } ``` -------------------------------- ### Test: gfmMathEnablesMathFeaturesAndOthersDoNot Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Append this test to DialectExtensionTest.kt to verify that GfmMath enables math features while GfmCompat and ChatFast do not. Requires imports MarkdownFeature and MarkdownDialect if absent. ```kotlin @Test fun gfmMathEnablesMathFeaturesAndOthersDoNot() { assertTrue(MarkdownDialect.GfmMath.blockFeatures.mathBlocks) assertTrue(MarkdownDialect.GfmMath.inlineFeatures.inlineMath) assertTrue(MarkdownDialect.GfmMath.supports(MarkdownFeature.MathBlock)) assertTrue(MarkdownDialect.GfmMath.supports(MarkdownFeature.InlineMath)) assertFalse(MarkdownDialect.GfmCompat.blockFeatures.mathBlocks) assertFalse(MarkdownDialect.GfmCompat.inlineFeatures.inlineMath) assertFalse(MarkdownDialect.ChatFast.supports(MarkdownFeature.MathBlock)) } ``` -------------------------------- ### MathRenderer interface in MarkdownMath.kt Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Defines the pluggable MathRenderer interface with BlockMath and inlineMathContent composable functions. markdown-compose ships only this interface; concrete implementations live in the consuming app. When no renderer is supplied, math falls back to its raw source text. ```kotlin package com.adamglin.compose.markdown.compose import androidx.compose.foundation.text.InlineTextContent import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.TextUnit /** * Pluggable renderer for LaTeX/math regions recognized by the parser. * * markdown-compose ships only this interface; concrete implementations (e.g. backed by a * LaTeX library) live in the consuming app. When no renderer is supplied, math falls back * to its raw source text. */ interface MathRenderer { /** Renders a display/block formula (`$$…$$` or `\[…\]`). */ @Composable fun BlockMath(latex: String, modifier: Modifier) /** * Builds the [InlineTextContent] used to lay an inline formula (`$…$` or `\(…\)`) inside a * line of text. The implementation owns the placeholder sizing (it may use [fontSize] and * `LocalDensity`). */ @Composable fun inlineMathContent(latex: String, fontSize: TextUnit): InlineTextContent } ``` -------------------------------- ### Add mathRenderer parameter to public Markdown composable Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a mathRenderer parameter to the public Markdown composable, defaulting to null, and forwards it to the private renderer. ```kotlin @Composable fun Markdown( snapshot: MarkdownSnapshot, style: MarkdownStyle, modifier: Modifier = Modifier, state: MarkdownRendererState = rememberMarkdownRendererState(snapshot = snapshot), codeHighlighter: CodeHighlighter? = null, mathRenderer: MathRenderer? = null, onLinkClick: (String) -> Unit = {}, ) { LaunchedEffect(snapshot) { state.render(snapshot) } Markdown( blocks = state.blocks, modifier = modifier, style = style, codeHighlighter = codeHighlighter, mathRenderer = mathRenderer, onLinkClick = onLinkClick, ) } ``` -------------------------------- ### Run inline math parser test Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Runs the specific test for the inline math parser. Expected to pass. ```bash ./gradlew :markdown-core:jvmTest --tests "com.adamglin.compose.markdown.core.inline.InlineMathParserTest" ``` -------------------------------- ### Commit inline math rendering changes Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Stages and commits the modified MarkdownRenderer.kt and MathBlockRenderingTest.kt files with a commit message about inline math rendering. ```bash git add markdown-compose/src/commonMain/kotlin/com/adamglin/compose/markdown/compose/MarkdownRenderer.kt \ markdown-compose/src/commonTest/kotlin/com/adamglin/compose/markdown/compose/MathBlockRenderingTest.kt git commit -m "feat(compose): render inline math via InlineTextContent" ``` -------------------------------- ### Add dollar inline math dispatch branch in parseSegment loop Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a branch after the backtick/code-span branch to parse $...$ inline math when dialect.inlineFeatures.inlineMath is enabled. ```kotlin if (char == '$' && dialect.inlineFeatures.inlineMath) { val parsed = parseInlineMathDollar(index = index, endExclusive = endExclusive) if (parsed != null) { flushText(index) nodes += parsed.node index = parsed.nextIndex textStart = index continue } } ``` -------------------------------- ### Add mathBlocks and inlineMath fields Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Add these fields with default false to MarkdownBlockFeatures and MarkdownInlineFeatures data classes in MarkdownDialect.kt. ```kotlin @Immutable data class MarkdownBlockFeatures( val atxHeadings: Boolean, val setextHeadings: Boolean, val fencedCodeBlocks: Boolean, val blockQuotes: Boolean, val lists: Boolean, val taskListItems: Boolean, val tables: Boolean, val rawHtml: Boolean, val mathBlocks: Boolean = false, ) ``` ```kotlin @Immutable data class MarkdownInlineFeatures( val inlineCode: Boolean, val emphasis: Boolean, val strong: Boolean, val strikethrough: Boolean, val inlineLinks: Boolean, val referenceLinks: Boolean, val autolinks: Boolean, val bareAutolinks: Boolean, val images: Boolean, val softBreaks: Boolean, val hardBreaks: Boolean, val inlineMath: Boolean = false, ) ``` -------------------------------- ### Add MathBlockView composable Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Defines MathBlockView, which uses mathRenderer.BlockMath when available, otherwise falls back to MarkdownText with streaming indicator. ```kotlin @Composable private fun MathBlockView( block: BlockNode.MathBlock, styles: MarkdownBlockStyles, mathRenderer: MathRenderer?, modifier: Modifier = Modifier, ) { if (mathRenderer != null) { mathRenderer.BlockMath(latex = block.latex, modifier = modifier.fillMaxWidth()) } else { MarkdownText( text = buildString { append(block.latex) if (!block.isClosed) { append(" streaming...") } }, style = styles.codeBlockTextStyle, modifier = modifier, ) } } ``` -------------------------------- ### Add MathBlockDelimiter import to BlockParser.kt Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the import for MathBlockDelimiter alongside other model imports in BlockParser.kt. ```kotlin import com.adamglin.compose.markdown.core.model.MathBlockDelimiter ``` -------------------------------- ### Run JVM benchmarks Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/performance-notes.md Runs the benchmark runner in the `benchmarks` module. Use `--smoke` for a quick smoke test (used by `ciCheck`). ```bash ./gradlew :benchmarks:run ``` ```bash ./gradlew :benchmarks:run --args="--smoke" ``` -------------------------------- ### Commit MathRenderer changes Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Commits the added MathRenderer slot and block-math rendering changes. ```bash git add markdown-compose/src/commonMain/kotlin/com/adamglin/compose/markdown/compose/MarkdownMath.kt \ markdown-compose/src/commonMain/kotlin/com/adamglin/compose/markdown/compose/MarkdownRenderer.kt \ markdown-compose/src/commonTest/kotlin/com/adamglin/compose/markdown/compose/MathBlockRenderingTest.kt \ markdown-compose/build.gradle.kts git commit -m "feat(compose): add MathRenderer slot and block-math rendering" ``` -------------------------------- ### Gradle dependency for UI test Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds the Compose UI test dependency to commonTest.dependencies in markdown-compose/build.gradle.kts. Required only if the file lacks a UI-test dependency; the compose extension is provided by the org.jetbrains.compose plugin. ```kotlin implementation(compose.uiTest) ``` -------------------------------- ### Failing test for inline math slot Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Adds a Compose UI test that verifies inline math is rendered via the math renderer slot. Uses FakeMathRenderer and expects the placeholder text 'INLINE:x+1' to be displayed. Run with the provided Gradle command to confirm it fails initially. ```kotlin @OptIn(ExperimentalTestApi::class) @Test fun inlineMathUsesTheSlot() = runComposeUiTest { val snapshot = MarkdownEngine(dialect = MarkdownDialect.GfmMath) .append("before \$x+1\$ after").snapshot setContent { Markdown(snapshot = snapshot, mathRenderer = FakeMathRenderer()) } onNodeWithText("INLINE:x+1").assertIsDisplayed() } ``` -------------------------------- ### Add enum entries to MarkdownFeature Source: https://github.com/adamglin0/compose-markdown/blob/main/docs/superpowers/plans/2026-06-29-latex-support.md Add these enum entries to MarkdownFeature before the closing brace. ```kotlin MathBlock, InlineMath, ```