Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Created with Copy to Gist
A lot of the solutions don't work inline. This is a cleaned-up solution offered by @AlekseyBykov using Google App Scripts to add a custom menu action:
Create a new script (Tools > Script Editor)
Copy the following code into the editor:
// Add new menu item
function onOpen() {
.addItem('Format Code', 'formatCode')
// Define code styling
var style = {};
style[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.CONSOLAS;
style[DocumentApp.Attribute.FONT_SIZE] = 10;
style[DocumentApp.Attribute.BACKGROUND_COLOR] = "#DDDDDD";
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.setAttributes(element.getStartOffset(), element.getEndOffsetInclusive(), style);
} else {
Assign a trigger to run the onOpen function "On open" (Edit > Current Project's Triggers)
After authorizing the script, reload the original document
Use the new menu item to format selected text (Styles > Format Code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment