editor.getSelectedText() no longer returns entire draft text by default

Did editor.getSelectedText() behavior change earlier this year?

It used to return the whole draft if there was no current selection.

In March or Feb, it stopped working that way - see conversation at https://drafts.discoursehosting.net/t/mermaid-diagram/7031

A function that returns all or selected text would be appreciated -

Thanks!

editor.getSelectedText() has never behaved that way, and shouldn’t. That’s not what you would typically want from a function like that. Here’s two alternatives:

// selection tag works that way...
let s = draft.processTemplate("[[selection]]");

// or
let s = editor.getSelectedRange()[1] > 0 ? editor.getSelectedText() : editor.getText();
1 Like

On either of these solutions: if text is selected, editor.setSelectedText(newText); will replace the selected text with newText, but if text is not selected, newText will be appended to the current draft. What would be needed to replace on either scenario?

setSelectedText will always replace the selected range. That range is a location and length, and that length can be zero - so likely what you are seeing is the last range selected in the document was just the cursor at the end.

What are you trying to do, exactly? You might need to query the range and apply some logic to determine if it’s the range you were hoping for.

The basic bones of script below came from I know not where; I just fixed the regex. It is meant to remove line breaks from paragraphs copied from PDFs, which sometimes have an assortment of carriage returns, line feeds, extra spaces, and hyphens at the end of the lines. It works fine on selected text, but I was hoping to modify to use the entire draft if no text is selected.

I can see that the script queries the range of the selected text and then sets a new range, but I have no idea how to fit in either of the two alternatives mentioned above that would allow it to replace the entire draft. The script actually works fine without the last line, so I’m not even sure it needs to query the range to function on selected text.

var text = editor.getSelectedText();
var [st, len] = editor.getSelectedRange();

newText = text.replace(/(\r\n|\n|\r)/gm," ");
newText = newText.replace(/\s+/gm," ");
newText = newText.replace(/-\s+/gm,"");

editor.setSelectedText(newText);
editor.setSelectedRange(st, newText.length);

Something like the below should work:

var [st, len] = editor.getSelectedRange();
if (len == 0) {
    var isFull = true
    var text = editor.getText()
} else {
    var isFull = false    
    var text = editor.getSelectedText()
}

newText = text.replace(/(\r\n|\n|\r)/gm," ");
newText = newText.replace(/\s+/gm," ");
newText = newText.replace(/-\s+/gm,"");

if (isFull) {
    editor.setText(newText)
} else {
    editor.setSelectedText(newText);
    editor.setSelectedRange(st, newText.length);
}