How can I cons a list of pairs on to auto-mode-alist?

elisp, emacs

Solution

You only need a single regexp (and hence entry in `auto-mode-alist`) to match all those options, and you can let `regexp-opt` do the work of building it for you.

(let* ((ruby-files '(".rake" ".thor" "Gemfile" "Rakefile" "Crushfile" "Capfile"))
       (ruby-regexp (concat (regexp-opt ruby-files t) "\\'")))
  (add-to-list 'auto-mode-alist (cons ruby-regexp 'ruby-mode)))

If you especially want individual entries, you might do something like this:

(mapc
 (lambda (file)
   (add-to-list 'auto-mode-alist
                (cons (concat (regexp-quote file) "\\'") 'ruby-mode)))
 '(".rake" ".thor" "Gemfile" "Rakefile" "Crushfile" "Capfile"))

Problem

I have a long list of files and file extensions which I would like to have Emacs open automatically in ruby-mode. From using Google, the most basic solution that works is this: ``` (setq auto-mode-alist (cons '("\.rake$" . ruby-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("\.thor$" . ruby-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("Gemfile$" . ruby-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("Rakefile$" . ruby-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("Crushfile$" . ruby-mode) auto-mode-alist)) (setq auto-mode-alist (cons '("Capfile$" . ruby-mode) auto-mode-alist)) ``` Which seems way repetitive to me. Is there a way I could define the list of pairs once and either loop or cons it directly onto `auto-mode-alist`? I've tried ``` (cons '(("\\.rake" . ruby-mode) ("\\.thor" . ruby-mode)) auto-mode-alist) ``` but that doesn't seem to work. Any suggestions?

Original source