Skip to content

Instantly share code, notes, and snippets.

@WesleyDRobinson
Last active June 2, 2016 08:13
Show Gist options
  • Save WesleyDRobinson/16527e9ee6dfd6cf5cfcacf784cdea5a to your computer and use it in GitHub Desktop.
Save WesleyDRobinson/16527e9ee6dfd6cf5cfcacf784cdea5a to your computer and use it in GitHub Desktop.
Synonyms Sidebar

Implementing a Thesauraus Extension for Google Docs

From within your document, select the menu item Tools > Script editor; If you are presented with a welcome screen, click Blank Project; Delete any code in the script editor and paste in the code from Code.gs in this Gist

Create a new file by selecting the menu item File > New > Html file; Name the file "Sidebar"; Delete any code in the new editor tab and paste in the code from Sidebar.html in this Gist

Select the menu item File > Save all; Name your new script "Synonyms" and click OK

You're done! It's pretty rough around the edges, but you can get a lot of synonyms from within the Google Doc!

Turning it on

Switch back to your document and reload the page; After a few seconds, a synonyms sub-menu will appear under the Add-ons menu; Click Add-ons > synonyms > Start; A dialog box will appear and tell you that the script requires authorization. Click Continue. A second dialog box will then request authorization for specific Google services. Read the notice carefully, then click Allow. A sidebar will appear. Select a word and click the blue Get Synonyms button.

If you enjoy using this a few times so we can work out the kinks and have some feedback for improvement, I can abstract this setup process away and publish the extension.

Thesaurus service provided by words.bighugelabs.com

