Home > Blockchain >  Get all text before cursor in Google Docs
Get all text before cursor in Google Docs

Time:11-07

I'm working with Google apps script in Google Docs for the first time and am trying to retrieve all text in the document up until the cursor position.

My idea is to iterate the paragraphs prior to the cursor and append the paragraph text to an empty array, but I struggle with finding the cursor paragraph index. But maybe my entire approach is skewed, so any ideas on how to pull this off are appreciated.

function getText() {
  const document = DocumentApp.getActiveDocument();
  const cursor = document.getCursor();
  const paragraphs = document.getBody().getParagraphs();
  const index = paragraphs.indexOf(cursor.getElement()); // fails to find the index of the cursor paragraph
  const selectedParagraphs = paragraphs.slice(0, index);

  const text = [];
  for (let i = 0; i < selectedParagraphs.length; i  ) {
    text.push(selectedParagraphs[i].getText());
  }

  // add the text of the cursor's element up until the cursor's position
  const cursorOffset = cursor.getOffset();
  const cursorText = cursor.getElement().asText().getText();
  text.push(cursorText.substring(0, cursorOffset));

  return text.join('\n');

CodePudding user response:

In your script, how about the following modification?

From:

const index = paragraphs.indexOf(cursor.getElement());

To:

const e = cursor.getElement();
const index = document.getBody().getChildIndex(e.getType() == DocumentApp.ElementType.PARAGRAPH ? e : e.getParent());
  • In this case, index is retrieved using getChildIndex method of Class Body.

Reference:

  • Related