SHARE
TWEET

Untitled

a guest Nov 4th, 2013 5,037 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // is called by google docs when a document is open
  2. // adds a menu with a menu item that applies a style to the currently selected text
  3. function onOpen() {
  4.   DocumentApp.getUi()
  5.   .createMenu('Extras')
  6.   .addItem('Apply code style', 'applyCodeStyle')
  7.   .addToUi();
  8. }
  9.  
  10. // definition of a style to be applied
  11. var style = {
  12.   bold: false,
  13.   backgroundColor: "#DDDDDD",
  14.   fontFamily: DocumentApp.FontFamily.CONSOLAS
  15. };
  16.  
  17. // helper function that strips the selected element and passes it to a handler
  18. function withElement(processPartial, processFull) {
  19.   var selection = DocumentApp.getActiveDocument().getSelection();
  20.   if (selection) {
  21.     var elements = selection.getSelectedElements();
  22.     for (var i = 0; i < elements.length; i++) {
  23.       var element = elements[i];
  24.       if (element.getElement().editAsText) {
  25.         var text = element.getElement();
  26.         if (element.isPartial()) {
  27.           var from = element.getStartOffset();
  28.           var to = element.getEndOffsetInclusive();
  29.           return processPartial(element, text, from, to);
  30.         } else {
  31.           return processFull(element, text);
  32.         }
  33.       }
  34.     }
  35.   }
  36. }
  37.  
  38. // called in response to the click on a menu item
  39. function applyCodeStyle() {
  40.   return withElement(
  41.     applyPartialStyle.bind(this, style),
  42.     applyFullStyle.bind(this, style)
  43.   );
  44. }
  45.  
  46. // applies the style to a selected text range
  47. function applyPartialStyle(style, element, text, from, to) {
  48.   text.setFontFamily(from, to, style.fontFamily);
  49.   text.setBackgroundColor(from, to, style.backgroundColor);
  50.   text.setBold(from, to, style.bold);
  51. }
  52.  
  53. // applies the style if the entire element is selected
  54. function applyFullStyle(style, element, text) {
  55.   text.setFontFamily(style.fontFamily);
  56.   text.setBackgroundColor(style.backgroundColor);
  57.   text.setBold(style.bold);
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top