Skip to content

Instantly share code, notes, and snippets.

@genegoykhman
Created November 3, 2019 00:27
Show Gist options
  • Save genegoykhman/5e080346ab61c499e6a811e544862866 to your computer and use it in GitHub Desktop.
Save genegoykhman/5e080346ab61c499e6a811e544862866 to your computer and use it in GitHub Desktop.
Zsh shell function 'ec' for opening emacsclient in an sshd or mosh session
#! /bin/zsh
function pid_has_ancestor_server() {
pstree -p $1 | grep $2
}
function pid_of_shell_process() {
if is_not_inside_local_tmux; then
echo "$$"
else
# current shell is under tmux
local tmux_current_session=$(tmux display-message -p '#S')
local tmux_client_id=$(tmux list-clients -t "${tmux_current_session}" -F '#{client_pid}')
# echo $tmux_current_session $tmux_client_id
echo "$tmux_client_id"
fi
}
function is_shell_parented_by_server() {
local pid=$(pid_of_shell_process)
local parent_found=$(pid_has_ancestor_server $pid $1) # or empty if not found
if [[ -z "$parent_found" ]]; then
return 1; # exit code 1: no such parent process
fi
return 0; # exit code 0: parent process found
}
function is_shell_parented_by_server() {
local pid=$(pid_of_shell_process)
local parent_found=$(pid_has_ancestor_server $pid $1) # or empty if not found
if [[ -z "$parent_found" ]]; then
return 1; # exit code 1: no such parent process
fi
return 0; # exit code 0: parent process found
}
function is_mosh() {
# Prevent grep from showing up in ps results
# by forcing regex match by putting [] around first character
# https://unix.stackexchange.com/questions/74185/how-can-i-prevent-grep-from-showing-up-in-ps-results
return $(is_shell_parented_by_server "[m]osh-server");
}
function is_sshd() {
return $(is_shell_parented_by_server "[s]shd");
}
function ec()
{
# In console mode, just open a tty into emacs
# aargh: what about when we're SSHing into Bali when
# it actually has a Emacs graphical frame running but
# we're in console mode?
if { is_sshd || is_mosh } then
emacsclient -t "$@"
else
# Open a new graphical frame if one does not exist, otherwise reuse the existing one
# From http://superuser.com/questions/358037/emacsclient-create-a-frame-if-a-frame-does-not-exist/862809#862809
found=`emacsclient -n -e "(if (> (length (frame-list)) 1) 't)" | grep t`
if [ "$found" = "t" ]; then
emacsclient -n -a "" "$@"
else
emacsclient -c -n -a "" "$@"
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment