Styles in Google Docs

Edit (March 2023): None of the below works anymore. Boo. But now there are extensions like Code Blocks, which should satisfy the same need.

ZOMG ... Finally! Google Docs used to allow custom stylesheets, but they nuked that functionality years ago. So you were stuck with Title, Subtitle, Normal, and several levels of (sub)headings. This elegant little hack lets you reformat, say, source code, to be consistent (Consolas 10 point in this example). I commented out the Attribute.BACKGROUND_COLOR and Attribute.FOREGROUND_COLOR lines, to preserve, e.g., the colored text I get when copying from OS X Terminal.app or Eclipse, and I made the FONT_SIZE 8, but otherwise, used it as-is.

Tools → Script Editor

// Add new menu item
function onOpen() {
  DocumentApp.getUi()
  .createMenu('Styles')
  .addItem('Format Code', 'formatCode')
  .addToUi();
}

// Define code styling
var style = {};
style[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.CONSOLAS;
style[DocumentApp.Attribute.FONT_SIZE] = 8;
//style[DocumentApp.Attribute.BACKGROUND_COLOR] = "#DDDDDD";
//style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#333333";
style[DocumentApp.Attribute.BOLD] = false;
style[DocumentApp.Attribute.SPACING_AFTER] =0;
style[DocumentApp.Attribute.SPACING_BEFORE] =0;

style[DocumentApp.Attribute.LINE_SPACING]=1;

// 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 {
          text.setAttributes(style);
        }
      }
    }
  }
}

Edit → Current Project's Triggers

Edit Project Name
Enter new project name [ whatever; defaults to Untitled ]

...
Click this: No triggers set up. Click here to add one now.

Run [onOpen] Events [From document] [On open] (click [Save])

Authorization required: Click [Review Permissions]

Click your account.

This app isn't verified: Click "Advanced" (lower left)

Click "Go to Untitled project (unsafe)" (Name will vary depending on what you entered above)

Untitled project wants to access your Google Account ... Click [Allow]

Close the code editor tab.

Reload the document tab.

Note the new Styles menu at the top, with the Format Code option...


Comments