renderer.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. const katex = require('katex')
  2. const chemParse = require('./mhchem')
  3. // ------------------------------------
  4. // Markdown - KaTeX Renderer
  5. // ------------------------------------
  6. //
  7. // Includes code from https://github.com/liradb2000/markdown-it-katex
  8. // Add \ce, \pu, and \tripledash to the KaTeX macros.
  9. katex.__defineMacro('\\ce', function(context) {
  10. return chemParse(context.consumeArgs(1)[0], 'ce')
  11. })
  12. katex.__defineMacro('\\pu', function(context) {
  13. return chemParse(context.consumeArgs(1)[0], 'pu')
  14. })
  15. // Needed for \bond for the ~ forms
  16. // Raise by 2.56mu, not 2mu. We're raising a hyphen-minus, U+002D, not
  17. // a mathematical minus, U+2212. So we need that extra 0.56.
  18. katex.__defineMacro('\\tripledash', '{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu' + '\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}')
  19. module.exports = {
  20. init (mdinst, conf) {
  21. if (conf.useInline) {
  22. mdinst.inline.ruler.after('escape', 'katex_inline', katexInline)
  23. mdinst.renderer.rules.katex_inline = (tokens, idx) => {
  24. try {
  25. return katex.renderToString(tokens[idx].content, {
  26. displayMode: false
  27. })
  28. } catch (err) {
  29. WIKI.logger.warn(err)
  30. return tokens[idx].content
  31. }
  32. }
  33. }
  34. if (conf.useBlocks) {
  35. mdinst.block.ruler.after('blockquote', 'katex_block', katexBlock, {
  36. alt: [ 'paragraph', 'reference', 'blockquote', 'list' ]
  37. })
  38. mdinst.renderer.rules.katex_block = (tokens, idx) => {
  39. try {
  40. return `<p>` + katex.renderToString(tokens[idx].content, {
  41. displayMode: true
  42. }) + `</p>`
  43. } catch (err) {
  44. WIKI.logger.warn(err)
  45. return tokens[idx].content
  46. }
  47. }
  48. }
  49. }
  50. }
  51. // Test if potential opening or closing delimieter
  52. // Assumes that there is a "$" at state.src[pos]
  53. function isValidDelim (state, pos) {
  54. let prevChar
  55. let nextChar
  56. let max = state.posMax
  57. let canOpen = true
  58. let canClose = true
  59. prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1
  60. nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1
  61. // Check non-whitespace conditions for opening and closing, and
  62. // check that closing delimeter isn't followed by a number
  63. if (prevChar === 0x20/* " " */ || prevChar === 0x09/* \t */ ||
  64. (nextChar >= 0x30/* "0" */ && nextChar <= 0x39/* "9" */)) {
  65. canClose = false
  66. }
  67. if (nextChar === 0x20/* " " */ || nextChar === 0x09/* \t */) {
  68. canOpen = false
  69. }
  70. return {
  71. canOpen: canOpen,
  72. canClose: canClose
  73. }
  74. }
  75. function katexInline (state, silent) {
  76. let start, match, token, res, pos
  77. if (state.src[state.pos] !== '$') { return false }
  78. res = isValidDelim(state, state.pos)
  79. if (!res.canOpen) {
  80. if (!silent) { state.pending += '$' }
  81. state.pos += 1
  82. return true
  83. }
  84. // First check for and bypass all properly escaped delimieters
  85. // This loop will assume that the first leading backtick can not
  86. // be the first character in state.src, which is known since
  87. // we have found an opening delimieter already.
  88. start = state.pos + 1
  89. match = start
  90. while ((match = state.src.indexOf('$', match)) !== -1) {
  91. // Found potential $, look for escapes, pos will point to
  92. // first non escape when complete
  93. pos = match - 1
  94. while (state.src[pos] === '\\') { pos -= 1 }
  95. // Even number of escapes, potential closing delimiter found
  96. if (((match - pos) % 2) === 1) { break }
  97. match += 1
  98. }
  99. // No closing delimter found. Consume $ and continue.
  100. if (match === -1) {
  101. if (!silent) { state.pending += '$' }
  102. state.pos = start
  103. return true
  104. }
  105. // Check if we have empty content, ie: $$. Do not parse.
  106. if (match - start === 0) {
  107. if (!silent) { state.pending += '$$' }
  108. state.pos = start + 1
  109. return true
  110. }
  111. // Check for valid closing delimiter
  112. res = isValidDelim(state, match)
  113. if (!res.canClose) {
  114. if (!silent) { state.pending += '$' }
  115. state.pos = start
  116. return true
  117. }
  118. if (!silent) {
  119. token = state.push('katex_inline', 'math', 0)
  120. token.markup = '$'
  121. token.content = state.src.slice(start, match)
  122. }
  123. state.pos = match + 1
  124. return true
  125. }
  126. function katexBlock (state, start, end, silent) {
  127. let firstLine; let lastLine; let next; let lastPos; let found = false; let token
  128. let pos = state.bMarks[start] + state.tShift[start]
  129. let max = state.eMarks[start]
  130. if (pos + 2 > max) { return false }
  131. if (state.src.slice(pos, pos + 2) !== '$$') { return false }
  132. pos += 2
  133. firstLine = state.src.slice(pos, max)
  134. if (silent) { return true }
  135. if (firstLine.trim().slice(-2) === '$$') {
  136. // Single line expression
  137. firstLine = firstLine.trim().slice(0, -2)
  138. found = true
  139. }
  140. for (next = start; !found;) {
  141. next++
  142. if (next >= end) { break }
  143. pos = state.bMarks[next] + state.tShift[next]
  144. max = state.eMarks[next]
  145. if (pos < max && state.tShift[next] < state.blkIndent) {
  146. // non-empty line with negative indent should stop the list:
  147. break
  148. }
  149. if (state.src.slice(pos, max).trim().slice(-2) === '$$') {
  150. lastPos = state.src.slice(0, max).lastIndexOf('$$')
  151. lastLine = state.src.slice(pos, lastPos)
  152. found = true
  153. }
  154. }
  155. state.line = next + 1
  156. token = state.push('katex_block', 'math', 0)
  157. token.block = true
  158. token.content = (firstLine && firstLine.trim() ? firstLine + '\n' : '') +
  159. state.getLines(start + 1, next, state.tShift[start], true) +
  160. (lastLine && lastLine.trim() ? lastLine : '')
  161. token.map = [ start, state.line ]
  162. token.markup = '$$'
  163. return true
  164. }