windrg00
windrg00

Reputation: 457

Dynamic project-wide variable in Emacs

I'd like to have a project-wide variable which I can change during looking at that project. In other words, I'd like to get it affected whenever opening a file. Yes, I know .dir-locals.el exist in Emacs world. But I think it would be reset to the value set in .dir-locals.el whenever opening a file under that project.

Could I get some hints from you, please?

Upvotes: 2

Views: 245

Answers (2)

Drew
Drew

Reputation: 30701

For this kind of thing you might want to use a function instead of a variable (directly). Specifically, use a getter and setter function.

All of your project code can invoke the getter function to get the value (which can be cached in a variable). And all of your code can invoke the setter function to change the value (which, again, can be cached in a variable).

These functions can be visible globally to your project. The cache variable would be accessed only by the getter and setter functions.


But as for code everywhere in your project being informed when the value gets updated and do what's appropriate with the new value whenever that happens, see @Phil's comment about the use of a variable - the same considerations apply.

You can have a hook in the setter function (or advise it), so that it does something additional (e.g. informs interested/subscribed code) whenever it updates the value.


For a variable you can do something similar using, as @Phils said in a comment, using add-variable-watcher.

For a user-option variable you can do something similar using :set and :get functions in the defcustom. (But those take effect only if changes are made using appropriate Customize functions or the Customize UI.)

Upvotes: 2

Rorschach
Rorschach

Reputation: 32426

You can eval in the dir-locals.el So, if you have a variable my-var that you want to be able to change with setq you could do something like

((nil . ((eval . (or (boundp 'my-var) (setq my-var 'default))))))

There are warnings about using eval in a dir-local though, since any code could be run there.

Upvotes: 1

Related Questions