Action

Gemini: Modify Selection

Posted by agiletortoise, Last update 10 days ago

Prompt for a text manipulation instruction and request Google Gemini AI perform that instruction on the selected text, replacing the selection with the result.

For example, select the text “my text” in the draft, run this action and give the instruction “uppercase” in the prompt, and the result selection will become “MY TEXT”.

This becomes more useful when you want to apply a series of instructions. For example, select the text “Happy Birthday Joe!” in a draft and use the instruction “uppercase and insert an 🎉 emoji between each word” to get “HAPPY 🎉 BIRTHDAY 🎉 JOE!”

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

Steps

  • script

    // get your input selected text, and store range for later
    const selection = editor.getSelectedText()
    const [st, len] = editor.getSelectedRange()
    // setup model name to use
    const model = "models/gemini-pro"
    
    let f = () => {
    	let p = new Prompt()
    	p.title = "Gemini: Modify Selection"
    	p.message = "What do you want Gemini to do with the selected text?"
    	p.addTextView("instruction", "Gemini Prompt", "")
    	p.addLabel("caption", "Provide an instruction to transform the selected text in the draft, for example `capitalize`, `translate into spanish`")
    	p.addSelect("result", "Result", ["Replace Selection", "Append to Selection", "Place in Clipboard"], ["Replace Selection"], false)
    	p.addButton("Modify")
    	
    	if (!p.show()) {
    		return false
    	}
    	const instruction = p.fieldValues["instruction"]
    	if (instruction == 0) { return false }
    
    	// build prompt with instruction and selection
    	let chatPrompt = `${instruction} the following text, returning only the result: ${selection}`
    
    	// send that to the AI
    	let ai = new GoogleAI()
    	let answer = ai.quickPrompt(chatPrompt, model)
    
    	// if we got no reply, cancel
    	if (!answer || answer.length == 0) {
    		context.fail()
    		return false
    	}
    	
    	switch(String(p.fieldValues["result"])) {
    	case "Replace Selection":
    		editor.setSelectedText(answer)
    		editor.setSelectedRange(st, answer.length)
    		break
    	case "Append to Selection":
    		editor.setSelectedText(`${selection}
    
    ${answer}
    `)
    		editor.setSelectedRange(st + selection.length + 2, answer.length)
    		break
    	default: // clipboard
    		app.setClipboard(answer)
    		break
    	}
    	return true
    }
    
    if (!f()) {
    	context.fail()
    }
    
    

Options

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