
High-performance LaTeX math parser and renderer supporting full syntax, \newcommand macros, incremental parsing, chemical-formula (\ce{}) support, and extensive style customization (colors, boxes, display modes).
A high-performance LaTeX mathematical formula parsing and rendering library developed based on Kotlin Multiplatform (KMP). It supports consistent rendering effects on Android, iOS, macOS Native (Apple Silicon), Desktop (JVM), and Web (Wasm/JS) platforms.
InlineTextContent directly with LatexMeasurerState.inlineContent(), while retaining precise pre-measurement support.HighlightConfig.parseWithDiagnostics() provides 8-category structured diagnostics with severity filtering.\RLE, \LRE, RTL/LTR environments, nesting).\frac, \dfrac, \tfrac, \cfrac, \genfrac, \splitfrac, \splitdfrac, \binom, \tbinom, \dbinom, and TeX infix forms \over, \atop, \choose, \above; plus \sqrt, \sqrt[n]{x}, x_i, x^2. Unbraced scripts consume exactly one character.
\omicron), uppercase (Γ–Ω), KaTeX uppercase aliases (\Alpha, \Beta, \Epsilon, \Omicron, ...), and variants (ε/ϵ, θ/ϑ, φ/ϕ, \varGamma–\varOmega, etc.)+, -, \times, \div, \pm, \mp, \cdot, \oplus, \otimes, …=, \neq, <, >, \leq, \geq, \approx, \equiv, \sim, \coloneqq, \eqqcolon, …\in, \notin, \subset, \cup, \cap, \emptyset, \mathbb{R}, …\land, \lor, \neg, \Rightarrow, \Leftrightarrow, \forall, \exists
\to, \rightarrow, \leftarrow, \leftrightarrow, \Rightarrow, \hookrightarrow, harpoons, …\ldots, \cdots, \vdots, \ddots, \dots (auto-adaptive)\not=, \not\in, \nleq, \ngeq, \ncong, \nmid, … (30+ AMS negated relations)\checkmark, \complement, \blacksquare, \aleph, \measuredangle, geometric symbols, double-headed arrows, …\sum, \prod, \int, \oint, \iint, \iiint, \bigcup, \bigcap, \bigvee, \bigwedge, \coprod, \bigoplus, \bigotimes, \bigsqcup, \bigodot, \biguplus
\lim, \max, \min, \sup, \inf, \limsup, \liminf
\operatorname{name}, \operatorname*{name}, \DeclareMathOperator{\Tr}{Tr}, \mathop{content}
\substack{cond1 \\ cond2}
\bmod (binary), \pmod{n} (parenthesized), \mod (wide spacing)\mathord, \mathbin, \mathrel, \mathopen, \mathclose, \mathpunct, \mathinner control TeX atom class and inter-atom spacingmatrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, smallmatrix, their mathtools starred forms with [l|c|r], plus array and subarray.
\left( \right), \left[ \right], \left\{ \right\}, \left| \right|, and \middle inside a delimited expression; angle, floor, ceiling, and vertical-bar variants\left. \right| (evaluation bar), \left\{ \right. (piecewise)\big, \Big, \bigg, \Bigg with \bigl, \bigr, \bigm variants\hat, \tilde, \bar, \overline, \underline, \dot, \ddot, \dddot, \grave, \acute, \check, \widecheck, \breve, \ring/\mathring, \vec, \widehat, \overparen, \underparen
\overbrace{...}^{text}, \underbrace{...}_{text}, \overbracket{...}, \underbracket{...}
\overrightarrow, \overleftarrow, \overleftrightarrow, \underleftarrow, \underrightarrow
\cancel, \bcancel (reverse), \xcancel (cross)\xrightarrow, \xleftarrow, \xhookrightarrow, \xhookleftarrow, \xRightarrow, \xLeftarrow, \xLeftrightarrow, \xmapsto, \xlongequal
\overset, \underset, \stackrel
\mathbf, \mathit, \mathrm, \mathsf, \mathtt, \mathbb, \mathfrak, \mathcal, \mathscr, \boldsymbol, \bm, \text, \mbox, \textnormal, \textup, \textmd, \textsc, \textsl, \emph, and Unicode-math style aliases.
\tiny, \scriptsize, \footnotesize, \small, \normalsize, \large, \Large, \LARGE, \huge, \Huge
\displaystyle, \textstyle, \scriptstyle, \scriptscriptstyle, $...$ (inline), $$...$$ (display). Denominators, radicals, and subscripts use cramped style automatically. Manual controls include \cramped{...}, \cramped[\scriptstyle]{...}, and LuaTeX's four \cramped...style commands.
equation(*), displaymath
align(*), aligned, flalign(*), alignat(*), alignedat
gather(*), gathered
cases, dcases (displaystyle), rcases (right brace), including starred formssplit, multline(*)
eqnarray(*), subequations, tabular (l/c/r column alignment)\\, \cr, \intertext, \shortintertext, \notag, \nonumber, \tag/\tag*, \label/\ref/\eqref
\ , named math spaces, \hspace{...}, \kern, \mkern, and \allowbreak. Escaped special characters such as \{, \}, \$, \%, \#, \&, and \_ are also supported. \| produces a double vertical bar, equivalent to \Vert.
\color{red}{...}, \textcolor{#FF5733}{...} (named + hex)\colorbox{yellow}{text}, \fcolorbox{borderColor}{bgColor}{text}
\ce{H2O}, ions, coefficients, isotope notation, single/double/triple bonds, and reaction arrows with [above][below] annotations; \bond{...} and \pu{...} are also accepted.
\boxed{E=mc^2}, \fbox{text}
\enclose{circle}{x}, \enclose{circle,box}{x}, \enclose{updiagonalstrike downdiagonalstrike}{x}, \circled{1}
box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike
mathcolor, mathbackground
\phantom, \smash, \vphantom, \hphantom, \mathstrut
\mathclap{content}, \mathllap{content}, \mathrlap{content}
\clap, \llap, \rlap, \raisebox, \rule
\Aboxed, \MoveEqLeft, \splitfrac, \splitdfrac, definition relations, and \DeclarePairedDelimiter
\dv{x}, \dv{f}{x}, \dv[2]{f}{x}, and the corresponding \pdv forms\bra/\Bra, \ket/\Ket, \braket/\Braket, \comm, \anticomm, \eval, \vb, \va, \abs, \norm
\SI, \si; modern \qty, \unit, \numrange, \qtyrange, \ang; common SI prefix/unit macros\href{url}{text}, \url{url} (blue underline, click callback)\sideset{_a^b}{_c^d}{\sum}
\prescript{A}{Z}{X} (isotope notation)\tensor{T}{^a_b^c}, \indices{^a_b}
\newcommand, \renewcommand, \def (0–9 parameters, optional argument defaults), \newenvironment, \renewenvironment, \DeclarePairedDelimiter
TeX extensions include scoped groups ({...}, \begingroup/\endgroup, \bgroup/\egroup), token-based macro expansion, local/global definitions, \providecommand, \let, \edef/\xdef, expansion control and conditionals. Math style choices, named colors, structured/verbatim text, and array spacing/dashed rules are also supported. See implementation scope and definition-node API changes.
\section, \subsection, \subsubsection, \paragraph, \subparagraph (with starred variants)
\RLE{...}, \LRE{...}, \textarabic{...}, \texthebrew{...}
\begin{RTL}...\end{RTL}, \begin{LTR}...\end{LTR}
\label, \ref, \eqref, \tag{1}, \tag*{A}
parseWithDiagnostics() provides structured diagnostics (8 categories, filter by severity)The project includes a Demo App (composeApp/androidapp) showcasing various complex LaTeX scenarios. The preview dataset also contains a dedicated Enclose / menclose group covering circles, boxes, combined borders, strike-throughs, and color/background attributes:
| Basic Math | Chemical Formulas | Incremental Parsing |
|---|---|---|
![]() |
![]() |
![]() |
| Basic Math Rendering | Supports \ce{...} syntax |
Real-time preview for incomplete input |
In a Compose Multiplatform project, you can use the Latex component directly. The component handles incremental parsing automatically and supports real-time preview:
import com.hrm.latex.renderer.Latex
import com.hrm.latex.renderer.model.LatexConfig
import com.hrm.latex.renderer.model.LatexTheme
import androidx.compose.ui.unit.sp
@Composable
fun MyScreen() {
Latex(
latex = "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
config = LatexConfig(
fontSize = 20.sp,
theme = LatexTheme.auto()
)
)
}[!WARNING] We strongly recommend adding the bundled
latex-fonts-katexfonts. The layout engine uses KaTeX-specific math metrics. Other fonts may cause missing glyphs, misaligned symbols or accents, incorrect script spacing, and distorted delimiter sizing. Correct rendering is not guaranteed without the matching fonts.
Add the optional latex-fonts-katex dependency (see Installation)
to use KaTeX automatically. No manual initialization is needed. The font module contains resources only; the renderer loads them
at runtime without referencing classes from that module.
commonMain.dependencies {
implementation(libs.latex.renderer)
implementation(libs.latex.fonts.katex)
}Use Latex(latex = "E = mc^2") with the default config. The first request starts
one shared asynchronous font load. System fonts are used while loading; successful
loading updates the active renderers. Each font resource is read once per process,
and both success and failure are cached. Recomposition, new views, and concurrent
requests do not trigger another load.
Omitting or excluding the font module is supported: missing resources or loading failures fall back to system fonts without crashing. A failed attempt is not retried until the process restarts. Web apps must make the font resources available before the first formula requests them.
Explicit LatexConfig.fontFamilies takes priority and bypasses automatic loading.
For example, LatexConfig(fontFamilies = systemLatexFontFamilies()) always selects
system fonts (systemLatexFontFamilies is in com.hrm.latex.renderer.model).
Reuse the config with LatexAutoWrap, LatexEditor, rememberLatexMeasurer, and
rememberLatexExporter for consistent fonts.
Use LatexTheme to control formula foreground/background colors:
import com.hrm.latex.renderer.model.LatexTheme
// Follow system light/dark mode
LatexConfig(theme = LatexTheme.auto())
// Fixed light theme
LatexConfig(theme = LatexTheme.light())
// Fixed dark theme
LatexConfig(theme = LatexTheme.dark())
// Follow current Material 3 ColorScheme
LatexConfig(theme = LatexTheme.material3())If you need custom colors, build them from LatexThemeColors:
import androidx.compose.ui.graphics.Color
import com.hrm.latex.renderer.model.LatexTheme
import com.hrm.latex.renderer.model.LatexThemeColors
LatexConfig(
theme = LatexTheme.auto(
light = LatexThemeColors(
color = Color(0xFF111111),
backgroundColor = Color.Transparent
),
dark = LatexThemeColors(
color = Color(0xFFF5F5F5),
backgroundColor = Color.Transparent
)
)
)For long formulas that need to wrap within the container width, use LatexAutoWrap:
import com.hrm.latex.renderer.LatexAutoWrap
@Composable
fun MyScreen() {
LatexAutoWrap(
latex = "E = mc^2 + \\frac{p^2}{2m} + V(x) + \\frac{1}{2}kx^2",
modifier = Modifier.fillMaxWidth(),
config = LatexConfig(fontSize = 20.sp)
)
}Line breaks occur at mathematically valid points: relation operators (=, <, >), then additive operators (+, -), then multiplicative operators (×, ÷). Atomic structures like fractions, roots, and matrices are never broken.
Export rendered LaTeX formulas as PNG, JPEG, or WEBP images. Use rememberLatexExporter() in a Composable scope, then call export() on a background thread:
import com.hrm.latex.renderer.export.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun MyScreen() {
val exporter = rememberLatexExporter()
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch(Dispatchers.Default) {
// Export as PNG (default, 2x resolution)
val result = exporter.export("E = mc^2")
val pngBytes = result?.bytes // PNG byte array
val bitmap = result?.imageBitmap // For in-app display
// Export as JPEG (3x resolution, quality 85)
val jpegResult = exporter.export(
latex = "\\frac{a}{b}",
exportConfig = ExportConfig(
scale = 3f,
format = ImageFormat.JPEG,
quality = 85
)
)
// Export with transparent background (PNG only)
val transparentResult = exporter.export(
latex = "x^2 + y^2 = r^2",
exportConfig = ExportConfig(transparentBackground = true)
)
}
}) {
Text("Export")
}
}ExportConfig parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
scale |
Float |
2f |
Resolution multiplier (1x, 2x, 3x, etc.) |
format |
ImageFormat |
PNG |
ImageFormat.PNG, ImageFormat.JPEG, or ImageFormat.WEBP
|
transparentBackground |
Boolean |
false |
Use transparent background (PNG and WEBP only; JPEG always uses opaque background) |
quality |
Int |
90 |
Compression quality (1–100) for JPEG and WEBP; ignored for PNG |
For print, responsive Web embedding, or resolution-independent output, use exportSvg(). It
reuses the exact same measure-and-draw pipeline as on-screen rendering and emits vector paths,
lines, and shapes—never a raster image wrapped in SVG:
val svgResult = exporter.exportSvg(
latex = "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
exportConfig = SvgExportConfig(
transparentBackground = true,
textMode = SvgTextMode.PATH
)
)
val svg = svgResult?.svg // SVG text for Web embedding
val svgBytes = svgResult?.bytes // UTF-8 bytes for saving or sharingSvgExportConfig is intentionally separate from raster options:
| Parameter | Type | Default | Description |
|---|---|---|---|
scale |
Float |
1f |
Changes the SVG viewport and formula size; SVG remains resolution-independent |
transparentBackground |
Boolean |
true |
Transparent output, or the resolved LatexConfig background |
textMode |
SvgTextMode |
PATH |
PATH embeds portable glyph outlines; TEXT is smaller/selectable but requires matching fonts |
prettyPrint |
Boolean |
true |
Format the generated XML |
The library provides built-in accessibility support for screen readers. When enabled, each Latex component exposes a MathSpeak-style natural language description via Compose semantics, making math formulas readable by TalkBack (Android), VoiceOver (iOS), and other assistive technologies.
Latex(
latex = "\\frac{1}{2}",
config = LatexConfig(accessibilityEnabled = true)
)
// Screen reader reads: "fraction: 1 over 2"The AccessibilityVisitor converts the LaTeX AST into descriptive text covering fractions, roots, superscripts/subscripts, matrices, Greek letters, operators, and more.
inlineContent() encapsulates formula pre-measurement, Placeholder sizing, and rendering for direct use with Compose Text:
val measurer = rememberLatexMeasurer(config)
val formula = measurer.inlineContent("\\frac{a}{b}", config, isDarkTheme = isSystemInDarkTheme())
Text(
text = buildAnnotatedString {
append("The fraction ")
appendInlineContent("formula", "a divided by b")
append(" represents a divided by b.")
},
inlineContent = formula?.let { mapOf("formula" to it) }.orEmpty()
)For blank input or measurement failure, inlineContent() returns null, allowing Compose to display the alternate text supplied to appendInlineContent(). Repeated calls with the same formula and configuration reuse the LatexMeasurerState cache. The returned content draws the pre-measured layout directly, so each formula is parsed and measured only once; pass isDarkTheme matching the current system theme, otherwise it is measured again with the system theme at render time.
For custom layouts, the lower-level measure() API remains available. LatexDimensions provides widthPx, heightPx, and baselinePx (including padding), plus corresponding content-only fields. Use measureBatch() for batch measurement.
Note: The editor API is experimental and may change in future versions. All editor APIs require the
@ExperimentalComposeUiApiannotation.
The library includes a built-in WYSIWYG (What You See Is What You Get) LaTeX editor component. Users can edit LaTeX source text and see the rendered formula in real-time, with cursor position synchronized between the source and the rendered output.
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyEditor() {
val editorState = rememberEditorState(initialText = "x^{2} + y^{2} = r^{2}")
LatexEditor(
editorState = editorState,
config = LatexConfig(fontSize = 20.sp),
showSourceText = true // Show source text input field
)
}Choose the variant matching your Kotlin version:
| Variant | Kotlin | Compose Multiplatform | Artifact Version |
|---|---|---|---|
| Standard | 2.3.10 | 1.10.3 | <version> |
| Kotlin 2.1.0 | 2.1.0 | 1.9.3 | <version>-kt2.1.0 |
Replace <version> with a published release and use the same version for all
LaTeX modules. KaTeX fonts require a release containing latex-fonts-katex.
Add to gradle/libs.versions.toml:
[versions]
latex = "<version>" # Use "<version>-kt2.1.0" for Kotlin 2.1.0
[libraries]
latex-base = { module = "io.github.huarangmeng:latex-base", version.ref = "latex" }
latex-parser = { module = "io.github.huarangmeng:latex-parser", version.ref = "latex" }
latex-renderer = { module = "io.github.huarangmeng:latex-renderer", version.ref = "latex" }
latex-fonts-katex = { module = "io.github.huarangmeng:latex-fonts-katex", version.ref = "latex" }In your module's build.gradle.kts, add to kotlin.sourceSets:
commonMain.dependencies {
implementation(libs.latex.renderer) // Includes parser and base
implementation(libs.latex.fonts.katex) // Strongly recommended: matching KaTeX fonts
}For Android/JVM-only modules, put these dependencies in dependencies.
The font dependency is optional, but omitting it may cause rendering issues.
KaTeX loads automatically when the dependency is present; no initialization is needed.
See Math Fonts. For parsing only, depend on
libs.latex.parser.
All four libraries provide macosArm64; use the commonMain dependencies above.
PlatformType.MACOS has desktop semantics, distinct from iOS and Desktop (JVM).
With Compose Multiplatform 1.10.3 / Material3 1.9.0, the consuming project must set:
org.jetbrains.compose.experimental.macos.enabled=trueFor KaTeX fonts, include latex-fonts-katex. The application host must stage
compose-resources/composeResources/ in the bundle's Resources directory;
unbundled executables must follow Compose's macOS resource lookup contract.
Run on an ARM64 Mac:
./gradlew :latex-base:macosArm64Test :latex-parser:macosArm64Test :latex-renderer:macosArm64Test :latex-fonts-katex:macosArm64Test --max-workers=2CI checks real byte fonts, glyphs, SVG/image ink, iOS compilation and publication metadata without publishing. Windows/Linux metadata checks do not validate Native linking or execution. Kotlin 2.1.0 alias versions are not covered by this job.
:latex-base: Base data structures and interfaces.:latex-parser: Core parsing engine, responsible for converting LaTeX strings to AST.:latex-renderer: Renders AST into Compose UI components; automatically loads optional KaTeX resources, falling back to system fonts.:latex-fonts-katex: Optional KaTeX TTF resources; no renderer dependency or initialization API.:latex-preview: Preview components and sample datasets.:composeApp: Cross-platform Demo application.:androidapp: Android Demo application../gradlew :composeApp:assembleDebug
./gradlew :composeApp:run
./gradlew :composeApp:wasmJsBrowserDevelopmentRun
iosApp/iosApp.xcworkspace in Xcode to run../run_parser_tests.shFor supported features and chapter-specific follow-up items, see PARSER_COVERAGE_ANALYSIS.md.
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2026 huarangmeng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
A high-performance LaTeX mathematical formula parsing and rendering library developed based on Kotlin Multiplatform (KMP). It supports consistent rendering effects on Android, iOS, macOS Native (Apple Silicon), Desktop (JVM), and Web (Wasm/JS) platforms.
InlineTextContent directly with LatexMeasurerState.inlineContent(), while retaining precise pre-measurement support.HighlightConfig.parseWithDiagnostics() provides 8-category structured diagnostics with severity filtering.\RLE, \LRE, RTL/LTR environments, nesting).\frac, \dfrac, \tfrac, \cfrac, \genfrac, \splitfrac, \splitdfrac, \binom, \tbinom, \dbinom, and TeX infix forms \over, \atop, \choose, \above; plus \sqrt, \sqrt[n]{x}, x_i, x^2. Unbraced scripts consume exactly one character.
\omicron), uppercase (Γ–Ω), KaTeX uppercase aliases (\Alpha, \Beta, \Epsilon, \Omicron, ...), and variants (ε/ϵ, θ/ϑ, φ/ϕ, \varGamma–\varOmega, etc.)+, -, \times, \div, \pm, \mp, \cdot, \oplus, \otimes, …=, \neq, <, >, \leq, \geq, \approx, \equiv, \sim, \coloneqq, \eqqcolon, …\in, \notin, \subset, \cup, \cap, \emptyset, \mathbb{R}, …\land, \lor, \neg, \Rightarrow, \Leftrightarrow, \forall, \exists
\to, \rightarrow, \leftarrow, \leftrightarrow, \Rightarrow, \hookrightarrow, harpoons, …\ldots, \cdots, \vdots, \ddots, \dots (auto-adaptive)\not=, \not\in, \nleq, \ngeq, \ncong, \nmid, … (30+ AMS negated relations)\checkmark, \complement, \blacksquare, \aleph, \measuredangle, geometric symbols, double-headed arrows, …\sum, \prod, \int, \oint, \iint, \iiint, \bigcup, \bigcap, \bigvee, \bigwedge, \coprod, \bigoplus, \bigotimes, \bigsqcup, \bigodot, \biguplus
\lim, \max, \min, \sup, \inf, \limsup, \liminf
\operatorname{name}, \operatorname*{name}, \DeclareMathOperator{\Tr}{Tr}, \mathop{content}
\substack{cond1 \\ cond2}
\bmod (binary), \pmod{n} (parenthesized), \mod (wide spacing)\mathord, \mathbin, \mathrel, \mathopen, \mathclose, \mathpunct, \mathinner control TeX atom class and inter-atom spacingmatrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, smallmatrix, their mathtools starred forms with [l|c|r], plus array and subarray.
\left( \right), \left[ \right], \left\{ \right\}, \left| \right|, and \middle inside a delimited expression; angle, floor, ceiling, and vertical-bar variants\left. \right| (evaluation bar), \left\{ \right. (piecewise)\big, \Big, \bigg, \Bigg with \bigl, \bigr, \bigm variants\hat, \tilde, \bar, \overline, \underline, \dot, \ddot, \dddot, \grave, \acute, \check, \widecheck, \breve, \ring/\mathring, \vec, \widehat, \overparen, \underparen
\overbrace{...}^{text}, \underbrace{...}_{text}, \overbracket{...}, \underbracket{...}
\overrightarrow, \overleftarrow, \overleftrightarrow, \underleftarrow, \underrightarrow
\cancel, \bcancel (reverse), \xcancel (cross)\xrightarrow, \xleftarrow, \xhookrightarrow, \xhookleftarrow, \xRightarrow, \xLeftarrow, \xLeftrightarrow, \xmapsto, \xlongequal
\overset, \underset, \stackrel
\mathbf, \mathit, \mathrm, \mathsf, \mathtt, \mathbb, \mathfrak, \mathcal, \mathscr, \boldsymbol, \bm, \text, \mbox, \textnormal, \textup, \textmd, \textsc, \textsl, \emph, and Unicode-math style aliases.
\tiny, \scriptsize, \footnotesize, \small, \normalsize, \large, \Large, \LARGE, \huge, \Huge
\displaystyle, \textstyle, \scriptstyle, \scriptscriptstyle, $...$ (inline), $$...$$ (display). Denominators, radicals, and subscripts use cramped style automatically. Manual controls include \cramped{...}, \cramped[\scriptstyle]{...}, and LuaTeX's four \cramped...style commands.
equation(*), displaymath
align(*), aligned, flalign(*), alignat(*), alignedat
gather(*), gathered
cases, dcases (displaystyle), rcases (right brace), including starred formssplit, multline(*)
eqnarray(*), subequations, tabular (l/c/r column alignment)\\, \cr, \intertext, \shortintertext, \notag, \nonumber, \tag/\tag*, \label/\ref/\eqref
\ , named math spaces, \hspace{...}, \kern, \mkern, and \allowbreak. Escaped special characters such as \{, \}, \$, \%, \#, \&, and \_ are also supported. \| produces a double vertical bar, equivalent to \Vert.
\color{red}{...}, \textcolor{#FF5733}{...} (named + hex)\colorbox{yellow}{text}, \fcolorbox{borderColor}{bgColor}{text}
\ce{H2O}, ions, coefficients, isotope notation, single/double/triple bonds, and reaction arrows with [above][below] annotations; \bond{...} and \pu{...} are also accepted.
\boxed{E=mc^2}, \fbox{text}
\enclose{circle}{x}, \enclose{circle,box}{x}, \enclose{updiagonalstrike downdiagonalstrike}{x}, \circled{1}
box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike
mathcolor, mathbackground
\phantom, \smash, \vphantom, \hphantom, \mathstrut
\mathclap{content}, \mathllap{content}, \mathrlap{content}
\clap, \llap, \rlap, \raisebox, \rule
\Aboxed, \MoveEqLeft, \splitfrac, \splitdfrac, definition relations, and \DeclarePairedDelimiter
\dv{x}, \dv{f}{x}, \dv[2]{f}{x}, and the corresponding \pdv forms\bra/\Bra, \ket/\Ket, \braket/\Braket, \comm, \anticomm, \eval, \vb, \va, \abs, \norm
\SI, \si; modern \qty, \unit, \numrange, \qtyrange, \ang; common SI prefix/unit macros\href{url}{text}, \url{url} (blue underline, click callback)\sideset{_a^b}{_c^d}{\sum}
\prescript{A}{Z}{X} (isotope notation)\tensor{T}{^a_b^c}, \indices{^a_b}
\newcommand, \renewcommand, \def (0–9 parameters, optional argument defaults), \newenvironment, \renewenvironment, \DeclarePairedDelimiter
TeX extensions include scoped groups ({...}, \begingroup/\endgroup, \bgroup/\egroup), token-based macro expansion, local/global definitions, \providecommand, \let, \edef/\xdef, expansion control and conditionals. Math style choices, named colors, structured/verbatim text, and array spacing/dashed rules are also supported. See implementation scope and definition-node API changes.
\section, \subsection, \subsubsection, \paragraph, \subparagraph (with starred variants)
\RLE{...}, \LRE{...}, \textarabic{...}, \texthebrew{...}
\begin{RTL}...\end{RTL}, \begin{LTR}...\end{LTR}
\label, \ref, \eqref, \tag{1}, \tag*{A}
parseWithDiagnostics() provides structured diagnostics (8 categories, filter by severity)The project includes a Demo App (composeApp/androidapp) showcasing various complex LaTeX scenarios. The preview dataset also contains a dedicated Enclose / menclose group covering circles, boxes, combined borders, strike-throughs, and color/background attributes:
| Basic Math | Chemical Formulas | Incremental Parsing |
|---|---|---|
![]() |
![]() |
![]() |
| Basic Math Rendering | Supports \ce{...} syntax |
Real-time preview for incomplete input |
In a Compose Multiplatform project, you can use the Latex component directly. The component handles incremental parsing automatically and supports real-time preview:
import com.hrm.latex.renderer.Latex
import com.hrm.latex.renderer.model.LatexConfig
import com.hrm.latex.renderer.model.LatexTheme
import androidx.compose.ui.unit.sp
@Composable
fun MyScreen() {
Latex(
latex = "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
config = LatexConfig(
fontSize = 20.sp,
theme = LatexTheme.auto()
)
)
}[!WARNING] We strongly recommend adding the bundled
latex-fonts-katexfonts. The layout engine uses KaTeX-specific math metrics. Other fonts may cause missing glyphs, misaligned symbols or accents, incorrect script spacing, and distorted delimiter sizing. Correct rendering is not guaranteed without the matching fonts.
Add the optional latex-fonts-katex dependency (see Installation)
to use KaTeX automatically. No manual initialization is needed. The font module contains resources only; the renderer loads them
at runtime without referencing classes from that module.
commonMain.dependencies {
implementation(libs.latex.renderer)
implementation(libs.latex.fonts.katex)
}Use Latex(latex = "E = mc^2") with the default config. The first request starts
one shared asynchronous font load. System fonts are used while loading; successful
loading updates the active renderers. Each font resource is read once per process,
and both success and failure are cached. Recomposition, new views, and concurrent
requests do not trigger another load.
Omitting or excluding the font module is supported: missing resources or loading failures fall back to system fonts without crashing. A failed attempt is not retried until the process restarts. Web apps must make the font resources available before the first formula requests them.
Explicit LatexConfig.fontFamilies takes priority and bypasses automatic loading.
For example, LatexConfig(fontFamilies = systemLatexFontFamilies()) always selects
system fonts (systemLatexFontFamilies is in com.hrm.latex.renderer.model).
Reuse the config with LatexAutoWrap, LatexEditor, rememberLatexMeasurer, and
rememberLatexExporter for consistent fonts.
Use LatexTheme to control formula foreground/background colors:
import com.hrm.latex.renderer.model.LatexTheme
// Follow system light/dark mode
LatexConfig(theme = LatexTheme.auto())
// Fixed light theme
LatexConfig(theme = LatexTheme.light())
// Fixed dark theme
LatexConfig(theme = LatexTheme.dark())
// Follow current Material 3 ColorScheme
LatexConfig(theme = LatexTheme.material3())If you need custom colors, build them from LatexThemeColors:
import androidx.compose.ui.graphics.Color
import com.hrm.latex.renderer.model.LatexTheme
import com.hrm.latex.renderer.model.LatexThemeColors
LatexConfig(
theme = LatexTheme.auto(
light = LatexThemeColors(
color = Color(0xFF111111),
backgroundColor = Color.Transparent
),
dark = LatexThemeColors(
color = Color(0xFFF5F5F5),
backgroundColor = Color.Transparent
)
)
)For long formulas that need to wrap within the container width, use LatexAutoWrap:
import com.hrm.latex.renderer.LatexAutoWrap
@Composable
fun MyScreen() {
LatexAutoWrap(
latex = "E = mc^2 + \\frac{p^2}{2m} + V(x) + \\frac{1}{2}kx^2",
modifier = Modifier.fillMaxWidth(),
config = LatexConfig(fontSize = 20.sp)
)
}Line breaks occur at mathematically valid points: relation operators (=, <, >), then additive operators (+, -), then multiplicative operators (×, ÷). Atomic structures like fractions, roots, and matrices are never broken.
Export rendered LaTeX formulas as PNG, JPEG, or WEBP images. Use rememberLatexExporter() in a Composable scope, then call export() on a background thread:
import com.hrm.latex.renderer.export.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun MyScreen() {
val exporter = rememberLatexExporter()
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch(Dispatchers.Default) {
// Export as PNG (default, 2x resolution)
val result = exporter.export("E = mc^2")
val pngBytes = result?.bytes // PNG byte array
val bitmap = result?.imageBitmap // For in-app display
// Export as JPEG (3x resolution, quality 85)
val jpegResult = exporter.export(
latex = "\\frac{a}{b}",
exportConfig = ExportConfig(
scale = 3f,
format = ImageFormat.JPEG,
quality = 85
)
)
// Export with transparent background (PNG only)
val transparentResult = exporter.export(
latex = "x^2 + y^2 = r^2",
exportConfig = ExportConfig(transparentBackground = true)
)
}
}) {
Text("Export")
}
}ExportConfig parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
scale |
Float |
2f |
Resolution multiplier (1x, 2x, 3x, etc.) |
format |
ImageFormat |
PNG |
ImageFormat.PNG, ImageFormat.JPEG, or ImageFormat.WEBP
|
transparentBackground |
Boolean |
false |
Use transparent background (PNG and WEBP only; JPEG always uses opaque background) |
quality |
Int |
90 |
Compression quality (1–100) for JPEG and WEBP; ignored for PNG |
For print, responsive Web embedding, or resolution-independent output, use exportSvg(). It
reuses the exact same measure-and-draw pipeline as on-screen rendering and emits vector paths,
lines, and shapes—never a raster image wrapped in SVG:
val svgResult = exporter.exportSvg(
latex = "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
exportConfig = SvgExportConfig(
transparentBackground = true,
textMode = SvgTextMode.PATH
)
)
val svg = svgResult?.svg // SVG text for Web embedding
val svgBytes = svgResult?.bytes // UTF-8 bytes for saving or sharingSvgExportConfig is intentionally separate from raster options:
| Parameter | Type | Default | Description |
|---|---|---|---|
scale |
Float |
1f |
Changes the SVG viewport and formula size; SVG remains resolution-independent |
transparentBackground |
Boolean |
true |
Transparent output, or the resolved LatexConfig background |
textMode |
SvgTextMode |
PATH |
PATH embeds portable glyph outlines; TEXT is smaller/selectable but requires matching fonts |
prettyPrint |
Boolean |
true |
Format the generated XML |
The library provides built-in accessibility support for screen readers. When enabled, each Latex component exposes a MathSpeak-style natural language description via Compose semantics, making math formulas readable by TalkBack (Android), VoiceOver (iOS), and other assistive technologies.
Latex(
latex = "\\frac{1}{2}",
config = LatexConfig(accessibilityEnabled = true)
)
// Screen reader reads: "fraction: 1 over 2"The AccessibilityVisitor converts the LaTeX AST into descriptive text covering fractions, roots, superscripts/subscripts, matrices, Greek letters, operators, and more.
inlineContent() encapsulates formula pre-measurement, Placeholder sizing, and rendering for direct use with Compose Text:
val measurer = rememberLatexMeasurer(config)
val formula = measurer.inlineContent("\\frac{a}{b}", config, isDarkTheme = isSystemInDarkTheme())
Text(
text = buildAnnotatedString {
append("The fraction ")
appendInlineContent("formula", "a divided by b")
append(" represents a divided by b.")
},
inlineContent = formula?.let { mapOf("formula" to it) }.orEmpty()
)For blank input or measurement failure, inlineContent() returns null, allowing Compose to display the alternate text supplied to appendInlineContent(). Repeated calls with the same formula and configuration reuse the LatexMeasurerState cache. The returned content draws the pre-measured layout directly, so each formula is parsed and measured only once; pass isDarkTheme matching the current system theme, otherwise it is measured again with the system theme at render time.
For custom layouts, the lower-level measure() API remains available. LatexDimensions provides widthPx, heightPx, and baselinePx (including padding), plus corresponding content-only fields. Use measureBatch() for batch measurement.
Note: The editor API is experimental and may change in future versions. All editor APIs require the
@ExperimentalComposeUiApiannotation.
The library includes a built-in WYSIWYG (What You See Is What You Get) LaTeX editor component. Users can edit LaTeX source text and see the rendered formula in real-time, with cursor position synchronized between the source and the rendered output.
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyEditor() {
val editorState = rememberEditorState(initialText = "x^{2} + y^{2} = r^{2}")
LatexEditor(
editorState = editorState,
config = LatexConfig(fontSize = 20.sp),
showSourceText = true // Show source text input field
)
}Choose the variant matching your Kotlin version:
| Variant | Kotlin | Compose Multiplatform | Artifact Version |
|---|---|---|---|
| Standard | 2.3.10 | 1.10.3 | <version> |
| Kotlin 2.1.0 | 2.1.0 | 1.9.3 | <version>-kt2.1.0 |
Replace <version> with a published release and use the same version for all
LaTeX modules. KaTeX fonts require a release containing latex-fonts-katex.
Add to gradle/libs.versions.toml:
[versions]
latex = "<version>" # Use "<version>-kt2.1.0" for Kotlin 2.1.0
[libraries]
latex-base = { module = "io.github.huarangmeng:latex-base", version.ref = "latex" }
latex-parser = { module = "io.github.huarangmeng:latex-parser", version.ref = "latex" }
latex-renderer = { module = "io.github.huarangmeng:latex-renderer", version.ref = "latex" }
latex-fonts-katex = { module = "io.github.huarangmeng:latex-fonts-katex", version.ref = "latex" }In your module's build.gradle.kts, add to kotlin.sourceSets:
commonMain.dependencies {
implementation(libs.latex.renderer) // Includes parser and base
implementation(libs.latex.fonts.katex) // Strongly recommended: matching KaTeX fonts
}For Android/JVM-only modules, put these dependencies in dependencies.
The font dependency is optional, but omitting it may cause rendering issues.
KaTeX loads automatically when the dependency is present; no initialization is needed.
See Math Fonts. For parsing only, depend on
libs.latex.parser.
All four libraries provide macosArm64; use the commonMain dependencies above.
PlatformType.MACOS has desktop semantics, distinct from iOS and Desktop (JVM).
With Compose Multiplatform 1.10.3 / Material3 1.9.0, the consuming project must set:
org.jetbrains.compose.experimental.macos.enabled=trueFor KaTeX fonts, include latex-fonts-katex. The application host must stage
compose-resources/composeResources/ in the bundle's Resources directory;
unbundled executables must follow Compose's macOS resource lookup contract.
Run on an ARM64 Mac:
./gradlew :latex-base:macosArm64Test :latex-parser:macosArm64Test :latex-renderer:macosArm64Test :latex-fonts-katex:macosArm64Test --max-workers=2CI checks real byte fonts, glyphs, SVG/image ink, iOS compilation and publication metadata without publishing. Windows/Linux metadata checks do not validate Native linking or execution. Kotlin 2.1.0 alias versions are not covered by this job.
:latex-base: Base data structures and interfaces.:latex-parser: Core parsing engine, responsible for converting LaTeX strings to AST.:latex-renderer: Renders AST into Compose UI components; automatically loads optional KaTeX resources, falling back to system fonts.:latex-fonts-katex: Optional KaTeX TTF resources; no renderer dependency or initialization API.:latex-preview: Preview components and sample datasets.:composeApp: Cross-platform Demo application.:androidapp: Android Demo application../gradlew :composeApp:assembleDebug
./gradlew :composeApp:run
./gradlew :composeApp:wasmJsBrowserDevelopmentRun
iosApp/iosApp.xcworkspace in Xcode to run../run_parser_tests.shFor supported features and chapter-specific follow-up items, see PARSER_COVERAGE_ANALYSIS.md.
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2026 huarangmeng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.