 
 CodeMirror.defineMIME 'text/apl', 'apl'
 CodeMirror.defineMode 'apl', (config) -> # https://codemirror.net/doc/manual.html#modeapi
-  startState: -> isHeader: 1, stack: '', dfnDepth: 0, kwStack: []
+  startState: -> isHeader: 1, stack: '', dfnDepth: 0, kwStack: [], indentStack: []
   token: (stream, state) ->
     if state.isHeader
       delete state.isHeader; stream.match /[^⍝\n\r]*/; s = stream.current()

        else 'apl-glb'
      else 'apl-err'

  electricInput: /:(?:else|end|andif|orif|case)$/

  indent: (state, textAfter) ->
    config.indentUnit *
      if state.dfnDepth
        state.dfnDepth - /^\s*\}/.test textAfter
      else
        state.kwStack.length - /^\s*:(?:end|else|andif|orif|case)/i.test textAfter

      else if c == '⍬' then 'apl-zld'
      else if c == '(' then state.stack += c; 'apl-par'
      else if c == '[' then state.stack += c; 'apl-brkt'
      else if c == '{' then state.stack += c; state.indentStack.push stream.indentation(); "apl-dfn#{++state.dfnDepth} apl-dfn"
      else if c == ')' then (if state.stack[-1..] == '(' then state.stack = state.stack[...-1]; 'apl-par'  else 'apl-err')
      else if c == ']' then (if state.stack[-1..] == '[' then state.stack = state.stack[...-1]; 'apl-brkt' else 'apl-err')
      else if c == '}'
        if state.stack[-1..] == '{'
          state.stack = state.stack[...-1]; state.indentStack.pop(); "apl-dfn apl-dfn#{state.dfnDepth--}"
        else
          'apl-err'
      else if c == ';' then 'apl-semi'
      else if c == '⋄' then 'apl-diam'
      else if /[\/⌿\\⍀¨⌸⍨⌶]/.test c then 'apl-op1'
