All files / src/render-enhancers code-block-styling.ts

6.74% Statements 6/89
0% Branches 0/49
12.5% Functions 1/8
7.14% Lines 6/84

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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 1771x 1x   1x       1x     1x                 1x                                                                                                                                                                                                                                                                                                                          
import { resolve } from "path";
import { scopeForLanguageName } from "../extension-helper";
import { BlockInfo } from "../lib/block-info";
import { escapeString, extensionDirectoryPath } from "../utility";
 
let Prism;
 
export default async function enhance($: CheerioStatic): Promise<void> {
  // spaced code blocks
  // this is for pandoc parser
  $("pre>code").each((i, codeElement) => {
    const $codeElement = $(codeElement);
    const code = $codeElement.text();
    const $container = $codeElement.parent();
    $codeElement.replaceWith(escapeString(code));
    $container.addClass("language-text");
  });
 
  // fenced code blocks
  $('[data-role="codeBlock"]').each((i, container) => {
    const $container = $(container);
 
    // hide this code block if hide=true in options or if any of previous enhances told so
    const hidden =
      $container.data("hiddenByEnhancer") ||
      ($container.data("normalizedInfo") as BlockInfo).attributes["hide"] ===
        true;
    if (hidden) {
      $container.remove();
      return;
    }
 
    // extract code text
    const code = $container.text();
 
    // determine code language
    const info: BlockInfo = $container.data("normalizedInfo");
    const language = guessPrismLanguage(
      scopeForLanguageName(info.language),
      code,
    );
 
    // try use Prism syntax highlighter
    try {
      if (!Prism) {
        Prism = require(resolve(
          extensionDirectoryPath,
          "./dependencies/prism/prism.js",
        ));
      }
      const html = Prism.highlight(code, Prism.languages[language]);
      $container.html(html);
    } catch (error) {
      // ...or regarded as plain text on failure
      $container.empty().append($(`<code></code>`).text(code));
    }
 
    $container.addClass(`language-${language}`);
    if (info.attributes["class"]) {
      $container.addClass(info.attributes["class"]);
      addLineNumbersIfNecessary($container, code);
    }
    // check highlight
    if (info.attributes["highlight"]) {
      highlightLines($container, code, info.attributes["highlight"]);
    }
 
    // previously used data is no longer needed, so removing it to reduce output size
    $container.removeAttr("data-parsed-info");
    $container.removeAttr("data-normalized-info");
  });
}
 
/**
 * helps color special cases (e.g. vega / vega lite json and yaml)
 * @param language
 * @param code
 */
function guessPrismLanguage(language: string, code: string) {
  if (language === "vega" || language === "vega-lite") {
    const firstChar = code.match(/^\s*(.)/)[1];
    return firstChar === "{" ? "json" : "yaml";
  }
  return language;
}
 
/**
 * Add line numbers to code block <pre> element
 * @param
 * @param code
 */
function addLineNumbersIfNecessary($container, code: string): void {
  if ($container.hasClass("numberLines")) {
    $container.addClass("line-numbers");
    $container.removeClass("numberLines");
  }
 
  if ($container.hasClass("line-numbers")) {
    if (!code.trim().length) {
      return;
    }
    const match = code.match(/\n(?!$)/g);
    const lineCount = match ? match.length + 1 : 1;
    let lines = "";
    for (let i = 0; i < lineCount; i++) {
      lines += "<span></span>";
    }
    $container.append(
      `<span aria-hidden="true" class="line-numbers-rows">${lines}</span>`,
    );
  }
}
 
/**
 * https://github.com/shd101wyy/mume/issues/97
 * @param $container
 * @param code
 * @param highlight
 */
function highlightLines(
  $container: Cheerio,
  code: string,
  highlight: string | string[] | number,
): void {
  if (!code.trim().length) {
    return;
  }
  if (typeof highlight === "number") {
    highlight = [highlight.toString()];
  } else if (typeof highlight === "string") {
    highlight = highlight.split(",");
  }
  const match = code.match(/\n(?!$)/g);
  const lineCount = match ? match.length + 1 : 1;
  const highlightElements = [];
  highlight.forEach((h) => {
    h = h.toString();
    if (h.indexOf("-") > 0) {
      let [start, end] = h.split("-").map((x) => parseInt(x, 10));
      if (isNaN(start) || isNaN(end) || start < 0 || end < 0) {
        return;
      }
      if (start > end) {
        [start, end] = [end, start];
      }
      if (end > lineCount) {
        return;
      }
      let lineBreaks = "";
      for (let i = start; i <= end; i++) {
        lineBreaks += "\n";
      }
      let preLineBreaks = "";
      for (let i = 0; i < start - 1; i++) {
        preLineBreaks += "\n";
      }
      highlightElements.push(
        `<div class="line-highlight-wrapper">${preLineBreaks}<div aria-hidden="true" class="line-highlight" data-range="${start}-${end}" data-start="${start}" data-end="${end}">${lineBreaks}</div></div>`,
      );
    } else {
      let preLineBreaks = "";
      const start = parseInt(h, 10);
      if (isNaN(start) || start < 0 || start > lineCount) {
        return;
      }
      for (let i = 0; i < start - 1; i++) {
        preLineBreaks += "\n";
      }
      highlightElements.push(
        `<div class="line-highlight-wrapper">${preLineBreaks}<div aria-hidden="true" class="line-highlight" data-range="${h}" data-start="${h}">${"\n"}</div></div>`,
      );
    }
  });
  $container.append(highlightElements.join(""));
  $container.attr("data-line", highlight.join(","));
}