     @subscriptions.dispose()
 
   disconnect: ->
+    # @pairingChannel.trigger 'client-disconnected', {colour: @markerColour}
     @pusher.disconnect()
-    @clearMarkers(@markerColour)
+    _.each @friendColours, (colour) => @clearMarkers(colour)
+    atom.views.getView(@editor).removeAttribute('id')
     @hidePanel()
 
   serialize: ->


  startPairing: ->
    @subscriptions.add atom.commands.add 'atom-workspace', 'pusht:disconnect': => @disconnect()
    triggerPush = true
    @editor = atom.workspace.getActiveEditor()

    atom.views.getView(@editor).setAttribute('id', 'pusht')

    buffer = @buffer = @editor.buffer

      @editor.setGrammar(grammar)
      @syncGrammars()

    @pairingChannel.bind 'client-share-whole-file', (file) =>
      @triggerPush = false
      buffer.setText(file)
      @triggerPush = true

    @pairingChannel.bind 'client-share-partial-file', (chunk) =>
      @triggerPush = false
      buffer.append(chunk)
      @triggerPush = true

    @pairingChannel.bind 'client-change', (data) => @changeBuffer(data)

    # @pairingChannel.bind 'client-disconnected', (data) =>
    #   @clearMarkers(data.colour)
    #   disconnectView = new AlertView "Your pair buddy has left the session."
    #   atom.workspace.addModalPanel(item: disconnectView, visible: true)


    @listenToBufferChanges()
    @syncSelectionRange()

  listenToBufferChanges: ->
    @buffer.onDidChange (event) =>
      return unless @triggerPush
      deletion = !(event.newText is "\n") and (event.newText.length is 0)
      @pairingChannel.trigger 'client-change', {deletion: deletion, event: event, colour: @markerColour}

  changeBuffer: (data) ->
    newRange = Range.fromObject(data.event.newRange)
    oldRange = Range.fromObject(data.event.oldRange)
    newText = data.event.newText

    @triggerPush = false

    @clearMarkers(data.colour)

    if data.deletion
      @buffer.delete oldRange
      @editor.scrollToBufferPosition(oldRange.start)
      @addMarker oldRange.start.toArray()[0], data.colour
    else if oldRange.containsRange(newRange)
      @buffer.setTextInRange oldRange, newText
      @editor.scrollToBufferPosition(oldRange.start)
      @addMarker oldRange.start.toArray()[0], data.colour
    else
      @buffer.insert newRange.start, newText
      @editor.scrollToBufferPosition(newRange.start)
      @addMarker(newRange.end.toArray()[0], data.colour)

    @triggerPush = true

  syncSelectionRange: ->
    @editor.onDidChangeSelectionRange (event) =>
      rows = event.newBufferRange.getRows()
      return unless rows.length > 1
