All files / src/custom-markdown-it-features math.ts

34.78% Statements 16/46
22.73% Branches 5/22
66.67% Functions 2/3
34.78% Lines 16/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87      1x   1x   1x 8x       8x 8x 8x       8x   8x 16x           8x 8x 16x               8x 8x                                                                         1x                      
// tslint:disable-next-line no-implicit-dependencies
import { MarkdownIt } from "markdown-it";
import { MarkdownEngineConfig } from "../markdown-engine-config";
import parseMath from "../parse-math";
 
export default (md: MarkdownIt, config: MarkdownEngineConfig) => {
  // @ts-ignore
  md.inline.ruler.before("escape", "math", (state, silent) => {
    Iif (config.mathRenderingOption === "None") {
      return false;
    }
 
    let openTag = null;
    let closeTag = null;
    let displayMode = true;
    const {
      mathBlockDelimiters: blockDelimiters,
      mathInlineDelimiters: inlineDelimiters,
    } = config;
 
    for (const tagPair of blockDelimiters) {
      Iif (state.src.startsWith(tagPair[0], state.pos)) {
        [openTag, closeTag] = tagPair;
        break;
      }
    }
 
    Eif (!openTag) {
      for (const tagPair of inlineDelimiters) {
        Iif (state.src.startsWith(tagPair[0], state.pos)) {
          [openTag, closeTag] = tagPair;
          displayMode = false;
          break;
        }
      }
    }
 
    Eif (!openTag) {
      return false; // not math
    }
 
    let content = null;
    let end = -1;
 
    let i = state.pos + openTag.length;
    while (i < state.src.length) {
      if (state.src.startsWith(closeTag, i)) {
        end = i;
        break;
      } else if (state.src[i] === "\\") {
        i += 1;
      }
      i += 1;
    }
 
    if (end >= 0) {
      content = state.src.slice(state.pos + openTag.length, end);
    } else {
      return false;
    }
 
    if (content && !silent) {
      const token = state.push("math");
      token.content = content.trim();
      token.openTag = openTag;
      token.closeTag = closeTag;
      token.displayMode = displayMode;
 
      state.pos += content.length + openTag.length + closeTag.length;
      return true;
    } else {
      return false;
    }
  });
 
  md.renderer.rules.math = (tokens, idx) => {
    const content: string = tokens[idx] ? tokens[idx].content : null;
    return parseMath({
      content,
      openTag: (tokens[idx] as any).openTag,
      closeTag: (tokens[idx] as any).closeTag,
      renderingOption: config.mathRenderingOption,
      displayMode: (tokens[idx] as any).displayMode,
    });
  };
};