Two modes on loading a file

Table of Contents

** This question was posted to the emacs stackexchange. 1

Clojure files should open in Clojure-mode. I also have Clojure files that contain color info and are used to generate my styles; they live under a /styles path. For these files, I want them to have both clojure-mode (a major mode) and rainbow-mode (a minor mode). I can implement this on a file-by-file basis be starting such files with a line like this:

;; -*- eval: (rainbow-mode) -*-

But I make and use enough of these files, I tried the following:

(use-package rainbow-mode
:mode "css\\|style")

Which adds that line to the top of auto-mode-alist. But that causes the auto-mode to no longer match my clojure files if they dwell under a style/* directory; it enables the rainbow minor mode and stops there. Is there a simple solution for getting both of these modes to load on clj files that are also under a style/ dir without having to preface every such file with the eval line?

Answer

Thanks to @phils, with a helpful suggestion from @mmmmmm , a matching hook will do it. There is also some good advice for using dirlocal variables that can be written to apply to anything down the directory tree – but I wanted this without needing to add any code to my projects. This answer does it! Also, cool use of and instead of an if or when control layer.

(add-hook 'clojure-mode-hook #'my-clojure-mode-hook)

(defun my-clojure-mode-hook ()
  "Custom `clojure-mode' behaviours."
  (and buffer-file-name
       (string-match "/\\(?:style\\|css\\)/" buffer-file-name)
       (rainbow-mode 1)))

Footnotes

1 Stackexchange question: https://emacs.stackexchange.com/questions/66236/how-to-enable-a-major-a-minor-mode-on-loading-a-file

Tory Anderson avatar
Tory Anderson
Full-time Web App Engineer, Digital Humanist, Researcher, Computer Psychologist