Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Google apps script to add header numbers to a document
var state = {
headerLevel1: 0,
headerLevel2: 0,
headerLevel3: 0,
}
var private = {
getSectionNumber: function (paragraph)
{
if ( paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING1 )
{
state.headerLevel2 = 0;
state.headerLevel3 = 0;
return (++state.headerLevel1) + " ";
}
else if ( paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING2 )
{
if (state.headerLevel1 == 0)
state.headerLevel1 = 1;
state.headerLevel3 = 0;
return state.headerLevel1 + "." + (++state.headerLevel2) + " ";
}
else if ( paragraph.getHeading() == DocumentApp.ParagraphHeading.HEADING3 )
{
if (state.headerLevel2 == 0)
state.headerLevel2 = 1;
return state.headerLevel1 + "." + state.headerLevel2 + "." + (++state.headerLevel3) + " ";
}
return "";
},
isNumber: function (text)
{
return !isNaN(text);
},
removeExistingHeaderNumber: function (paragraph)
{
var text = paragraph.getText();
for (var i = 0; i < text.length; i++)
{
if ( private.isNumber(text.charAt(i)) || text.charAt(i) == "." )
continue;
break;
}
return text.substr(0, i);
}
};
var _addHeaderNumbers =
{
testUrl: "xyzzy",
implHelper : function addHeaderNumbers(doc)
{
var body = doc.getBody()
for (var i = 0; i < body.getNumChildren(); i++)
{
var element = body.getChild(i);
if ( element.getType() != DocumentApp.ElementType.PARAGRAPH )
continue;
var paragraph = element.asParagraph();
if ( paragraph.getHeading() != DocumentApp.ParagraphHeading.NORMAL )
{
var sectionNumber = private.getSectionNumber(paragraph);
var oldText = private.removeExistingHeaderNumber(paragraph);
if ( oldText.length > 0 )
paragraph.replaceText(oldText, "");
if ( sectionNumber.length > 0 )
paragraph.insertText(0, sectionNumber);
}
}
doc.saveAndClose();
}
};
function _test_addHeaderNumber()
{
_addHeaderNumbers.implHelper(DocumentApp.openByUrl(_addHeaderNumbers.testUrl));
}
function addHeaderNumbers()
{
_addHeaderNumbers.implHelper(DocumentApp.getActiveDocument());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment