7

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.

7

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

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

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.

| improve this answer | |
  • This option has the advantage of not hardcoding the settings and relevant directories in the main configuration file. – T. Verron Jun 26 '15 at 12:04
1
;;; .dir-locals.el

((nil
  (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.

| improve this answer | |
  • 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 '15 at 12:04
  • Why not run the code directly ? – politza Jun 27 '15 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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