Skip to content

zly2006/latex

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

144 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Kotlin Multiplatform LaTeX Rendering Library

Kotlin Compose Multiplatform Android API License Maven Central

A high-performance LaTeX mathematical formula parsing and rendering library developed based on Kotlin Multiplatform (KMP). It supports consistent rendering effects on Android, iOS, Desktop (JVM), and Web (Wasm/JS) platforms.

δΈ­ζ–‡η‰ˆζœ¬

🌟 Key Features

  • High-Performance Parsing: AST-based recursive descent parser with support for incremental updates.
  • Multi-platform Consistency: Uses Compose Multiplatform for consistent rendering on Android, iOS, Desktop (JVM), and Web (Wasm/JS).
  • Automatic Line Breaking: Smart line wrapping for long formulas at logical breakpoints (operators, relations).
  • Image Export: Export rendered formulas as PNG/JPEG/WEBP images with configurable resolution scaling.
  • Pre-measurement API: Synchronous pre-measurement of formula dimensions (width/height/baseline) for Compose InlineTextContent inline math embedding.
  • Accessibility: Built-in screen reader support with MathSpeak-style formula descriptions (MathSpeak).
  • LaTeX β†’ MathML: Convert LaTeX AST to Presentation MathML output.
  • Formula Highlight: Highlight sub-expressions within formulas via HighlightConfig.
  • Animation: Animated formula transitions (crossfade / slide / fade+slide).
  • WYSIWYG Editor (Experimental): Built-in LaTeX editor with cursor positioning, tap-to-place, and real-time rendered preview.
  • Structured Diagnostics: parseWithDiagnostics() provides 8-category structured diagnostics with severity filtering.
  • RTL Support: Complete right-to-left text direction support (\RLE, \LRE, RTL/LTR environments, nesting).

πŸ“ Supported LaTeX Features (372+)

Math Formulas β€” fractions, roots, binomials

\frac, \dfrac, \tfrac, \cfrac, \binom, \tbinom, \dbinom, \sqrt, \sqrt[n]{x}

Symbols (130+) β€” Greek letters, operators, arrows, AMS symbols
  • Greek letters: all lowercase (α–ω), uppercase (Γ–Ω), and variants (Ξ΅/Ο΅, ΞΈ/Ο‘, Ο†/Ο•, etc.)
  • Operators: +, -, \times, \div, \pm, \mp, \cdot, \oplus, \otimes, …
  • Relations: =, \neq, <, >, \leq, \geq, \approx, \equiv, \sim, \ll, \gg, …
  • Set theory: \in, \notin, \subset, \cup, \cap, \emptyset, \mathbb{R}, …
  • Logic: \land, \lor, \neg, \Rightarrow, \Leftrightarrow, \forall, \exists
  • Arrows: \to, \rightarrow, \leftarrow, \leftrightarrow, \Rightarrow, \hookrightarrow, harpoons, …
  • Ellipsis: \ldots, \cdots, \vdots, \ddots, \dots (auto-adaptive)
  • Negation: \not=, \not\in, \nleq, \ngeq, \ncong, \nmid, … (30+ AMS negated relations)
  • AMS extras: \checkmark, \complement, \blacksquare, \aleph, \measuredangle, geometric symbols, double-headed arrows, …
Large Operators (28) β€” sums, integrals, limits, modular arithmetic
  • Sums/Integrals: \sum, \prod, \int, \oint, \iint, \iiint, \bigcup, \bigcap, \bigvee, \bigwedge, \coprod, \bigoplus, \bigotimes, \bigsqcup, \bigodot, \biguplus
  • Limits: \lim, \max, \min, \sup, \inf, \limsup, \liminf
  • Custom operators: \operatorname{name}, \DeclareMathOperator{\Tr}{Tr}, \mathop{content}
  • Multi-line subscripts: \substack{cond1 \\ cond2}
  • Modular arithmetic: \bmod (binary), \pmod{n} (parenthesized), \mod (wide spacing)
Matrices (8) β€” all standard matrix environments

matrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix, smallmatrix, array

Delimiters β€” auto-scaling & manual sizing
  • Auto-scaling: \left( \right), \left[ \right], \left\{ \right\}, \left| \right|, \langle, \rangle, \lfloor, \rfloor, \lceil, \rceil, \lvert, \rvert, \lVert, \rVert
  • Asymmetric: \left. \right| (evaluation bar), \left\{ \right. (piecewise)
  • Manual sizing: \big, \Big, \bigg, \Bigg with \bigl, \bigr, \bigm variants
Accents & Decorations (35) β€” accents, cancels, extensible arrows, stacking, bracket annotations
  • Accents: \hat, \tilde, \bar, \overline, \underline, \dot, \ddot, \dddot, \grave, \acute, \check, \breve, \ring/\mathring, \vec, \widehat
  • Brace annotations: \overbrace{...}^{text}, \underbrace{...}_{text}, \overbracket{...}, \underbracket{...}
  • Arrow decorations: \overrightarrow, \overleftarrow
  • Cancel lines: \cancel, \bcancel (reverse), \xcancel (cross)
  • Extensible arrows: \xrightarrow, \xleftarrow, \xhookrightarrow, \xhookleftarrow, \xRightarrow, \xLeftarrow, \xLeftrightarrow, \xmapsto
  • Stacking: \overset, \underset, \stackrel
Font Styles (17)

\mathbf, \mathit, \mathrm, \mathsf, \mathtt, \mathbb, \mathfrak, \mathcal, \mathscr, \boldsymbol, \bm, \text, \mbox, \symbf, \symit, \symsf, \symrm

Math Mode Switching

\displaystyle, \textstyle, \scriptstyle, \scriptscriptstyle, $...$ (inline), $$...$$ (display)

Environments (21) β€” alignment, piecewise, matrices, tables
  • Equation environments: equation(*), displaymath
  • Alignment environments: align(*), aligned, flalign(*), alignat(*)
  • Centering environments: gather(*), gathered
  • Piecewise functions: cases, dcases (displaystyle), rcases (right brace)
  • Multi-line/splitting: split, multline(*)
  • Others: eqnarray(*), subequations, tabular (l/c/r column alignment)
  • Auto-numbering: Supports \tag/\tag*, \label/\ref/\eqref, starred environments skip numbering
Spacing

\,, \:, \;, \quad, \qquad, \!, \hspace{...}, normal spaces

Colors & Background
  • Text color: \color{red}{...}, \textcolor{#FF5733}{...} (named + hex)
  • Background color: \colorbox{yellow}{text}, \fcolorbox{borderColor}{bgColor}{text}
Chemical Formulas (13) β€” mhchem package

\ce{H2O}, \ce{H2SO4}, \ce{Na+}, \ce{SO4^{2-}}, \ce{A + B -> C}, \ce{A <=> B}, coefficients, isotope notation, complexes

Special Effects & Layout (9)
  • Boxes: \boxed{E=mc^2}, \fbox{text}
  • Phantoms & spacing: \phantom, \smash, \vphantom, \hphantom
  • Zero-width overlaps: \mathclap{content}, \mathllap{content}, \mathrlap{content}
Advanced Annotations (6) β€” hyperlinks, tensors, four-corner scripts
  • Hyperlinks: \href{url}{text}, \url{url} (blue underline, click callback)
  • Four-corner scripts: \sideset{_a^b}{_c^d}{\sum}
  • Pre-scripts: \prescript{A}{Z}{X} (isotope notation)
  • Tensor indices: \tensor{T}{^a_b^c}, \indices{^a_b}
Custom Commands & Macros (9)

\newcommand, \renewcommand, \def (0–9 parameters, optional argument defaults), \newenvironment, \renewenvironment

Section Structure Commands

\section, \subsection, \subsubsection, \paragraph, \subparagraph (with starred variants)

RTL Text Direction
  • Commands: \RLE{...}, \LRE{...}, \textarabic{...}, \texthebrew{...}
  • Environments: \begin{RTL}...\end{RTL}, \begin{LTR}...\end{LTR}
  • Nesting: supports RTL inside LTR and vice versa
Labels & References

\label, \ref, \eqref, \tag{1}, \tag*{A}

Error Handling
  • Unrecognized commands rendered in error color instead of silent failure
  • parseWithDiagnostics() provides structured diagnostics (8 categories, filter by severity)

πŸ“Έ Rendering Preview

The project includes a Demo App (composeApp/androidApp) showcasing various complex LaTeX scenarios:

Basic Math Chemical Formulas Incremental Parsing
Basic Math Chemical Formulas Incremental Parsing
Basic Math Rendering Supports \ce{...} syntax Real-time preview for incomplete input

πŸ› οΈ Usage

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 androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp

@Composable
fun MyScreen() {
    Latex(
        latex = "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
        config = LatexConfig(
            fontSize = 20.sp,
            color = Color.Black,
            darkColor = Color.White // Automatic dark mode support
        )
    )
}

Automatic Line Wrapping

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.

Image Export

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

Accessibility

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.

Pre-measurement API (Inline Math Support)

Pre-measure formula dimensions for embedding inline math via InlineTextContent:

val measurer = rememberLatexMeasurer(config)
val dims = measurer.measure("\\frac{a}{b}", config) ?: return

val placeholder = Placeholder(
    width = with(density) { dims.widthPx.toSp() },
    height = with(density) { dims.heightPx.toSp() },
    placeholderVerticalAlign = PlaceholderVerticalAlign.TextCenter
)

LatexDimensions provides widthPx, heightPx, baselinePx (with padding) and their content-only counterparts. Use measureBatch() for multiple formulas.

WYSIWYG Editor (Experimental)

Note: The editor API is experimental and may change in future versions. All editor APIs require the @ExperimentalComposeUiApi annotation.

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
    )
}

