Controlling Emacs using AppleScript
On Mac OS X, neither GNU Emacs nor Aquamacs Emacs is a scriptable application. You can, however, use emacsclient to control both remotely using Lisp forms. Here’s how.
If you haven’t already, add a line like this to your ~/.emacs file:
(server-start)
Restart Emacs or type M-x server-start.
In AppleScript, run a command like this:
do shell script "emacsclient --eval '(manual-entry \"ls\")'"
You may need to specify a full path for emacsclient: note that GNU Emacs running under Aqua AppleScript scripts and applications, like other Aqua apps, do not get your $PATH from your shell’s rc file. (You can set your $PATH or other environment variables for Aqua apps following these steps.)
As a practical example of the sort of thing you might use this for, here is a script which you can run to display a UNIX man page in GNU Emacs:
-- Display a manual page entry in GNU Emacs or Aquamacs Emacs
--
-- In order for the script to work properly, Emacs server must be running. Add a line like (server-start) to your ~/.emacs file.
property EMACS_APP : "Emacs"
property EMACSCLIENT : "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient"
on run
set man_page to ""
tell application EMACS_APP
activate
set man_page to text returned of (display dialog "Man page:" default answer "")
end tell
display_man_page(man_page)
end run
on display_man_page(man_page)
set form to "(manual-entry \"" & man_page & "\")"
tell_emacs(form)
end display_man_page
on tell_emacs(form)
tell application EMACS_APP to activate
try
do shell script quoted form of EMACSCLIENT & space & "--eval" & space & quoted form of form
on error (e)
tell application EMACS_APP to display dialog ("Error: " & (ASCII character 10) & (ASCII character 10) & e) buttons {"Cancel"} default button "Cancel"
end try
end tell_emacs
Update July 28th: Thank you to Reddit user gst for linking to this post.
Leave a Reply