Skip to content

Instantly share code, notes, and snippets.

@aadennis
Last active February 26, 2022 15:40
Show Gist options
  • Save aadennis/9cf50f6ace141607fff77d03bd9cc02f to your computer and use it in GitHub Desktop.
Save aadennis/9cf50f6ace141607fff77d03bd9cc02f to your computer and use it in GitHub Desktop.
Set Google Docs Heading
// reference:
// https://developers.google.com/apps-script/reference/document/body#getchildindexchild
// https://developers.google.com/apps-script/reference/document/body#getattributes
// https://stackoverflow.com/questions/8273047/javascript-function-similar-to-python-range
function log(message) {
//Logger.log(message)
}
function getTextLineFromBody(theBody, index) {
bodyAsTextLines = theBody.getText().split("\n");
return bodyAsTextLines[index]
}
function countWordsInLine(textLine) {
a = textLine.split(" ")
//log("array from line: [" + a + "]")
b = a.length
//log("length of line/array is: [" + b + "]")
return b
}
function setHeading(theBody, index) {
var element = theBody.getChild(index)
log("1. Element (type) is: [" + element + "]");
log("2. Element (type) is: [" + element.getType().toString() + "]");
if (element.getType().toString() === 'TABLE_OF_CONTENTS') {
// heading does not apply to TOC: early return
return;
}
var line = getTextLineFromBody(theBody, index)
//log(line)
let wordCountForLine = countWordsInLine(line)
log("Count in line: [" + wordCountForLine + "]")
// a paragraph is a header if there are between 1 and
// 9 words inclusive
if (0 < wordCountForLine && wordCountForLine < 10) {
log("candidate line at index [" + index + "]")
log(element)
element.setHeading(DocumentApp.ParagraphHeading.HEADING2)
}
}
function setHeadings() {
var body = DocumentApp.getActiveDocument().getBody();
var numChildrenInBody = body.getNumChildren()
log("There are " + body.getNumChildren() + " elements in the document body.");
for (let i of Array(numChildrenInBody).keys()) {
setHeading(body, i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment