2
votes

I'm trying to write a script that puts the cursor's surrounding text to uppercase and set the enclosing paragraph to HEADING1. I'm able to do the first thing while I can't figure out the way to get the paragraph containing the cursor using the getCursor() method. Here is what I tried:

 var cursor = DocumentApp.getActiveDocument().getCursor();
 var element = cursor.getElement();
 var paragraph = element.asParagraph();

However, element is a TEXT element and can't be cast as PARAGRAPH. Is there a way to get the paragraph from the text element?

Thanks.

2

2 Answers

3
votes

It took me some time but I got it ;-) Paragraph is the parent of the textElement surrounding the cursor.

I added a couple of log because I was curious ;-)

function myFunction() {
  var cursor = DocumentApp.getActiveDocument().getCursor();
  var element = cursor.getElement();
  var paragraph = element.getParent().asParagraph();
  var att = paragraph.getAttributes();// optional
  Logger.log(att); // just out of curiosity... if you want to see
  var style = {};
  style[DocumentApp.Attribute.HEADING] =
    DocumentApp.ParagraphHeading.HEADING1;
  paragraph.setAttributes(style);
  var att = paragraph.getAttributes();// optional
  Logger.log(att); // just out of curiosity... if you want to see
  }
0
votes
var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundingText = cursor.getSurroundingText().getText();

surroundingText will give you the current paragraph.