πŸ“¦ Installation

Version Compatibility

This library publishes two variants for each release to support different Kotlin/Compose versions:

Variant Kotlin Compose Multiplatform Artifact Version
Standard 2.3.0+ 1.10.0+ 1.3.0
Kotlin 2.1.0 2.1.0 1.9.3 1.3.0-kt2.1.0

Choose the variant that matches your project's Kotlin version. If your project uses Kotlin 2.1.0, use the -kt2.1.0 suffixed version.

Standard Version (Kotlin 2.3.0+)

Add dependencies in gradle/libs.versions.toml:

[versions]
latex = "1.3.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" }

Kotlin 2.1.0 Compatible Version

If your project uses Kotlin 2.1.0, use the -kt2.1.0 suffixed artifacts:

[versions]
latex = "1.3.0-kt2.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" }

Add to Your Module

Reference in your module's build.gradle.kts:

dependencies {
    implementation(libs.latex.base) // Basic logging
    implementation(libs.latex.renderer) // Rendering logic
    implementation(libs.latex.parser) // Parsing logic
}

πŸ—οΈ Project Structure

  • :latex-base: Base data structures and interfaces.
  • :latex-parser: Core parsing engine, responsible for converting LaTeX strings to AST.
  • :latex-renderer: Responsible for rendering AST into Compose UI components.
  • :latex-preview: Preview components and sample datasets.
  • :composeApp: Cross-platform Demo application.
  • :androidApp: Android Demo application.

πŸš€ Quick Start

Running the Demo App

  • Android: ./gradlew :androidApp:assembleDebug
  • Desktop: ./gradlew :composeApp:run
  • Web (Wasm): ./gradlew :composeApp:wasmJsBrowserDevelopmentRun
  • iOS: Open iosApp/iosApp.xcworkspace in Xcode to run.

Running Tests

./run_parser_tests.sh

πŸ“Š Roadmap & Coverage

For a detailed list of supported features, please refer to: PARSER_COVERAGE_ANALYSIS.md

πŸ™ Acknowledgements

  • KaTeX β€” This project uses font files from KaTeX for mathematical formula rendering. KaTeX is licensed under the MIT License.

πŸ’‘ Recommended

  • Markdown β€” A Kotlin Multiplatform Markdown parsing and rendering library by the same author. If you need both LaTeX and Markdown rendering in your project, check it out!

πŸ“„ License

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.

About

Compose Latex

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Kotlin 99.9%
  • Other 0.1%