Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Styles a paragraph as code. When adding this script using the Google Docs script editor it will appear under a new menu called "Extras"
// is called by google docs when a document is open
// adds a menu with a menu item that applies a style to the currently selected text
function onOpen() {
.addItem('Apply code style', 'applyCodeStyle')
var backgroundColor = "#DDDDDD";
// definition of a style to be applied
var style = {
bold: false,
backgroundColor: backgroundColor,
fontFamily: "Consolas",
fontSize: 9
// helper function that strips the selected element and passes it to a handler
function withElement(processPartial, processFull) {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
var trueElement = element.getElement();
var parent = trueElement.getParent();
Logger.log("parent: " + parent.getType());
Logger.log("Type of element:" + trueElement.getType());
if (element.isPartial()) {
var from = element.getStartOffset();
var to = element.getEndOffsetInclusive();
processPartial(element, text, from, to);
} else {
processFull(element, text);
if(trueElement.getType() === DocumentApp.ElementType.PARAGRAPH && parent.getType() === DocumentApp.ElementType.BODY_SECTION){
// insert table
var index = parent.getChildIndex(trueElement);
Logger.log("Index of element: " + index);
var removed = parent.removeChild(trueElement);
var newTable = parent.insertTable(index, [[trueElement.getText()]]);
var tableStyle = {};
tableStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
tableStyle[DocumentApp.Attribute.FONT_FAMILY] = style.fontFamily;
tableStyle[DocumentApp.Attribute.FONT_SIZE] = style.fontSize;
var cell0 = newTable.getChild(0).getChild(0);
Logger.log(cell0 + ": " + cell0.getBackgroundColor());
// called in response to the click on a menu item
function applyCodeStyle() {
return withElement(
applyPartialStyle.bind(this, style),
applyFullStyle.bind(this, style)
// applies the style to a selected text range
function applyPartialStyle(style, element, text, from, to) {
text.setFontFamily(from, to, style.fontFamily);
text.setBackgroundColor(from, to, style.backgroundColor);
text.setBold(from, to, style.bold);
text.setFontSize(from, to, style.fontSize);
// applies the style if the entire element is selected
function applyFullStyle(style, element, text) {
Copy link

juliaogris commented Dec 17, 2020

Line 16 should be updated to
fontFamily: "Consolas",
as the FontFamily enum is now deprecated.

Copy link

fatso83 commented Dec 17, 2020

Thanks, @juliaogris. Updated.

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