 _ = require 'underscore'
 
-splitWord = word ->
-  word.match(/(^ +|)\W+ +/g)
-
-
-buildWord = (word, prepend='', append='') ->
-  tmp = word.match /(^ +|)\W+ +/g
-  tmp2 = []
-
-  if tmp.length == 1
-    tmp2.push (new Word (prepend+tmp.pop()+append))
-  else
-    tmp2.push (new Word (prepend+tmp.pop(0)))
-    while tmp.length > 1
-      tmp2.push (new Word (tmp.pop(0) + ' '))
-
-    tmp2.push (new Word (tmp.pop() + append + ' '))
-
-  tmp2.reverse()
-
+# XRegExp = require('xregexp').XRegExp
+WordRegExp = /\S+\s*/g
+PreSpacesRegExp = /^\s+/
+PostSpacesRegExp = /\s+$/
 # Simple class that contains a word and links to the selections pointing
 # to it
 class Word

    index = sel.startPos.word   #position to work from
    pos = sel.startPos.pos

    wordsToInsert = content.match /\w+ +/g
    preSpaces = content.search /^ +/

    currWord = @getWord index

    # Get spaces of next input and append them to last word to insert
    if index < @_rte.words.length - 1 and pos == (currWord.length - 1)
      nextWord = @getWord (index+1)
      preSpaces = nextWord.search /^ +/
      if preSpaces > -1         # add them to current word
        @setWord (index+1) nextWord.substring(preSpaces)
        last = _.last(wordsToInsert) + nextWord.substring(0, preSpaces)
        wordsToInsert[wordsToInsert.length-1] = last
    else if pos < (currWord.length - 1)
      nextWord = currWord.substring(pos)
      preSpaces = nextWord.search /^ +/
      if preSpaces > -1
        if not preSpaces == (nextWord.length-1)
          @insertWord (index+1) nextWord.substring(preSpaces)
        last = _.last(wordsToInsert) + nextWord.substring(0, preSpaces)
        wordsToInsert[wordsToInsert.length-1] = last

    # Add the spaces at beginning of input string to previous word
    # if any, or create an empty one
    if preSpaces > -1
      if pos == 0
        if index == 0
          emptyWord = new Word content.substring(0, preSpaces)
          @insertWord 0, emptyWord
        else
          # update previous word
          prevWord = @getWord (index-1)
          prevWord += content.substring(0, preSpaces)
          @setWord (index-1), prevWord


  split: (n) ->

      throw new Error "Index out of bounds"
    @_rte.words[index].word = content

  # Append new words at the end of the word list
  # @param [String] content the string to append
  push: (content) ->
    preSpaces = content.match PreSpacesRegExp
    if preSpaces isnt null
      @_rte.words.push(new Word (preSpaces[0]))
    words = content.match WordRegExp
    if _.isArray(words)
      for w in words
        @_rte.words.push (new Word w)

  # Insert words at position
  #
