Directory shortcuts in emacs buffer

The Emacs component that's responsible for expanding ~ in file names is expand-file-name. Unfortunately, it's written in C, and deep inside its bowels is code that assumes that what comes after ~ is a user name. Fortunately, Emacs has a generic way of adding a wrapper around functions, so you can do what you want if you don't mind repeating some of the logic in the built-in function.

Here's some completely untested code that should get you going. Look up “Advising Emacs Lisp Functions” in the Emacs Lisp manual for more information; the basic idea is that defadvice adds some code to run before the actual code of expand-file-name. Please signal the mistakes I've inevitably made in comments (whether you know how to fix them or not).

(defvar expand-file-name-custom-tilde-alist
  '(("foo" . "/home/Documents/foo")))

(defadvice expand-file-name (before expand-file-name-custom-tilde
                             (name &optional default-directory)
                             activate compile)
  "User-defined expansions for ~NAME in file names."
  (save-match-data
    (when (string-match "\\`\\(\\(.*/\\)?~\\([^:/]+\\)\\)/" name)
      (let ((replacement (assoc (match-string 3 name) expand-file-name-custom-tilde-alist)))
        (when replacement
          (setq name (replace-match (cdr replacement) t t name 1)))))))

I'll leave parsing the shortcuts in .zshrc to fill expand-file-name-custom-tilde-alist (or whatever technique you choose to keep the aliases in synch) as an exercise.


Simply use $foo instead of ~foo in the minibuffer. Emacs will treat foo as the name of an environment variable and use its value.

Tags:

Emacs

Zsh