How to use AppleScript application with “open file -a AppleScriptApp”

applescript

Some information about what I am trying to achieve

I am using emacs inside of terminal. I know about existence of cocoa versions of emacs (like GNU Emacs for OS X, Aquamacs and Emacs Mac Port). But I prefer to code inside of terminal.

Everything is fine in my setup except the fact that sometimes I want to open file inside of emacs from Finder or any other software. So I need find running process of emacs in terminal or create new one and open the fine inside of running emacs.

So basically I need to create an .app wrapper for opening files in terminal emacs.

Trying to get it done

As far as I understand, open -a my_emacs_app /path/to/file is the same as opening file in application from finder. So that's why I am testing my_emacs_app using open command.

My first attempt is to create application using AppleScript. Here is the code that process passed arguments:

on run argv
    if (count of argv) > 0 then
        -- get file path from argv
        -- and log to logfile for testing purposes
        return "defined"
    else
        -- no args means no file
        -- log to logfile that we can't extract file path
        -- from empty arguments
        return "failed"
    end if
end run

And actually it works when I try to run it using

$ osascript my_emacs_app.scpt /path/to/file

It opens the file and logs what expected to log file.

When I run it using

$ osascript my_emacs_app.scpt

It logs to file that no arguments were passed.
So I was happy with it. But remember, I need an .app wrapper. So I am exporting this script as application (and place it inside of /Applications/ folder). And then when I try to

$ open -a my_emacs_app /path/to/file

I see that application is executed for a short time and then is closed. But nothing good happens. I mean, file is not opened in emacs and nothing is logged into log file.

Does any one know, how to export such scripts?

Best Answer

After few different attempts and hacks I found good solution to solve my problem. First - implement the script. Then open the Automator.app and create new application. Then combine Get Specified Finder Items action and Run AppleScript. So now open -a my_automator_app /path/to/file will pass /path/to/file/ to my script. And that's cool.

P. S. in the argv will be stored the alias to the file, not the posix file path. To convert it from alias to posix you should use

set aliasPath to item 1 of item 1 of argv
set filePath to (the POSIX path of aliasPath)

Oh and don't forget that you might want to get the quoted form of filePath in case it contains some special characters (like space or ~).

You can get more information about alias/posix paths here