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 (
Extensions > Apps Script
) - Copy the following code into the 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] = 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 {
text.setAttributes(style);
}
}
}
}
}
- Choose Deploy > "New deployment"Run the onOpen function once from the code editor to trigger the authorization prompts and approve them.
- Use the new menu itemin your document to format selected text (
Styles > Format Code
)