Action

Claude: Modify Selection

Posted by agiletortoise, Last update 7 months ago

Prompt for a text manipulation instruction and request Anthropic’s Claude 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 Antropic Claude, 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 models = AnthropicAI.knownModels()
    
    let f = () => {
    	let p = new Prompt()
    	p.title = "Claude: Modify Selection"
    	p.message = "What do you want Claude to do with the selected text?"
    	p.addTextView("instruction", "Claude 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.addSelect("model", "Model", models, [models[0]], 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 AnthropicAI()
    	const model = p.fieldValues["model"][0]
    	let answer = ai.quickPrompt(chatPrompt, {"model": 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.