marked.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import { marked, type MarkedExtension, type Tokens } from "marked"
  2. import markedShiki from "marked-shiki"
  3. import katex from "katex"
  4. import { bundledLanguages, type BundledLanguage } from "shiki"
  5. import { createSimpleContext } from "./helper"
  6. import { getSharedHighlighter, registerCustomTheme, ThemeRegistrationResolved } from "@pierre/diffs"
  7. export const KirinCodeTheme = {
  8. name: "KirinCode",
  9. bg: "var(--color-background-stronger)",
  10. fg: "var(--text-base)",
  11. colors: {
  12. "editor.background": "var(--color-background-stronger)",
  13. "editor.foreground": "var(--text-base)",
  14. "gitDecoration.addedResourceForeground": "var(--syntax-diff-add)",
  15. "gitDecoration.deletedResourceForeground": "var(--syntax-diff-delete)",
  16. "gitDecoration.modifiedResourceForeground": "var(--syntax-diff-unknown)",
  17. // "gitDecoration.conflictingResourceForeground": "#ffca00",
  18. // "gitDecoration.modifiedResourceForeground": "#1a76d4",
  19. // "gitDecoration.untrackedResourceForeground": "#00cab1",
  20. // "gitDecoration.ignoredResourceForeground": "#84848A",
  21. // "terminal.titleForeground": "#adadb1",
  22. // "terminal.titleInactiveForeground": "#84848A",
  23. // "terminal.background": "#141415",
  24. // "terminal.foreground": "#adadb1",
  25. // "terminal.ansiBlack": "#141415",
  26. // "terminal.ansiRed": "#ff2e3f",
  27. // "terminal.ansiGreen": "#0dbe4e",
  28. // "terminal.ansiYellow": "#ffca00",
  29. // "terminal.ansiBlue": "#008cff",
  30. // "terminal.ansiMagenta": "#c635e4",
  31. // "terminal.ansiCyan": "#08c0ef",
  32. // "terminal.ansiWhite": "#c6c6c8",
  33. // "terminal.ansiBrightBlack": "#141415",
  34. // "terminal.ansiBrightRed": "#ff2e3f",
  35. // "terminal.ansiBrightGreen": "#0dbe4e",
  36. // "terminal.ansiBrightYellow": "#ffca00",
  37. // "terminal.ansiBrightBlue": "#008cff",
  38. // "terminal.ansiBrightMagenta": "#c635e4",
  39. // "terminal.ansiBrightCyan": "#08c0ef",
  40. // "terminal.ansiBrightWhite": "#c6c6c8",
  41. },
  42. tokenColors: [
  43. {
  44. scope: ["comment", "punctuation.definition.comment", "string.comment"],
  45. settings: {
  46. foreground: "var(--syntax-comment)",
  47. },
  48. },
  49. {
  50. scope: ["entity.other.attribute-name"],
  51. settings: {
  52. foreground: "var(--syntax-property)", // maybe attribute
  53. },
  54. },
  55. {
  56. scope: ["constant", "entity.name.constant", "variable.other.constant", "variable.language", "entity"],
  57. settings: {
  58. foreground: "var(--syntax-constant)",
  59. },
  60. },
  61. {
  62. scope: ["entity.name", "meta.export.default", "meta.definition.variable"],
  63. settings: {
  64. foreground: "var(--syntax-type)",
  65. },
  66. },
  67. {
  68. scope: ["meta.object.member"],
  69. settings: {
  70. foreground: "var(--syntax-primitive)",
  71. },
  72. },
  73. {
  74. scope: [
  75. "variable.parameter.function",
  76. "meta.jsx.children",
  77. "meta.block",
  78. "meta.tag.attributes",
  79. "entity.name.constant",
  80. "meta.embedded.expression",
  81. "meta.template.expression",
  82. "string.other.begin.yaml",
  83. "string.other.end.yaml",
  84. ],
  85. settings: {
  86. foreground: "var(--syntax-punctuation)",
  87. },
  88. },
  89. {
  90. scope: ["entity.name.function", "support.type.primitive"],
  91. settings: {
  92. foreground: "var(--syntax-primitive)",
  93. },
  94. },
  95. {
  96. scope: ["support.class.component"],
  97. settings: {
  98. foreground: "var(--syntax-type)",
  99. },
  100. },
  101. {
  102. scope: "keyword",
  103. settings: {
  104. foreground: "var(--syntax-keyword)",
  105. },
  106. },
  107. {
  108. scope: [
  109. "keyword.operator",
  110. "storage.type.function.arrow",
  111. "punctuation.separator.key-value.css",
  112. "entity.name.tag.yaml",
  113. "punctuation.separator.key-value.mapping.yaml",
  114. ],
  115. settings: {
  116. foreground: "var(--syntax-operator)",
  117. },
  118. },
  119. {
  120. scope: ["storage", "storage.type"],
  121. settings: {
  122. foreground: "var(--syntax-keyword)",
  123. },
  124. },
  125. {
  126. scope: ["storage.modifier.package", "storage.modifier.import", "storage.type.java"],
  127. settings: {
  128. foreground: "var(--syntax-primitive)",
  129. },
  130. },
  131. {
  132. scope: [
  133. "string",
  134. "punctuation.definition.string",
  135. "string punctuation.section.embedded source",
  136. "entity.name.tag",
  137. ],
  138. settings: {
  139. foreground: "var(--syntax-string)",
  140. },
  141. },
  142. {
  143. scope: "support",
  144. settings: {
  145. foreground: "var(--syntax-primitive)",
  146. },
  147. },
  148. {
  149. scope: ["support.type.object.module", "variable.other.object", "support.type.property-name.css"],
  150. settings: {
  151. foreground: "var(--syntax-object)",
  152. },
  153. },
  154. {
  155. scope: "meta.property-name",
  156. settings: {
  157. foreground: "var(--syntax-property)",
  158. },
  159. },
  160. {
  161. scope: "variable",
  162. settings: {
  163. foreground: "var(--syntax-variable)",
  164. },
  165. },
  166. {
  167. scope: "variable.other",
  168. settings: {
  169. foreground: "var(--syntax-variable)",
  170. },
  171. },
  172. {
  173. scope: [
  174. "invalid.broken",
  175. "invalid.illegal",
  176. "invalid.unimplemented",
  177. "invalid.deprecated",
  178. "message.error",
  179. "markup.deleted",
  180. "meta.diff.header.from-file",
  181. "punctuation.definition.deleted",
  182. "brackethighlighter.unmatched",
  183. "token.error-token",
  184. ],
  185. settings: {
  186. foreground: "var(--syntax-critical)",
  187. },
  188. },
  189. {
  190. scope: "carriage-return",
  191. settings: {
  192. foreground: "var(--syntax-keyword)",
  193. },
  194. },
  195. {
  196. scope: "string source",
  197. settings: {
  198. foreground: "var(--syntax-variable)",
  199. },
  200. },
  201. {
  202. scope: "string variable",
  203. settings: {
  204. foreground: "var(--syntax-constant)",
  205. },
  206. },
  207. {
  208. scope: [
  209. "source.regexp",
  210. "string.regexp",
  211. "string.regexp.character-class",
  212. "string.regexp constant.character.escape",
  213. "string.regexp source.ruby.embedded",
  214. "string.regexp string.regexp.arbitrary-repitition",
  215. "string.regexp constant.character.escape",
  216. ],
  217. settings: {
  218. foreground: "var(--syntax-regexp)",
  219. },
  220. },
  221. {
  222. scope: "support.constant",
  223. settings: {
  224. foreground: "var(--syntax-primitive)",
  225. },
  226. },
  227. {
  228. scope: "support.variable",
  229. settings: {
  230. foreground: "var(--syntax-variable)",
  231. },
  232. },
  233. {
  234. scope: "meta.module-reference",
  235. settings: {
  236. foreground: "var(--syntax-info)",
  237. },
  238. },
  239. {
  240. scope: "punctuation.definition.list.begin.markdown",
  241. settings: {
  242. foreground: "var(--syntax-punctuation)",
  243. },
  244. },
  245. {
  246. scope: ["markup.heading", "markup.heading entity.name"],
  247. settings: {
  248. fontStyle: "bold",
  249. foreground: "var(--syntax-info)",
  250. },
  251. },
  252. {
  253. scope: "markup.quote",
  254. settings: {
  255. foreground: "var(--syntax-info)",
  256. },
  257. },
  258. {
  259. scope: "markup.italic",
  260. settings: {
  261. fontStyle: "italic",
  262. // foreground: "",
  263. },
  264. },
  265. {
  266. scope: "markup.bold",
  267. settings: {
  268. fontStyle: "bold",
  269. foreground: "var(--text-strong)",
  270. },
  271. },
  272. {
  273. scope: [
  274. "markup.raw",
  275. "markup.inserted",
  276. "meta.diff.header.to-file",
  277. "punctuation.definition.inserted",
  278. "markup.changed",
  279. "punctuation.definition.changed",
  280. "markup.ignored",
  281. "markup.untracked",
  282. ],
  283. settings: {
  284. foreground: "var(--text-base)",
  285. },
  286. },
  287. {
  288. scope: "meta.diff.range",
  289. settings: {
  290. fontStyle: "bold",
  291. foreground: "var(--syntax-unknown)",
  292. },
  293. },
  294. {
  295. scope: "meta.diff.header",
  296. settings: {
  297. foreground: "var(--syntax-unknown)",
  298. },
  299. },
  300. {
  301. scope: "meta.separator",
  302. settings: {
  303. fontStyle: "bold",
  304. foreground: "var(--syntax-unknown)",
  305. },
  306. },
  307. {
  308. scope: "meta.output",
  309. settings: {
  310. foreground: "var(--syntax-unknown)",
  311. },
  312. },
  313. {
  314. scope: "meta.export.default",
  315. settings: {
  316. foreground: "var(--syntax-unknown)",
  317. },
  318. },
  319. {
  320. scope: [
  321. "brackethighlighter.tag",
  322. "brackethighlighter.curly",
  323. "brackethighlighter.round",
  324. "brackethighlighter.square",
  325. "brackethighlighter.angle",
  326. "brackethighlighter.quote",
  327. ],
  328. settings: {
  329. foreground: "var(--syntax-unknown)",
  330. },
  331. },
  332. {
  333. scope: ["constant.other.reference.link", "string.other.link"],
  334. settings: {
  335. fontStyle: "underline",
  336. foreground: "var(--syntax-unknown)",
  337. },
  338. },
  339. {
  340. scope: "token.info-token",
  341. settings: {
  342. foreground: "var(--syntax-info)",
  343. },
  344. },
  345. {
  346. scope: "token.warn-token",
  347. settings: {
  348. foreground: "var(--syntax-warning)",
  349. },
  350. },
  351. {
  352. scope: "token.debug-token",
  353. settings: {
  354. foreground: "var(--syntax-info)",
  355. },
  356. },
  357. ],
  358. semanticTokenColors: {
  359. comment: "var(--syntax-comment)",
  360. string: "var(--syntax-string)",
  361. number: "var(--syntax-constant)",
  362. regexp: "var(--syntax-regexp)",
  363. keyword: "var(--syntax-keyword)",
  364. variable: "var(--syntax-variable)",
  365. parameter: "var(--syntax-variable)",
  366. property: "var(--syntax-property)",
  367. function: "var(--syntax-primitive)",
  368. method: "var(--syntax-primitive)",
  369. type: "var(--syntax-type)",
  370. class: "var(--syntax-type)",
  371. namespace: "var(--syntax-type)",
  372. enumMember: "var(--syntax-primitive)",
  373. "variable.constant": "var(--syntax-constant)",
  374. "variable.defaultLibrary": "var(--syntax-unknown)",
  375. },
  376. } as unknown as ThemeRegistrationResolved
  377. registerCustomTheme("KirinCode", () => Promise.resolve(KirinCodeTheme))
  378. function renderMathInText(text: string): string {
  379. let result = text
  380. // Display math: $$...$$
  381. const displayMathRegex = /\$\$([\s\S]*?)\$\$/g
  382. result = result.replace(displayMathRegex, (_, math) => {
  383. try {
  384. return katex.renderToString(math, {
  385. displayMode: true,
  386. throwOnError: false,
  387. })
  388. } catch {
  389. return `$$${math}$$`
  390. }
  391. })
  392. // Inline math: \(...\)
  393. const inlineMathRegex = /\\\(((?:\\.|[^\\\n])*?)\\\)/g
  394. result = result.replace(inlineMathRegex, (_, math) => {
  395. try {
  396. return katex.renderToString(math, {
  397. displayMode: false,
  398. throwOnError: false,
  399. })
  400. } catch {
  401. return `\\(${math}\\)`
  402. }
  403. })
  404. return result
  405. }
  406. const inlineMathRegex = /^\\\(((?:\\.|[^\\\n])*?)\\\)/
  407. const blockMathRegex = /^\$\$\n([\s\S]+?)\n\$\$(?:\n|$)/
  408. const katexExtension: MarkedExtension = {
  409. extensions: [
  410. {
  411. name: "inlineKatex",
  412. level: "inline",
  413. start(src) {
  414. const index = src.indexOf("\\(")
  415. if (index === -1) return
  416. return index
  417. },
  418. tokenizer(src) {
  419. const match = src.match(inlineMathRegex)
  420. if (!match) return
  421. return {
  422. type: "inlineKatex",
  423. raw: match[0],
  424. text: match[1].trim(),
  425. displayMode: false,
  426. }
  427. },
  428. renderer: renderKatexToken,
  429. },
  430. {
  431. name: "blockKatex",
  432. level: "block",
  433. tokenizer(src) {
  434. const match = src.match(blockMathRegex)
  435. if (!match) return
  436. return {
  437. type: "blockKatex",
  438. raw: match[0],
  439. text: match[1].trim(),
  440. displayMode: true,
  441. }
  442. },
  443. renderer: renderKatexToken,
  444. },
  445. ],
  446. }
  447. function renderKatexToken(token: Tokens.Generic) {
  448. return katex.renderToString(typeof token.text === "string" ? token.text : "", {
  449. displayMode: token.displayMode === true,
  450. throwOnError: false,
  451. })
  452. }
  453. function renderMathExpressions(html: string): string {
  454. // Split on code/pre/kbd tags to avoid processing their contents
  455. const codeBlockPattern = /(<(?:pre|code|kbd)[^>]*>[\s\S]*?<\/(?:pre|code|kbd)>)/gi
  456. const parts = html.split(codeBlockPattern)
  457. return parts
  458. .map((part, i) => {
  459. // Odd indices are the captured code blocks - leave them alone
  460. if (i % 2 === 1) return part
  461. // Process math only in non-code parts
  462. return renderMathInText(part)
  463. })
  464. .join("")
  465. }
  466. async function highlightCodeBlocks(html: string): Promise<string> {
  467. const codeBlockRegex = /<pre><code(?:\s+class="language-([^"]*)")?>([\s\S]*?)<\/code><\/pre>/g
  468. const matches = [...html.matchAll(codeBlockRegex)]
  469. if (matches.length === 0) return html
  470. const highlighter = await getSharedHighlighter({
  471. themes: ["KirinCode"],
  472. langs: [],
  473. preferredHighlighter: "shiki-wasm",
  474. })
  475. let result = html
  476. for (const match of matches) {
  477. const [fullMatch, lang, escapedCode] = match
  478. const code = escapedCode
  479. .replace(/&lt;/g, "<")
  480. .replace(/&gt;/g, ">")
  481. .replace(/&amp;/g, "&")
  482. .replace(/&quot;/g, '"')
  483. .replace(/&#39;/g, "'")
  484. let language = lang || "text"
  485. if (!(language in bundledLanguages)) {
  486. language = "text"
  487. }
  488. if (!highlighter.getLoadedLanguages().includes(language)) {
  489. await highlighter.loadLanguage(language as BundledLanguage)
  490. }
  491. const highlighted = highlighter.codeToHtml(code, {
  492. lang: language,
  493. theme: "KirinCode",
  494. tabindex: false,
  495. })
  496. result = result.replace(fullMatch, () => highlighted)
  497. }
  498. return result
  499. }
  500. export type NativeMarkdownParser = (markdown: string) => Promise<string>
  501. export const { use: useMarked, provider: MarkedProvider } = createSimpleContext({
  502. name: "Marked",
  503. init: (props: { nativeParser?: NativeMarkdownParser }) => {
  504. const jsParser = marked.use(
  505. {
  506. renderer: {
  507. link({ href, title, text }) {
  508. const titleAttr = title ? ` title="${title}"` : ""
  509. return `<a href="${href}"${titleAttr} class="external-link" target="_blank" rel="noopener noreferrer">${text}</a>`
  510. },
  511. },
  512. },
  513. katexExtension,
  514. markedShiki({
  515. async highlight(code, lang) {
  516. const highlighter = await getSharedHighlighter({
  517. themes: ["KirinCode"],
  518. langs: [],
  519. preferredHighlighter: "shiki-wasm",
  520. })
  521. if (!(lang in bundledLanguages)) {
  522. lang = "text"
  523. }
  524. if (!highlighter.getLoadedLanguages().includes(lang)) {
  525. await highlighter.loadLanguage(lang as BundledLanguage)
  526. }
  527. return highlighter.codeToHtml(code, {
  528. lang: lang || "text",
  529. theme: "KirinCode",
  530. tabindex: false,
  531. })
  532. },
  533. }),
  534. )
  535. if (props.nativeParser) {
  536. const nativeParser = props.nativeParser
  537. return {
  538. async parse(markdown: string): Promise<string> {
  539. const html = await nativeParser(markdown)
  540. const withMath = renderMathExpressions(html)
  541. return highlightCodeBlocks(withMath)
  542. },
  543. }
  544. }
  545. return jsParser
  546. },
  547. })