Created
March 30, 2023 10:05
-
-
Save akinuri/c5b2d67744d6e4f5ea56a2f55a512a73 to your computer and use it in GitHub Desktop.
Adds custom text styles to Google Docs
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
let customStyles = { | |
"code" : { | |
"title" : "Code", | |
"style" : { | |
[DocumentApp.Attribute.FONT_FAMILY] : DocumentApp.FontFamily.CONSOLAS, | |
[DocumentApp.Attribute.FONT_SIZE] : 11, | |
[DocumentApp.Attribute.BACKGROUND_COLOR] : "#E8E8E8", | |
}, | |
}, | |
"comic" : { | |
"title" : "Comic Sans", | |
"style" : { | |
[DocumentApp.Attribute.FONT_FAMILY] : DocumentApp.FontFamily.COMIC_SANS_MS, | |
[DocumentApp.Attribute.BACKGROUND_COLOR] : "#DDDDDD", | |
}, | |
}, | |
}; | |
// https://stackoverflow.com/questions/64383424/set-anonymous-dynamic-functions-to-menu | |
(function IIFE(scope) { | |
'use strict'; | |
for (let customStyleKey in customStyles) { | |
let customStyle = customStyles[customStyleKey]; | |
let functionName = generateFormatTextFunctionName(customStyleKey); | |
scope[functionName] = function () { | |
formatText(customStyle.style); | |
}; | |
} | |
})(this); | |
// Add new menu item | |
function onOpen() { | |
let ui = DocumentApp.getUi(); | |
let menu = ui.createMenu("Custom Styles"); | |
for (let customStyleKey in customStyles) { | |
let customStyle = customStyles[customStyleKey]; | |
let functionName = generateFormatTextFunctionName(customStyleKey); | |
menu.addItem(customStyle.title, functionName); | |
} | |
menu.addToUi(); | |
} | |
function generateFormatTextFunctionName(name, style) { | |
return "formatText_" + name; | |
} | |
// https://webapps.stackexchange.com/questions/24249/how-do-i-add-new-styles-to-google-docs | |
function formatText(style) { | |
var selection = DocumentApp.getActiveDocument().getSelection(); | |
if (selection) { | |
var elements = selection.getRangeElements(); | |
for (var i = 0; i < elements.length; i++) { | |
var element = elements[i]; | |
// Only modify elements that can be edited as text; skip images and other non-text elements. | |
if (element.getElement().editAsText) { | |
var text = element.getElement().editAsText(); | |
// Style the selected part of the element, or the full element if it's completely selected. | |
if (element.isPartial()) { | |
text.setAttributes(element.getStartOffset(), element.getEndOffsetInclusive(), style); | |
} else { | |
text.setAttributes(style); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment