3

I want to set variables, in particular, compile-command and tabbing related variables based on the path of the file I'm editing.

In my .vimrc I use the following to do this.

autocmd BufRead,BufNewFile */path/*.ext set tabbing-setting
autocmd BufRead,BufNewFile */path/*.ext set makeprg=build.sh

These cause vim to run the set ... commands whenever I create or read a file that matches the pattern */path/*.ext.

I don't want to use directory-local variables because I want this to live with the rest of my emacs configuration.

1 Answer 1

6

Directory-local variables were actually designed for this use case as well. Read the docs, especially at the end, where it discusses dir-locals-set-directory-class. The idea here is that you can keep the directory-local settings somewhere other than in the .dir-locals.el file.

Another way to accomplish this same thing is to make settings directory-dependent in the relevant mode hooks. For example, something like:

(defun my-set-c-style ()
  (if (buffer-file-name)
      (cond
       ((string-match "/some/random/path" (buffer-file-name))
        (c-set-style "BSD")
        (make-local-variable 'c-basic-offset)
        (setq c-basic-offset 4)))
... you get the idea

This function would be attached to c-mode-hook.

The advantage of the directory-local approach is that you can keep all the settings related to a project in one spot. The advantage of the second approach is that it can also be used for things that you can't do via directory-locals, for example binding a key.

2
  • What if I want to specify the directory with wildcards? Can a directory class be made to work with that? Or should I use the hook strategy? Commented Feb 25, 2015 at 12:06
  • There isn't a built-in way to make the directory class approach work with wildcards, so yeah, you'd have to use hooks. If it's a small list of directories, though, you can just list them all.
    – Tom Tromey
    Commented Feb 25, 2015 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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