emacsclient.sh 1.2 KB

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