syntax-highlight.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import hljs from "highlight.js/lib/index.js";
  2. import { decodeHtmlEntityAt } from "./html.ts";
  3. export type HighlightFormatter = (text: string) => string;
  4. export type HighlightTheme = Partial<Record<string, HighlightFormatter>>;
  5. export interface HighlightOptions {
  6. language?: string;
  7. ignoreIllegals?: boolean;
  8. languageSubset?: string[];
  9. theme?: HighlightTheme;
  10. }
  11. const SPAN_CLOSE = "</span>";
  12. const HIGHLIGHT_CLASS_PREFIX = "hljs-";
  13. function getScopeFromSpanTag(tag: string): string | undefined {
  14. const match = /\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag);
  15. const classValue = match?.[1] ?? match?.[2];
  16. if (!classValue) {
  17. return undefined;
  18. }
  19. for (const className of classValue.split(/\s+/)) {
  20. if (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {
  21. return className.slice(HIGHLIGHT_CLASS_PREFIX.length);
  22. }
  23. }
  24. return undefined;
  25. }
  26. function getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {
  27. const exact = theme[scope];
  28. if (exact) {
  29. return exact;
  30. }
  31. const dotIndex = scope.indexOf(".");
  32. if (dotIndex !== -1) {
  33. const prefixFormatter = theme[scope.slice(0, dotIndex)];
  34. if (prefixFormatter) {
  35. return prefixFormatter;
  36. }
  37. }
  38. const dashIndex = scope.indexOf("-");
  39. if (dashIndex !== -1) {
  40. const prefixFormatter = theme[scope.slice(0, dashIndex)];
  41. if (prefixFormatter) {
  42. return prefixFormatter;
  43. }
  44. }
  45. return undefined;
  46. }
  47. function getActiveFormatter(scopes: Array<string | undefined>, theme: HighlightTheme): HighlightFormatter | undefined {
  48. for (let i = scopes.length - 1; i >= 0; i--) {
  49. const scope = scopes[i];
  50. if (!scope) {
  51. continue;
  52. }
  53. const formatter = getScopeFormatter(scope, theme);
  54. if (formatter) {
  55. return formatter;
  56. }
  57. }
  58. return theme.default;
  59. }
  60. function isSpanOpenTagStart(html: string, index: number): boolean {
  61. if (!html.startsWith("<span", index)) {
  62. return false;
  63. }
  64. const nextChar = html[index + "<span".length];
  65. return nextChar === ">" || nextChar === " " || nextChar === "\t" || nextChar === "\n" || nextChar === "\r";
  66. }
  67. export function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {
  68. let output = "";
  69. let textBuffer = "";
  70. const scopes: Array<string | undefined> = [];
  71. const flushText = () => {
  72. if (!textBuffer) {
  73. return;
  74. }
  75. const formatter = getActiveFormatter(scopes, theme);
  76. output += formatter ? formatter(textBuffer) : textBuffer;
  77. textBuffer = "";
  78. };
  79. let index = 0;
  80. while (index < html.length) {
  81. if (isSpanOpenTagStart(html, index)) {
  82. const tagEndIndex = html.indexOf(">", index + 5);
  83. if (tagEndIndex !== -1) {
  84. flushText();
  85. const tag = html.slice(index, tagEndIndex + 1);
  86. const scope = getScopeFromSpanTag(tag);
  87. scopes.push(scope);
  88. index = tagEndIndex + 1;
  89. continue;
  90. }
  91. }
  92. if (html.startsWith(SPAN_CLOSE, index)) {
  93. flushText();
  94. if (scopes.length > 0) {
  95. scopes.pop();
  96. }
  97. index += SPAN_CLOSE.length;
  98. continue;
  99. }
  100. if (html[index] === "&") {
  101. const decoded = decodeHtmlEntityAt(html, index);
  102. if (decoded) {
  103. textBuffer += decoded.text;
  104. index += decoded.length;
  105. continue;
  106. }
  107. }
  108. textBuffer += html[index];
  109. index++;
  110. }
  111. flushText();
  112. return output;
  113. }
  114. export function highlight(code: string, options: HighlightOptions = {}): string {
  115. const html = options.language
  116. ? hljs.highlight(code, {
  117. language: options.language,
  118. ignoreIllegals: options.ignoreIllegals,
  119. }).value
  120. : hljs.highlightAuto(code, options.languageSubset).value;
  121. return renderHighlightedHtml(html, options.theme);
  122. }
  123. export function supportsLanguage(name: string): boolean {
  124. return hljs.getLanguage(name) !== undefined;
  125. }