├── README.markdown └── apply_code_style.js /README.markdown: -------------------------------------------------------------------------------- 1 | Google Docs Scripts 2 | =================== 3 | 4 | Usage: 5 | 6 | 1. Go to `Tools > Script editor...` 7 | 2. Paste the contents of one of the scripts here and save it. 8 | 3. Reload the currently open document. 9 | -------------------------------------------------------------------------------- /apply_code_style.js: -------------------------------------------------------------------------------- 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 | fontSize: 9 16 | }; 17 | 18 | // helper function that strips the selected element and passes it to a handler 19 | function withElement(processPartial, processFull) { 20 | var selection = DocumentApp.getActiveDocument().getSelection(); 21 | if (selection) { 22 | var elements = selection.getRangeElements(); 23 | for (var i = 0; i < elements.length; i++) { 24 | var element = elements[i]; 25 | if (element.getElement().editAsText) { 26 | var text = element.getElement().editAsText(); 27 | if (element.isPartial()) { 28 | var from = element.getStartOffset(); 29 | var to = element.getEndOffsetInclusive(); 30 | processPartial(element, text, from, to); 31 | } else { 32 | processFull(element, text); 33 | } 34 | } 35 | } 36 | } 37 | } 38 | 39 | // called in response to the click on a menu item 40 | function applyCodeStyle() { 41 | return withElement( 42 | applyPartialStyle.bind(this, style), 43 | applyFullStyle.bind(this, style) 44 | ); 45 | } 46 | 47 | // applies the style to a selected text range 48 | function applyPartialStyle(style, element, text, from, to) { 49 | text.setFontFamily(from, to, style.fontFamily); 50 | text.setBackgroundColor(from, to, style.backgroundColor); 51 | text.setBold(from, to, style.bold); 52 | text.setFontSize(from, to, style.fontSize); 53 | } 54 | 55 | // applies the style if the entire element is selected 56 | function applyFullStyle(style, element, text) { 57 | text.setFontFamily(style.fontFamily); 58 | text.setBackgroundColor(style.backgroundColor); 59 | text.setBold(style.bold); 60 | text.setFontSize(style.fontSize); 61 | } 62 | 63 | --------------------------------------------------------------------------------