diff --git a/Editor.js b/Editor.js index 5b5e306f..228280ce 100644 --- a/Editor.js +++ b/Editor.js @@ -120,6 +120,9 @@ function Editor(doc, renderer) addListener(container, "mousewheel", bind(this.onMouseWheel, this)); this.doc = doc; + doc.addChangeListener(function(startRow, endRow) { + console.log(startRow, endRow); + }); renderer.setDocument(doc); this.cursor = { @@ -229,10 +232,11 @@ Editor.prototype = { if (this.hasSelection()) { - this.cursor = this.doc.remove(this.getSelectionRange()); + this.cursor = this.doc.replace(this.getSelectionRange(), text); this.clearSelection(); + } else { + this.cursor = this.doc.insert(this.cursor, text); } - this.cursor = this.doc.insert(this.cursor, text); this.draw(); this.renderer.scrollCursorIntoView(); }, diff --git a/TextDocument.js b/TextDocument.js index 96bf48f7..ff869a5a 100644 --- a/TextDocument.js +++ b/TextDocument.js @@ -2,6 +2,8 @@ function TextDocument(text) { this.lines = this._split(text); this.modified = true; + + this.listeners = []; } TextDocument.prototype = @@ -10,6 +12,21 @@ TextDocument.prototype = return text.split(/[\n\r]/) }, + addChangeListener : function(listener) { + this.listeners.push(listener); + }, + + fireChangeEvent : function(firstRow, lastRow) + { + if (lastRow === undefined) { + lastRow = this.lines.length-1; + } + + for (var i=0; i < this.listeners.length; i++) { + this.listeners[i](firstRow, lastRow); + }; + }, + getWidth : function() { if (this.modified) @@ -104,7 +121,17 @@ TextDocument.prototype = } }, - insert : function(position, text) + insert : function(position, text) + { + var end = this._insert(position, text); + this.fireChangeEvent( + position.row, + position.row == end.row ? position.row : undefined + ); + return end; + }, + + _insert : function(position, text) { this.modified = true; @@ -153,6 +180,17 @@ TextDocument.prototype = }, remove : function(range) + { + var end = this._remove(range); + + this.fireChangeEvent( + range.start.row, + range.end.row == range.start.row ? range.start.row : undefined + ); + return end; + }, + + _remove : function(range) { this.modified = true; @@ -170,11 +208,19 @@ TextDocument.prototype = replace : function(range, text) { - this.remove(range); + this._remove(range); if (text) { - return this.insert(range.start, text); + var end = this._insert(range.start, text); } else { - return range.start; + end = range.start; } + + var lastRemoved = range.end.column == 0 ? range.end.column-1 : range.end.column; + this.fireChangeEvent( + range.start.row, + lastRemoved == end.row ? lastRemoved : undefined + ); + + return end; } } \ No newline at end of file