Search code examples
google-apps-scriptgoogle-docsgoogle-docs-api

How To Put A Number In Front Of Every Suggestion Corretcly?


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


Solution

  • 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