Parent directory

emacsclient.sh

1409 bytes
 1#!/bin/sh
 2
 3emacsfun() {
 4  local cmd frames
 5
 6  # Build the Emacs Lisp command to check for suitable frames
 7  # See https://www.gnu.org/software/emacs/manual/html_node/elisp/Frames.html#index-framep
 8  case "$*" in
 9  *-t*|*--tty*|*-nw*) cmd="(memq 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are tty frames
10  *) cmd="(delete 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are graphical terminals (x, w32, ns)
11  esac
12
13  # Check if there are suitable frames
14  frames="$(emacsclient -a '' -n -e "$cmd" 2>/dev/null |sed 's/.*\x07//g' )"
15
16  # Only create another X frame if there isn't one present
17  if [ -z "$frames" -o "$frames" = nil ]; then
18    emacsclient --alternate-editor="" --create-frame "$@"
19    return $?
20  fi
21
22  emacsclient --alternate-editor="" "$@"
23}
24
25# Adapted from https://github.com/davidshepherd7/emacs-read-stdin/blob/master/emacs-read-stdin.sh
26# If the second argument is - then write stdin to a tempfile and open the
27# tempfile. (first argument will be `--no-wait` passed in by the plugin.zsh)
28if [ $# -ge 2 -a "$2" = "-" ]; then
29  # Create a tempfile to hold stdin
30  tempfile="$(mktemp --tmpdir emacs-stdin-$USERNAME.XXXXXXX 2>/dev/null \
31    || mktemp -t emacs-stdin-$USERNAME)" # support BSD mktemp
32  # Redirect stdin to the tempfile
33  cat - > "$tempfile"
34  # Reset $2 to the tempfile so that "$@" works as expected
35  set -- "$1" "$tempfile" "${@:3}"
36fi
37
38emacsfun "$@"