Cleaning up blank lines in a document
The hierarchy array lists out all the heading levels to consider for conversion. I guess there may be some reason that you want to exclude some.
// this is the list of heading types to convert..(them all in this case) var heirarchy = [ DocumentApp.ParagraphHeading.HEADING1, DocumentApp.ParagraphHeading.HEADING2, DocumentApp.ParagraphHeading.HEADING3, DocumentApp.ParagraphHeading.HEADING4, DocumentApp.ParagraphHeading.HEADING5, DocumentApp.ParagraphHeading.HEADING6, DocumentApp.ParagraphHeading.SUBTITLE, DocumentApp.ParagraphHeading.TITLE ];
The demote variable says what heading level matching blank paragraphs should be set to.
// what to set blank lines to,normally it would be normal var demote = DocumentApp.ParagraphHeading.NORMAL;
This function provides a dry run capability that reports which headings it plans to demote, then set this false when ready to commit.
var DRY_RUN = false;
Here’s the kind of update you get.
adjusting paragraph 0 from Title to Normal adjusting paragraph 2 from Title to Normal adjusting paragraph 3 from Title to Normal adjusting paragraph 4 from Title to Normal adjusting paragraph 7 from Subtitle to Normal adjusting paragraph 1059 from Heading 3 to Normal adjusting paragraph 1137 from Title to Normal adjusting paragraph 1138 from Title to Normal adjusting paragraph 1149 from Heading 3 to Normal adjusting paragraph 1248 from Heading 2 to Normal adjusting paragraph 1301 from Heading 3 to Normal
And that’s all there is to it. Here’s the code
// blank lines in documetns are sometimes set to header levels rather thannoemal text. // this converts them to normal text function demoteHeaderLevels () { var doc = DocumentApp.getActiveDocument(); // set this to false when it looks like it does what's needed var DRY_RUN = true; // this is the list of heading types to convert..(them all in this case) var heirarchy = [ DocumentApp.ParagraphHeading.HEADING1, DocumentApp.ParagraphHeading.HEADING2, DocumentApp.ParagraphHeading.HEADING3, DocumentApp.ParagraphHeading.HEADING4, DocumentApp.ParagraphHeading.HEADING5, DocumentApp.ParagraphHeading.HEADING6, DocumentApp.ParagraphHeading.SUBTITLE, DocumentApp.ParagraphHeading.TITLE ]; // what to set blank lines to,normally it would be normal var demote = DocumentApp.ParagraphHeading.NORMAL; doc.getBody().getParagraphs().forEach (function (d,i) { var heading = d.getHeading(); var idx = heirarchy.indexOf(heading); // check it's an interesting one if (idx !== -1) { // if only blank then demote to normal text if (!d.getText().replace(/\s/gmi,"")) { if (!DRY_RUN) { d.setHeading (demote); } Logger.log( (DRY_RUN ? ' would have adjusted' : ' adjusting') + ' paragraph ' + i + ' from ' + heading + ' to ' + demote); } } }); }
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.