2011/11/28: Dir-tracking. Or: how to keep pwd up-to-date for an emacs-shell

By default emacs tracks the working directory of a shell by inspecting all commands executed. This is bound to fail, if the working directory is changed by other means like a custom script, e.g., changing between a code directory and the corresponding test directory.

This was annoying me for a while till a few days ago, I decided it was too much. I (essentially) followed the emacs wiki and did the following.

I added the following line to my .emacs_bash to make the bash in emacs produce an easy to recognise prompt.


PS1="|PrOmPt|\w|\w \$ "
download

In my .emacs configuration file, I require the package dirttrack and configure the hooks in the following way to


;; shell -- dirtrack

(require 'dirtrack)
(add-hook 'shell-mode-hook
          (lambda ()
            (setq dirtrack-list '("^|PrOmPt|\\([^|]*\\)|" 1 nil))
            (dirtrack-mode nil)
            (add-hook 'comint-preoutput-filter-functions
                      'dirtrack nil t)
            (add-hook 'comint-preoutput-filter-functions
                      'dirtrack-filter-out-pwd-prompt t t)))
;; Now strip the goofy strings from the prompt before it gets into
;; the shell buffer.
(defun dirtrack-filter-out-pwd-prompt (string)
  "dirtrack-mode doesn't remove the PWD match from the prompt.  This does."
  (if (and (stringp string) (string-match (first dirtrack-list) string))
      (replace-match "" t t string 0)
    string))
download