first commit
This commit is contained in:
+107
@@ -0,0 +1,107 @@
|
||||
import type {Data, Literal} from 'mdast'
|
||||
|
||||
export {mathFromMarkdown, mathToMarkdown} from './lib/index.js'
|
||||
|
||||
export type {ToOptions} from './lib/index.js'
|
||||
|
||||
/**
|
||||
* Math (flow).
|
||||
*/
|
||||
export interface Math extends Literal {
|
||||
/**
|
||||
* Node type of math (flow).
|
||||
*/
|
||||
type: 'math'
|
||||
|
||||
/**
|
||||
* Custom information relating to the node.
|
||||
*/
|
||||
meta?: string | null | undefined
|
||||
|
||||
/**
|
||||
* Data associated with the mdast math (flow).
|
||||
*/
|
||||
data?: MathData | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Info associated with mdast math (flow) nodes by the ecosystem.
|
||||
*/
|
||||
export interface MathData extends Data {}
|
||||
|
||||
/**
|
||||
* Math (text).
|
||||
*/
|
||||
export interface InlineMath extends Literal {
|
||||
/**
|
||||
* Node type of math (text).
|
||||
*/
|
||||
type: 'inlineMath'
|
||||
|
||||
/**
|
||||
* Data associated with the mdast math (text).
|
||||
*/
|
||||
data?: InlineMathData | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Info associated with mdast math (text) nodes by the ecosystem.
|
||||
*/
|
||||
export interface InlineMathData extends Data {}
|
||||
|
||||
// Add custom data tracked to turn markdown into a tree.
|
||||
declare module 'mdast-util-from-markdown' {
|
||||
interface CompileData {
|
||||
/**
|
||||
* Whether we’re in math (flow).
|
||||
*/
|
||||
mathFlowInside?: boolean | undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Add custom data tracked to turn a tree into markdown.
|
||||
declare module 'mdast-util-to-markdown' {
|
||||
interface ConstructNameMap {
|
||||
/**
|
||||
* Math (flow).
|
||||
*
|
||||
* ```markdown
|
||||
* > | $$
|
||||
* ^^
|
||||
* > | a
|
||||
* ^
|
||||
* > | $$
|
||||
* ^^
|
||||
* ```
|
||||
*/
|
||||
mathFlow: 'mathFlow'
|
||||
|
||||
/**
|
||||
* Math (flow) meta flag.
|
||||
*
|
||||
* ```markdown
|
||||
* > | $$a
|
||||
* ^
|
||||
* | b
|
||||
* | $$
|
||||
* ```
|
||||
*/
|
||||
mathFlowMeta: 'mathFlowMeta'
|
||||
}
|
||||
}
|
||||
|
||||
// Add nodes to tree.
|
||||
declare module 'mdast' {
|
||||
interface BlockContentMap {
|
||||
math: Math
|
||||
}
|
||||
|
||||
interface PhrasingContentMap {
|
||||
inlineMath: InlineMath
|
||||
}
|
||||
|
||||
interface RootContentMap {
|
||||
inlineMath: InlineMath
|
||||
math: Math
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
// Note: Types exported from `index.d.ts`.
|
||||
export {mathFromMarkdown, mathToMarkdown} from './lib/index.js'
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Create an extension for `mdast-util-from-markdown`.
|
||||
*
|
||||
* @returns {FromMarkdownExtension}
|
||||
* Extension for `mdast-util-from-markdown`.
|
||||
*/
|
||||
export function mathFromMarkdown(): FromMarkdownExtension;
|
||||
/**
|
||||
* Create an extension for `mdast-util-to-markdown`.
|
||||
*
|
||||
* @param {ToOptions | null | undefined} [options]
|
||||
* Configuration (optional).
|
||||
* @returns {ToMarkdownExtension}
|
||||
* Extension for `mdast-util-to-markdown`.
|
||||
*/
|
||||
export function mathToMarkdown(options?: ToOptions | null | undefined): ToMarkdownExtension;
|
||||
export type HastElement = import('hast').Element;
|
||||
export type HastElementContent = import('hast').ElementContent;
|
||||
export type CompileContext = import('mdast-util-from-markdown').CompileContext;
|
||||
export type FromMarkdownExtension = import('mdast-util-from-markdown').Extension;
|
||||
export type FromMarkdownHandle = import('mdast-util-from-markdown').Handle;
|
||||
export type ToMarkdownHandle = import('mdast-util-to-markdown').Handle;
|
||||
export type ToMarkdownExtension = import('mdast-util-to-markdown').Options;
|
||||
export type InlineMath = import('../index.js').InlineMath;
|
||||
export type Math = import('../index.js').Math;
|
||||
/**
|
||||
* Configuration.
|
||||
*/
|
||||
export type ToOptions = {
|
||||
/**
|
||||
* Whether to support math (text) with a single dollar (default: `true`).
|
||||
*
|
||||
* Single dollars work in Pandoc and many other places, but often interfere
|
||||
* with “normal” dollars in text.
|
||||
* If you turn this off, you can still use two or more dollars for text math.
|
||||
*/
|
||||
singleDollarTextMath?: boolean | null | undefined;
|
||||
};
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* @typedef {import('hast').Element} HastElement
|
||||
* @typedef {import('hast').ElementContent} HastElementContent
|
||||
* @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext
|
||||
* @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
|
||||
* @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
|
||||
* @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle
|
||||
* @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
|
||||
* @typedef {import('../index.js').InlineMath} InlineMath
|
||||
* @typedef {import('../index.js').Math} Math
|
||||
*
|
||||
* @typedef ToOptions
|
||||
* Configuration.
|
||||
* @property {boolean | null | undefined} [singleDollarTextMath=true]
|
||||
* Whether to support math (text) with a single dollar (default: `true`).
|
||||
*
|
||||
* Single dollars work in Pandoc and many other places, but often interfere
|
||||
* with “normal” dollars in text.
|
||||
* If you turn this off, you can still use two or more dollars for text math.
|
||||
*/
|
||||
|
||||
import {ok as assert} from 'devlop'
|
||||
import {longestStreak} from 'longest-streak'
|
||||
|
||||
/**
|
||||
* Create an extension for `mdast-util-from-markdown`.
|
||||
*
|
||||
* @returns {FromMarkdownExtension}
|
||||
* Extension for `mdast-util-from-markdown`.
|
||||
*/
|
||||
export function mathFromMarkdown() {
|
||||
return {
|
||||
enter: {
|
||||
mathFlow: enterMathFlow,
|
||||
mathFlowFenceMeta: enterMathFlowMeta,
|
||||
mathText: enterMathText
|
||||
},
|
||||
exit: {
|
||||
mathFlow: exitMathFlow,
|
||||
mathFlowFence: exitMathFlowFence,
|
||||
mathFlowFenceMeta: exitMathFlowMeta,
|
||||
mathFlowValue: exitMathData,
|
||||
mathText: exitMathText,
|
||||
mathTextData: exitMathData
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function enterMathFlow(token) {
|
||||
/** @type {HastElement} */
|
||||
const code = {
|
||||
type: 'element',
|
||||
tagName: 'code',
|
||||
properties: {className: ['language-math', 'math-display']},
|
||||
children: []
|
||||
}
|
||||
this.enter(
|
||||
{
|
||||
type: 'math',
|
||||
meta: null,
|
||||
value: '',
|
||||
data: {hName: 'pre', hChildren: [code]}
|
||||
},
|
||||
token
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function enterMathFlowMeta() {
|
||||
this.buffer()
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function exitMathFlowMeta() {
|
||||
const data = this.resume()
|
||||
const node = this.stack[this.stack.length - 1]
|
||||
assert(node.type === 'math')
|
||||
node.meta = data
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function exitMathFlowFence() {
|
||||
// Exit if this is the closing fence.
|
||||
if (this.data.mathFlowInside) return
|
||||
this.buffer()
|
||||
this.data.mathFlowInside = true
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function exitMathFlow(token) {
|
||||
const data = this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, '')
|
||||
const node = this.stack[this.stack.length - 1]
|
||||
assert(node.type === 'math')
|
||||
this.exit(token)
|
||||
node.value = data
|
||||
// @ts-expect-error: we defined it in `enterMathFlow`.
|
||||
const code = /** @type {HastElement} */ (node.data.hChildren[0])
|
||||
assert(code.type === 'element')
|
||||
assert(code.tagName === 'code')
|
||||
code.children.push({type: 'text', value: data})
|
||||
this.data.mathFlowInside = undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function enterMathText(token) {
|
||||
this.enter(
|
||||
{
|
||||
type: 'inlineMath',
|
||||
value: '',
|
||||
data: {
|
||||
hName: 'code',
|
||||
hProperties: {className: ['language-math', 'math-inline']},
|
||||
hChildren: []
|
||||
}
|
||||
},
|
||||
token
|
||||
)
|
||||
this.buffer()
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function exitMathText(token) {
|
||||
const data = this.resume()
|
||||
const node = this.stack[this.stack.length - 1]
|
||||
assert(node.type === 'inlineMath')
|
||||
this.exit(token)
|
||||
node.value = data
|
||||
const children = /** @type {Array<HastElementContent>} */ (
|
||||
// @ts-expect-error: we defined it in `enterMathFlow`.
|
||||
node.data.hChildren
|
||||
)
|
||||
children.push({type: 'text', value: data})
|
||||
}
|
||||
|
||||
/**
|
||||
* @this {CompileContext}
|
||||
* @type {FromMarkdownHandle}
|
||||
*/
|
||||
function exitMathData(token) {
|
||||
this.config.enter.data.call(this, token)
|
||||
this.config.exit.data.call(this, token)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an extension for `mdast-util-to-markdown`.
|
||||
*
|
||||
* @param {ToOptions | null | undefined} [options]
|
||||
* Configuration (optional).
|
||||
* @returns {ToMarkdownExtension}
|
||||
* Extension for `mdast-util-to-markdown`.
|
||||
*/
|
||||
export function mathToMarkdown(options) {
|
||||
let single = (options || {}).singleDollarTextMath
|
||||
|
||||
if (single === null || single === undefined) {
|
||||
single = true
|
||||
}
|
||||
|
||||
inlineMath.peek = inlineMathPeek
|
||||
|
||||
return {
|
||||
unsafe: [
|
||||
{character: '\r', inConstruct: 'mathFlowMeta'},
|
||||
{character: '\n', inConstruct: 'mathFlowMeta'},
|
||||
{
|
||||
character: '$',
|
||||
after: single ? undefined : '\\$',
|
||||
inConstruct: 'phrasing'
|
||||
},
|
||||
{character: '$', inConstruct: 'mathFlowMeta'},
|
||||
{atBreak: true, character: '$', after: '\\$'}
|
||||
],
|
||||
handlers: {math, inlineMath}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {ToMarkdownHandle}
|
||||
* @param {Math} node
|
||||
*/
|
||||
// Note: fixing this code? Please also fix the similar code for code:
|
||||
// <https://github.com/syntax-tree/mdast-util-to-markdown/blob/main/lib/handle/code.js>
|
||||
function math(node, _, state, info) {
|
||||
const raw = node.value || ''
|
||||
const tracker = state.createTracker(info)
|
||||
const sequence = '$'.repeat(Math.max(longestStreak(raw, '$') + 1, 2))
|
||||
const exit = state.enter('mathFlow')
|
||||
let value = tracker.move(sequence)
|
||||
|
||||
if (node.meta) {
|
||||
const subexit = state.enter('mathFlowMeta')
|
||||
value += tracker.move(
|
||||
state.safe(node.meta, {
|
||||
after: '\n',
|
||||
before: value,
|
||||
encode: ['$'],
|
||||
...tracker.current()
|
||||
})
|
||||
)
|
||||
subexit()
|
||||
}
|
||||
|
||||
value += tracker.move('\n')
|
||||
|
||||
if (raw) {
|
||||
value += tracker.move(raw + '\n')
|
||||
}
|
||||
|
||||
value += tracker.move(sequence)
|
||||
exit()
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {ToMarkdownHandle}
|
||||
* @param {InlineMath} node
|
||||
*/
|
||||
// Note: fixing this code? Please also fix the similar code for inline code:
|
||||
// <https://github.com/syntax-tree/mdast-util-to-markdown/blob/main/lib/handle/inline-code.js>
|
||||
function inlineMath(node, _, state) {
|
||||
let value = node.value || ''
|
||||
let size = 1
|
||||
|
||||
if (!single) size++
|
||||
|
||||
// If there is a single dollar sign on its own in the math, use a fence of
|
||||
// two.
|
||||
// If there are two in a row, use one.
|
||||
while (
|
||||
new RegExp('(^|[^$])' + '\\$'.repeat(size) + '([^$]|$)').test(value)
|
||||
) {
|
||||
size++
|
||||
}
|
||||
|
||||
const sequence = '$'.repeat(size)
|
||||
|
||||
// If this is not just spaces or eols (tabs don’t count), and either the
|
||||
// first and last character are a space or eol, or the first or last
|
||||
// character are dollar signs, then pad with spaces.
|
||||
if (
|
||||
// Contains non-space.
|
||||
/[^ \r\n]/.test(value) &&
|
||||
// Starts with space and ends with space.
|
||||
((/^[ \r\n]/.test(value) && /[ \r\n]$/.test(value)) ||
|
||||
// Starts or ends with dollar.
|
||||
/^\$|\$$/.test(value))
|
||||
) {
|
||||
value = ' ' + value + ' '
|
||||
}
|
||||
|
||||
let index = -1
|
||||
|
||||
// We have a potential problem: certain characters after eols could result in
|
||||
// blocks being seen.
|
||||
// For example, if someone injected the string `'\n# b'`, then that would
|
||||
// result in an ATX heading.
|
||||
// We can’t escape characters in `inlineMath`, but because eols are
|
||||
// transformed to spaces when going from markdown to HTML anyway, we can swap
|
||||
// them out.
|
||||
while (++index < state.unsafe.length) {
|
||||
const pattern = state.unsafe[index]
|
||||
|
||||
// Only look for `atBreak`s.
|
||||
// Btw: note that `atBreak` patterns will always start the regex at LF or
|
||||
// CR.
|
||||
if (!pattern.atBreak) continue
|
||||
|
||||
const expression = state.compilePattern(pattern)
|
||||
/** @type {RegExpExecArray | null} */
|
||||
let match
|
||||
|
||||
while ((match = expression.exec(value))) {
|
||||
let position = match.index
|
||||
|
||||
// Support CRLF (patterns only look for one of the characters).
|
||||
if (
|
||||
value.codePointAt(position) === 10 /* `\n` */ &&
|
||||
value.codePointAt(position - 1) === 13 /* `\r` */
|
||||
) {
|
||||
position--
|
||||
}
|
||||
|
||||
value = value.slice(0, position) + ' ' + value.slice(match.index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
return sequence + value + sequence
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string}
|
||||
*/
|
||||
function inlineMathPeek() {
|
||||
return '$'
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2020 Titus Wormer <tituswormer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"name": "mdast-util-math",
|
||||
"version": "3.0.0",
|
||||
"description": "mdast extension to parse and serialize math",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"unist",
|
||||
"mdast",
|
||||
"mdast-util",
|
||||
"util",
|
||||
"utility",
|
||||
"markdown",
|
||||
"markup",
|
||||
"math",
|
||||
"katex",
|
||||
"latex",
|
||||
"tex"
|
||||
],
|
||||
"repository": "syntax-tree/mdast-util-math",
|
||||
"bugs": "https://github.com/syntax-tree/mdast-util-math/issues",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
},
|
||||
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
|
||||
"contributors": [
|
||||
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
"files": [
|
||||
"lib/",
|
||||
"index.d.ts",
|
||||
"index.js"
|
||||
],
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
"devlop": "^1.0.0",
|
||||
"longest-streak": "^3.0.0",
|
||||
"mdast-util-from-markdown": "^2.0.0",
|
||||
"mdast-util-to-markdown": "^2.1.0",
|
||||
"unist-util-remove-position": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"c8": "^8.0.0",
|
||||
"micromark-extension-math": "^3.0.0",
|
||||
"prettier": "^3.0.0",
|
||||
"remark-cli": "^11.0.0",
|
||||
"remark-preset-wooorm": "^9.0.0",
|
||||
"type-coverage": "^2.0.0",
|
||||
"typescript": "^5.0.0",
|
||||
"xo": "^0.55.0"
|
||||
},
|
||||
"scripts": {
|
||||
"prepack": "npm run build && npm run format",
|
||||
"build": "tsc --build --clean && tsc --build && type-coverage",
|
||||
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
|
||||
"test-api-dev": "node --conditions development test.js",
|
||||
"test-api-prod": "node --conditions production test.js",
|
||||
"test-api": "npm run test-api-dev && npm run test-api-prod",
|
||||
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
|
||||
"test": "npm run build && npm run format && npm run test-coverage"
|
||||
},
|
||||
"prettier": {
|
||||
"bracketSpacing": false,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "none",
|
||||
"useTabs": false
|
||||
},
|
||||
"remarkConfig": {
|
||||
"plugins": [
|
||||
"remark-preset-wooorm"
|
||||
]
|
||||
},
|
||||
"typeCoverage": {
|
||||
"atLeast": 100,
|
||||
"detail": true,
|
||||
"ignoreCatch": true,
|
||||
"strict": true
|
||||
},
|
||||
"xo": {
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"**/*.ts"
|
||||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"@typescript-eslint/consistent-type-definitions": "off"
|
||||
}
|
||||
}
|
||||
],
|
||||
"prettier": true,
|
||||
"rules": {
|
||||
"unicorn/prefer-at": "off",
|
||||
"unicorn/prefer-string-replace-all": "off"
|
||||
}
|
||||
}
|
||||
}
|
||||
+489
@@ -0,0 +1,489 @@
|
||||
# mdast-util-math
|
||||
|
||||
[![Build][build-badge]][build]
|
||||
[![Coverage][coverage-badge]][coverage]
|
||||
[![Downloads][downloads-badge]][downloads]
|
||||
[![Size][size-badge]][size]
|
||||
[![Sponsors][sponsors-badge]][collective]
|
||||
[![Backers][backers-badge]][collective]
|
||||
[![Chat][chat-badge]][chat]
|
||||
|
||||
[mdast][] extensions to parse and serialize math (`$C_L$`).
|
||||
|
||||
## Contents
|
||||
|
||||
* [What is this?](#what-is-this)
|
||||
* [When to use this](#when-to-use-this)
|
||||
* [Install](#install)
|
||||
* [Use](#use)
|
||||
* [API](#api)
|
||||
* [`mathFromMarkdown()`](#mathfrommarkdown)
|
||||
* [`mathToMarkdown(options?)`](#mathtomarkdownoptions)
|
||||
* [`InlineMath`](#inlinemath)
|
||||
* [`Math`](#math)
|
||||
* [`ToOptions`](#tooptions)
|
||||
* [HTML](#html)
|
||||
* [Syntax](#syntax)
|
||||
* [Syntax tree](#syntax-tree)
|
||||
* [Nodes](#nodes)
|
||||
* [Content model](#content-model)
|
||||
* [Types](#types)
|
||||
* [Compatibility](#compatibility)
|
||||
* [Related](#related)
|
||||
* [Contribute](#contribute)
|
||||
* [License](#license)
|
||||
|
||||
## What is this?
|
||||
|
||||
This package contains two extensions that add support for math syntax in
|
||||
markdown to [mdast][].
|
||||
These extensions plug into
|
||||
[`mdast-util-from-markdown`][mdast-util-from-markdown] (to support parsing
|
||||
math in markdown into a syntax tree) and
|
||||
[`mdast-util-to-markdown`][mdast-util-to-markdown] (to support serializing
|
||||
math in syntax trees to markdown).
|
||||
|
||||
## When to use this
|
||||
|
||||
This project is useful when you want to support math in markdown.
|
||||
Extending markdown with a syntax extension makes the markdown less portable.
|
||||
LaTeX equations are also quite hard.
|
||||
But this mechanism works well when you want authors, that have some LaTeX
|
||||
experience, to be able to embed rich diagrams of math in scientific text.
|
||||
|
||||
You can use these extensions when you are working with
|
||||
`mdast-util-from-markdown` and `mdast-util-to-markdown` already.
|
||||
|
||||
When working with `mdast-util-from-markdown`, you must combine this package
|
||||
with [`micromark-extension-math`][micromark-extension-math].
|
||||
|
||||
When you don’t need a syntax tree, you can use [`micromark`][micromark]
|
||||
directly with
|
||||
[`micromark-extension-math`][micromark-extension-math].
|
||||
|
||||
All these packages are used [`remark-math`][remark-math], which
|
||||
focusses on making it easier to transform content by abstracting these
|
||||
internals away.
|
||||
|
||||
This utility adds [fields on nodes][fields] so that the utility responsible for
|
||||
turning mdast (markdown) nodes into hast (HTML) nodes,
|
||||
[`mdast-util-to-hast`][mdast-util-to-hast], turns text (inline) math nodes into
|
||||
`<code class="language-math math-inline">…</code>` and flow (block) math nodes
|
||||
into `<pre><code class="language-math math-display">…</code></pre>`.
|
||||
|
||||
## Install
|
||||
|
||||
This package is [ESM only][esm].
|
||||
In Node.js (version 16+), install with [npm][]:
|
||||
|
||||
```sh
|
||||
npm install mdast-util-math
|
||||
```
|
||||
|
||||
In Deno with [`esm.sh`][esmsh]:
|
||||
|
||||
```js
|
||||
import {mathFromMarkdown, mathToMarkdown} from 'https://esm.sh/mdast-util-math@3'
|
||||
```
|
||||
|
||||
In browsers with [`esm.sh`][esmsh]:
|
||||
|
||||
```html
|
||||
<script type="module">
|
||||
import {mathFromMarkdown, mathToMarkdown} from 'https://esm.sh/mdast-util-math@3?bundle'
|
||||
</script>
|
||||
```
|
||||
|
||||
## Use
|
||||
|
||||
Say our document `example.md` contains:
|
||||
|
||||
```markdown
|
||||
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` looks as follows:
|
||||
|
||||
```js
|
||||
import fs from 'node:fs/promises'
|
||||
import {math} from 'micromark-extension-math'
|
||||
import {fromMarkdown} from 'mdast-util-from-markdown'
|
||||
import {mathFromMarkdown, mathToMarkdown} from 'mdast-util-math'
|
||||
import {toMarkdown} from 'mdast-util-to-markdown'
|
||||
|
||||
const doc = await fs.readFile('example.md')
|
||||
|
||||
const tree = fromMarkdown(doc, {
|
||||
extensions: [math()],
|
||||
mdastExtensions: [mathFromMarkdown()]
|
||||
})
|
||||
|
||||
console.log(tree)
|
||||
|
||||
const out = toMarkdown(tree, {extensions: [mathToMarkdown()]})
|
||||
|
||||
console.log(out)
|
||||
```
|
||||
|
||||
…now running `node example.js` yields (positional info and data removed for
|
||||
brevity):
|
||||
|
||||
```js
|
||||
{
|
||||
type: 'root',
|
||||
children: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
children: [
|
||||
{type: 'text', value: 'Lift('},
|
||||
{type: 'inlineMath', value: 'L', data: {/* … */}},
|
||||
{type: 'text', value: ') can be determined by Lift Coefficient ('},
|
||||
{type: 'inlineMath', value: 'C_L', data: {/* … */}},
|
||||
{type: 'text', value: ') like the following\nequation.'}
|
||||
]
|
||||
},
|
||||
{type: 'math', meta: null, value: 'L = \\frac{1}{2} \\rho v^2 S C_L', data: {/* … */}}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```markdown
|
||||
Lift($L$) can be determined by Lift Coefficient ($C_L$) like the following
|
||||
equation.
|
||||
|
||||
$$
|
||||
L = \frac{1}{2} \rho v^2 S C_L
|
||||
$$
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
This package exports the identifiers
|
||||
[`mathFromMarkdown`][api-math-from-markdown]
|
||||
and [`mathToMarkdown`][api-math-to-markdown].
|
||||
There is no default export.
|
||||
|
||||
### `mathFromMarkdown()`
|
||||
|
||||
Create an extension for [`mdast-util-from-markdown`][mdast-util-from-markdown].
|
||||
|
||||
###### Returns
|
||||
|
||||
Extension for `mdast-util-from-markdown`
|
||||
([`FromMarkdownExtension`][from-markdown-extension]).
|
||||
|
||||
### `mathToMarkdown(options?)`
|
||||
|
||||
Create an extension for [`mdast-util-to-markdown`][mdast-util-to-markdown].
|
||||
|
||||
###### Parameters
|
||||
|
||||
* `options` ([`ToOptions`][api-to-options], optional)
|
||||
— configuration
|
||||
|
||||
###### Returns
|
||||
|
||||
Extension for `mdast-util-to-markdown`
|
||||
([`ToMarkdownExtension`][to-markdown-extension]).
|
||||
|
||||
### `InlineMath`
|
||||
|
||||
Math (text) (TypeScript type).
|
||||
|
||||
###### Type
|
||||
|
||||
```ts
|
||||
import type {Data, Literal} from 'mdast'
|
||||
|
||||
interface InlineMath extends Literal {
|
||||
type: 'inlineMath'
|
||||
data?: InlineMathData | undefined
|
||||
}
|
||||
|
||||
export interface InlineMathData extends Data {}
|
||||
```
|
||||
|
||||
### `Math`
|
||||
|
||||
Math (flow) (TypeScript type).
|
||||
|
||||
###### Type
|
||||
|
||||
```ts
|
||||
import type {Data, Literal} from 'mdast'
|
||||
|
||||
interface Math extends Literal {
|
||||
type: 'math'
|
||||
meta?: string | null | undefined
|
||||
data?: MathData | undefined
|
||||
}
|
||||
|
||||
export interface MathData extends Data {}
|
||||
```
|
||||
|
||||
### `ToOptions`
|
||||
|
||||
Configuration (TypeScript type).
|
||||
|
||||
###### Fields
|
||||
|
||||
* `singleDollarTextMath` (`boolean`, default: `true`)
|
||||
— whether to support math (text) with a single dollar.
|
||||
Single dollars work in Pandoc and many other places, but often interfere
|
||||
with “normal” dollars in text.
|
||||
If you turn this off, you can still use two or more dollars for text math
|
||||
|
||||
## HTML
|
||||
|
||||
This plugin integrates with [`mdast-util-to-hast`][mdast-util-to-hast].
|
||||
When mdast is turned into hast the math nodes are turned into
|
||||
`<code class="language-math math-inline">…</code>` and
|
||||
`<pre><code class="language-math math-display">…</code></pre>` elements.
|
||||
|
||||
## Syntax
|
||||
|
||||
See [Syntax in `micromark-extension-frontmatter`][syntax].
|
||||
|
||||
## Syntax tree
|
||||
|
||||
The following interfaces are added to **[mdast][]** by this utility.
|
||||
|
||||
### Nodes
|
||||
|
||||
#### `Math`
|
||||
|
||||
```idl
|
||||
interface Math <: Literal {
|
||||
type: 'code'
|
||||
meta: string?
|
||||
}
|
||||
```
|
||||
|
||||
**Math** (**[Literal][dfn-literal]**) represents a block of math,
|
||||
such as LaTeX mathematical expressions.
|
||||
|
||||
**Math** can be used where **[flow][dfn-flow-content]** content is expected.
|
||||
Its content is represented by its `value` field.
|
||||
|
||||
This node relates to the **[phrasing][dfn-phrasing-content]** content concept
|
||||
**[InlineMath][dfn-inline-math]**.
|
||||
|
||||
A `meta` field can be present.
|
||||
It represents custom information relating to the node.
|
||||
|
||||
For example, the following markdown:
|
||||
|
||||
```markdown
|
||||
$$
|
||||
L = \frac{1}{2} \rho v^2 S C_L
|
||||
$$
|
||||
```
|
||||
|
||||
Yields:
|
||||
|
||||
```js
|
||||
{
|
||||
type: 'math',
|
||||
meta: null,
|
||||
value: 'L = \\frac{1}{2} \\rho v^2 S C_L',
|
||||
data: {/* … */}
|
||||
}
|
||||
```
|
||||
|
||||
#### `InlineMath`
|
||||
|
||||
```idl
|
||||
interface InlineMath <: Literal {
|
||||
type: 'inlineMath'
|
||||
}
|
||||
```
|
||||
|
||||
**InlineMath** (**[Literal][dfn-literal]**) represents a fragment of computer
|
||||
code, such as a file name, computer program, or anything a computer could parse.
|
||||
|
||||
**InlineMath** can be used where **[phrasing][dfn-phrasing-content]** content
|
||||
is expected.
|
||||
Its content is represented by its `value` field.
|
||||
|
||||
This node relates to the **[flow][dfn-flow-content]** content concept
|
||||
**[Math][dfn-math]**.
|
||||
|
||||
For example, the following markdown:
|
||||
|
||||
```markdown
|
||||
$L$
|
||||
```
|
||||
|
||||
Yields:
|
||||
|
||||
```js
|
||||
{type: 'inlineMath', value: 'L', data: {/* … */}}
|
||||
```
|
||||
|
||||
### Content model
|
||||
|
||||
#### `FlowContent` (math)
|
||||
|
||||
```idl
|
||||
type FlowContentMath = Math | FlowContent
|
||||
```
|
||||
|
||||
#### `PhrasingContent` (math)
|
||||
|
||||
```idl
|
||||
type PhrasingContentMath = InlineMath | PhrasingContent
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
This package is fully typed with [TypeScript][].
|
||||
It exports the additional types [`InlineMath`][api-inline-math],
|
||||
[`Math`][api-math], and [`ToOptions`][api-to-options].
|
||||
|
||||
It also registers the node types with `@types/mdast`.
|
||||
If you’re working with the syntax tree, make sure to import this utility
|
||||
somewhere in your types, as that registers the new node types in the tree.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @typedef {import('mdast-util-math')}
|
||||
*/
|
||||
|
||||
import {visit} from 'unist-util-visit'
|
||||
|
||||
/** @type {import('mdast').Root} */
|
||||
const tree = getMdastNodeSomeHow()
|
||||
|
||||
visit(tree, function (node) {
|
||||
// `node` can now be one of the nodes for math.
|
||||
})
|
||||
```
|
||||
|
||||
## Compatibility
|
||||
|
||||
Projects maintained by the unified collective are compatible with maintained
|
||||
versions of Node.js.
|
||||
|
||||
When we cut a new major release, we drop support for unmaintained versions of
|
||||
Node.
|
||||
This means we try to keep the current release line, `mdast-util-math@^3`,
|
||||
compatible with Node.js 16.
|
||||
|
||||
This plugin works with `mdast-util-from-markdown` version 2+ and
|
||||
`mdast-util-to-markdown` version 2+.
|
||||
|
||||
## Related
|
||||
|
||||
* [`remark-math`][remark-math]
|
||||
— remark plugin to support math
|
||||
* [`micromark-extension-math`][micromark-extension-math]
|
||||
— micromark extension to parse math
|
||||
|
||||
## Contribute
|
||||
|
||||
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
|
||||
ways to get started.
|
||||
See [`support.md`][support] for ways to get help.
|
||||
|
||||
This project has a [code of conduct][coc].
|
||||
By interacting with this repository, organization, or community you agree to
|
||||
abide by its terms.
|
||||
|
||||
## License
|
||||
|
||||
[MIT][license] © [Titus Wormer][author]
|
||||
|
||||
<!-- Definitions -->
|
||||
|
||||
[build-badge]: https://github.com/syntax-tree/mdast-util-math/workflows/main/badge.svg
|
||||
|
||||
[build]: https://github.com/syntax-tree/mdast-util-math/actions
|
||||
|
||||
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/mdast-util-math.svg
|
||||
|
||||
[coverage]: https://codecov.io/github/syntax-tree/mdast-util-math
|
||||
|
||||
[downloads-badge]: https://img.shields.io/npm/dm/mdast-util-math.svg
|
||||
|
||||
[downloads]: https://www.npmjs.com/package/mdast-util-math
|
||||
|
||||
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=mdast-util-math
|
||||
|
||||
[size]: https://bundlejs.com/?q=mdast-util-math
|
||||
|
||||
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
|
||||
|
||||
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
|
||||
|
||||
[collective]: https://opencollective.com/unified
|
||||
|
||||
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
|
||||
|
||||
[chat]: https://github.com/syntax-tree/unist/discussions
|
||||
|
||||
[npm]: https://docs.npmjs.com/cli/install
|
||||
|
||||
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
|
||||
|
||||
[esmsh]: https://esm.sh
|
||||
|
||||
[typescript]: https://www.typescriptlang.org
|
||||
|
||||
[license]: license
|
||||
|
||||
[author]: https://wooorm.com
|
||||
|
||||
[health]: https://github.com/syntax-tree/.github
|
||||
|
||||
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
|
||||
|
||||
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
|
||||
|
||||
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
|
||||
|
||||
[remark-math]: https://github.com/remarkjs/remark-math
|
||||
|
||||
[mdast]: https://github.com/syntax-tree/mdast
|
||||
|
||||
[mdast-util-from-markdown]: https://github.com/syntax-tree/mdast-util-from-markdown
|
||||
|
||||
[mdast-util-to-markdown]: https://github.com/syntax-tree/mdast-util-to-markdown
|
||||
|
||||
[mdast-util-to-hast]: https://github.com/syntax-tree/mdast-util-to-hast
|
||||
|
||||
[micromark]: https://github.com/micromark/micromark
|
||||
|
||||
[micromark-extension-math]: https://github.com/micromark/micromark-extension-math
|
||||
|
||||
[syntax]: https://github.com/micromark/micromark-extension-math#syntax
|
||||
|
||||
[fields]: https://github.com/syntax-tree/mdast-util-to-hast#fields-on-nodes
|
||||
|
||||
[dfn-literal]: https://github.com/syntax-tree/mdast#literal
|
||||
|
||||
[from-markdown-extension]: https://github.com/syntax-tree/mdast-util-from-markdown#extension
|
||||
|
||||
[to-markdown-extension]: https://github.com/syntax-tree/mdast-util-to-markdown#options
|
||||
|
||||
[api-math-from-markdown]: #mathfrommarkdown
|
||||
|
||||
[api-math-to-markdown]: #mathtomarkdownoptions
|
||||
|
||||
[api-math]: #math
|
||||
|
||||
[api-inline-math]: #inlinemath
|
||||
|
||||
[api-to-options]: #tooptions
|
||||
|
||||
[dfn-flow-content]: #flowcontent-math
|
||||
|
||||
[dfn-phrasing-content]: #phrasingcontent-math
|
||||
|
||||
[dfn-inline-math]: #inlinemath-1
|
||||
|
||||
[dfn-math]: #math-1
|
||||
Reference in New Issue
Block a user