Search code examples
google-apps-scriptgoogle-docs

Using gApp Scripts in gDocs to move cursor to Selection and "Delete the next line"


I have tried to delete certain paragraphs in the Header and Body Sections of a Google Doc using google apps scripts... however, if the paragraph is the last paragraph in a section there is an exception: Can't remove the last paragraph in a document section.

And yet that is the very paragraph I want to delete.

I have tried merging the paragraph with the previous paragraph but alas it does not work - the paragraph remains.

The only effective way of achieving this aim is to manually delete the paragraph by putting my cursor at the end of the previous line and pressing "forward" delete. This deletes the next line with no exceptions etc... however I need to automate this using apps script - so I am asking is there a way to search for an element in the script and then simulate pressing delete from that point? This is more of a hack but can't see another way of doing it?

An example might be:

var foundElement = body.findText("Dialogue");

while (foundElement != null) {
  // Get the text object from the element
  var foundText = foundElement.getElement().asText();

  // Where in the element is the found text?
  var start = foundElement.getStartOffset();
  var end = foundElement.getEndOffsetInclusive();  

 //PSUEDO CODE PRESS FORWARD DELETE TWICE FROM the **end** of the search phrase...
 end.pressdelete(twice)       
}

Error Msg Last Para inside Header Delete Para inside table First Para of Body and before table

UPDATE:

I was able to delete the header paragraph by looping through all the headers in the doc - apparently, there can be more than one...

I am still stuck deleting the empty para in the table after Dialogue (screenshot 2)...

var p = d.getBody().getParent(); 
  var headers = [];
  var footers = [];
  // let's loop through all the child elements in the document including headers and footers etc...
  for ( var i = 0; i < p.getNumChildren(); i += 1 ) {
    var t = p.getChild(i).getType();
    if ( t === DocumentApp.ElementType.BODY_SECTION ) continue; // not interested in the body    
    if ( t === DocumentApp.ElementType.HEADER_SECTION ) {
      //OLD CODE FOR FIRST HEADER
      if (headers.length > -1) {
        headers.push(p.getChild(i).asHeaderSection())
      }      
      var h = p.getChild(i).asHeaderSection().getText();      
    } else if ( t === DocumentApp.ElementType.FOOTER_SECTION ) {
      var f = p.getChild(i).asFooterSection().getText();      
    }
  } 


  function cleanHeaders(p) {

    p.forEach(function(h, j, ar) {

      var para = h.getParagraphs();

      para.forEach(function(e, i, arr) {
        var children = e.getNumChildren()
        //Logger.log("::Children:: " + children);
        if (children < 1) {
          var t = e.getText();
          var type = e.getType();      
          var parent = e.getParent();
          var pChildren = parent.getNumChildren();
          var childIndex = parent.getChildIndex(e);
          //Logger.log("::Element::" + e + " ::Number:: " + i + " ::Type:: " + type + " ::Text:: " + t + " ::Children:: " + children + " ::Parent:: " + parent + " ::ParentChildren:: " + pChildren + " ::childIndex:: " + childIndex);

          for ( var i = 0; i < parent.getNumChildren(); i += 1 ) {
            Logger.log(parent.getChild(i));
            if (i != 0) {
              parent.getChild(i).asParagraph().merge();
            }
          } 

          if (parent != 'DocumentBodySection' && parent != 'HeaderSection') {
            //e.getPreviousSibling().merge();
          }          
        }        
      });       
    });
  }

  Logger.log("HEADERS: " + headers.length);  
  cleanHeaders(headers);

Solution

  • As a workaround to Can't remove the last paragraph, you can insert an additional dummy paragraph

    Sample:

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
      body.appendParagraph('');
      var foundElement = body.findText("TargetText at end of line");
      while (foundElement != null) {
        var foundText = foundElement.getElement().asText();
        var paragraph = foundText.getParent();
        paragraph.removeFromParent();
        foundElement = body.findText("TargetText at end of line");    
      }
    }
    

    UPDATE

    If you want to deleter the last paragraph of multiples sections, you can implement an catch..try statement:

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
      var foundElement = body.findText("TargetText at end of line");
      while (foundElement != null) {
        var foundText = foundElement.getElement().asText();
        var paragraph = foundText.getParent();
        var parent = paragraph.getParent();
        try{
          paragraph.removeFromParent();
        }catch(err){
          body.appendParagraph('');
        }
        foundElement = body.findText("TargetText at end of line");    
      }
    }
    

    UPDATE

    To delete paragraphs following foundElement both i the the header and body, including tables you can use the following code:

    function myFunction() {
      var body = DocumentApp.getActiveDocument().getBody();
      var foundElement = body.findText("TargetText at end of line");
      while (foundElement != null) {
        var foundText = foundElement.getElement().asText();
        var paragraph = foundText.getParent();
        var nextParagraph = paragraph.getNextSibling();
        var parent = paragraph.getParent();
        if(nextParagraph!= null && nextParagraph.getType()=="PARAGRAPH"){
          try{
            nextParagraph.removeFromParent();
          }catch(err){
            var dummyParagraph = body.appendParagraph('');
            nextParagraph.removeFromParent();
            dummyParagraph.merge();
          }
        }
        foundElement = body.findText("TargetText at end of line", foundElement);    
      }
    
      var header = DocumentApp.getActiveDocument().getHeader();
      foundElement = header.findText("TargetText at end of line");
      while (foundElement != null) {
        var foundText = foundElement.getElement().asText();
        var paragraph = foundText.getParent();
        var nextParagraph = paragraph.getNextSibling();
        var parent = paragraph.getParent();
        if(nextParagraph!= null && nextParagraph.getType()=="PARAGRAPH"){
          Logger.log(nextParagraph.asText().getText());
          try{
            nextParagraph.removeFromParent();
          }catch(err){
            var dummyParagraph = header.appendParagraph('');
            nextParagraph.removeFromParent();
            dummyParagraph.merge();
          }
        }
        foundElement = header.findText("TargetText at end of line", foundElement);    
      }  
    }