Adding to @ccstone’s excellent tips:
If you want to know whether Finder is frontmost:
if application id "com.apple.finder" is frontmost then
tell app id "com.apple.finder" to if it is frontmost then
# Obviously, your Emacs.app file is located in a different place:
set myEmacsAppPath to "/Users/******/Documents/Repositories/emacs/nextstep/"
# This is the name of the empty default Emacs buffer you want to open:
set myScratchBufferName to "turlututu"
# This part is unlikely to change, it assumes that you use the emacsclient
# that corresponds to the selected Emacs.app. And that you run Emacs as a server.
set myEmacsclient to myEmacsAppPath & "Emacs.app/Contents/MacOS/bin/emacsclient"
set myEmacsApp to myEmacsAppPath & "Emacs.app"
Assuming you’ve launched
Emacs.app at least once in the past, then it will have been registered with Launch Services, which keeps track of all applications on your system. Therefore, you can declare
myEmacsClient like so:
set myEmacsApp to the POSIX path of (path to application "Emacs")
set myEmacsClient to myEmacsApp & "/Contents/MacOS/bin/emacsclient"
It saves you having to hard-code the path into your script, and aids portability. If you end up moving the
Emacs.app application file to a different location, you won’t need to make any adjustments to your script.
tell application "System Events" to tell process "Emacs" to set frontmost to true
tell application myEmacsApp
System Events shouldn’t have to be involved here. This entire block could likely be replaced with:
tell application "Emacs" to activate