| 1 | // Ported from https://github.com/waylonflinn/markdown-it-katex |
| 2 | |
| 3 | /* Process inline math */ |
| 4 | /* |
| 5 | Like markdown-it-simplemath, this is a stripped down, simplified version of: |
| 6 | https://github.com/runarberg/markdown-it-math |
| 7 | |
| 8 | It differs in that it takes (a subset of) LaTeX as input and relies on KaTeX |
| 9 | for rendering output. |
| 10 | */ |
| 11 | |
| 12 | import type { KatexOptions } from 'katex' |
| 13 | import type { MarkdownExit, RuleBlock, Token } from 'markdown-exit' |
| 14 | import katex from 'katex' |
| 15 | import { escapeVueInCode, normalizeRangeStr } from './utils' |
| 16 | |
| 17 | const RE_KATEX_BLOCK_INFO = /^\{([\w*,|-]+)\}\s*(\{[^}]*\})?/ |
| 18 | |
| 19 | // Test if potential opening or closing delimiter |
| 20 | // Assumes that there is a "$" at state.src[pos] |
| 21 | function isValidDelim(state: any, pos: number) { |
| 22 | const max = state.posMax |
| 23 | let can_open = true |
| 24 | let can_close = true |
| 25 | |
| 26 | const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1 |
| 27 | const nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1 |
| 28 | |
| 29 | // Check non-whitespace conditions for opening and closing, and |
| 30 | // check that closing delimeter isn't followed by a number |
| 31 | if (prevChar === 0x20/* " " */ || prevChar === 0x09 ||/* \t */ (nextChar >= 0x30/* "0" */ && nextChar <= 0x39/* "9" */)) |
| 32 | can_close = false |
| 33 | |
| 34 | if (nextChar === 0x20/* " " */ || nextChar === 0x09/* \t */) |
| 35 | can_open = false |
| 36 | |
| 37 | return { |
| 38 | can_open, |
| 39 | can_close, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function math_inline(state: any, silent: boolean) { |
| 44 | let match, token, res, pos |
| 45 | |
| 46 | if (state.src[state.pos] !== '$') |
| 47 | return false |
| 48 | |
| 49 | res = isValidDelim(state, state.pos) |
| 50 | if (!res.can_open) { |
| 51 | if (!silent) |
| 52 | state.pending += '$' |
| 53 | state.pos += 1 |
| 54 | return true |
| 55 | } |
| 56 | |
| 57 | // First check for and bypass all properly escaped delimiters |
| 58 | // This loop will assume that the first leading backtick can not |
| 59 | // be the first character in state.src, which is known since |
| 60 | // we have found an opening delimiter already. |
| 61 | const start = state.pos + 1 |
| 62 | match = start |
| 63 | // eslint-disable-next-line no-cond-assign |
| 64 | while ((match = state.src.indexOf('$', match)) !== -1) { |
| 65 | // Found potential $, look for escapes, pos will point to |
| 66 | // first non escape when complete |
| 67 | pos = match - 1 |
| 68 | while (state.src[pos] === '\\') pos -= 1 |
| 69 | |
| 70 | // Even number of escapes, potential closing delimiter found |
| 71 | if (((match - pos) % 2) === 1) |
| 72 | break |
| 73 | match += 1 |
| 74 | } |
| 75 | |
| 76 | // No closing delimter found. Consume $ and continue. |
| 77 | if (match === -1) { |
| 78 | if (!silent) |
| 79 | state.pending += '$' |
| 80 | state.pos = start |
| 81 | return true |
| 82 | } |
| 83 | |
| 84 | // Check if we have empty content, ie: $$. Do not parse. |
| 85 | if (match - start === 0) { |
| 86 | if (!silent) |
| 87 | state.pending += '$$' |
| 88 | state.pos = start + 1 |
| 89 | return true |
| 90 | } |
| 91 | |
| 92 | // Check for valid closing delimiter |
| 93 | res = isValidDelim(state, match) |
| 94 | if (!res.can_close) { |
| 95 | if (!silent) |
| 96 | state.pending += '$' |
| 97 | state.pos = start |
| 98 | return true |
| 99 | } |
| 100 | |
| 101 | if (!silent) { |
| 102 | token = state.push('math_inline', 'math', 0) |
| 103 | token.markup = '$' |
| 104 | token.content = state.src.slice(start, match) |
| 105 | } |
| 106 | |
| 107 | state.pos = match + 1 |
| 108 | return true |
| 109 | } |
| 110 | |
| 111 | const math_block: RuleBlock = function (state, start, end, silent) { |
| 112 | let firstLine |
| 113 | let lastLine |
| 114 | let next |
| 115 | let lastPos |
| 116 | let found = false |
| 117 | let pos = state.bMarks[start] + state.tShift[start] |
| 118 | let max = state.eMarks[start] |
| 119 | |
| 120 | if (pos + 2 > max) |
| 121 | return false |
| 122 | if (state.src.slice(pos, pos + 2) !== '$$') |
| 123 | return false |
| 124 | |
| 125 | pos += 2 |
| 126 | firstLine = state.src.slice(pos, max).trim() |
| 127 | |
| 128 | if (silent) |
| 129 | return true |
| 130 | |
| 131 | let singleLine = false |
| 132 | if (firstLine.slice(-2) === '$$') { |
| 133 | // Single line expression |
| 134 | firstLine = firstLine.slice(0, -2).trim() |
| 135 | found = true |
| 136 | singleLine = true |
| 137 | } |
| 138 | |
| 139 | for (next = start; !found;) { |
| 140 | next++ |
| 141 | |
| 142 | if (next >= end) |
| 143 | break |
| 144 | |
| 145 | pos = state.bMarks[next] + state.tShift[next] |
| 146 | max = state.eMarks[next] |
| 147 | |
| 148 | if (pos < max && state.tShift[next] < state.blkIndent) { |
| 149 | // non-empty line with negative indent should stop the list: |
| 150 | break |
| 151 | } |
| 152 | |
| 153 | if (state.src.slice(pos, max).trim().slice(-2) === '$$') { |
| 154 | lastPos = state.src.slice(0, max).lastIndexOf('$$') |
| 155 | lastLine = state.src.slice(pos, lastPos) |
| 156 | found = true |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | state.line = next + 1 |
| 161 | |
| 162 | const token = state.push('math_block', 'math', 0) |
| 163 | token.block = true |
| 164 | |
| 165 | if (singleLine) { |
| 166 | token.content = firstLine |
| 167 | } |
| 168 | else { |
| 169 | token.info = firstLine |
| 170 | token.content = state.getLines(start + 1, next, state.tShift[start], true) |
| 171 | + (lastLine && lastLine.trim() ? lastLine : '') |
| 172 | } |
| 173 | |
| 174 | token.map = [start, state.line] |
| 175 | token.markup = '$$' |
| 176 | return true |
| 177 | } |
| 178 | |
| 179 | export default function MarkdownItKatex(md: MarkdownExit, options: KatexOptions) { |
| 180 | // set KaTeX as the renderer for markdown-it-simplemath |
| 181 | const katexInline = function (latex: string) { |
| 182 | options.displayMode = false |
| 183 | try { |
| 184 | return escapeVueInCode(katex.renderToString(latex, options)) |
| 185 | } |
| 186 | catch (error) { |
| 187 | if (options.throwOnError) |
| 188 | |
| 189 | console.warn(error) |
| 190 | return latex |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | const inlineRenderer = function (tokens: any, idx: number) { |
| 195 | return katexInline(tokens[idx].content) |
| 196 | } |
| 197 | |
| 198 | const katexBlock = function (latex: string) { |
| 199 | options.displayMode = true |
| 200 | try { |
| 201 | return `<p>${escapeVueInCode(katex.renderToString(latex, options))}</p>` |
| 202 | } |
| 203 | catch (error) { |
| 204 | if (options.throwOnError) |
| 205 | |
| 206 | console.warn(error) |
| 207 | return latex |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | const blockRenderer = function (tokens: Token[], idx: number) { |
| 212 | const token = tokens[idx] |
| 213 | const [, rangeStr, options] = RE_KATEX_BLOCK_INFO.exec(token.info) || [] |
| 214 | const ranges = normalizeRangeStr(rangeStr) |
| 215 | const optionsProp = options ? `v-bind="${options}"` : '' |
| 216 | return `<KaTexBlockWrapper ${optionsProp} :ranges='${JSON.stringify(ranges)}'>${katexBlock(tokens[idx].content)}</KaTexBlockWrapper>\n` |
| 217 | } |
| 218 | |
| 219 | md.inline.ruler.after('escape', 'math_inline', math_inline) |
| 220 | md.block.ruler.after('blockquote', 'math_block', math_block, { |
| 221 | alt: ['paragraph', 'reference', 'blockquote', 'list'], |
| 222 | }) |
| 223 | md.renderer.rules.math_inline = inlineRenderer |
| 224 | md.renderer.rules.math_block = blockRenderer |
| 225 | } |
| 226 |