Skip to content

Instantly share code, notes, and snippets.

@djsudduth
Last active September 6, 2024 20:13
Show Gist options
  • Save djsudduth/1456dd0cecca6ae57dc902dceff167e9 to your computer and use it in GitHub Desktop.
Save djsudduth/1456dd0cecca6ae57dc902dceff167e9 to your computer and use it in GitHub Desktop.
Google Apps Script to convert exported Google Keep note titles to headers
function boldTitlesToHeaders(headerSize) {
// headerSize = 2;
var headerStyle = p__getHeadingType(headerSize);
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var numParagraphs = body.getNumChildren();
for (var i = 0; i < numParagraphs; i++) {
var element = body.getChild(i);
if (element.getType() == DocumentApp.ElementType.PARAGRAPH) {
var paragraph = element.asParagraph();
var text = paragraph.getText();
// Check each text element within the paragraph
for (var j = 0; j < paragraph.getNumChildren(); j++) {
var child = paragraph.getChild(j);
if (child.getType() == DocumentApp.ElementType.TEXT) {
var textElement = child.asText();
if (textElement.isBold()) {
p__changeNoteTitle(paragraph, headerStyle);
break; // We've found bold text, so we don't need to check further.
}
}
}
}
}
}
function p__getHeadingType(headerSize) {
switch(headerSize) {
case 1: return DocumentApp.ParagraphHeading.HEADING1;
case 2: return DocumentApp.ParagraphHeading.HEADING2;
case 3: return DocumentApp.ParagraphHeading.HEADING3;
case 4: return DocumentApp.ParagraphHeading.HEADING4;
case 5: return DocumentApp.ParagraphHeading.HEADING5;
default: return DocumentApp.ParagraphHeading.HEADING4;
}
}
function p__changeNoteTitle(paragraph, headingStyle) {
var text = paragraph.getText();
// Insert a new Heading paragraph directly after the current paragraph
var parent = paragraph.getParent();
var index = parent.getChildIndex(paragraph);
var newHeading = paragraph.copy().setHeading(headingStyle);
parent.insertParagraph(index + 1, newHeading);
// Remove the original paragraph
parent.removeChild(paragraph);
}
@djsudduth
Copy link
Author

djsudduth commented Sep 6, 2024

Usage:

  1. Open the Google Doc that was exported from Google Keep
  2. Select Extensions / Apps Script
  3. Paste the Gist code above into the project window
  4. Uncomment out the //headerSize = 2; Set the headerSize to what you'd like from H1 to H5 using just the numeric value. 4 is a good choice.
  5. Run the code directly on the current Doc by hitting the Run button (your Doc should now have headers on the left Docs outline)
  6. You can make it a library and save the library to use on any Doc (https://developers.google.com/apps-script/guides/libraries) or just add the code to each Doc

Example:
Saved the code as a library with the name "KeepHeaders"

Use:
In any Doc then, add this code:

function myFunction() {
  KeepHeaders.boldTitlesToHeaders(3);
}

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