/**
* Creates a menu entry in the Google Docs UI when the document is opened.
*
* @param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
/**
* Runs when the add-on is installed.
*
* @param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE.)
*/
function onInstall(e) {
onOpen(e);
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
*/
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('Synonyms')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
DocumentApp.getUi().showSidebar(ui);
}
/**
* Gets the text the user has selected. If there is no selection,
* this function displays an error message.
*
* @return {Array.<string>} The selected text.
*/
function getSelectedText() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var text = [];
var elements = selection.getSelectedElements();
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
text.push(element.getText().substring(startIndex, endIndex + 1));
} else {
var element = elements[i].getElement();
// Only translate elements that can be edited as text; skip images and
// other non-text elements.
if (element.editAsText) {
var elementText = element.asText().getText();
// This check is necessary to exclude images, which return a blank
// text element.
if (elementText != '') {
text.push(elementText);
}
}
}
}
if (text.length == 0) {
throw 'Please select some text.';
}
return text;
} else {
throw 'Please select some text.';
}
}
/**
* Gets the user-selected text and provides some synonyms
*
* @return {object} The result of the translation
*/
function getSynonyms() {
var word = getSelectedText();
var response = UrlFetchApp.fetch("http://words.bighugelabs.com/api/2/9f04fb6c0ad64879bcc2cfd437844c34/"+ word +"/json");
if (response.getResponseCode() !== 200) return JSON.parse('Sorry, no synonyms found :(');
return JSON.parse(response.getContentText("UTF-8"));
}
/**
* Replaces the text of the current selection with the provided text, or
* inserts text at the current cursor location. (There will always be either
* a selection or a cursor.) If multiple elements are selected, only inserts the
* translated text in the first element that can contain text and removes the
* other elements.
*
* @param {string} newText The text with which to replace the current selection.
*/
function insertText(newText) {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var replaced = false;
var elements = selection.getSelectedElements();
if (elements.length == 1 &&
elements[0].getElement().getType() ==
DocumentApp.ElementType.INLINE_IMAGE) {
throw "Can't insert text into an image.";
}
for (var i = 0; i < elements.length; i++) {
if (elements[i].isPartial()) {
var element = elements[i].getElement().asText();
var startIndex = elements[i].getStartOffset();
var endIndex = elements[i].getEndOffsetInclusive();
var remainingText = element.getText().substring(endIndex + 1);
element.deleteText(startIndex, endIndex);
if (!replaced) {
element.insertText(startIndex, newText);
replaced = true;
} else {
// This block handles a selection that ends with a partial element. We
// want to copy this partial text to the previous element so we don't
// have a line-break before the last partial.
var parent = element.getParent();
parent.getPreviousSibling().asText().appendText(remainingText);
// We cannot remove the last paragraph of a doc. If this is the case,
// just remove the text within the last paragraph instead.
if (parent.getNextSibling()) {
parent.removeFromParent();
} else {
element.removeFromParent();
}
}
} else {
var element = elements[i].getElement();
if (!replaced && element.editAsText) {
// Only translate elements that can be edited as text, removing other
// elements.
element.clear();
element.asText().setText(newText);
replaced = true;
} else {
// We cannot remove the last paragraph of a doc. If this is the case,
// just clear the element.
if (element.getNextSibling()) {
element.removeFromParent();
} else {
element.clear();
}
}
}
}
} else {
var cursor = DocumentApp.getActiveDocument().getCursor();
var surroundingText = cursor.getSurroundingText().getText();
var surroundingTextOffset = cursor.getSurroundingTextOffset();
// If the cursor follows or preceds a non-space character, insert a space
// between the character and the translation. Otherwise, just insert the
// translation.
if (surroundingTextOffset > 0) {
if (surroundingText.charAt(surroundingTextOffset - 1) != ' ') {
newText = ' ' + newText;
}
}
if (surroundingTextOffset < surroundingText.length) {
if (surroundingText.charAt(surroundingTextOffset) != ' ') {
newText += ' ';
}
}
cursor.insertText(newText);
}
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<!-- The CSS package above applies Google styling to buttons and other elements. -->
<style>
.branding-below {
bottom: 56px;
top: 0;
}
.branding-text {
left: 7px;
position: relative;
top: 3px;
}
.col-contain {
overflow: hidden;
}
.col-one {
float: left;
width: 50%;
}
.logo {
vertical-align: middle;
}
.radio-spacer {
height: 20px;
}
.width-100 {
width: 100%;
}
</style>
</head>
<body>
<div class="sidebar branding-below">
<form>
<div class="block col-contain">
<div class="col-one">
<b>Selected text</b>
<div>
<input type="radio" name="origin" id="radio-origin-auto" value="" checked="checked">
<label for="radio-origin-auto">Auto-detect</label>
</div>
</div>
</div>
<div class="block form-group">
<label for="synonymous-words"><b>Synonyms</b></label>
<textarea class="width-100" id="synonymous-words" rows="10"></textarea>
</div>
<div class="block" id="button-bar">
<button class="blue" id="run-synonyms">Get Synonyms</button>
<button id="insert-text">Insert</button>
</div>
</form>
</div>
<div class="sidebar bottom">
<span class="gray branding-text">Synonyms by Wesley Robinson</span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
/**
* On document load, assign click handlers to each button and try to load the
* user's origin and destination language preferences if previously set.
*/
$(function() {
$('#run-synonyms').click(runSynonyms);
$('#insert-text').click(insertText);
});
/**
* Runs a server-side function to translate the user-selected text and update
* the sidebar UI with the resulting translation.
*/
function runSynonyms() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(
function(message, element) {
var val = '';
console.log(message);
for (type in message) {
let syns = message[type].syn.join(', ') || 'no synonyms found';
val += type + ': ' + syns + ' |**| ';
}
$('#synonymous-words').val(val);
element.disabled = false;
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.getSynonyms();
}
/**
* Runs a server-side function to insert the translated text into the document
* at the user's cursor or selection.
*/
function insertText() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(
function(returnSuccess, element) {
element.disabled = false;
})
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.insertText($('#synonymous-words').val());
}
/**
* Inserts a div that contains an error message after a given element.
*
* @param msg The error message to display.
* @param element The element after which to display the error.
*/
function showError(msg, element) {
var div = $('<div id="error" class="error">' + msg + '</div>');
$(element).after(div);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment