marked.tsx 14 KB

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