markdown.mjs 4.9 KB

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