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

83.33% Statements 30/36
72.22% Branches 13/18
100% Functions 3/3
83.33% Lines 30/36

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                  1x   1x 8x       7x     1x 1x 1x   1x 1x 24x   24x 1x 1x   23x     1x   1x         1x 1x 1x   1x 1x           1x 1x 1x       1x     1x 1x 1x 1x           1x      
/**
 * inline [[]]
 * [[...]]
 */
 
// tslint:disable-next-line no-implicit-dependencies
import { MarkdownIt } from "markdown-it";
import { MarkdownEngineConfig } from "../markdown-engine-config";
 
export default (md: MarkdownIt, config: MarkdownEngineConfig) => {
  // @ts-ignore
  md.inline.ruler.before("autolink", "wikilink", (state, silent) => {
    if (
      !config.enableWikiLinkSyntax ||
      !state.src.startsWith("[[", state.pos)
    ) {
      return false;
    }
 
    let content = null;
    const tag = "]]";
    let end = -1;
 
    let i = state.pos + tag.length;
    while (i < state.src.length) {
      Iif (state.src[i] === "\\") {
        i += 1;
      } else if (state.src.startsWith(tag, i)) {
        end = i;
        break;
      }
      i += 1;
    }
 
    Eif (end >= 0) {
      // found ]]
      content = state.src.slice(state.pos + tag.length, end);
    } else {
      return false;
    }
 
    Eif (content && !silent) {
      const token = state.push("wikilink");
      token.content = content;
 
      state.pos += content.length + 2 * tag.length;
      return true;
    } else {
      return false;
    }
  });
 
  md.renderer.rules.wikilink = (tokens, idx) => {
    const { content } = tokens[idx];
    Iif (!content) {
      return;
    }
 
    const splits = content.split("|");
    let wikiLink: string;
    let linkText: string;
    Eif (splits.length === 1) {
      linkText = splits[0].trim();
      const filename = linkText.replace(/\s/g, "_");
      wikiLink = `${filename}${config.wikiLinkFileExtension}`;
    } else {
      linkText = splits[0].trim();
      wikiLink = `${splits[1].trim()}${config.wikiLinkFileExtension}`;
    }
 
    return `<a href="${wikiLink}">${linkText}</a>`;
  };
};