observablehq / framework

A static site generator for data apps, dashboards, reports, and more. Observable Framework combines JavaScript on the front-end for interactive graphics with any language on the back-end for data analysis.
https://observablehq.com/framework/
ISC License
2.53k stars 121 forks source link

Add an option to allow LaTeX embeddings using $ and $$ notation #981

Open johnblommers opened 8 months ago

johnblommers commented 8 months ago

Consider please adding an option so that LaTeX formulas can be entered like this:

$f(x)=x^2$ for inline equations

$$f(x)=x^2$$ for centered equations

mbostock commented 8 months ago

Just to be clear, you can currently render TeX using the built-in tex template literal:

${tex`f(x)=x^2`}

And the built-in tex fenced code block:

```tex
f(x)=x^2

However, this syntax is more verbose than inline `$…$` and also means that TeX is rendered on the client rather than the server. (Though see #141 for server-side rendered TeX.)

Since [1.1.0](https://github.com/observablehq/framework/releases/tag/v1.1.0) you can register markdown-it plugins using the [**markdownIt** config option](https://observablehq.com/framework/config#markdownit). This would allow you to use a plugin such as [markdown-it-texmath](https://github.com/goessner/markdown-it-texmath) for inline math. Here is an example config:

```js
import katex from "katex";
import texmath from "markdown-it-texmath";

export default {
  markdownIt: (md) => md.use(texmath, {engine: katex})
};  

And here is some example Markdown:

# Math rulez!

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.css">

$\sqrt{3x-1}+(1+x)^2$

And if we fix #692, then you would be able to add npm:katex/dist/katex.min.css to your head option, and then you’d automatically have the KaTeX stylesheet applied across all pages, and it would download the stylesheet for self-hosting rather than loading it from jsDelivr.

It’d be nice to have a more convenient way to opt-in to this syntax, though!

huw commented 8 months ago

The only issue with that approach is that the texmath parser conflicts with the inline expression parser. For example:

${1 + 2} $ + 3$

Produces:

Screenshot 2024-03-06 at 8 55 48 PM

I tried a couple of other parsers but they tended to break inline expressions entirely. I'd hope that this is just a matter of changing the parser order so that inline expressions are evaluated first and removed from the AST so that the math parser doesn't confused? Happy to raise a separate issue :)

mbostock commented 8 months ago

I think that issue is blocked by #597 which is a more substantial rearchitecting of the parser.