Version X14 (24.0) introduces a new JavaScript object to handle the position and length of a text selection. It can be also used to replace the current selection with text in a certain format.

The Selection object can be retrieved and set through the selection property of the TXTextControl object. The following JavaScript code snippet gets the current Selection and writes the current selection start and length values to the console:

var sel = TXTextControl.selection;
sel.getStart(function(selStart) {
sel.getLength(function(selLength) {
var bounds = { start: selStart, length: selLength }
console.log(bounds);
});
})
view raw test.js hosted with ❤ by GitHub

The getBounds method takes a callback function with one parameter as a parameter. The callback function is called with a SelectionBounds object as a parameter.

In order to set a new selection in the document, the setBounds method is used. This method takes a SelectionBounds object as a parameter:

var sel = TXTextControl.selection
var bounds = { "start":1,"length":2 }
sel.setBounds(bounds)
view raw test2.js hosted with ❤ by GitHub

When a selection should be replaced with plain or formatted ext, the text needs to be selected first. After that, the load method can be used to replace the selected text.

The following code snippet selects text and inserts plain text into the selection:

var sel = TXTextControl.selection
var bounds = { "start":5,"length":2 }
sel.setBounds(bounds)
var html = "New text";
var encoded = btoa(html);
sel.load(TXTextControl.StreamType.PlainText, encoded);
view raw test3.js hosted with ❤ by GitHub