Skip to content

Instantly share code, notes, and snippets.

@ericdraken
Created September 28, 2022 01:39
Show Gist options
  • Save ericdraken/755d36ef84f91df7df678aaebc0fa869 to your computer and use it in GitHub Desktop.
Save ericdraken/755d36ef84f91df7df678aaebc0fa869 to your computer and use it in GitHub Desktop.
Auto-number each paragraph for a patent application using Web App and Google Docs
// Eric Draken, 2022, ericdraken.com
// Quick Web App script to auto-number paragraphs in a patent application in Google Docs.
// This will re-number paragraphs in order when run again.
//
// Before:
// HEADER
// Some fany words
// HEADER
// More fancy words
// Even more fany words
//
// Afer:
// HEADER
// [0001] Some fany words
// HEADER
// [0002] More fancy words
// [0003] Even more fany words
//
function AutoNumberTheParagraphs() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var index = 1;
// e.g. [0001]
var re = '(\\W|^)\\[[0-9]{4,}\\]\\W{1,}'; // Uses Google RE2 regex
paragraphs.forEach((p, ind) => {
// Ignore centered titles in the parent application.
// There is some bug where "no alignment" is not "Left" but blank.
if(p.getAlignment() !== DocumentApp.HorizontalAlignment.CENTER &&
p.getAlignment() !== DocumentApp.HorizontalAlignment.RIGHT){
var txt = p.getText();
// Remove existing paragraph numbers
if(!!txt.match(re)){
p.replaceText(re, '');
}
// Quick check in case this 'paragraph' is just a line break or 'todo' or '...'
if(txt.length > 10){
// Add the numbers
// Google will prepend text with the properties of the preceding paragraph,
// so shim the inserted text with properties.
p.editAsText().insertText(0, '[' + String(index++).padStart(4, '0') + '] ').setAttributes(0, 6, p.getAttributes());
}
}
})
}
@ericdraken
Copy link
Author

This is a quick script I wrote. If you can improve it, please do! Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment