In my MediaWiki extension I'm plugging Ace into an editor-hosting widget which needs to sometimes set the selection from start/end character values like this. This seems to work for me (context.codeEditor here is the Ace editor instance):
'setSelection': function( options ) {
// Ace stores positions for ranges as row/column pairs.
// To convert from character offsets, we'll need to iterate through the document
var doc = context.codeEditor.getSession().getDocument();
var lines = doc.getAllLines();
var offsetToPos = function( offset ) {
var row = 0, col = 0;
var pos = 0;
while ( row < lines.length && pos + lines[row].length < offset) {
pos += lines[row].length;
pos++; // for the newline
row++;
}
col = offset - pos;
return {row: row, column: col};
}
var start = offsetToPos( options.start ),
end = offsetToPos( options.end );
var sel = context.codeEditor.getSelection();
var range = sel.getRange();
range.setStart( start.row, start.column );
range.setEnd( end.row, end.column );
sel.setSelectionRange( range );
return context.$textarea;
},
The inverse to convert Ace's row/col positions to character positions to report them back should also be fairly straightforward. This is a naive implementation and can probably be done more efficiently by peeking into Ace's internals as well. :)
-- brion vibber (brion @
pobox.com)