diff --git a/zsh/.zshrc b/zsh/.zshrc index 8ea233f..f883383 100644 --- a/zsh/.zshrc +++ b/zsh/.zshrc @@ -167,6 +167,66 @@ if [[ "$INSIDE_EMACS" = 'vterm' ]]; then alias ff='find_file' fi +# Utility function that will open a file or let contents get piped into Emacs. +# Borrowed from: https://www.reddit.com/r/emacs/comments/fk7p49/comment/fkrr5i2 +# Allow piping to a buffer +function e () { + local EMACSOPT="" + + FILES=() + while [[ $# -gt 0 ]]; do + key="$1" + case $key in + -*) EMACSOPT+="$key "; shift;; + *) FILES+=("$key"); shift;; + esac + done + + # No options given, make our best guess + if [[ ! "${EMACSOPT}" ]]; then + if [[ "$INSIDE_EMACS" ]]; then + EMACSOPT="" + elif [[ "$DISPLAY" ]]; then + EMACSOPT="-c " + else + EMACSOPT="-nw " + fi + fi + + if [ -p /dev/stdin ]; then + # Input is a pipe, set up temp file + TMP="$(mktemp)" + cat > $TMP + FILES+=("$TMP") + elif [[ -z "$FILES" && -p /dev/stdout ]]; then + TMP="$(mktemp)" # piping out needs a temp file + FILES+=("$TMP") + fi + + for FILE in "${FILES[@]}"; do + FILE=$(readlink -f "${FILE}") # Absolute file path + if [[ -p /dev/stdout || "$EMACSOPT" || "$TMP" ]];then + emacsclient -q ${EMACSOPT} "$FILE" ; + else + if [[ $SSH_CONNECTION ]]; then + emacsclient -q -e "(find-file-other-window \"/ssh:${ssh_hostname}:$FILE\")"; + else + emacsclient -q -e "(find-file-other-window \"$FILE\")"; + fi + fi + + if [ -p /dev/stdout ]; then + # Output is a pipe + cat $FILE + fi + done + + if [[ ! -z "$TMP" && -f "$TMP" ]]; then + # Cleanup tmp files + rm $TMP + fi +} + # This is to change the title of the buffer based on information provided by the # shell. See, http://tldp.org/HOWTO/Xterm-Title-4.html, for the meaning of the # various symbols.