0

Detail Of The Problem

As title, I am using Google App Script and Google Docs API's Batchupdate, trying to put number in front of every suggestion. However, I can place it correctly at the very first one, but it starts to deviate after the first one.

Result I Currently Have

Please refer to the image below. Result I Currently Have

What I have Tried

Below is the snippet I currently have

function markNumberInFrontOfMark(fileID) {
  fileID = "MYFILEID";
  let doc = Docs.Documents.get(fileID);
  let requests = doc.body.content.flatMap(content => {
    if (content.paragraph) {
      let elements = content.paragraph.elements;
      return elements.flatMap(element => element.textRun.suggestedDeletionIds ? {
        insertText: {
          text: "(1)",
          location: {
            index: element.startIndex
          }
        }
      } : []);
    }
    return [];
  });
  Docs.Documents.batchUpdate({requests}, fileID);
  return true;
}

Result I Want To Have

Please refer to the image below

Result I Want To Have

Post I Refer to

How to change the text based on suggestions through GAS and Google DOC API

Steven Yin
  • 15
  • 5
  • It appears you need to add 3 to `startIndex` for each `insertText`, which makes sense. As you `batchUpdate`, the first request adds 3 characters to the document so it grew in length. – TheWizEd Jan 26 '23 at 15:45
  • @TheWizEd Much thanks for your reply. I have added 3 to each `startIndex` for each `insertText`, but the problem persists. Could you make an example so that I can understand you better? – Steven Yin Jan 26 '23 at 15:57

1 Answers1

0

Here is an example of how to insert text. In this case I am adding 3 characters "(1)" for example. If the number of additions exceeds 9 you will have to adjust the number of characters added.

function markNumberInFrontOfMark() {
  try {
    let doc = DocumentApp.getActiveDocument();
    let id = doc.getId();
    doc = Docs.Documents.get(id);
    let contents = doc.body.content;
    let requests = [];
    let num = 0;
    contents.forEach( content => {
        if( content.paragraph ) {
          let elements = content.paragraph.elements;
          elements.forEach( element => {
              if( element.textRun.suggestedDeletionIds ) {
                num++;
                let text = "("+num+")"
                let request = { insertText: { text, location: { index: element.startIndex+3*(num-1) } } };
                requests.push(request);
              }
            }
          );
        }
      }
    );
    if( requests.length > 0 ) {
      Docs.Documents.batchUpdate({requests}, id);
    }
  }
  catch(err) {
    console.log(err)
  }
}

And the resulting updated document.

enter image description here

TheWizEd
  • 7,517
  • 2
  • 11
  • 19