     math[i] = block
     "MATH#{i}ENDMATH"
   [text, math]
+
+putMathBack = (tex, math) ->
+  ## Restore math
+  tex.replace /MATH(\d+)ENDMATH/g, (match, p1) -> math[p1]
 
 postprocessKaTeX = (text, math) ->
   replacer = (block) ->

    #  after: sanitized
  sanitized

@formatBody = (format, body, leaveTeX = false) ->
  [body, math] = preprocessKaTeX body unless leaveTeX or format == 'latex'
  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 or format == 'latex'
  if format of formats
    title = formats[format] title, true
  else
    console.warn "Unrecognized format '#{format}'"
  ## Remove surrounding <P> block caused by Markdown and LaTeX formatters.
  title = title
  .replace /^\s*<P>\s*/i, ''
  .replace /\s*<\/P>\s*$/i, ''
  title = postprocessKaTeX title, math unless leaveTeX
  sanitize postprocessCoauthorLinks title

@formatBadFile = (fileId) ->
  """<i class="bad-file">&lt;unknown file with ID #{fileId}&gt;</i>"""

  .replace /\\subsubsection\s*\*?\s*{((?:[^{}]|{[^{}]*})*)}/g, '<h4>$1</h4>'
  .replace /\\paragraph\s*\*?\s*{((?:[^{}]|{[^{}]*})*)}\s*/g, '<p><b>$1</b> '
  .replace /\\footnote\s*{((?:[^{}]|{[^{}]*})*)}/g, '[$1]'
  .replace /\\includegraphics\s*(\[[^\[\]]*\]\s*)?{((?:[^{}]|{[^{}]*})*)}/g,
    (match, optional, graphic) ->
      style = ''
      optional.replace /width\s*=\s*([0-9.]+)\s*([a-zA-Z]*)/g,
        (match2, value, unit) ->
          style += "width: #{value}#{unit};"
          ''
      .replace /height\s*=\s*([0-9.]+)\s*([a-zA-Z]*)/g,
        (match2, value, unit) ->
          style += "height: #{value}#{unit};"
          ''
      style = ' style="' + style + '"' if style
      """<img src="#{graphic}"#{style}>"""
  .replace /\\begin\s*{(problem|theorem|conjecture|lemma|corollary)}/g, (m, p1) -> "<blockquote><b>#{s.capitalize p1}:</b> "
  .replace /\\end\s*{(problem|theorem|conjecture|lemma|corollary)}/g, '</blockquote>'
  .replace /\\begin\s*{(proof|pf)}/g, '<b>Proof:</b> '
