3
votes

I'm coding a simple google script for a Google Doc sidebar and I'm facing the following problem: I have to insert some text where cursor is located

That text needs to be a paragraph as it is an specific code that must be separated from other text. Next is the code (working)

function insertText(actionObject) {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\nblablabla";

  cursor.insertText(stringToInsert);
}

Problem is that Google replaces \n with \r, so it is just a break line, but not a paragraph. This means, that my code works, but not as expected from technical point of view.

I cannot use appendParagraph function as it always adds it at the end of the file (and it could be needed to add that paragraph in the middle of the file).

SO, I have to use the insertParagraph(childIndex, paragraph) method available for Body object. But having the cursor, I'm not able to find a way that allows me to find out my current paragraph position and insert a new one just before...

Could anybody help me on this?

Thanks in advance!!

2

2 Answers

4
votes

To insert a paragraph use insertParagraph(childIndex,text).

function insertMyText(){
  var myText = 'My Text';
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var cursor = doc.getCursor();
  var element = cursor.getElement();
  var container = element.getParent();
  try {
    var childIndex = body.getChildIndex(container);
    body.insertParagraph(childIndex, myText);
  } catch (e) {
    DocumentApp.getUi().alert("There was a problem: " + e.message);
  }
}
-1
votes

If you want to be able to put your cursor in the middle of a paragraph and then have the text you insert become a new paragraph you could try:

function insertText() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\n\nWords to enter\n\n";

  cursor.insertText(stringToInsert);
}

which would create a new paragraph containing "Words to enter" with a blank line before and after it.