From 5e95fc482dda6b9b0bceccd936e8bf8ddd97abaa Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Thu, 2 Feb 2012 12:30:25 -0700 Subject: [PATCH] Buffer.setText emits the proper change events --- spec/atom/buffer-spec.coffee | 18 ++++++++++++++++++ src/atom/buffer.coffee | 18 +++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) 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 b78b5fa40..7fe469b85 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 @@ -37,6 +41,15 @@ class Buffer getLine: (row) -> @lines[row] + 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] @@ -66,8 +79,7 @@ class Buffer @trigger 'change', { preRange, postRange, string: newText } - numLines: -> - @getLines().length + save: -> if not @path then throw new Error("Tried to save buffer with no url")