8

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.

Tikhon Jelvis
  • 6,252
  • 2
  • 28
  • 41

3 Answers3

7

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

Drew
  • 77,472
  • 10
  • 114
  • 243
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.

erikstokes
  • 12,927
  • 2
  • 36
  • 56
  • 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.

  • 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