Skip to content

IamCoder18/render-latex

Repository files navigation

KaTeX Math Rendering Utility (render-latex)

This utility provides a robust way to find and render LaTeX mathematical expressions embedded within a larger text string using the KaTeX library. It intelligently handles various delimiters, escaped characters, and overlaps.

Features

  • Renders LaTeX to HTML: Uses the KaTeX library for fast and accurate math rendering.
  • Multiple Delimiter Support: Recognizes common inline ($...$, \(...\)) and display ($$...$$, \[...\], \begin{align}..., \begin{align*}...) math delimiters.
  • Escaped Character Handling: Correctly interprets escaped delimiters (e.g., \$) and backslashes (\\) within both text and math contexts.
  • Overlap Prevention: Prioritizes delimiter matches to prevent issues where delimiters might overlap.
  • Segmented Processing: Parses the input into distinct 'text' and 'math' segments for accurate rendering.
  • COMING SOON: Configurable Delimiters: The set of delimiters can be configured within the code.

Installation

Install the package using npm or yarn:

npm install render-latex
# or
yarn add render-latex

You also must include the KaTeX CSS stylesheet in your project for the math to render correctly. Add the following to the <head> of your HTML:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css" integrity="sha384-5TcZemv2l/9On385z///+d7MSYlvIEw9FuZTIdZ14vJLqWphw7e7ZPuOiCHJcFCP" crossorigin="anonymous">

Usage

Import the renderMath function from the package and pass it the string you want to process. Remember to include the KaTeX CSS.

import { renderMath } from 'render-latex';

const inputText = `
This is a paragraph with inline math like $E=mc^2$.
$$
\\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}
$$
More text after math.
`;

const renderedHtml = renderMath(inputText);

console.log(renderedHtml);

How It Works

  1. Escaping: The input string first has potentially problematic sequences like \\ and \$ replaced with unique placeholder characters. This prevents them from being misinterpreted as delimiters or LaTeX commands during parsing.
  2. Delimiter Parsing (parseDelimiters):
    • The code iterates through a predefined list of delimiters ($, $$, \(, \[, \begin{align*}, etc.).
    • For each delimiter, it uses regular expressions to find all occurrences in the escaped input string.
    • It keeps track of character indices that have already been matched to prevent processing overlapping delimiters (e.g., it won't process $b$ inside $$a $b$ c$$ separately if $$...$$ is found first).
    • The string is segmented into an ordered array of objects, each marked as either text or math, along with its content and whether display mode should be used for math.
  3. Rendering (renderMath):
    • The function iterates through the parsed segments.
    • Text Segments: Placeholder characters are reverted to their original form (\ and $). The text is appended to the output.
    • Math Segments: Placeholder characters are reverted to their LaTeX-compatible forms (\\ and $). The content is then rendered using katex.renderToString with appropriate options (displayMode, error handling disabled).
  4. Output: The final result is a string containing the original text interleaved with HTML generated by KaTeX for the math segments.

Supported Delimiters

The following delimiters are configured by default:

Start End Type
$$ $$ display
$ $ inline
\[ \] display
\( \) inline
\begin{align*} \end{align*} display
\begin{align} \end{align} display

KaTeX Options

The following options are passed to katex.renderToString internally:

  • displayMode: Set to true for display math, false for inline math.
  • throwOnError: false: Prevents KaTeX from throwing errors on invalid syntax, rendering an error message instead.
  • strict: false: Disables strict mode, allowing some non-standard LaTeX commands.
  • trust: true: Allows certain commands like \htmlClass

About

Parse and render LaTeX easily with KaTeX

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors