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