Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active July 19, 2019 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/8ae93935ae0601ec9c48cfb1746d4234 to your computer and use it in GitHub Desktop.
Save JoshCheek/8ae93935ae0601ec9c48cfb1746d4234 to your computer and use it in GitHub Desktop.
Google Apps script to translate selections back and forth between English and Spanish
/**
* @OnlyCurrentDoc Limits the script to only accessing the current sheet.
*/
function onOpen() {
DocumentApp.getUi()
.createMenu('Translate')
.addItem('Translate selection to Spanish', 'translateSelectionToSpanish')
.addItem('Translate selection to English', 'translateSelectionToEnglish')
.addToUi();
}
function translateSelectionToSpanish() {
translateSelection('en', 'es')
}
function translateSelectionToEnglish() {
translateSelection('es', 'en')
}
function translateSelection(sourceLang, destLang) {
const doc = DocumentApp.getActiveDocument()
const ui = DocumentApp.getUi()
const selection = doc.getSelection()
if (!selection) {
ui.alert('Nothing is selected')
}
const elements = selection.getRangeElements()
const newSelection = doc.newRange()
for (var i = 0; i < elements.length; i++) {
const element = elements[i]
// only modify elements that can be edited as text; skip images and other non-text elements.
if (!element.getElement().editAsText) {
return
}
// the selection can be within a text element, so we have to track the text, what came before it, and what came after it
const textElement = element.getElement().editAsText()
var preText = ''
var text = textElement.getText()
var postText = ''
if (element.isPartial()) {
preText = text.substring(0, element.getStartOffset())
postText = text.substring(1+element.getEndOffsetInclusive(), text.length)
text = text.substring(element.getStartOffset(), 1+element.getEndOffsetInclusive())
}
// now perform the translation
const translated = LanguageApp.translate(text, sourceLang, destLang)
// and update the contents
textElement.setText(preText + translated + postText)
// select the replaced text
newSelection.addElement(textElement, preText.length, preText.length+translated.length-1)
}
doc.setSelection(newSelection.build())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment