     if currentLine.length > 0
       nodeLines.push currentLine
       currentLine = []
-    # console.log 's' + @showNodeLines nodeLines
     nodeLines
 
   showNodeLines: (nodeLines) ->

    winSelection.removeAllRanges()
    winSelection.addRange docRange

  # TODO: use point or array
  getNodeAndOffsetForPos: (rowNr, colNr) ->
    console.log "getNodeAndOffsetForPos: #{rowNr} #{colNr}"
    nodeLines = @getNodeLines()
    nodeLine = nodeLines[rowNr]
    relativeCol = colNr
    for node, i in nodeLine
      if node.nodeType == Node.TEXT_NODE
        textLen = node.textContent.length
        if relativeCol <= textLen
          return [node, relativeCol]
        else
          relativeCol -= textLen
      else if node.nodeType == Node.ELEMENT_NODE && node.tagName == 'BR'
        return [node, 0]
        break;
      else # We should only have text and a single <br>
         console.error 'getNodeAndOffsetForPos: unhandled node type or tagName: ' + node.nodeType + ' & ' + node.tagName
    ## TODO: handle beyond end of line, and don't return br, but simply last text elt
    return null

  getText: ->
    textLines =
      for nodeLine in @getNodeLines()
        _.map nodeLine, (n) -> if n.nodeType == Node.TEXT_NODE then n.textContent else ''
          .join('')
    textLines.join('\n')

  setText: (txt) ->
    @$editableDiv.empty()
    for line in txt.split '\n'
      lineDiv = $('<div>').text line
      @$editableDiv.append lineDiv

class Buffer
  textManager: null

  constructor: ($editableDiv) ->
    @textManager = new TextManager($editableDiv)

  getText: ->
    @textManager.getText()

  setText: (txt) ->
    @textManager.setText txt

  getSelectionRange: ->
    [anchorPos,focusPos] = @textManager.getSelectionPoss()
    new Range( [anchorPos[0], anchorPos[1]], [focusPos[0], focusPos[1]] )

  setSelectionRange: (range) ->
    range = Range.fromObj(range)
    [startNode, startOffset] = @textManager.getNodeAndOffsetForPos range.start.row, range.start.column
    [endNode,   endOffset]   = @textManager.getNodeAndOffsetForPos range.end.row, range.end.column
    @textManager.setDocSelection startNode, startOffset, endNode, endOffset

  delete: (range) ->
    @setTextInRange range, ''


    @setSelectionRange [@positionForCharacterIndex(selStartIx), @positionForCharacterIndex(selEndIx)]

    # TODO: check if okay when selection was null

  positionForCharacterIndex: (ix) ->
    bufferText = @getText()
