index rss mastodon twitter github linkedin email
Álvaro Ramírez
sponsor

Álvaro Ramírez

11 July 2021 macOS: Show in Finder / Show in Emacs

From Christian Tietze's Open macOS Finder Window in Emacs Dired, I learned about reveal-in-osx-finder. This is handy for the few times I want to transition from Emacs to Finder for file management. I say few times since Emacs's directory editor, dired, is just awesome. I've written about dired customizations here and here, but since dired is just another buffer, you can apply your Emacs magic like multiple cursors to batch rename files in an editable dired buffer.

To transition from macOS Finder to Emacs, Christian offers an Emacs interactive command that fetches Finder's location and opens a dired buffer via AppleScript. On a similar note, I learned from redditor u/pndc that Finder's proxy icons can be dragged over to Emacs, which handily drops ya into a dired buffer.

With these two solutions in mind, I looked into a third one to offer a context menu option in Finder to show the file in Emacs. This turned out to be fairly easy using Automator, which I've rarely used.

show_in_emacs.gif

I created a flow that runs a shell script to "Show in Emacs", revealing the selected file or folder in an dired buffer. This is similar to Christian's solution, but invoked from Finder itself. The flow also uses dired-goto-file which moves the point (cursor) to the file listed under dired.

show_in_emacs.png

current_dir=$(dirname "$1")
osascript -e 'tell application "Emacs" to activate'
path/to/emacsclient --eval "(progn (dired \"$current_dir\") (dired-goto-file \"$1\"))"

As a bonus, I added an "Open in Emacs" option, which does as it says on the tin. Rather than show the file listed in a dired buffer, it gets Emacs to open it in your favorite major mode. This option is not technically needed since Finder already provides an "Open With" context menu, but it does remove a few click here and there.

open_in_emacs.png

osascript -e 'tell application "Emacs" to activate'
/Users/alvaro/homebrew/bin/emacsclient --eval "(find-file \"$1\")"

On a side note, Emacs defaults to creating new frames when opening files via "Open With" menu (or "open -a Emacs foo.txt"). I prefer to use my existing Emacs frame, which can be accomplished by setting ns-pop-up-frames to nil.

(setq ns-pop-up-frames nil)