Created
May 20, 2025 21:02
-
-
Save snasirca/f7ab2fe1f1dd363ac17a08cada6340b3 to your computer and use it in GitHub Desktop.
Formatting Google Docs using Apps Script
This file contains hidden or 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
| function formatDoc() { | |
| const doc = DocumentApp.getActiveDocument(); | |
| const ps = doc.getBody().getParagraphs(); | |
| ps.forEach(p => applySpacing(p, 0, 6, 1.15)); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING1, 15, 7, 1); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING2, 15, 5, 1); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING3, 15, 5, 1); | |
| formatLists(ps, 0, 6, 1.15); | |
| removeLeadingBold(ps); | |
| } | |
| function applySpacing(p, before, after, line) { | |
| p.setSpacingBefore(before).setSpacingAfter(after).setLineSpacing(line); | |
| } | |
| function formatHeadings(paragraphs, type, before, after, line) { | |
| paragraphs.forEach(p => { | |
| if (p.getHeading() === type) applySpacing(p, before, after, line); | |
| }); | |
| } | |
| function formatLists(paragraphs, innerAfter, lastAfter, line) { | |
| let inList = false, lastRoot = -1, rootIndent = 0; | |
| paragraphs.forEach((p, i) => { | |
| const isItem = p.getType() === DocumentApp.ElementType.LIST_ITEM; | |
| if (isItem) { | |
| const indent = p.getIndentStart(); | |
| if (!inList) rootIndent = indent; | |
| inList = true; | |
| if (indent === rootIndent) lastRoot = i; | |
| applySpacing(p, 0, innerAfter, line); | |
| } else if (inList) { | |
| paragraphs[lastRoot].setSpacingAfter(lastAfter).setLineSpacing(line); | |
| inList = false; | |
| } | |
| }); | |
| if (inList && lastRoot !== -1) paragraphs[lastRoot].setSpacingAfter(lastAfter).setLineSpacing(line); | |
| } | |
| /* Remove any bold styling on the leading characters of every list item */ | |
| function removeLeadingBold(paragraphs) { | |
| paragraphs.forEach(p => { | |
| if (p.getType() !== DocumentApp.ElementType.LIST_ITEM) return; | |
| const text = p.editAsText(); | |
| const len = text.getText().length; | |
| let end = 0; | |
| while (end < len && text.isBold(end)) end++; // walk past leading bold run | |
| if (end > 0) text.setBold(0, end - 1, false); // strip it | |
| }); | |
| } | |
| function formatDoc() { | |
| const doc = DocumentApp.getActiveDocument(); | |
| const ps = doc.getBody().getParagraphs(); | |
| ps.forEach(p => applySpacing(p,0,6,1.15)); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING1,15,7,1); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING2,15,5,1); | |
| formatHeadings(ps, DocumentApp.ParagraphHeading.HEADING3,15,5,1); | |
| formatLists(ps,0,6,1.15); | |
| removeLeadingBold(ps); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment