Skip to content

Instantly share code, notes, and snippets.

@marcorei
Created March 10, 2016 12:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marcorei/cb3017c21023044b6602 to your computer and use it in GitHub Desktop.
Save marcorei/cb3017c21023044b6602 to your computer and use it in GitHub Desktop.
Google Apps Script which cleans the Table of Content from unwanted headings.
/**
* Creates a menu entry in the Google Docs UI when the document is opened.
*
* @param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Clean Table of Contents', 'cleanToC')
.addToUi();
}
/**
* Runs when the add-on is installed.
*
* @param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE.)
*/
function onInstall(e) {
onOpen(e);
}
/**
* Remove unwanted elements from ToC.
* Takes some time...
*/
function cleanToC() {
var body = DocumentApp.getActiveDocument().getBody();
var toc = body.findElement(DocumentApp.ElementType.TABLE_OF_CONTENTS).getElement().asTableOfContents();
for (var i = toc.getNumChildren() - 1; i >= 0; i--) {
var tocElem = toc.getChild(i);
var level;
var heading;
// Search for the text of the ToC element.
var searchText = tocElem.getText();
// This loops through all elements of the document.
// Time to go get some coffee.
for (var j = 0; j < body.getNumChildren(); j++) {
var bodyElem = body.getChild(j);
if(bodyElem.getType() == DocumentApp.ElementType.PARAGRAPH) {
var par = bodyElem.asParagraph();
if(par.getText() == searchText) {
level = par.getHeading();
}
}
}
// Enter all headings you wanna keep!
if(level !== DocumentApp.ParagraphHeading.HEADING2) {
tocElem.removeFromParent();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment