add document indexToPosition and positionToIndex

This commit is contained in:
nightwing 2012-12-26 20:31:20 +04:00
commit 0908b41268
2 changed files with 23 additions and 30 deletions

View file

@ -592,6 +592,28 @@ var Document = function(text) {
}
};
this.indexToPosition = function(index, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
for (var i = startRow || 0, l = lines.length; i < l; i++) {
index -= lines[i].length + newlineLength;
if (index < 0)
return {row: i, column: index + lines[i].length + newlineLength};
}
return {row: l-1, column: lines[l-1].length};
};
this.positionToIndex = function(pos, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
var index = 0;
var row = Math.min(pos.row, lines.length);
for (var i = startRow || 0; i < row; ++i)
index += lines[i].length;
return index + newlineLength * i + pos.column;
};
}).call(Document.prototype);
exports.Document = Document;

View file

@ -50,7 +50,7 @@ oop.inherits(JsonWorker, Mirror);
try {
var result = parse(value);
} catch (e) {
var pos = this.charToDocumentPosition(e.at-1);
var pos = this.doc.indexToPosition(e.at-1);
this.sender.emit("error", {
row: pos.row,
column: pos.column,
@ -62,35 +62,6 @@ oop.inherits(JsonWorker, Mirror);
this.sender.emit("ok");
};
this.charToDocumentPosition = function(charPos) {
var i = 0;
var len = this.doc.getLength();
var nl = this.doc.getNewLineCharacter().length;
if (!len) {
return { row: 0, column: 0};
}
var lineStart = 0;
while (i < len) {
var line = this.doc.getLine(i);
var lineLength = line.length + nl;
if (lineStart + lineLength > charPos)
return {
row: i,
column: charPos - lineStart
};
lineStart += lineLength;
i += 1;
}
return {
row: i-1,
column: line.length
};
};
}).call(JsonWorker.prototype);
});