How can I use a different theme (or color scheme) for files in a specific directory?

Currently in my system, a single theme is applied to all buffers. The theme is chosen in ~/.emacs as

(load-theme 'zenburn t)

I would like to use this theme by default, but I would like to use a different one when I visited a file in the specific directory. When I switch to a buffer not associated with a file in this directory, I would like the theme to go back to the default.

1 Answer 1


Generally, if you want to call some function on opening a buffer from some specific directory, then you can use .dir-locals.el, e.g. you could use the following definitions:

((nil . ((eval (lambda () (load-theme 'zenburn t)))
         (eval (lambda () (add-hook 'kill-buffer-hook (lambda ()
                                                        (disable-theme 'zenburn))
                                    nil t))))))

However, this switches the theme only on creating or killing the buffer.

Therefore, to make it load/disable a theme on switching to/from the buffer you could use the following (hook-)function:

(defun conditionally-switch-theme ()
  (when buffer-file-name
    (if (string= (file-name-directory buffer-file-name)
        (load-theme 'zenburn t)
      (disable-theme 'zenburn))))

(add-hook 'window-configuration-change-hook #'conditionally-switch-theme)

Finally, loading a theme does not disable the currently enabled themes. But as that is often not really necessary, I did not bother to sort it out. But if some things are not working as expected, then add some logic to remember the current custom-enabled-themes, disable them before loading the 'local' theme on entering the buffer, and enable the themes in the stored value of the previous custom-enabled-themes after disabling the 'local' theme when leaving the buffer (see also Custom themes in the Emacs manual).

  • 1
    The window-configuration-change-hook isn't perfect, but I think it does do the job well enough. I am not sure which hook could be used better otherwise, e.g. I think pre/post-command-hook is too 'aggressive'. Anyway, you have a good start now to investigate further the available options, (incl. e.g. adding logic). Mar 21 at 11:50

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.