Action

Gemini: Translate Selection

Posted by agiletortoise, Last update 10 days ago

Prompt to select from a list of languages and ask Google Gemini to translate the selected text in the editor to that language, replacing the text with the result.

For more information and examples incorporating Google Gemini, visit the integration guide

Steps

  • script

    // setup languages available in prompt
    const targetLanguages = ["Spanish", "French", "German", "English"]
    
    let f = () => {
    	let p = new Prompt()
    	p.title = "Translate Selection"
    	p.message = "Select language for translation."
    	p.addSelect("lang", "Language", targetLanguages, [targetLanguages[0]])
    	p.addButton("Translate")
    
    	if (!p.show()) {
    		return false
    	}
    	const targetLanguage = p.fieldValues["lang"][0]
    	
    	// get editor values
    	const [st, len] = editor.getSelectedRange()
    	const selection = editor.getSelectedText()
    
    	// build prompt
    	const chatPrompt = `Translate the following text into ${targetLanguage}: "${selection}"`
    
    	// create GoogleAI API object and use single response
    	// convenience function to send prompt
    	let ai = new GoogleAI()
    	let answer = ai.quickPrompt(chatPrompt)
    
    	// if we got a reply, add it to the draft
    	if (answer && answer.length > 0) {
    		answer = answer.trim().replace(/^"+|"+$/g, '')
    		editor.setSelectedText(answer)
    		editor.setSelectedRange(st, answer.length)
    		return true
    	}
    	else {
    		return false
    	}
    }
    
    if (!f()) {
    	context.cancel()
    }
    

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.