Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

elisp

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?

like image 559
bitops Avatar asked Feb 20 '23 04:02

bitops


2 Answers

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"))
like image 128
phils Avatar answered Feb 28 '23 02:02

phils


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))
like image 29
cobbal Avatar answered Feb 28 '23 02:02

cobbal