Last active
February 26, 2022 15:40
-
-
Save aadennis/9cf50f6ace141607fff77d03bd9cc02f to your computer and use it in GitHub Desktop.
Set Google Docs Heading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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