Skip to content

Instantly share code, notes, and snippets.

@shuxiao9058
Forked from d12frosted/Tuto.md
Created April 19, 2018 08:59
Show Gist options
  • Save shuxiao9058/00cfe9fe2fd0143605b9b14e498dc745 to your computer and use it in GitHub Desktop.
Save shuxiao9058/00cfe9fe2fd0143605b9b14e498dc745 to your computer and use it in GitHub Desktop.
Starting Emacs in GUI with shell environment variables correctly set

Problem

When starting Emacs.app on Mac, the Emacs doesn't have some environment variable set correctly. Typically it is terrible when you use GPG, pinentry-mac, gpg-agent But also a lot of different variables used to make git works correctly, etc...

Solution

  1. Create the file ~/bin/init-app-env.sh:

    #!/usr/bin/env zsh
    source ~/.zshrc
    for i in $(export); do
        var=$(echo $i|sed 's/=.*//')
        val=$(echo $i|sed 's/^[^=]*=//')
        [[ $val != "" ]] && {
            launchctl setenv $var $val
        }
    done

    If you use bash you can safely replace zshrc by bashrc in the script.

  2. Create a file ~/Library/LaunchAgents/com.user.loginscript.plist (replace ME by your login name):

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    	<dict>
    		<key>Label</key>
    		<string>com.user.loginscript</string>
    		<key>Program</key>
    		<string>/Users/ME/bin/init-app-env.sh</string>
    		<key>RunAtLoad</key>
    		<true/>
    	</dict>
    </plist>
  3. Run in a Terminal

    launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist
    

Congrats!

Now at each login the script will run with your zsh environment. Beware, it can take a few seconds before the script is launched. So don't rush to launch Emacs.app just after login.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment