AI-Assisted Refactoring of a Lightweight TeX Formula Rendering Engine: Boundaries and Practice

    This article explores the feasible scope and practical approach for building a lightweight TeX formula rendering engine. It first explains the common options for displaying formulas on the web and their drawbacks, then discusses why TeX is difficult to integrate lightly (its macro language and Turing completeness), and defines the boundaries of a restricted parser that covers only common math structures, including supported and unsupported commands, font metric sources, AST node design, and layout rules. The article also compares trade-offs between the restricted engine, MathJax, KaTeX, and a full TeX distribution, and summarizes serverless deployment boundaries, caching, and offline batch processing considerations. The numeric values in the article are initial design assumptions and must be confirmed by actual testing.

    1. Why Formulas Are Difficult to Display on the Web

    If you have ever shared a paper excerpt containing formulas on a social platform or messaging app, you have probably seen garbled text or screenshots. Most platforms do not parse LaTeX syntax, so creators typically have only three options.

    The first is to take screenshots from a PDF. The image resolution is fixed, it becomes blurry when enlarged, the font does not match the body text, and search engines cannot read the symbols inside.

    The second is to call an online rendering service. LaTeX is submitted to a remote server to generate an image, and latency depends on the other side’s response speed. If the service goes down, the page fails with it. Formula content passes through a third-party server, which poses privacy risks when unpublished research is involved.

    The third is to write an approximation in plain text. This loses information, and readers have difficulty verifying it.

    Client-side rendering libraries such as MathJax and KaTeX solve part of the problem, but they depend on large JavaScript packages. On mobile devices, or when static images need to be generated directly on the server side, these solutions may not be suitable. This is what creates the need for a lightweight rendering engine.

    2. Why TeX Is Difficult to Integrate in a Lightweight Way

    TeX was created by Donald Knuth. In 1977, dissatisfied with the quality of the phototypesetting system newly adopted by his publisher, he decided to write his own typesetting engine. He initially estimated six months would suffice, but actually spent nearly ten years. TeX’s version number gradually approaches π and is currently 3.141592653. Knuth also set up a bug bounty starting at $2.56, with the reward doubling for each bug found. These details come from Knuth’s public statement, and the original page should be used as the authoritative source when citing them.

    The difficulty with TeX is that it is itself a programming language. It supports conditionals, loops, recursion, and macro expansion. People have implemented Mandelbrot set rendering and Conway’s Game of Life using TeX macros, which shows that TeX is Turing-complete.

    This characteristic leads to three direct problems. First, the number of macro expansion steps is hard to predict, and rendering time can vary greatly with input; it cannot be completed in a single pass like a regex replacement. Second, readers need to understand the whole set of macro definitions and category codes to judge the result of an input. Third, early implementations were mostly written in Pascal or C, and the legacy code is difficult to embed directly into modern web frontends or mobile applications.

    Turing completeness means there is no way to fully determine the execution result of a piece of TeX code using static rules. Once the macro language is stripped away, what remains is only a subset of mathematical formulas. This subset can be implemented independently, but it is not equivalent to full TeX.

    3. Feasible Scope of AI-Assisted Refactoring

    The idea here is to narrow the goal. Rather than implementing full TeX, implement a restricted math formula parser that covers only common structures. AI coding tools can help generate first drafts of lexical analysis, syntax analysis, and layout code, and can also translate the grammar rules of an existing implementation into another language. AI-generated code still needs to be tested item by item.

    Before asking AI to generate code, boundaries need to be defined first, including supported commands, unsupported commands, and acceptance criteria.

    The supported scope can be defined as follows:

    • Superscripts and subscripts: ^, _
    • Fractions: \frac, \dfrac
    • Radicals: \sqrt, with an optional degree argument
    • Greek letters: common lowercase and uppercase letters such as \alpha through \omega
    • Large operators: \sum, \prod, \int, with upper and lower limits
    • Matrices: pmatrix and bmatrix environments
    • Delimiters: parentheses paired by \left and \right

    The following are not supported: user macro definitions such as \def and \newcommand, control structures such as \if and \loop, file reads such as \input and \include, and external command calls such as \write18. When these inputs are encountered, an error is returned directly and no attempt is made to simulate execution.

    The source of fonts and metrics needs to be clear. Using the OpenType MATH table in an open-source math font (such as Latin Modern Math or STIX Two Math) is recommended; glyph widths, superscript and subscript offsets, and delimiter sizes are read from it. Font files are packaged with the service to avoid accessing system fonts at runtime.

    An abstract syntax tree (AST) can be divided into four node types. A symbol node represents a character or Greek letter and carries font attributes. A structure node represents a superscript, subscript, fraction, or radical, each containing child nodes. An environment node represents a matrix and records the row and column counts. A delimiter node represents a pair of delimiters. During the layout stage, four values are computed for each node: width, height, depth, and baseline offset.

    Baseline rules follow an approach similar to TeX. The numerator and denominator of a fraction are placed symmetrically relative to the fraction bar, and superscripts and subscripts are positioned according to the recommended offsets in the font’s MATH table. The restricted engine does not yet support line breaking. When a single-line formula exceeds the maximum width, the caller must choose to scale down the output or return an error.

    Test methods should be determined before coding. Build a set of reference samples, where each sample records the LaTeX source, the target image, and the rendering result from MathJax or KaTeX. Comparison metrics include the pixel difference ratio and baseline position deviation. Before reference results exist, output should not be claimed as correct.

    4. Trade-offs vs. Existing Solutions

    Compared with MathJax or KaTeX, the restricted engine’s advantage is that it does not depend on a browser and is suitable for generating images directly on the server side. The cost is smaller command coverage; formulas outside the subset will fail to render.

    Compared with calling a full TeX distribution, the restricted engine is small, starts fast, and deploys easily. The cost is that it cannot handle custom macros or more complex typesetting needs such as multiple columns, complex table alignment, and footnotes.

    If you only render a few formulas occasionally, using a mature open-source rendering library directly is more reliable. A self-built restricted engine is only worth the investment when stable server-side image output is required and the formula structure is relatively fixed.

    5. Cloud Deployment Considerations

    Serverless deployment is suitable for on-demand rendering. The following limits need to be set:

    • Input length per request must not exceed 4 KB.
    • Macro expansion or layout recursion depth must not exceed 64 levels.
    • A single render times out at 2 seconds and returns 504 on timeout.
    • The memory limit is set to 256 MB and adjusted based on actual measurements.
    • The runtime environment may read and write only the temporary directory, must not access other file paths, and must not make external network requests.

    The API should return clear status codes. 200 indicates success and returns an image in image/png format. 400 indicates a LaTeX syntax error and includes the error location. 413 indicates the input exceeds the length limit. 422 indicates an unsupported command is included. 504 indicates a render timeout. Callers can use these to distinguish error types and decide whether to retry or modify the input.

    Caching can reduce repeated rendering. The cache key is the SHA-256 hash of the concatenated LaTeX source, rendering parameters, and engine version number. When the engine version is upgraded, the cache key changes and old images naturally expire. Images are stored in object storage and cached through a CDN. The Cache-Control max-age duration in response headers should be set according to how often content is updated.

    Offline batch processing is suitable for formula extraction from large document sets. The container image includes the engine and font files. Failed tasks are retried with exponential backoff, up to three times. Tasks exceeding the retry count are recorded in a failed queue for manual review.

    The parameters above are initial design values and have not yet been stress-tested. Before launch, cold-start time, single-render latency, and peak memory should be measured on the target platform, and the limits adjusted accordingly.

    6. Conclusion

    TeX’s value lies in typesetting quality; the macro language is merely the means to achieve that quality. Separating the math formula subset from TeX yields a rendering tool that is small and has clear boundaries. AI can speed up the drafting of prototype code, but the correctness of parsing, layout, and rendering still depends on reference tests and manual review.

    This article discusses a technical path, not a complete implementation report. The numeric values and command scope described are design assumptions, and readers should confirm them against their own test results before adopting them.