remarkjs / remark-math

remark and rehype plugins to support math
https://remark.js.org
MIT License
378 stars 57 forks source link

KaTeX Macros With Global Scope #98

Closed fweth closed 4 months ago

fweth commented 4 months ago

Initial checklist

Problem

I like to use KaTex macros, especially where I put all my custom commands in a single math block at the top of the file. This is supported by many KaTeX based editors, including VSCode with it's built in preview. However, I couldn't get this to work with remark:

import rehypeDocument from 'rehype-document';
import rehypeKatex from 'rehype-katex';
import rehypeParse from 'rehype-parse';
import rehypeStringify from 'rehype-stringify';
import { unified } from 'unified';

const htmlString = `
<p class="language-math">\\def\\foo{abc}</p>
<p class="language-math">\\abc</p>
`;

const html = await unified()
  .use(rehypeParse, { fragment: true })
  .use(rehypeDocument, {
    css: 'https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css',
  })
  .use(rehypeKatex)
  .use(rehypeStringify)
  .process(htmlString);

document.body.innerHTML += html;

Here the scope of the definition is its own math block, so it can't be used outside of the block. Would be awesome if there is a way to get this working!

Solution

Abbreviations should be stored in a global context, not scoped to individual math blocks.

Alternatives

I can't think of an alternative solution.

ChristianMurphy commented 4 months ago

Welcome @fweth! 👋 have you tried the macros option? https://github.com/remarkjs/remark-math/blob/e99b9d088709d743adf6a43551fd416d7e0014ed/packages/rehype-katex/test.js#L131-L149

Abbreviations should be stored in a global context, not scoped to individual math blocks.

That feels unexpected. From the readme:

to be able to embed rich diagrams of math to scientific documentation

Embedded documents, are just that, independent documents inside of a host document.

It sounds like you want interleaving of different languages, perhaps something like https://mdxjs.com/ or https://jupyter.org/

fweth commented 4 months ago

Thanks, this sounds great!

Still, KaTeX/MathJax editors like VSCode (with preview), iA Writer, HackMD, etc. support global math contexts. KaTeX docs also say

Macros defined by \gdef, \xdef, \global\def, \global\edef, \global\let, and \global\futurelet will persist between math expressions. (Exception: macro persistence may be disabled. There are legitimate security reasons for that.)

github-actions[bot] commented 4 months ago

Hi! This was closed. Team: If this was fixed, please add phase/solved. Otherwise, please add one of the no/* labels.