0

I have blacken-mode enabled on all python buffers like this:

(add-hook 'python-mode-hook
          (lambda ()
            (blacken-mode 1)
            ;; other config
            ))

But on some existing projects, where black is not used, I don't want it on by default. I would like to enable blacken-mode per buffer manually.

So I attempted to disable blacken-mode in a project by adding the following .dir-locals.el:

((python-mode . ((blacken-mode . nil))))

However, the behaviour I get is strange. When I open a Python file (after marking the directory local variables as safe), edit, and save. black still reformats it, however running M-x blacken-mode RET I get the message "Blacken mode enabled in current buffer". So I have to repeat M-xblacken-modeRET, and then I get "Blacken mode disabled in current buffer", after that black does not reformat the buffer any more.

So the directory local variables are getting picked up, but it doesn't behave the way I'm expecting. What am I doing wrong?

1 Answer 1

3

Setting a variable is not enough to disable the mode: you have to call the mode function with a negative argument. You can use the eval pseudo-variable for that:

((python-mode . ((eval . (blacken-mode -1)))))

The setting of file-local (or directory-local) variables happens after the mode hook is run, so the mode turns on blacken-mode, but then we eval the expression above and turn it off again. See the function run-mode-hooks for the details of how that happens.

1
  • Thanks for the tip about run-mode-hooks :)
    – suvayu
    Dec 7, 2022 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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