I'll eventually find the time to combine this script with the one that I describe in An even newer version of my Capture app. For now, I call this script by saving it as an AppleScript application that I named ">Emacs.app".
####################################
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
#########
# This is standard AppleScript with no extra.
# No need to declare anything more than the scripting additions.
#########
property myEmacs : "/Users/suzume/Documents/Repositories/emacs/nextstep/Emacs.app"
property myEmacsclient : "/Users/suzume/Documents/Repositories/emacs/nextstep/Emacs.app/Contents/MacOS/bin/emacsclient"
property myEmacsFront : false
#########
# I decided to use properties instead of variables in this script.
#########
tell application myEmacs
activate
end tell
#########
# Here, I activate Emacs, which has the effect to either put it at the front
# or to launch it.
#########
repeat while myEmacsFront = false
try
tell application "System Events" to tell process "Emacs" to set frontmost to true
set myEmacsFront to true
on error
delay 1
end try
end repeat
#########
# If Emacs is not launched, it may take some time to start it.
# In which case the script will error because Emacs won't be here
# when the script needs it.
# So I loop every second on the myEmacsFront property that
# will eventually be set to true once Emacs is set to the front.
#########
tell application "Finder"
set fileSelection to selection as alias list
end tell
#########
# The Finder gives us the list of selected files.
#########
try
repeat with selectedFile in fileSelection
set myEditCommand to myEmacsclient & " -e \"(find-file \\\"" & (POSIX path of selectedFile) & "\\\")\" -n"
try
do shell script myEditCommand
on error
display alert "Emacs can't open the file"
end try
end repeat
on error
display alert "The script can't find the file"
end try
#########
# This is the core of the script. It asks emacsclient to evaluate
# (find-file "file path").
# The error messages try to describe the error location.
#
# The only difficult part in this script was the escape sequences
# needed to create myEditCommand.
#########