           @element.addClass "invalid"
           @errorMsg.show()
 
-  existingNames: ->
-    @element.find(".token-text-area-results li")
-      .map (index, element) ->
-        $(element).html()
-      .get()
-      
-  existingIds: ->
-    @element.find(".token-text-area-results li")
-      .map (index, element) ->
-        $(element).attr("data-id")
-      .get()
-
   isArrow: (code) ->
     $.inArray(code, [37, 38, 39, 40]) != -1
 
-  getCaretPos: ->
+  getRange: ->
     if window.getSelection and window.getSelection().rangeCount > 0
       range = window.getSelection().getRangeAt(0).cloneRange()
     else
       range = document.selection.createRange()
     range.collapse(true)
+    range
+
+  getSelection: ->
+    # Determine the length of text in the input.
+    range = @getRange()
     range.setStart(@element[0], 0)
-    range.toString().length
-
-  getSelection: ->
-    caretPos = @getCaretPos()
-
-    # Remove each token in range and remove them from the caret position.
+    caretPos = range.toString().length
+
+    # Remove each token in range and deduct them from the caret position.
     # Otherwise, autocomplete suggestions will include existing tokens.
     html = $('<p>' + @input.html() + '</p>')
 

    id = result.data('id')
    return false unless id

    # Replace typing with token.
    name = result.html()
    token = '<span class="token" contenteditable="false" data-id="' + id + '">' + name + '</span>'
    sel = window.getSelection()
    console.log sel
    if (sel.getRangeAt && sel.rangeCount)
      # Set range to metric name fragment.
      range = sel.getRangeAt(0)
      range.setStart(range.startContainer, range.endOffset - @word[0].length)
      range.deleteContents()

      # Create and insert new token.
      node = document.createElement('span')


  registerEvents: ->
    @input.on "keyup paste input", (event) =>
      @range = @getRange()

      @checkAutocomplete()

      # Spans lose contenteditable attr when pasted. (!?)
