2
votes

In the google docs add-on quick start, there's a great method to insert text anywhere in the document. It handles well for selections as well as inserting at the cursor, but it has a problem when you "select" the "character" at the end of any line in the doc.

It doesn't actually select anything (or at least nothing is returned from the document's getSelection() method), but when I try to get the position with the document's getCursor() method that returns null as well, so I have no frame of reference to know where the position is on the doc.

Here's an image to show what I mean. Note that it's not a space key being selected; it's a selection you can make at the end of any line in a google doc. Also, note the error, showing that there's no position to use getSurroundingText() on because the getCursor() method returns null.

I need the position right before that selection to insert text, so how would I get this position (if at all possible)?

1

1 Answers

2
votes

From the docs:

A representation of the user's selection, or null if the user does not have anything selected in the document, if only the end of a paragraph is selected, if only the end of a paragraph and a new line are selected, or if the script is not bound to the document.

That piece you have selected in the "end of paragraph" that the docs are referring to, so it is returning null exactly as it is defined to do.

I would look into using the getCursor which returns the Position, which can then be used to insertText.

var document = DocumentApp.getActiveDocument();
var position = document.getCursor();

if (position !== null) {
    position.insertText("lorem ipsum");
}

Note that this solution would likely force you to simply put your cursor at the end of the line, rather than select the end of paragraph.