     throw new Error 'Only text documents can be attached to CodeMirror2'
 
   sharedoc = @
+  editorDoc = editor.getDoc()
+
   check = ->
     window.setTimeout ->
         editorText = editor.getValue()


  @detach_cm = ->
    # TODO: can we remove the insert and delete event callbacks?
    editor.off 'onChange', editorListener
    delete @detach_cm

  return

  # Listen for edits in CodeMirror.
  editorListener = (ed, change) ->
    return if suppress
    applyCMToShareJS editorDoc, change, sharedoc
    check()

  editorDoc.on 'change', editorListener

  @on 'insert', (pos, text) ->
    suppress = true
