highlightLines.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.highlightLinePlugin = void 0;
  4. const RE = /{([\d,-]+)}/;
  5. const wrapperRE = /^<pre .*?><code>/;
  6. exports.highlightLinePlugin = (md) => {
  7. const fence = md.renderer.rules.fence;
  8. md.renderer.rules.fence = (...args) => {
  9. const [tokens, idx, options] = args;
  10. const token = tokens[idx];
  11. const rawInfo = token.info;
  12. if (!rawInfo || !RE.test(rawInfo)) {
  13. return fence(...args);
  14. }
  15. const langName = rawInfo.replace(RE, '').trim();
  16. // ensure the next plugin get the correct lang.
  17. token.info = langName;
  18. const lineNumbers = RE.exec(rawInfo)[1]
  19. .split(',')
  20. .map((v) => v.split('-').map((v) => parseInt(v, 10)));
  21. const code = options.highlight
  22. ? options.highlight(token.content, langName)
  23. : token.content;
  24. const rawCode = code.replace(wrapperRE, '');
  25. const highlightLinesCode = rawCode
  26. .split('\n')
  27. .map((split, index) => {
  28. const lineNumber = index + 1;
  29. const inRange = lineNumbers.some(([start, end]) => {
  30. if (start && end) {
  31. return lineNumber >= start && lineNumber <= end;
  32. }
  33. return lineNumber === start;
  34. });
  35. if (inRange) {
  36. return `<div class="highlighted">&nbsp;</div>`;
  37. }
  38. return '<br>';
  39. })
  40. .join('');
  41. const highlightLinesWrapperCode = `<div class="highlight-lines">${highlightLinesCode}</div>`;
  42. return highlightLinesWrapperCode + code;
  43. };
  44. };
  45. //# sourceMappingURL=highlightLines.js.map