Add New Style To Google Docs

In order to enable it you need to create a new script: Tools >> Script Editor>> New and paste the code there. Then you will have to authorize the script and reload the document so that the menu appears on in the menu bar. Then select a patch of text and pick Extras >> Apply code style. The following code snippet was taken from here- http://pastebin.com/4pNBJ9pC

// 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() {
  DocumentApp.getUi()
  .createMenu('Extras')
  .addItem('Apply code style', 'applyCodeStyle')
  .addToUi();
}
 
// definition of a style to be applied
var style = {
  bold: false,
  backgroundColor: "#DDDDDD",
  fontFamily: DocumentApp.FontFamily.CONSOLAS
};
 
// 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.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      if (element.getElement().editAsText) {
        var text = element.getElement();
        if (element.isPartial()) {
          var from = element.getStartOffset();
          var to = element.getEndOffsetInclusive();
          return processPartial(element, text, from, to);
        } else {
          return processFull(element, text);
        }
      }
    }
  }
}
 
// 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);
}
 
// applies the style if the entire element is selected
function applyFullStyle(style, element, text) {
  text.setFontFamily(style.fontFamily);
  text.setBackgroundColor(style.backgroundColor);
  text.setBold(style.bold);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s