---
title: "KaTeX (Math)"
description: "Render inline and display LaTeX math formulas in Comark with KaTeX."
canonical_url: "https://comark.dev/plugins/official/katex"
---
# KaTeX (Math)

> Render inline and display LaTeX math formulas in Comark with KaTeX.

The `@comark/plugin-katex` plugin renders LaTeX math formulas using [KaTeX](https://katex.org/). It supports both inline and display math expressions, and ships KaTeX as a dependency, so there is nothing else to install.

```bash [terminal]
npm install @comark/plugin-katex
```

KaTeX requires its stylesheet to render correctly. Import it once in your app entry point:

```ts
import '@comark/plugin-katex/katex.css'
```

## Usage

```typescript
import { parseMarkdown } from 'comark'
import math from '@comark/plugin-katex'

const result = await parseMarkdown('Inline $x^2$ and display $$E = mc^2$$', {
  plugins: [math()]
})
```

With framework components, pass both the plugin and the `Math` renderer component:

::code-group
```vue [Vue]
<script setup lang="ts">
import { Markdown } from '@comark/vue'
import math from '@comark/plugin-katex'
import { Math } from '@comark/plugin-katex/vue'
</script>

<template>
  <Suspense>
    <Markdown
      :components="{ math: Math }"
      :plugins="[math()]"
    >{{ content }}</Markdown>
  </Suspense>
</template>
```

```tsx [React]
import { Markdown } from '@comark/react'
import math from '@comark/plugin-katex'
import { Math } from '@comark/plugin-katex/react'

<Markdown
  components={{ math: Math }}
  plugins={[math()]}
>
  {content}
</Markdown>
```

```svelte [Svelte]
<script lang="ts">
  import { Markdown } from '@comark/svelte'
  import math from '@comark/plugin-katex'
  import { Math } from '@comark/plugin-katex/svelte'
</script>

<Markdown {content} components={{ math: Math }} plugins={[math()]} />
```

~~~ts [Angular]
import { Component } from '@angular/core'
import { Markdown } from '@comark/angular'
import math from '@comark/plugin-katex'
import { Math } from '@comark/plugin-katex/angular'

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Markdown],
  template: `
    <comark-markdown
      value="$E = mc^2$"
      [plugins]="plugins"
      [components]="components"
    />
  `,
})
export class AppComponent {
  plugins = [math()]
  components = { Math }
}
~~~
::

::note
Every framework adapter ships in `@comark/plugin-katex`: `./vue`, `./react`, `./svelte` and `./angular`. The Angular component is built with ng-packagr, so `@comark/plugin-katex/angular` exports it as a named export.
::

---

## Features

### Inline math

Use single `$` delimiters for inline expressions:

```mdc
The formula $E = mc^2$ relates energy and mass.

The Pythagorean theorem: $a^2 + b^2 = c^2$
```

### Display math

Use double `$$` delimiters for block-level expressions:

```mdc
$$
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$
```

### Dollar signs in text

The plugin avoids matching dollar signs that are not math. It requires at least one character between `$` delimiters and content that does not start with a digit:

```mdc
Prices like $100 or $200 won't be parsed as math.
```

### Bracket delimiters

LLMs often write `\(...\)` for inline and `\[...\]` for display math. `math({ brackets: true })` parses them too. It is off by default because `\(` and `\[` are Markdown escapes for literal brackets. With it on, brackets that hold only numbers (`\[1\]`), code, and display math broken by a blank line still stay text, and `renderMarkdown()` writes the original delimiters back.

`\[...\]` on its own lines is a display block. Inside a paragraph (`so \[x^2\] holds`), it renders as inline math.

While streaming, auto-close leaves closed `\(...\)` and `\[...\]` alone, but it doesn't yet add the missing `\)` or `\]` to an unfinished `\(` or `\[`. Until the closer arrives, it shows as text.

::tip
See [KaTeX supported functions](https://katex.org/docs/supported.html) for the full LaTeX reference.
::

### Backslash escaping

In JavaScript strings, escape backslashes before LaTeX commands:

```javascript
const latex = '\\frac{a}{b}' // correct
const wrong = '\frac{a}{b}'  // wrong: \f is a JS escape sequence
```

---

## API

### `math(options?)`

Returns a `ComarkPlugin` that tokenizes `$...$` and `$$...$$` expressions.

**Parameters:**

- `options?`: Optional `MathConfig`:
  - `throwOnError?: boolean`: **Deprecated**, ignored by the parser. Only affects the deprecated `renderMath()` helper and will be removed in `0.9.0`. Default: `false`
  - `options?: Record<string, unknown>`: Additional [KaTeX render options](https://katex.org/docs/options.html)
  - `brackets?: boolean`: Also parse `\(...\)` and `\[...\]`. Default: `false`

**Returns:** `ComarkPlugin`

The plugin stores LaTeX source as plain text in the AST. Rendering requires passing `Math` to the `components` prop of `<Markdown>` (see [Usage](#usage)). The `Math` components load KaTeX on first use, so pages without math don't load it. A formula KaTeX can't typeset, such as one still streaming in, shows as its TeX source. Vue and React server rendering waits for KaTeX; Svelte and Angular render the source on the server and typeset in the browser.

### Rendering math manually

To render or validate LaTeX outside a `Math` component (for example in a custom component or a server-side pipeline), load the KaTeX copy the plugin ships and call it directly:

```ts
import { loadKatex } from '@comark/plugin-katex'

const katex = await loadKatex()

// Render to an HTML string
const inline = katex.renderToString('E = mc^2', { displayMode: false, throwOnError: false })
const display = katex.renderToString('x^2', { displayMode: true, throwOnError: false })

// Validate LaTeX syntax
function isValidMath(code: string): boolean {
  try {
    katex.renderToString(code, { throwOnError: true })
    return true
  } catch {
    return false
  }
}
```

::warning
`renderMath()` and `validateMath()` exported from `@comark/plugin-katex` are deprecated and will be removed in `0.9.0`. Replace them with the snippet above.
::

---

## Component props

Props accepted by the `<Math>` component:

| Prop      | Type     | Default  | Description                                                                             |
| --------- | -------- | -------- | --------------------------------------------------------------------------------------- |
| `content` | `string` | required | The LaTeX expression to render                                                          |
| `class`   | `string` | `''`     | CSS classes. Renders inline when the classes include `'inline'`; otherwise display mode |

---

- [Parse API](https://comark.dev/reference/parse)
- [Plugins](https://comark.dev/plugins)


## Sitemap

See the full [sitemap](https://comark.dev/sitemap.md) for all pages.
