Coder Social home page Coder Social logo

remarkjs / remark-math Goto Github PK

View Code? Open in Web Editor NEW
349.0 9.0 49.0 1.06 MB

remark and rehype plugins to support math

Home Page: https://remark.js.org

License: MIT License

JavaScript 100.00%
remark remark-plugin rehype rehype-plugin markdown html math latex katex tex

remark-math's Introduction

remark-math

Build Coverage Downloads Size Sponsors Backers Chat

This project is a monorepo that contains several packages for dealing with math in markdown and HTML.

Contents

What is this?

This repository contains unified (rehype and remark) plugins to add support for math. You can use them to add support for parsing and serializing a syntax extension and to render math with KaTeX or MathJax.

When dealing with markdown, you optionally use remark-math, or alternatively use fenced code (```math). Then, you either use rehype-katex or rehype-mathjax to render math in HTML.

When should I use this?

This project is useful when you want to support LaTeX math. This mechanism works well when you want authors, that have some LaTeX experience, to be able to embed rich diagrams of math to scientific documentation. The extra syntax extension supported by remark-math for math in markdown does not work everywhere so it makes markdown less portable. This project is also useful as it renders math with KaTeX or MathJax at compile time, which means that there is no client side JavaScript needed.

Examples

Example: KaTeX

Say our document example.md contains:

Lift($$L$$) can be determined by Lift Coefficient ($$C_L$$) like the following
equation.

$$
L = \frac{1}{2} \rho v^2 S C_L
$$

…and our module example.js contains:

import rehypeKatex from 'rehype-katex'
import rehypeStringify from 'rehype-stringify'
import remarkMath from 'remark-math'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {read} from 'to-vfile'
import {unified} from 'unified'

const file = await unified()
  .use(remarkParse)
  .use(remarkMath)
  .use(remarkRehype)
  .use(rehypeKatex)
  .use(rehypeStringify)
  .process(await read('example.md'))

console.log(String(file))

…then running node example.js yields:

<p>Lift(<code class="language-math math-inline"><span class="katex"></span></code>) like the following
equation.</p>
<pre><code class="language-math math-display"><span class="katex-display"><span class="katex"></span></span></code></pre>

👉 Note: KaTeX requires CSS to render correctly. Use katex.css somewhere on the page where the math is shown to style it properly:

<!-- Get the latest one from: https://katex.org/docs/browser -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" rel="stylesheet">

Example: MathJax

Supporting either MathJax or KaTeX is very similar. Take the above KaTeX example and change:

@@ -1,4 +1,4 @@
-import rehypeKatex from 'rehype-katex'
+import rehypeMathjax from 'rehype-mathjax'
 import rehypeStringify from 'rehype-stringify'
 import remarkMath from 'remark-math'
 import remarkParse from 'remark-parse'
@@ -10,7 +10,7 @@ const file = await unified()
   .use(remarkParse)
   .use(remarkMath)
   .use(remarkRehype)
-  .use(rehypeKatex)
+  .use(rehypeMathjax)
   .use(rehypeStringify)
   .process(await read('example.md'))

…then running node example.js yields:

<p>Lift(<mjx-container class="MathJax" jax="SVG"><!--…--></mjx-container>) can be determined by Lift Coefficient (<mjx-container class="MathJax" jax="SVG"><!--…--></mjx-container>) like the following
equation.</p>
<mjx-container class="MathJax" jax="SVG" display="true"><!--…--></mjx-container><style>
mjx-container[jax="SVG"] {
  direction: ltr;
}
/* … */
</style>

Security

Assuming you trust KaTeX/MathJax, using rehype-katex/rehype-mathjax is safe. If a vulnerability is introduced in them, it opens you up to a cross-site scripting (XSS) attack. See their readmes for more info.

Contribute

See contributing.md in remarkjs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Junyoung Choi and TANIGUCHI Masaya

remark-math's People

Contributors

enteleform avatar greydevv avatar hexrcs avatar johnjeng avatar kimbaudi avatar maclockard avatar martyo256 avatar mgreenbe avatar pd4d10 avatar pjkaufman avatar rokt33r avatar stephenlrandall avatar tani avatar uetchy avatar unindented avatar vhf avatar wooorm avatar xiaoliu-heng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

remark-math's Issues

TypeError: Cannot read property '3' of undefined when render Matrices with double $ sign

Initial checklist

Affected packages and versions

5.1.0

Link to runnable example

https://codesandbox.io/s/react-markdown-debug-forked-83556?file=/src/App.js

Steps to reproduce

import React from "react";
import Markdown from "react-markdown";

import raw from "rehype-raw";
import math from "remark-math";
import "katex/dist/katex.min.css";
import rehypeKatex from "rehype-katex";
const markdownSource = $$\\left(\\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix}\\right)$$;

export default function App() {
return (
<Markdown
remarkPlugins={[math]}
rehypePlugins={[raw, rehypeKatex]}
>
{markdownSource}

);
}

Expected behavior

It should render the matrices

image

Actual behavior

I got TypeError: Cannot read property '3' of undefined
image
But if i only use single dollar sign ($) it can render normally
Example:
$\\left(\\begin{matrix} 1 & 0 \\\\ 0 & 1 \\end{matrix}\\right)$

Runtime

Node v16

Package manager

npm v7

OS

Windows

Build and bundle tools

Next.js

Allow users to pass the option displayMode true

Initial checklist

Problem

I'm reading the docs for the options and it states that All other options, except for displayMode, are passed to KaTeX.. I am interested in turning displayMode to true, however this is explicitly forbidden here. Can you let me know why that is?

https://unifiedjs.com/explore/package/rehype-katex/#options

Solution

Allow users to pass displayMode:true

Alternatives

Have an option to configure the presentation to the equivalent to displayMode:true

Prevent spaced inline math from being parsed

Subject of the issue

Math is breaking a perfectly normal sentence with dollar signs, therefore we would like to prevent spaced inline math from being parsed.

Your environment

All OSes and versions are impacted; the renderer needs to use at least remark-math and rehype-katex, I am not sure which one of the two is causing the problem, altough I would go for these Regex.

Actual behaviour

Right now, math is parsed even when it breaks the sentence; for instance:

Hey, I'd like to buy this computer, but $1,000 is really expensive, I'll buy the one at $600 instead.

Here, the content between the two dollar signs is parsed as math, altough it is not what we would expect.

Expected behaviour

Inline math should only be parsed if no space is leading or trailing the content inside; in other words, the leading delimiter shall have no trailing space, and the trailing delimiter shall have no leading space.

When there are non space characters after $$ the parser ends up interpreting the whole doc as part of the node (v3)

When trying to parse the following document:

# Debug

$$
\LaTeX
$$ words

more words

I end up with the following HTML:

<h1 id="debug">Debug</h1>
<div class="math math-display">\LaTeX
$$ words

more words


export const _frontmatter = {}</div>

So the $$ latter is not interpreted as the end of the node and the rest of the document is consumed =\

Your environment

  • OS: macOS 10.15.7
  • Packages: remark-math 3.0.1.
  • Env: Node v15.6.0
  • This is done in the context of Gatsby & gatsby-plugin-mdx (1.10.1) and hence remark 12.

Steps to reproduce

Render the example above.

Codesandbox: https://codesandbox.io/s/remark-rehype-debug-forked-no50m?file=/src/index.js

Expected behavior

Only content inside $$ is interpreted as part of the node

Actual behavior

The second $$ is ignored and the rest of the document is consumed

rehype-katex fails with new NextJS TypeScript Project

Initial checklist

Affected packages and versions

[email protected]

Link to runnable example

No response

Steps to reproduce

Apologies if this ends up being a NextJS issue but wanted to file it here first. See this repo for an example.

  1. Create a NextJS project npx create-next-app --typescript --use-npm next-rehype-katex-issue
  2. Install dependencies npm i --save @next/mdx @mdx-js/loader rehype-katex remark-math
  3. cd my-next-app && touch next.config.mjs
  4. Add the following config to next.config.mjs:
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import mdx from "@next/mdx";

const withMDX = mdx({
  extension: /\.mdx?$/,
  options: {
    rehypePlugins: [rehypeKatex],
    remarkPlugins: [remarkMath],
  },
});

const config = withMDX({
  pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
});

export default config;
  1. npm run dev

Expected behavior

I should be able to run the NextJS dev server without error. This issue does not happen with earlier versions of rehype-katex (e.g. 4.0.0).

Actual behavior

An error similar to the following occurs (seems to be an issue with ES modules versus CommonJS resolution.

<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Can't resolve 'url' in '/Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib'
<w> while resolving 'url' in /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib as file
<w>  at resolve esm file url
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib/minurl.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib/minurl.js
<w>  at resolve esm file ./minurl.js
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib/index.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/lib/index.js
<w>  at resolve esm file ./lib/index.js
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/index.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/vfile/index.js
<w>  at resolve esm file vfile
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/unified/lib/index.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/unified/lib/index.js
<w>  at resolve esm file ./lib/index.js
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/unified/index.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/node_modules/unified/index.js
<w>  at resolve esm file unified
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/index.js
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/node_modules/rehype-katex/index.js
<w>  at resolve esm file rehype-katex
<w>  at file dependencies /Users/mikesukmanowsky/code/personal/nextjs-math/next.config.mjs
<w>  at file /Users/mikesukmanowsky/code/personal/nextjs-math/next.config.mjs
<w>  at resolve commonjs /Users/mikesukmanowsky/code/personal/nextjs-math/next.config.mjs

Runtime

Node v17

Package manager

npm v7

OS

macOS

Build and bundle tools

Next.js

Add mhchem support to rehype-katex

Initial checklist

Problem

I'm using LaTeX to write some docs about Chemistry, and I need mhchem to write equations easily.

Solution

However, rehype-katex is pure, and does not support \ce{} syntax by default. To use mhchem in KaTeX, I need mhchem extension, which is an official extension made by KaTeX team.

Adding <script /> into <head /> directly is not recommended, and doesn't work properly with Next.js built-in router.

Alternatives

Well, switching to rehype-mathjax works, but, #80 happens to me, too.

Related

#69 and #34 are both closed and marked as wontfix, a little bit confused, why not?

`rehype-katex` does not catch non-parse errors

Initial checklist

Affected packages and versions

5.1.1

Link to runnable example

https://codesandbox.io/s/markdown-editor-with-katex-forked-x63zo4

Steps to reproduce

use invalid latex code with rehypeKatex and react-markdown:

\begin{split}
A & = \frac{\pi r^2}{2} \\
 & = \frac{1}{2} \pi r^2
\end{{split}}

Expected behavior

invalid latex code is displayed with red color
here is a fixed version of rehypeKatex that has expected behavior:

/**
 * @typedef {import('hast').Root} Root
 * @typedef {import('katex').KatexOptions} Options
 */

import katex from 'katex'
import {visit} from 'unist-util-visit'
import {removePosition} from 'unist-util-remove-position'
import {toText} from 'hast-util-to-text'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'

const assign = Object.assign

const parseHtml = unified().use(rehypeParse, {fragment: true})

const source = 'rehype-katex'

/**
 * Plugin to transform `<span class=math-inline>` and `<div class=math-display>`
 * with KaTeX.
 *
 * @type {import('unified').Plugin<[Options?]|void[], Root>}
 */
export default function rehypeKatex(options) {
  const settings = options || {}
  const throwOnError = settings.throwOnError || false

  return (tree, file) => {
    visit(tree, 'element', (element) => {
      const classes =
        element.properties && Array.isArray(element.properties.className)
          ? element.properties.className
          : []
      const inline = classes.includes('math-inline')
      const displayMode = classes.includes('math-display')

      if (!inline && !displayMode) {
        return
      }
      const value = toText(element, {whitespace: 'pre'})

      /** @type {string | null} */
      let result = null

      try {
        result = katex.renderToString(
          value,
          assign({}, settings, {displayMode, throwOnError: true})
        )
      } catch (error_) {
        const error = /** @type {Error} */ (error_)
        if (error instanceof katex.ParseError) {
            const fn = throwOnError ? 'fail' : 'message'
            const origin = [source, error.name.toLowerCase()].join(':')
    
            file[fn](error.message, element.position, origin)
            result = katex.renderToString(
              value,
              assign({}, settings, {
                displayMode,
                throwOnError: false,
                strict: 'ignore'
              })
            )    
        }else{
          result = `<div style="color: red">${value}</div>`
        }
      }
      // @ts-expect-error: assume no `doctypes` in KaTeX result.
      element.children = removePosition(parseHtml.parse(result), true).children
    })
  }
}

Actual behavior

element crash.

Runtime

No response

Package manager

No response

OS

No response

Build and bundle tools

No response

The dollar sign is not showing in single $ quote

Initial checklist

Affected packages and versions

"rehype-katex": "^6.0.2",     "remark-math": "^5.1.1",

Link to runnable example

No response

Steps to reproduce

Markdown viewer, children is just the markdown text

import ReactMarkdown from "react-markdown";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import "katex/dist/katex.min.css"; // `rehype-katex` does not import the CSS for you

<ReactMarkdown
	remarkPlugins={[remarkMath]}
	rehypePlugins={[rehypeKatex]}
>
	{props.children}
</ReactMarkdown>

Expected behavior

give

$$
\$10
$$

or

$
\$10
$

will show

$10

Actual behavior

Only double $$ sign quote can show correct dollar currency symbol, single quote can't show

image

Runtime

Node v16

Package manager

yarn 2

OS

Linux

Build and bundle tools

Create React App

Use KaTeX AST instead of reparsing the whole tree

Right now remark-math uses KaTeX's renderToString method to generate HTML, then reparses it directly afterwards using rehype-parse.

This is expensive, but was necessary because KaTeX used to not expose their internal AST.

I opened a while ago an issue on their side to expose this AST in order to have better renderers. It seems like now they do. KaTeX/KaTeX#800 (comment)

It would be great if remark-math did the conversion from KaTeX's AST to HAST nodes directly, instead of parsing the stringified DOM tree

Could not find a declaration file for module 'remark-math'

I'm trying to use it as a plugin for react-markdown. I get the following error
Could not find a declaration file for module 'remark-math'
I tried to install types for it. using npm install @types/remark-math but I get 404 error. Please make it available

rehype-mathjax should not have a dependency on @types/web

Initial checklist

Affected packages and versions

4.0.2

Link to runnable example

No response

Steps to reproduce

Install reyhpe-mathjax via a package manager

Expected behavior

The typescript project referencing rehype-mathjax should not throw any new errors.

Actual behavior

Typescript (e.g. in VSCode) gives the following errors for@types/web and @typescript/lib-dom, because we basically have double definitions.

Should rehype-mathjax not only have @types/web as a devDependency or peerDependency so it does not interfere with the typescript setup of the project that uses it?

Why is the specific version of @types/web here required anyway?

Definitions of the following identifiers conflict with those in another file: NodeFilter, XPathNSResolver, SVGMatrix, WebKitCSSMatrix, SVGPoint, SVGRect, location, webkitURL, ImportExportKind, TableKind, ValueType, ExportValue, Exports, ImportValue, Imports, ModuleImports, ElementTagNameMap, name, AlgorithmIdentifier, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, COSEAlgorithmIdentifier, CSSNumberish, CanvasImageSource, ClipboardItemData, ClipboardItems, ConstrainBoolean, ConstrainDOMString, ConstrainDouble, ConstrainULong, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HTMLOrSVGImageElement, HTMLOrSVGScriptElement, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, InsertPosition, Int32List, LineAndPositionSetting, MediaProvider, MessageEventSource, MutationRecordType, NamedCurve, OnBeforeUnloadEventHandler, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReader, RenderingContext, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, UvmEntries, UvmEntry, VibratePattern, WindowProxy, XMLHttpRequestBodyInit, AlignSetting, AnimationPlayState, AnimationReplaceState, AppendMode, AttestationConveyancePreference, AudioContextLatencyCategory, AudioContextState, AuthenticatorAttachment, AuthenticatorTransport, AutoKeyword, AutomationRate, BinaryType, BiquadFilterType, CanPlayTypeResult, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ChannelCountMode, ChannelInterpretation, ClientTypes, ColorGamut, ColorSpaceConversion, CompositeOperation, CompositeOperationOrAuto, CredentialMediationRequirement, DOMParserSupportedType, DirectionSetting, DisplayCaptureSurfaceType, DistanceModelType, DocumentReadyState, EndOfStreamError, EndingType, FillMode, FontFaceLoadStatus, FontFaceSetLoadStatus, FullscreenNavigationUI, GamepadHapticActuatorType, GamepadMappingType, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, IterationCompositeOperation, KeyFormat, KeyType, KeyUsage, LineAlignSetting, MediaDecodingType, MediaDeviceKind, MediaEncodingType, MediaKeyMessageType, MediaKeySessionClosedReason, MediaKeySessionType, MediaKeyStatus, MediaKeysRequirement, MediaSessionAction, MediaSessionPlaybackState, MediaStreamTrackState, NotificationDirection, NotificationPermission, OrientationLockType, OrientationType, OscillatorType, OverSampleType, PanningModelType, PaymentComplete, PermissionName, PermissionState, PlaybackDirection, PositionAlignSetting, PredefinedColorSpace, PremultiplyAlpha, PresentationStyle, PublicKeyCredentialType, PushEncryptionKeyName, RTCBundlePolicy, RTCDataChannelState, RTCDegradationPreference, RTCDtlsTransportState, RTCIceCandidateType, RTCIceComponent, RTCIceConnectionState, RTCIceCredentialType, RTCIceGathererState, RTCIceGatheringState, RTCIceProtocol, RTCIceTcpCandidateType, RTCIceTransportPolicy, RTCIceTransportState, RTCPeerConnectionState, RTCPriorityType, RTCRtcpMuxPolicy, RTCRtpTransceiverDirection, RTCSdpType, RTCSignalingState, RTCStatsIceCandidatePairState, RTCStatsType, ReadyState, RecordingState, ReferrerPolicy, RemotePlaybackState, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResidentKeyRequirement, ResizeObserverBoxOptions, ResizeQuality, ResponseType, ScrollBehavior, ScrollLogicalPosition, ScrollRestoration, ScrollSetting, SecurityPolicyViolationEventDisposition, SelectionMode, ServiceWorkerState, ServiceWorkerUpdateViaCache, ShadowRootMode, SlotAssignmentMode, SpeechSynthesisErrorCode, TextTrackKind, TextTrackMode, TouchType, TransferFunction, UserVerificationRequirement, VideoFacingModeEnum, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType

Thanks a lot for your support!

Runtime

Node v16

Package manager

yarn 1

OS

Windows

Build and bundle tools

Vite

react-markdown example

I'm rather new to TypeScript but would like to use this package with react-markdown. I've successfully loaded remarkGfm as following. However, when I insert an equation, it is not properly processed.

import React, { useEffect, useState } from 'react'

import ReactMarkdown from 'react-markdown'
import rehypeKatex from 'rehype-katex'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'

import './App.css'

function App()
{
    const [data, setData] = useState('Loading...')
    useEffect(() =>
    {
        async function fetchData()
        {
            const resp = await fetch('content/index.md')
            setData(await resp.text())
        }
        fetchData()
    })
    return <ReactMarkdown plugins={[remarkGfm, remarkMath, rehypeKatex]}>{data}</ReactMarkdown>
}

export default App;

Expected Behavior

  • LaTeX equations enclosed in $..$, $$..$$, \(..\), or \[..\] are converted to KaTeX equations.

Observed Behavior

  • Equations with $..$ or $$..$$ resulted in Error: Renderer for type inlineMath not defined or is not renderable (I believe $$..$$ is not inlineMath, but the error message was inlineMath)
  • Equations with \(..\) or \[..\] was transformed to plaintext with (..) or [..] respectively

What am I missing?

How to customize the delimiters?

In README, it says

Some TeX packages and Markdown processors use double dollars, $$, as a inline token. Remark Math will parse it also properly.

That is what I want. And I want more as follows:

$300 is just regular text, just how many $ in my pocket, no math here.
And $$ax^2+bx+c=0$$ shouble be parsed into inline math, while $$
ax^2+bx+c=0
$$
parsed into display math.

I really do not want $ as inline math delimiter. And $$...$$ for inline math and $$\n...\n$$ for display math is good enough.
The benefit is that there is no need to escape $ in regular text for a dollar sign in most cases.

Inlcude support for mhchem in the rehype-katex module

Initial checklist

Problem

Hello,

I would like to request to incorporate mhchem into the rehype-katex module. Mhchem is a chemistry notation parser that is usually used on top of other latex systems such as katex or MathJax.

Katex doesn't provide functionality for mhchem out of the box as such it needs to be imported separately.

Below is the documentation that explains how to load it through CDN:
https://github.com/KaTeX/KaTeX/blob/master/contrib/mhchem/README.md

I was wondering if I can get any insight into how we can integrate mhchem into rehype-katex.

Solution

In the KaTex documentation, they do have an in integration for mhchem in their dist folder as shown here: https://github.com/KaTeX/KaTeX/blob/master/contrib/mhchem/mhchem.js

There is another issue that would relate to rehype-katex / javascript modules about how one can integrate this library:
KaTeX/KaTeX#1995

Alternatives

An alternative to this feature request would be to use MathJax. MathJax V3 now comes with support for mhchem straight from the box. A downside of it is that it doesn't provide the same types of styling as provided for Katex.

Lastly please let me know if there is any other information that I should provide to make my request clearer. Thank you!

Update Katex from 0.12.0 to its latest available version 0.13.2 [rehype-katex]

Update Katex from 0.12.0 to its latest available version 0.13.2

The current version gives a nasty Katex Parse Error: No environment found... when processing Latex that involves \begin{equation} and other similar features.

Your environment

Is irrelevant.

Steps to reproduce

This markdown causes it to trip.

$$
\begin{equation}
    \gamma^2+\theta^2=\omega^2
\end{equation}
$$

Expected behavior

Math should be correctly converted to HTML?

Actual behavior

Throws a Katex Error, which does not happen with the updated Katex package.

Solution

I manually updated Katex to its latex version and got it to work.

Bump peer dep for remark-parse

Hi there! I've been using remark-math on a React/Redux/Electron/TypeScript project with remark-parse at >=v4.0.0 with no (known) issues. I hadn't really been paying attention to Yarn warnings, but I came across this when setting up a new dev machine:

warning "[email protected]" has unmet peer dependency "remark-parse@>=3.0.0".

Any chance you could bump the peer deps on this repo?

rehype-mathjax: mathjax is 500kb+ minzipped

Subject of the feature

MathJax’ SVG output is heavy, probably due to its font support, figure out a way to make it smaller.

Expected behaviour

Not be 500kb+ in browsers or in Node.

Will \( \) style math formula be supported

Subject of the feature

Describe your issue here.

in some mathjax configs people write \(a+b\) as formulas, will this be supported?

Problem

If the feature requests relates to a problem, please describe the problem you are trying to solve here.

Expected behaviour

What should happen? Please describe the desired behaviour.

parse \(\) as inline and \[\] as dispay

Alternatives

What are the alternative solutions? Please describe what else you have considered?

possible related #21

adding LaTeX environment without mathmode

In LaTeX, you can use \begin{array} without the $$ b/c the array environment includes a standalone math environment. There are also text model LaTeX commands such as \emph that can be used in text (without $ b/c they are textmode commands).

To achieve complete mixed LaTeX markdown syntax, we could add support to basic LaTeX command parsing + some white listed environments. We could even allow users to configure these white list and parsing rules.


\[ is already in LaTeX macro land, so in this sense you are only one step away from adding support for something like this:

https://www.sharelatex.com/learn/Display_style_in_math_mode#Setting_mathematical_styles

In-line maths elements can be set with a different style: \(f(x) = \displaystyle \frac{1}{1+x}\). The same is true the other way around:
 
\begin{eqnarray*}
\begin{eqnarray*}
f(x) = \sum_{i=0}^{n} \frac{a_i}{1+x} \\
\textstyle f(x) = \textstyle \sum_{i=0}^{n} \frac{a_i}{1+x} \\
\scriptstyle f(x) = \scriptstyle \sum_{i=0}^{n} \frac{a_i}{1+x} \\
\scriptscriptstyle f(x) = \scriptscriptstyle \sum_{i=0}^{n} \frac{a_i}{1+x}
\end{eqnarray*}
\end{eqnarray*}

Comment support for katex

Initial checklist

Affected packages and versions

[email protected]

Link to runnable example

No response

Steps to reproduce

try the following equation in the markdown

$$
\begin{split}
   f(-2) &= \sqrt{-2+4} \\
   &= x % Test Comment
\end{split}
$$

with following processors

let processor = unified()
    .use(markdown)
    .use(math)
    .use(remark2rehype)
    .use(katex)
    .use(document, {css: ['https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css']})
    .use(html);

Expected behavior

Comments should work properly

Actual behavior

The following warnings appear in the console:

LaTeX-incompatible input and strict mode is set to 'warn': % comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $) [commentAtEnd]
docs/maths-1/ch1/ex1.1/q1-i.md
  3:1-8:3  warning  KaTeX parse error: Expected & or \\ or \cr or \end at end of input: …ent \end{split}  parseerror  rehype-katex

Runtime

Node v14

Package manager

No response

OS

macOS

Build and bundle tools

Other (please specify in steps to reproduce)

katex error: Module parse failed: Identifier directly after number

Initial checklist

Affected packages and versions

"rehype-katex": "^6.0.1"

Link to runnable example

https://github.com/jackykwandesign/react-markdown-katex-error

Steps to reproduce

  1. just use rehype-katex in react-markdown will produce error

Expected behavior

show katex

Actual behavior

show babel-loader error

Failed to compile.

./node_modules/hast-util-to-text/index.js 363:65
Module parse failed: Identifier directly after number (363:65)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|     //     break is the zero-width space character (U+200B), then the break is
|     //     removed, leaving behind the zero-width space.
>     if (lines[index].charCodeAt(lines[index].length - 1) === 0x20_0b
|     /* ZWSP */
|     || index < lines.length - 1 && lines[index + 1].charCodeAt(0) === 0x20_0b

Runtime

Node v12

Package manager

yarn v1

OS

Linux

Build and bundle tools

Create React App

Use dashes for classes instead of camelCase

Subject of the feature

Classes in HTML/CSS are typically written as lowercase and with dashes: this-that, not thisThat.

Problem

This library uses camelcase.

Expected behaviour

  • Block math: <div class="math math-display>
  • Inline math: <span class="math math-inline> (optionally with math-display class for $$)

/cc @Rokt33r

Flexibility of math syntax

There are tons of styles to present displayMath and inlineMath. The current version(v0.2) is also one of the dialects.

We could switch the most famous rule. But, it won't satisfy everyone's need. So, I'm going to give options to choose your favorite syntax style.

remark()
  .use(math, {
    style: 'kramdown'
  })

Currently, @vhf is trying to implement the one of kramdown

If you want other styles, please leave a comment. Or, if you're in hurry, you can always create a new PR.

We also could discuss this at remark gitter

Overload resolution fails for rehype-katex

Subject of the issue

I am using a markdown processing pipeline in a next.js project with rehype-katex (shown below), and after upgrading some packages, I have been unable to compile my code (I'm using typescript) due to an overload resolution problem.

Your environment

  • OS: macOS 11.5.1 on Apple M1
  • Packages: "rehype-katex": "^5.0.0", "rehype-stringify": "^9.0.1", "remark-math": "^4.0.0", "remark-rehype": "^8.1.0", "unified": "^10.1.0" (taken from package.json)
  • Env: node v16.6.0

Steps to reproduce

My code is extremely similar to the example from the readme, actually:

import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeKatex from "rehype-katex";
import rehypeStringify from "rehype-stringify";
import math from "remark-math";

export default async function markdownToHtml(markdown: string) {
  const result = await unified()
    .use(remarkParse)
    .use(math)
    .use(remarkRehype)
    .use(rehypeKatex) // <--- this fails
    .use(rehypeStringify)
    .process(markdown);

  return result.value;
}

Expected behavior

I had been using this code without problems until I bumped some package versions, which I expected would continue.

Actual behavior

There is an error when compiling the files, indicating an overload issue in rehype-katex:

Type error: No overload matches this call.
  Overload 1 of 3, '(plugin: Plugin<[KatexOptions?], Node, Node>, ...settings: [KatexOptions?] | [boolean]): Processor<Node, Node, Node, void>', gave the following error.
    Argument of type 'Plugin<[KatexOptions?], Settings>' is not assignable to parameter of type 'Plugin<[KatexOptions?], Node, Node>'.
      The 'this' types of each signature are incompatible.
        Type 'Processor<void, Node, void, void>' is not assignable to type 'Processor<Settings>'.
          Types of property 'use' are incompatible.
            Type '{ <PluginParameters extends any[] = any[], Input = Node, Output = Input>(plugin: Plugin<PluginParameters, Input, Output>, ...settings: [boolean] | PluginParameters): UsePlugin<...>; <PluginParameters extends any[] = any[], Input = Node, Output = Input>(tuple: [...] | [...]): UsePlugin<...>; (presetOrList: Preset | P...' is not assignable to type '{ <S extends any[] = [Settings?]>(plugin: Plugin<S, Settings>, ...settings: S): Processor<Settings>; <S extends any[] = [Settings?]>(preset: Preset<S, Settings>): Processor<...>; <S extends any[] = [...?]>(pluginTuple: [...]): Processor<...>; (list: PluggableList<...>): Processor<...>; (processorSettings: ProcessorS...'.
              Types of parameters 'plugin' and 'plugin' are incompatible.
                The 'this' types of each signature are incompatible.
                  Type 'Processor<void, void, void, void> | Processor<void, any, void, void> | Processor<void, any, any, any> | Processor<any, any, void, void>' is not assignable to type 'Processor<Settings>'.
                    Type 'Processor<void, void, void, void>' is not assignable to type 'Processor<Settings>'.
                      Types of property 'use' are incompatible.
                        Types of parameters 'plugin' and 'plugin' are incompatible.
                          Type 'void | Transformer' is not assignable to type 'void | Transformer<any, any>'.
                            Type 'Transformer' is not assignable to type 'void | Transformer<any, any>'.
                              Type 'Transformer' is not assignable to type 'Transformer<any, any>'.
                                Types of parameters 'file' and 'file' are incompatible.
                                  Property 'contents' is missing in type 'import("/Users/nicholasjunge/Workspaces/web/personal-website/node_modules/unified/node_modules/vfile/lib/index").VFile' but required in type 'import("/Users/nicholasjunge/Workspaces/web/personal-website/node_modules/vfile/types/index").VFile'.
  Overload 2 of 3, '(tuple: [Plugin<any[], Node, Node>, ...any[]] | [Plugin<any[], Node, Node>, boolean]): Processor<Node, Node, Node, void>', gave the following error.
    Argument of type 'Plugin<[KatexOptions?], Settings>' is not assignable to parameter of type '[Plugin<any[], Node, Node>, ...any[]] | [Plugin<any[], Node, Node>, boolean]'.
      Type 'Plugin<[KatexOptions?], Settings>' is not assignable to type '[Plugin<any[], Node, Node>, boolean]'.
  Overload 3 of 3, '(presetOrList: Preset | PluggableList): Processor<Node, Node, Node, void>', gave the following error.
    Argument of type 'Plugin<[KatexOptions?], Settings>' is not assignable to parameter of type 'Preset | PluggableList'.
      Type 'Plugin<[KatexOptions?], Settings>' is missing the following properties from type 'Pluggable<any[]>[]': pop, push, concat, join, and 27 more.

Removing the .use(rehypeKatex) line makes everything compile, but that would of course have the disadvantage that math is not being styled anymore in my pages. I am not a very adept JS/TS user, so my ability to fix this on my own is limited - hence this issue. If there's any more info I need to provide, I am happy to add that though.

Strangely, my git history indicates that I had been using rehype-katex@^5.0.0 even before when everything was working fine (I just resumed my project after ~3 months), so maybe this is a cascading issue from another package?

Esmodule version of the introduction of hast-util-from-dom leads to errors...

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/rehype-mathjax/lib/renderer.js b/node_modules/rehype-mathjax/lib/renderer.js
index 1a6c927..a724d53 100644
--- a/node_modules/rehype-mathjax/lib/renderer.js
+++ b/node_modules/rehype-mathjax/lib/renderer.js
@@ -1,6 +1,6 @@
 const mathjax = require('mathjax-full/js/mathjax').mathjax
 const register = require('mathjax-full/js/handlers/html').RegisterHTMLHandler
-const fromDom = require('hast-util-from-dom')
+const fromDom = require('hast-util-from-dom').default
 const toText = require('hast-util-to-text')
 const createAdaptor = require('./adaptor')
 

This issue body was partially generated by patch-package.

image

repo: https://github.com/rxliuli/joplin-search-intergration/blob/ff95928d5e02823cb2738ef72d826196aea09ade/src/pages/options/pages/note/util/render.ts#L27

Extend remark-stringify for remark-math

Currently, rendering markdown with math block requires to use remark-html.
Remark-stringify should be able to render math inlines and blocks from their node.

invalid javascript @ generated object keys

Initial checklist

Affected packages and versions

rehype-mathjax: 4.0.2

Link to runnable example

No response

Steps to reproduce

// @ vite.config.js
{
  plugins: [
    XDM({
      rehypePlugins: [Rehype_MathJax],
      remarkPlugins: [Remark_Math   ],
    })
  ]
}

Expected behavior

Example snippet

Lift($L$) can be determined by Lift Coefficient ($C_L$) like the following equation.

should compile from an mdx file without error.

Actual behavior

Browser Error:

Uncaught (in promise) SyntaxError: Unexpected token '-'

image

It seems that the error would be prevented by wrapping the generated mdx-container key in quotes.

Through trial & error I found that this issue:

  • occurs when parsing mdx files via either mdx-js or xdm
  • does not occur when swapping rehype-katex in place of rehype-mathjax

Runtime

Node v16

Package manager

yarn v1

OS

Windows

Build and bundle tools

Vite

remark-math-katex

I think the usage of remark-math-katex should be like the following.

const remark = require('remark')
const math = require('remark-math')
const katex = require('remark-math-katex')

const remarkProcessor = remark()
  .use(math)
  .use(katex)
  .use(html)

The problem is that remark-math-katex can not access options.handlers of remark-html.

Of course, if I provide data.hName and data.hChildren, this can be solved easily.

But here comes another problem. I think math and inlineMath should use value as its content, instead of children: [{type: 'text', value: value}], just like code and inlineCode.

If we keep using children, some transformers might misunderstand its content as a text node of paragraph.

So, I think handlers of remark-html should be exposed to inject handlers from other plugins.

Alternative Ideas

Of course, there are some alternatives like the below.

Provide katex handlers into options of remark-html

const remark = require('remark')
const math = require('remark-math')
const katex = require('remark-math-katex')

const remarkProcessor = remark()
  .use(math)
  .use(html, {
    handlers: {
      inlineMath: ~~,
      math: ~~
    }
  })

PRO: No need to modify remark-html
CON: Bad usability

Transform math nodes

const visit = require('unist-util-visit')
const katex = require('katex')

module.exports = function plugin (p, opts = {}) {
  if (opts.throwOnError == null) opts.throwOnError = false
  return function transform (node) {
    visit(node, 'inlineMath', function (inlineMath) {
      inlineMath.type = 'html'
      inlineMath.value = ~~
    })
    visit(node, 'math', function (math) {
      math.type = 'html'
      math.value = ~~
    })

    return node
  }
}

PRO: No need to modify remark-html
CON: AST would be compromised(remark-html has no side effect to parsed AST)

dist version is not compiled down to es5

I am running into this problem while using react-scripts.

When a project uses remark-math, if we run react-scripts build, CRA tool reports this error:

Failed to minify the code from this file: 

 	./node_modules/remark-math/index.js:4 

Inspection of the file above shows that this index.js uses a es2015 feature: default value for function parameters. The file looks like this:

// node_modules/remark-math/index.js

const inlinePlugin = require('./inline')
const blockPlugin = require('./block')

module.exports = function mathPlugin (opts = {}) {
  blockPlugin.call(this, opts)
  inlinePlugin.call(this, opts)
}

I'm not familiar with lerna, is it possible to compile the dis version to es5? This has been a recurring theme with a lot of libraries (including my own), and the community tend to end up compiling to es5 in the end.

On CRA (Create React App) and react-scripts

CRA is the way to write react app nowadays, and it doesn't allow custom webpack.config so adding whitelisted loading is out of the question (TLDR;).

Hard break identifier immediately preceding $$ is not registered as a hard break.

Initial checklist

Affected packages and versions

"remark-math": "^5.1.1", "rehype-katex": "^6.0.2",

Link to runnable example

No response

Steps to reproduce

import ReactMarkdown from "react-markdown";
import remarkMath from "remark-math";
import remarkBreaks from "remark-breaks"
import rehypeKatex from "rehype-katex";
import "katex/dist/katex.min.css";

<ReactMarkdown
      remarkPlugins={[remarkMath, remarkBreaks]}
      rehypePlugins={[rehypeKatex]}
    >
   {markdownText}
</ReactMarkdown>

Expected behavior

A hard break can be caused by ␠␠ or by \.

When markdownText = "empty \n \ \n line"
It produces:

new
line
empty

line

as expected.

Though if we are using $$ then the hard break characters are not converted into a hard break.
When markdownText = "new line empty \n \ \n $$line$$"
We expect:

new
line
empty

line

With the last line being written in latex.

Actual behavior

It actually produces:

new
line
empty
line

With the last line being written in latex.

This is the same no matter how many new lines and hard breaks are placed before it.
eg. markdownText = "new \n line \n empty \n \ \n \ \n \ \n \ \n \ \n $$line$$"

Runtime

Node v17

Package manager

npm 8

OS

macOS

Build and bundle tools

No response

Update for changes in remark

Hi! 👋

remark just changed: you can read more about the changed here.

That means that this plugin doesn’t work with the latest remark. If you get around to updating, use the previously mentioned changelog for help, but feel free to respond below or ask questions on Gitter!

rehype-sanitize breaks math rendering

Initial checklist

Affected packages and versions

[email protected], [email protected], [email protected]

Link to runnable example

https://codesandbox.io/s/react-markdown-debug-forked-3rbkc?file=/src/App.js

Steps to reproduce

The above sandbox link should work! code copied below for posterity.

Code:
import React from "react";
import Markdown from "react-markdown";
import rehypeKatex from "rehype-katex";
import rehypeSanitize from "rehype-sanitize";
import remarkMath from "remark-math";

import "katex/dist/katex.min.css";

const mathMarkdown = `
Lift($L$) can be determined by Lift Coefficient ($C_L$) like the following
equation.

$$
L = \\frac{1}{2} \\rho v^2 S C_L
$$
`;

export default function App() {
  return (
    <>
      <h1>Without sanitize</h1>
      <Markdown rehypePlugins={[rehypeKatex]} remarkPlugins={[remarkMath]}>
        {mathMarkdown}
      </Markdown>
      <h1>With sanitize</h1>
      <Markdown
        rehypePlugins={[rehypeKatex, rehypeSanitize]}
        remarkPlugins={[remarkMath]}
      >
        {mathMarkdown}
      </Markdown>
    </>
  );
}

Result:

Screen Shot 2021-09-29 at 1 36 11 PM

Expected behavior

rehype-katex should still be able to correctly render math after rehype-sanitize runs. According to https://github.com/remarkjs/remark-math#security its advised to add rehype-sanitize if accepting user input. Even if safe without sanitize, I still need rehype-sanitize since I'm also using rehype-raw and rehype-autolink-headings.

Note, this breaks regardless of the order of plugins are added.

Actual behavior

Math does not correctly render.

Runtime

Other (please specify in steps to reproduce)

Package manager

yarn v1

OS

macOS

Build and bundle tools

Webpack

rehype-mathjax: allow configuration of TeX input processor

Problem

The options for the rehype-mathjax plugin are not that of the whole MathJax instance.
Rather, they are only the options for the SVG output processor.

Hence, it is currently not possible to configure the TeX input processor, in order to, for example, enable automatic equation tagging (with MathJax configuration { tex: { tags: "ams" } }).

Expected behavior

The options parameter for the renderSvg(options) function below should be of the form { tex: { /* ... */ }, svg: { /* ... */ } } as in the MathJax documentation.
This way, both the TeX input and SVG output processors may be configured.

function renderSvg(options) {
return createRenderer(createInput(), createOutput(options))
}

Currently, those options are only that of the SVG output processor.
This could instead read something like return new Svg((options || {}).svg || {}).

function createOutput(options) {
return new Svg(options)
}

Below, the createInput() function should have an options parameter, and still have all the packages as default value.
This could instead read something like return new Tex({packages: packages, ...(options || {}).tex}).

function createInput() {
return new Tex({packages: packages})
}

One problem that could arise with these changes is that when using automatic equation numbering, the numbers could continue across multiple documents being processed using the same instance of rehype.
That is, new instances of the TeX input and SVG output processors should be used for each document being processed to prevent the numbering from continuing onto the next document.
This problem may be ignored if instances of rehype are not meant to be reused for multiple documents.

Escaping $ and $ in raw should not get parsed as math

remark-math has a quite painful parsing bug due to this regular expression: https://github.com/Rokt33r/remark-math/blob/2445b979253214997174092785589386d79892e5/packages/remark-math/inline.js#L6

How to reproduce:

$foo\$

Explanation: This gets matched by the regex because it starts with $, ends with $, and between the starting $ and ending $ there's no \$.

Also an issue:

$foo`$`

Here are failing test cases:

it('must escape a dollar with back slash', () => {
  const processor = remark()
    .use(math)

  const targetText = '$\\alpha\\$'

  const ast = processor.parse(targetText)
  expect(ast).toMatchObject(u('root', [
    u('paragraph', [
      u('text', '$\\alpha'),
      u('text', '$')
    ])
  ]))
})

it('must not parse a raw dollar', () => {
  const processor = remark()
    .use(math)

  const targetText = '$\\alpha`$`'

  const ast = processor.parse(targetText)
  expect(ast).toMatchObject(u('root', [
    u('paragraph', [
      u('text', '$'),
      u('text', '\\alpha'),
      u('text', '$')
    ])
  ]))
})

Option to accept double dollar ($$) for inline maths

Initial checklist

Problem

Single dollars can easily conflict with financial data in a Markdown content.

For example the following markdown content will be parsed with an inline math node:

The **Team** plan starts at $40 per month and includes your first 5 users. Every user after your first 5 users is charged an additional $8 per month.

Solution

For GitBook, we've solved this problem in our custom markdown parser by also using $$ for inline maths.

A math block:

$$
a = b
$$

An inline one $$a = b$$

It'd be great if remark-math could accept an option to use double dollars for inlines.

Alternatives

An alternative could be to only parse inline maths if there is no spaces in it. But it'd not be a great UX for people writing markdown.

Ex:

This is an inline math: $a=b$

This is not an inline math $a = b$

remark-parse 5.0.0

Is there anything preventing the project from accepting remark-parse 5.0.0 as a peer dependency?

Generate (`pre` and) `code` elements instead of `div`, `span`

Initial checklist

Affected packages and versions

all

Link to runnable example

No response

Steps to reproduce

examples in readme, all tests

Expected behavior

Use <code class="math math-inline">…</code> and <pre><code class="math math-display">…</code></pre> instead of spans and divs.

Likely even improved, use <code class="lang-math math-inline">…</code> and <pre><code class="lang-math math-display">…</code></pre>.
This is better because it means it would generate the same as:

```math
\sqrt{3}
```

Which is a good alternative to introducing a custom syntax, and GitHub says that they support it (although it doesn’t render for me here).

That second idea comes with another question though: does math-display and math-inline then still make sense?

Actual behavior

see examples in readme, all tests

Runtime

No response

Package manager

No response

OS

No response

Build and bundle tools

No response

Next.js hydration issue

Initial checklist

Affected packages and versions

remark-math, rehype-mathjax, all latest versions

Link to runnable example

No response

Steps to reproduce

yarn create next-app
yarn add @next/mdx @mdx-js/loader @mdx-js/react remark-math rehype-mathjax

create a next.config.mjs with the contents:

import mdx from "@next/mdx";
import remarkMath from "remark-math";
import rehypeMathJax from "rehype-mathjax";

const withMDX = mdx({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [rehypeMathJax],
  },
});

export default withMDX({
  reactStrictMode: true,
  pageExtensions: ["tsx", "jsx", "mdx"],
});

Expected behavior

Should render without errors.

Actual behavior

Renders correctly, but with the error
Error: Text content does not match server-rendered HTML.

Runtime

Node v16

Package manager

yarn 1

OS

macOS

Build and bundle tools

Next.js (bug is seen on both v13 and v12)

rehype-mathjax: use `abstractAdopter` instead of `jsdomAdaptor` / `browserAdaptor`

Problem

JsDom is heavy, and an alternative to rehype, which we’re already using. It’s probably better to use AbstractAdopter and map it to hast, instead of using jsdomAdaptor / browserAdaptor to create a DOM and then transform that to hast.

Expected behaviour

Directly do mathjax -> hast, instead of mathjax -> dom -> hast

Adding type definitions

Subject of the feature

It would be awesome if we have a built-in type definition (d.ts) for TypeScript.
I want to make sure it's ok to ship the modules with type definitions before sending a PR.

Refs

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.