 latex2html = (tex) ->
   defs = {}
   tex = tex.replace /%.*$\n?/mg, ''
-  tex = tex.replace /\\def\s*\\([a-zA-Z]+)\s*{((?:[^{}]|{[^{}]*})*)}/g, (match, p1, p2) ->
+  tex = tex.replace /\\def\s*\\([a-zA-Z]+)\s*{((?:[^{}]|{(?:[^{}]|{[^{}]*})*})*)}/g, (match, p1, p2) ->
     defs[p1] = p2
     ''
   for def, val of defs
-    console.log def, val
-    tex = tex.replace new RegExp("\\\\#{def}\\s*", 'g'), val
+    #console.log "\\#{def} = #{val}"
+    tex = tex.replace ///\\#{def}\s*///g, val
   tex = '<p>' + tex
   .replace /\\\\/g, '[DOUBLEBACKSLASH]'
   .replace /\\(BY|YEAR)\s*{([^{}]*)}/g, '<span style="border: thin solid; margin-left: 0.5em; padding: 0px 4px; font-variant:small-caps">$2</span>'

  [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

      .replace /</g, '&lt;'
      .replace />/g, '&gt;'
      "<SPAN CLASS='katex-error' TITLE='#{title}'>#{latex}</SPAN>"
  if math?
    text.replace /MATH(\d+)ENDMATH/g, (match, p1) ->
      replacer math[p1]
  else
    replaceMathBlocks text, replacer

jsdiff = require 'diff'

