Skip to content

feat: add mathematical expressions support #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions demo/src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@

<link rel="icon" type="image/png" sizes="32x32" href="%sveltekit.assets%/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="%sveltekit.assets%/favicon-16x16.png" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css"
integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV"
crossorigin="anonymous"
/>

<meta name="viewport" content="width=device-width, initial-scale=1" />

Expand Down
20 changes: 20 additions & 0 deletions demo/src/routes/docs/[...7]testing/[...1]katex/+page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# KaTeX support

Mathematical expressions can be written inline, such as $a=1$, or as a block, such as the example below:

$$
b=2
$$

You can add all sorts of mathematical operations.

$$
\frac {a}{b} = \frac {1}{2}
$$

$$
\sum_{i=1}^{5}b*i = 30
$$


And also inline them $\sum_{i=1}^{5}b*i = 30$, just like that
12 changes: 12 additions & 0 deletions packages/kit-docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@
"unplugin-icons": "^0.17.0",
"vite": "^4.4.9"
},
"peerDependencies": {
"markdown-it-texmath": "^1.0.0",
"katex": "^0.16.9"
},
"peerDependenciesMeta": {
"markdown-it-texmath": {
"optional": true
},
"katex": {
"optional": true
}
},
"publishConfig": {
"access": "public"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import {
extractTitlePlugin,
hoistTagsPlugin,
importCodePlugin,
katexPlugin,
linksPlugin,
removeAnnotationPlugin,
tocPlugin,
} from './plugins';
import type {
Expand Down Expand Up @@ -49,6 +51,21 @@ export async function createMarkdownParser(

const parser = MarkdownIt({ html: true });

// Optional math expressions plugins
try {
const markdownItTexmath = await import('markdown-it-texmath');
const katex = await import('katex');

try {
parser.use(katexPlugin, { plugin: markdownItTexmath, katex });
parser.use(removeAnnotationPlugin);
} catch (error) {
console.error(error);
}
} catch {
console.log('no KaTeX support, failed to import');
}

parser.use(emojiPlugin);
parser.use(anchorPlugin);
parser.use(tocPlugin);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export * from './extract-headers-plugin';
export * from './extract-title-plugin';
export * from './hoist-tags-plugin';
export * from './import-code-plugin';
export * from './katex-plugin';
export * from './links-plugin';
export * from './remove-annotation-plugin';
export * from './shiki-plugin';
export * from './toc-plugin';
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { PluginWithOptions } from 'markdown-it';

export const katexPlugin: PluginWithOptions = (parser, { plugin, katex }) => {
return plugin.default(parser, {
engine: katex.default,
delimiters: 'dollars',
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { type PluginSimple } from 'markdown-it';
const annotationRe = /(<annotation[\s\S]+?>)([\s\S]+?)(<\/annotation>)/g;

/**
* Resolves link URLs.
*/
export const removeAnnotationPlugin: PluginSimple = (parser) => {
Object.entries(parser.renderer.rules).forEach(([name, fn]) => {
if (!name.startsWith('math')) return;
if (!fn) return;

// Fix math rules, to remove annotation blocks afterward
parser.renderer.rules[name] = (tokens, idx, options, env, renderer) => {
let result = fn(tokens, idx, options, env, renderer);

[...result.matchAll(annotationRe)].forEach((match) => {
/* Given an annotation rule with a backslash or curly braces, modify it using svelte's @html
to avoid svelte attempting to parse variables, or processing backslashes

Input: <annotation>\rule {braces}</annotation>
Output: <annotation>{@html `\\rule {braces}`}<annotation> */
result = result.replace(
match[0],
`${match[1]}{@html \`${match[2].replace('\\', '\\\\')}\`}${match[3]}`,
);
});

return result;
};
});
};
22 changes: 22 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.