JS0
JS0

Reputation: 173

How to set default major mode in directory-local file?

for some complex reason, I would like to open files in certain directory (can have any name, no extension) in C mode, and I don't want to modify them for Emacs (file-local variables are out). I am struggling with Emacs to do it, however. I tried to put this into my dir-locals.el:

((nil . ((major-mode . c-mode))))

Although the major-mode variable is indeed overridden to c-mode when I open file from that directory, the C mode is not enabled on the buffer. What's going on and how do I make it apply?

Alternatively, I could add to the auto-mode-alist just for this directory, but I don't know how to do that via directory locals.

Also, is there some easy way to cause execution of code from dir-locals.el? I know it's unsafe, but it could even be the code that is in config - the point is to call it only when variables from dir-locals are processed (opening a file).

Thanks for help.

Upvotes: 12

Views: 2197

Answers (3)

Nicolas Dudebout
Nicolas Dudebout

Reputation: 9262

Apart from eval, there is also another special variable named mode which can help you. It is the same variable used by file-local variables. You could also write:

((nil . ((mode . c))))

Upvotes: 14

Nicolas Dudebout
Nicolas Dudebout

Reputation: 9262

In .dir-locals.el you can only set variables to a certain value. What your code does is set the major-mode variable to the c-mode value. However, this is not the way a mode is activated. To activate it you need to call the function c-mode. There is a special variable that you can set in .dir-locals.el to run a function: eval.

Therefore, the following code works:

((nil . ((eval . (c-mode)))))

Upvotes: 8

user2141046
user2141046

Reputation: 902

i can't answer your first question (and in fact, will like to hear the answer for that myself) but fir the auto-mode-alist you can have

(setq auto-mode-alist (cons '("<your dir path here>\." . c-mode) auto-mode-alist))`

this should give you the result you want

Upvotes: 2

Related Questions