Skip to content

Instantly share code, notes, and snippets.

@brookinc
Created June 27, 2019 01:14
Show Gist options
  • Save brookinc/03a4305bf5f2f22237e9cabc3e4887f8 to your computer and use it in GitHub Desktop.
Save brookinc/03a4305bf5f2f22237e9cabc3e4887f8 to your computer and use it in GitHub Desktop.
Google Apps Script that adds a "Format Code" menu option for documents.
// Source: https://webapps.stackexchange.com/a/117682
// Docs: https://developers.google.com/apps-script/reference/document/
// Add new menu item
function onOpen() {
DocumentApp.getUi()
.createMenu('Styles')
.addItem('Format Code', 'formatCode')
.addToUi();
}
// Define code styling
var fontFamily = "Roboto Mono";
var style = {};
style[DocumentApp.Attribute.FONT_SIZE] = 9;
style[DocumentApp.Attribute.BACKGROUND_COLOR] = "#E7E7E7";
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#333333";
style[DocumentApp.Attribute.BOLD] = false;
// Apply code formatting
function formatCode() {
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.setFontFamily(element.getStartOffset(), element.getEndOffsetInclusive(), fontFamily);
text.setAttributes(element.getStartOffset(), element.getEndOffsetInclusive(), style);
} else {
text.setFontFamily(fontFamily);
text.setAttributes(style);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment