Open Magit for Current Repository from the Terminal

I’m having all my project in git repositories. And since I discovered the magic of Magit in Emacs, I sometimes want to have a familiar, interactive interface to select hunks for a commit without having to fire up a proper GUI app for stuff that I don’t already edit in Emacs.

In line with my recent idea to connect Finder and Emacs dired, I figured it might be nice to have a bash/zsh alias that visits the current directory in Emacs using Magit. (I use iTerm 2 as my terminal emulator of choice, not Emacs.)

With the emacsclient program, I can -e evaluate Lisp code from the shell. And with (magit-status PATH-TO-REPO), I can show the git repository at pwd in Magit.

After a short web search, I discovered some more elaborate aliases on Reddit and ended up combining the emacsclient invocation with a osascript call to bring Emacs to the foreground. The resulting alias is:

alias magit='emacsclient -a emacs -e "(magit-status \"$(git rev-parse --show-toplevel)\")"; if [[ -f `which osascript` ]]; then osascript -e "tell application \"Emacs\" to activate"; fi'

Split into a function for readability:

function magit () {
    git_root=$(git rev-parse --show-toplevel)
    emacsclient -a emacs \
        -e "(magit-status \"${git_root}\")"
    if [[ -f `which osascript` ]]; then
        osascript -e "tell application \"Emacs\" to activate"
    fi
}

If osascript is not found, e.g. on non-macOS systems, you won’t get an error. Looking at this for longer, it might make sense to extract an bringemacstofront alias in the future for reuse.

I don’t know how to write a “bring app window to front” for any flavor of Linux distro. Please share how you’d do that in the comments – I bet it’s different for every window manager of desktop environment anyway, but maybe there a universal X server command or something?