 
 katex = require 'katex'
 
-postprocessKatex = (text) ->
-  replaceMathBlocks text, (block) ->
+preprocessKaTeX = (text) ->
+  math = []
+  i = 0
+  text = replaceMathBlocks text, (block) ->
+    i += 1
+    math[i] = block
+    "MATH#{i}ENDMATH"
+  [text, math]
+
+postprocessKaTeX = (text, math) ->
+  #replaceMathBlocks text, (block) ->
+  text.replace /MATH(\d+)ENDMATH/g, (match, p1) ->
+    block = math[p1]
     start$ = /^\$+/.exec block
     end$ = /\$+$/.exec block
     display = start$[0].length >= 2
     block = block[start$[0].length...end$.index]
-    .replace /&lt;/g, '<'
-    .replace /&gt;/g, '>'
-    .replace /’/g, "'"
-    .replace /‘/g, "`"  ## remove bad Marked automatic behavior
+    #.replace /&lt;/g, '<'
+    #.replace /&gt;/g, '>'
+    #.replace /’/g, "'"
+    #.replace /‘/g, "`"  ## remove bad Marked automatic behavior
     try
       katex.renderToString block,
         displayMode: display

  title = title
  .replace /^\s*<P>\s*/i, ''
  .replace /\s*<\/P>\s*$/i, ''
  sanitize postprocess title, leaveTeX

@stripHTMLTags = (html) ->
  html.replace /<[^>]*>/gm, ''

  sanitized

@formatBody = (format, body, leaveTeX = false) ->
  [body, math] = preprocessKaTeX body unless leaveTeX
  if format of formats
    body = formats[format] body, false
  else
    console.warn "Unrecognized format '#{format}'"
  body = postprocessKaTeX body, math unless leaveTeX
  sanitize postprocessCoauthorLinks body

@formatTitle = (format, title, leaveTeX = false) ->
  [title, math] = preprocessKaTeX title unless leaveTeX
  if format of formats
    title = formats[format] title, true
  else
