I'm writing an add on for Google Docs to allow users to choose from lists of canned text samples to insert into their document. I want the text inserted like this:
1st_text_insertion
2nd_text_insertion
3rd_text_insertion
However, my code results in the following:
3rd_text_insertion
2nd_text_insertion
1st_text_insertion
The reverse ordering occurs because the cursor position remains in the same place rather than updating to the end of the last text insertion.
Here's the code I'm using:
function insertText(text) {
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
newPosition = cursor.insertText(text + '\r');
doc.setCursor(newPosition);
}
The code needs to be flexible enough to insert text wherever the cursor is placed and then add new entries following a return character. For example, if the user placed their cursor on a blank line between existing text items B and C, the inserted text should appear on new lines between items B and C.
Example before text insertion:
existing_text_A
existing_text_B
existing_text_C
Desired output after text insertion:
existing_text_A
existing_text_B
1st_text_insertion
2nd_text_insertion
3rd_text_insertion
existing_text_C
I've tried several approaches, such as using appendText or getNextSibling, but they don't produce the desired output. Thanks for any help!