Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.