diff --git a/spec/atom/buffer-spec.coffee b/spec/atom/buffer-spec.coffee index b58a37655..e22c3d43b 100644 --- a/spec/atom/buffer-spec.coffee +++ b/spec/atom/buffer-spec.coffee @@ -102,6 +102,24 @@ describe 'Buffer', -> expect(buffer.getLine(3)).toBe " var pivot = sort(Array.apply(this, arguments));" expect(buffer.getLine(4)).toBe "};" + describe ".setText(text)", -> + it "changes the entire contents of the buffer and emits a change event", -> + lastRow = buffer.lastRow() + expectedPreRange = new Range([0,0], [lastRow, buffer.getLine(lastRow).length]) + changeHandler = jasmine.createSpy('changeHandler') + buffer.on 'change', changeHandler + + newText = "I know you are.\nBut what am I?" + buffer.setText(newText) + + expect(buffer.getText()).toBe newText + expect(changeHandler).toHaveBeenCalled() + + [event] = changeHandler.argsForCall[0] + expect(event.string).toBe newText + expect(event.preRange).toEqual expectedPreRange + expect(event.postRange).toEqual(new Range([0, 0], [1, 14])) + describe ".save()", -> describe "when the buffer has a path", -> filePath = null diff --git a/src/atom/buffer.coffee b/src/atom/buffer.coffee index a002a6e69..4839e22d2 100644 --- a/src/atom/buffer.coffee +++ b/src/atom/buffer.coffee @@ -8,6 +8,7 @@ class Buffer constructor: (@path) -> @url = @path # we want this to be path on master, but let's not break it on a branch + @lines = [''] if @path and fs.exists(@path) @setText(fs.read(@path)) else @@ -17,7 +18,10 @@ class Buffer @lines.join('\n') setText: (text) -> - @lines = text.split('\n') + @change(@getRange(), text) + + getRange: -> + new Range([0, 0], [@lastRow(), @lastLine().length]) getTextInRange: (range) -> if range.start.row == range.end.row @@ -40,6 +44,15 @@ class Buffer insert: (point, text) -> @change(new Range(point, point), text) + numLines: -> + @getLines().length + + lastRow: -> + @getLines().length - 1 + + lastLine: -> + @getLine(@lastRow()) + change: (preRange, newText) -> postRange = new Range(_.clone(preRange.start), _.clone(preRange.start)) prefix = @lines[preRange.start.row][0...preRange.start.column] @@ -68,12 +81,6 @@ class Buffer @lines[preRange.start.row..preRange.end.row] = linesToInsert @trigger 'change', { preRange, postRange, string: newText } - numLines: -> - @getLines().length - - lastRow: -> - @numLines() - 1 - save: -> if not @path then throw new Error("Tried to save buffer with no url") fs.write @path, @getText()