What is a good way to assign a function to run when I open any file in a specified directory? Just like a hook but based on the location of a file rather than a major mode.

It would be nice if I could enable this by having a special file in the directory, but adding the hook in my central config file would be good too.

3 Answers 3


find-file-hook, and in your hook function, check whether the candidate file is in the given directory.

  • Yep, that looks like it'll work. I just couldn't find that specific hook via Google. Jun 25, 2015 at 23:15
  • 4
    Ask Emacs, not Google. M-x apropos-variable RET file hook.
    – Drew
    Jun 26, 2015 at 5:06

This sounds like what directory local variables are for. Just create a .dir-locals.el file in the directory with the settings you want, and every file will inherit those settings.

  • This option has the advantage of not hardcoding the settings and relevant directories in the main configuration file.
    – T. Verron
    Jun 26, 2015 at 12:04
;;; .dir-locals.el

  (eval add-hook 'find-file-hook (lambda ()
                                   (message "my find-file hook called...")) nil t)))

The nil means this applies to all files in the directories bellow .dir-locals.el.

The t passed to add-hook makes find-file-hook buffer-local. Therefore the hook runs only for this file.

dir-locals runs before find-file-hook, so the whole thing works.

  • 2
    Welcome to mx.sx! The idea is good, and I think @erikstokes 's answer would benefit from an example, but it seems that your example is incorrect: after a file is opened in the directory, the function will be added to find-file-hook, and executed for all files that are opened afterwards, won't it?
    – T. Verron
    Jun 26, 2015 at 12:04
  • Why not run the code directly ?
    – politza
    Jun 27, 2015 at 13:18

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.