Action

Shortcut: Insert Result

Posted by agiletortoise, Last update 10 days ago

Send the selected text in the editor to a shortcut in the Shortcuts as as input. Replaces the text in the editor with the result text from the shortcut.

This is meant as an example action to demonstrate how to call a shortcut and get a result via the Shortcut script object

To change the name of the shortcut being called, right-click on the action in the action list and “Configure” the action.

Steps

  • configurationKey

    name
    Shortcut Name
    key
    shortcutName
  • script (iOS only)

    // load shortcut name
    let shortcutName = "UPPERCASE"
    if (context.configuredValues["shortcutName"]) {
    	shortcutName = context.configuredValues["shortcutName"]
    }
    // get input text
    let selectedText = editor.getSelectedText()
    const [st, len] = editor.getSelectedRange()
    
    let shortcut = Shortcut.create(shortcutName, selectedText)
    if (shortcut.run()) {
    	if (shortcut.result) {
    		editor.setSelectedText(shortcut.result)
    		editor.setSelectedRange(st, shortcut.result.length)
    	}
    }
    else {
    	console.log(`Shortcuts Error: ${JSON.stringify(shortcut.response)}`)
    	context.fail()
    }
  • script (macOS only)

    // load shortcut name
    let shortcutName = ""
    if (context.configuredValues["shortcutName"]) {
    	shortcutName = context.configuredValues["shortcutName"]
    }
    
    let method = "execute";
    let script = `on execute(theInput)
    	tell application "Shortcuts Events"
    		set theResult to (run the shortcut named "${shortcutName}" with input theInput)
    		return item 1 of theResult
    	end tell
    end execute`;
    
    const [st, len] = editor.getSelectedRange()
    let input = editor.getSelectedText().replaceAll('"', '\"')
    
    let runner = AppleScript.create(script);
    if (runner.execute(method, [input])) {
    	// the AppleScript ran without error
    	// if the script returned a result, it's available...
    	editor.setSelectedText(runner.lastResult)
    	editor.setSelectedRange(st, runner.lastResult.length)
    }
    else {
    	alert(runner.lastError);
    	context.fail()
    }

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.