Directory local variables

Posted: August 14, 2007 in Emacs

You probably know file local variables. If not read (info "(emacs)File Variables"). They’re quite handy if you work on projects that use different coding conventions, e.g. some indent with tabs and others don’t. The problem with this approach is that it requires you to modify the files.

To escape this restriction I came up with this:

(defvar th-dir-local-variables-alist
  '(("~/repos/gnus/" . ((indent-tabs-mode . t)
                        (tab-width . 8))))
  "An alist with (PATH . LIST) pairs.  PATH is a path and LIST is
a list of variables to set locally for files below that path.  It
has elements of the form (VAR . VAL) where VAR is a symbol and
VAL is its value.")

(defun th-set-dir-local-variables ()
  "Locally set the variables defined in
`th-dir-local-variables-alist' for the current buffer."
  (interactive)
  (let ((file (buffer-file-name (current-buffer))))
    (when file
      (dolist (pair th-dir-local-variables-alist)
        (when (string-match (concat "^" (regexp-quote (expand-file-name (car pair))))
                            file)
          (dolist (var (cdr pair))
            (if (local-variable-if-set-p (car var))
                (set (car var) (cdr var))
              (set (make-local-variable (car var)) (cdr var)))))))))

(add-hook 'find-file-hook
          'th-set-dir-local-variables)
Advertisements
Comments
  1. anon says:

    There also is Tom Tromey’s project.el, which may appear in the main Emacs distribution someday.

  2. Tassilo Horn says:

    That looks nice, too. But till it’s included I’ll stay with my simple approach.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s