When creating heading levels in a document, it’s easy to get confused about which level a paragraph should be at. If you reduce a header level, the headings below need to be adjusted also, and its not till you come to creating a contents page that you notice it’s all out of line.

Here’s a snippet to adjust header levels so that sub headings are never more than one deeper than the previous header.

Adjusting heading levels

This one provides a dry run capability, where the log file tells you what it would have done. Set it to false when you are ready to go for real.

The code

// sometimes header levels get screwed up and need to be readjusted
// this will ensure that a header level is never more than one higher than the one before it
function workHeaderLevels () {
  var doc = DocumentApp.getActiveDocument();
  // set this to false when it looks like it does what's needed
  var DRY_RUN = true;
  // these are the only ones to be considered
  var heirarchy = [ 

  doc.getBody().getParagraphs().reduce (function (p,c) {
    var heading = c.getHeading();
    var idx = heirarchy.indexOf(heading);
    // check it's an interesting one
    if (idx !== -1) {
      if (idx > p+1) {
        Logger.log( (DRY_RUN ? 'would have adjusted ' : 'adjusting ') + 
          c.getText().slice(0,10) + ' from ' + heading + ' to ' + heirarchy[p]);
        // really do it
        if (!DRY_RUN) {
          c.setHeading (heirarchy[p]);

      else {
        p = idx;
    return p;
For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.