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?
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"))
cons takes an item and a list and returns a new list with that item at the head. (for example (cons 1 '(2 3)) gives '(1 2 3))
What you want to do is take a list and a list and append them together
(setq auto-mode-alist
  (append '(("\\.rake" . ruby-mode)
            ("\\.thor" . ruby-mode))
   auto-mode-alist))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With