Google Docs - Format Matching Text Script

From NoskeWiki
Revision as of 19:09, 14 November 2022 by NoskeWiki (talk | contribs)
Jump to navigation Jump to search

About

NOTE: This page is a daughter page of: Google Docs App Scripts


This demos a Google Docs Add On / App Script to format text. :)

What the thing looks like after a run


Instructions

The right API to help is the Google Docs API... but that's slow to process, so here's what you need to do to create a new menu item that does something:

  1. Create a brand new Google Doc ............... (tip: Try typing into Chrome: docs.new)
  2. Click menu bar: Extensions > App Scripts.
  3. Enter the javascript code below into the Script Editor and hit "Save" and "Deploy" (as "Editor Add-On")
    ..... (tip: You can hit the play button to test one of the functions before saving)
  4. Reload your Google Doc and approve permissions.
  5. Run the Script by clicking the new menu item that appears: Special Formatting > Format Stat Numbers.

(see pictures of this process)



Google Docs Add On - Format Matching Text Script

Code.gs

 /**
 * @fileoverview This script uses Google Docs API to forat certain strings.
 * Instrutions and documentation for the script lives at:
 * http://andrewnoske.com/wiki/Google_Docs_-_Format_Matching_Text_Script
 */


/**
  * Formats the matching strings with .
  * param@ {string} findMe Regex string to look for.
  * param@ {string} color Color string in the form "#ffffff".
  * param@ {number} fontSize The font size to set.
  */
 function formatMatchingStrings(findMe, color, fontSize) {
  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  // Find and color each match:
  var foundElement = body.findText(findMe);
  while (foundElement != null) {
    // Color the next match:
    var foundText = foundElement.getElement().asText();
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    // Change the color and font size:
    foundText.setForegroundColor(start, end, color);
    foundText.setFontSize(start, end, fontSize);

    // Find the next match:
    foundElement = body.findText(findMe, foundElement);
  }

} 

/**
  * Formats stats numbers starting with "±".
  */
 function formatStatNumbers(findMe, color, fontSize) {
   formatMatchingStrings('±.*', '#dddddd', 7);  // Regex enabled.
   // INSTRUCTIONS: Add a bunch more formatting rules here if you like.
 }

/**
 * Called when doc opens. Creates menu iteam for "Special Formatting".
 */
function onOpen() {
  // Add a menu item:
  DocumentApp.getUi().createMenu('Special Formatting')
      .addItem('Format Stat Numbers', 'formatStatNumbers')
      .addToUi();
}