renderer.js 5.5 KB

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