Wednesday, April 20, 2016

Mac OS vs Emacs: Getting on the right (exec) PATH

One of the minor annoyances about using Emacs on Mac OS is that the PATH environment variable isn't set properly when you launch Emacs from the GUI (that is, the way we always do it). This is because the Mac OS GUI doesn't really care about the shell as a way to launch things, but if you are using brew, or other packages that install command line tools, you do.

Apple has changed the way that the PATH is set over the years, and the old environment.plist method doesn't actually work anymore, for security reasons. For the past few releases, the official way to properly set up the PATH is to use the path_helper utility program. But again, that only really works if your shell profile or rc file is run before you launch Emacs.

So, we need to put a bit of code into Emacs' site_start.el file to get things set up for us:

(when (file-executable-p "/usr/libexec/path_helper")
  (let ((path (shell-command-to-string
        "eval `/usr/libexec/path_helper -s`;
echo -n \"$PATH\"")))
    (setenv "PATH" path)
    (setq exec-path (append (parse-colon-path path)
                    (list exec-directory)))))

This code runs the path_helper utility, saves the output into a string, and then uses the string to set both the PATH environment variable and the Emacs exec-path lisp variable, which Emacs uses to run subprocesses when it doesn't need to launch a shell.

If you are using the brew version of Emacs, put this code in /usr/local/share/emacs/site-lisp/site-start.el and restart Emacs.

No comments: