6

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?
  • Where is this snippet from? I tried it out in bash it didn't work. – Robert Dec 18 '14 at 16:15
  • I've never gotten into ANSI escape sequences, which is what that looks like, but I suspect your TERM variable is not getting set appropriately after you ssh into another machine. Try echo $TERM both before and after ssh'ing around and compare the results. – Jeff Schaller Jun 9 '15 at 13:59
1

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.