emacsclient.sh 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. # Adapted 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. # Create a tempfile to hold stdin
  24. tempfile="$(mktemp --tmpdir emacs-stdin-$USERNAME.XXXXXXX 2>/dev/null \
  25. || mktemp -t emacs-stdin-$USERNAME)" # support BSD mktemp
  26. # Redirect stdin to the tempfile
  27. cat - > "$tempfile"
  28. # Reset $2 to the tempfile so that "$@" works as expected
  29. set -- "$1" "$tempfile" "${@:3}"
  30. fi
  31. emacsfun "$@"