Search code examples
macosapplescripttranslation

Automator Quick Action (AppleScript) for Deepl Translator


I have an Automator quick action (service) to get texts from applications and open them on the Deepl website to translate them. It works, but the spaces between the words get replaced with + signs. The translation is filled with + signs, like this:

"...+in+third+place+on+the+list+of+the+most+..."

What is causing this?

on run {input, parameters}
    set output to "https://www.deepl.com/translator#pt/en/" & urldecode(input as string)
    return output
end run

on urldecode(x)
    set cmd to "'require \"cgi\"; puts CGI.escape(STDIN.read.chomp)'"
    do shell script "echo " & quoted form of x & " | ruby -e " & cmd
end urldecode

Solution

  • I'd use 'Listing 32-7 AppleScriptObjC: Handler that URL encodes text' from Encoding and Decoding Text.

    Example AppleScript code:

    use framework "Foundation"
    use scripting additions
    
    on run {input, parameters}
        set output to "https://www.deepl.com/translator#pt/en/" & encodeText(input as string)
        return output
    end run
    
    on encodeText(theText)
        set theString to stringWithString_(theText) of NSString of current application
        set theEncoding to NSUTF8StringEncoding of current application
        set theAdjustedString to stringByAddingPercentEscapesUsingEncoding_(theEncoding) of theString
        return (theAdjustedString as string)
    end encodeText