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

最后都变了- 提交于 2019-12-23 13:08:44

问题


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?


回答1:


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"))



回答2:


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))



回答3:


My favorite would be

(push '("\\(\\.\\(rake\\|thor\\)\\|\\(Gem\\|Rake\\|Crush\\|Cap\\)file\\)\\'" . ruby-mode) auto-mode-alist)


来源:https://stackoverflow.com/questions/11027783/how-can-i-cons-a-list-of-pairs-on-to-auto-mode-alist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!