Shell – Tracking the shell path in Emacs

emacsshellssh

Not a long time ago, I found the following precious snippet that allows Emacs to track my current directory on any ansi-term buffer.

More specifically, if I cd <some/path> from within a terminal inside Emacs, and I then press C-x C-f, Emacs will run find-file from <some/path> directly, which is very, very handy.

if [ -n "$INSIDE_EMACS" ]; then
  chpwd() { print -P "\033AnSiTc %d" }
  print -P "\033AnSiTu %n"
  print -P "\033AnSiTc %d"
fi

However, the above trick doesn't work if I ssh to a remote machine from the shell. Ideally in this case, if I press C-x C-f Emacs should recognize that I have sshed to some machine, and use tramp to run find-file on the corresponding machine and remote path.

This takes me to the following two questions:

  1. How and why does the snippet above work?
  2. How can I extend it so that it can also track my remote paths after I ssh into another machine?

Best Answer

First, as mentioned in the comment by Robert, your snippet isn't valid. At a minimum you need either a semicolon or new line before }. The print statements are probably not correct either.

However there's enough here to guess what is going on, so I'll explain that.

When you run ansi-term, it invokes a shell with the environment variable $INSIDE_EMACS set. The shell code then does additional stuff, the main thing to redefine the function chpwd so that it prints additional stuff, which no doubt includes the current working directory. You can easily verify this by noting that on every command you probably see the current directory somewhere in the prompt area after the completion of the last command proper.

When ansi-term sees something that looks like a directory at the beginning of a line, it tracks that. So in this sense that code is not special; the directory could have been shown by any number of ways, such as adding \w to the prompt via setting environment variable PS1.

As for #2, see "Open remote file while in emacs ansi-term buffer/window: ansi-term + tramp"

Related Question