markdown.mjs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import MarkdownIt from 'markdown-it'
  2. import mdAttrs from 'markdown-it-attrs'
  3. import mdDecorate from 'markdown-it-decorate'
  4. import { full as mdEmoji } from 'markdown-it-emoji'
  5. import mdTaskLists from 'markdown-it-task-lists'
  6. import mdExpandTabs from 'markdown-it-expand-tabs'
  7. import mdAbbr from 'markdown-it-abbr'
  8. import mdSup from 'markdown-it-sup'
  9. import mdSub from 'markdown-it-sub'
  10. import mdMark from 'markdown-it-mark'
  11. import mdMultiTable from 'markdown-it-multimd-table'
  12. import mdFootnote from 'markdown-it-footnote'
  13. import mdMdc from 'markdown-it-mdc'
  14. import katex from 'katex'
  15. import mdImsize from './modules/markdown-it-imsize.mjs'
  16. import mdUnderline from './modules/markdown-it-underline.mjs'
  17. // import 'katex/dist/contrib/mhchem'
  18. import twemoji from 'twemoji'
  19. import plantuml from './modules/plantuml.mjs'
  20. import kroki from './modules/kroki.mjs'
  21. import katexHelper from './modules/katex.mjs'
  22. import hljs from 'highlight.js'
  23. import { escape, times } from 'lodash-es'
  24. const quoteStyles = {
  25. chinese: '””‘’',
  26. english: '“”‘’',
  27. french: ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'],
  28. german: '„“‚‘',
  29. greek: '«»‘’',
  30. japanese: '「」「」',
  31. hungarian: '„”’’',
  32. polish: '„”‚‘',
  33. portuguese: '«»‘’',
  34. russian: '«»„“',
  35. spanish: '«»‘’',
  36. swedish: '””’’'
  37. }
  38. export async function render (input, config) {
  39. const md = new MarkdownIt({
  40. html: config.allowHTML,
  41. breaks: config.lineBreaks,
  42. linkify: config.linkify,
  43. typography: config.typographer,
  44. quotes: quoteStyles[config.quotes] ?? quoteStyles.english,
  45. highlight (str, lang) {
  46. if (lang === 'diagram') {
  47. return `<pre class="diagram">${Buffer.from(str, 'base64').toString()}</pre>`
  48. } else if (['mermaid', 'plantuml'].includes(lang)) {
  49. return `<pre class="codeblock-${lang}"><code>${escape(str)}</code></pre>`
  50. } else {
  51. const highlighted = lang ? hljs.highlight(str, { language: lang, ignoreIllegals: true }) : { value: str }
  52. const lineCount = highlighted.value.match(/\n/g).length
  53. const lineNums = lineCount > 1 ? `<span aria-hidden="true" class="line-numbers-rows">${times(lineCount, n => '<span></span>').join('')}</span>` : ''
  54. return `<pre class="codeblock hljs ${lineCount > 1 && 'line-numbers'}"><code class="language-${lang}">${highlighted.value}${lineNums}</code></pre>`
  55. }
  56. }
  57. })
  58. .use(mdAttrs, {
  59. allowedAttributes: ['id', 'class', 'target']
  60. })
  61. .use(mdDecorate)
  62. .use(mdEmoji)
  63. .use(mdTaskLists, { label: false, labelAfter: false })
  64. .use(mdExpandTabs, { tabWidth: config.tabWidth })
  65. .use(mdAbbr)
  66. .use(mdSup)
  67. .use(mdSub)
  68. .use(mdMark)
  69. .use(mdFootnote)
  70. .use(mdImsize)
  71. .use(mdMdc)
  72. if (config.underline) {
  73. md.use(mdUnderline)
  74. }
  75. if (config.mdmultiTable) {
  76. md.use(mdMultiTable, { multiline: true, rowspan: true, headerless: true })
  77. }
  78. // --------------------------------
  79. // PLANTUML
  80. // --------------------------------
  81. if (config.plantuml) {
  82. plantuml.init(md, { server: config.plantumlServerUrl })
  83. }
  84. // --------------------------------
  85. // KROKI
  86. // --------------------------------
  87. if (config.kroki) {
  88. kroki.init(md, { server: config.krokiServerUrl })
  89. }
  90. // --------------------------------
  91. // KATEX
  92. // --------------------------------
  93. const macros = {}
  94. // TODO: Add mhchem (needs esm conversion)
  95. // Add \ce, \pu, and \tripledash to the KaTeX macros.
  96. // katex.__defineMacro('\\ce', function (context) {
  97. // return chemParse(context.consumeArgs(1)[0], 'ce')
  98. // })
  99. // katex.__defineMacro('\\pu', function (context) {
  100. // return chemParse(context.consumeArgs(1)[0], 'pu')
  101. // })
  102. // Needed for \bond for the ~ forms
  103. // Raise by 2.56mu, not 2mu. We're raising a hyphen-minus, U+002D, not
  104. // a mathematical minus, U+2212. So we need that extra 0.56.
  105. katex.__defineMacro('\\tripledash', '{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu' + '\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}')
  106. md.inline.ruler.after('escape', 'katex_inline', katexHelper.katexInline)
  107. md.renderer.rules.katex_inline = (tokens, idx) => {
  108. try {
  109. return katex.renderToString(tokens[idx].content, {
  110. displayMode: false, macros
  111. })
  112. } catch (err) {
  113. console.warn(err)
  114. return tokens[idx].content
  115. }
  116. }
  117. md.block.ruler.after('blockquote', 'katex_block', katexHelper.katexBlock, {
  118. alt: ['paragraph', 'reference', 'blockquote', 'list']
  119. })
  120. md.renderer.rules.katex_block = (tokens, idx) => {
  121. try {
  122. return '<p>' + katex.renderToString(tokens[idx].content, {
  123. displayMode: true, macros
  124. }) + '</p>'
  125. } catch (err) {
  126. console.warn(err)
  127. return tokens[idx].content
  128. }
  129. }
  130. // --------------------------------
  131. // TWEMOJI
  132. // --------------------------------
  133. md.renderer.rules.emoji = (token, idx) => {
  134. return twemoji.parse(token[idx].content, {
  135. callback (icon, opts) {
  136. return `/_assets/svg/twemoji/${icon}.svg`
  137. }
  138. })
  139. }
  140. return md.render(input)
  141. }