2012-06-14 36 views
3

我有一長串文件和文件擴展名,我希望Emacs以ruby模式自動打開。從使用谷歌,最基本的解決方案是這樣的:如何將自動模式對的列表對齊?

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

這似乎對我來說是重複的。有沒有一種方法可以定義對的列表一次,並循環或直接將其放在auto-mode-alist?我試過

(cons '(("\\.rake" . ruby-mode) 
     ("\\.thor" . ruby-mode)) auto-mode-alist) 

但這似乎並不奏效。有什麼建議麼?

回答

4

你只需要一個單一的正則表達式(並因此在auto-mode-alist條目)匹配所有這些選項,並且您可以讓regexp-opt爲您構建它。

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

如果你特別想個別項目,你可能會做這樣的事情:

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

謝謝!一個問題 - 「let」和「let *」有什麼區別? – bitops

+1

使用'let *',每個本地綁定表達式都可以看到列表中以前表達式生成的本地綁定。在這種情況下,我需要查看'ruby-files'來設置'ruby-regexp'。參見:'C-h f let * RET'與'C-h f let RET'。 – phils

1

cons需要一個項目和一個列表,並返回一個新的列表與該項目的頭部。 (例如(cons 1 '(2 3))'(1 2 3)

你想要做的是採取一個列表,列表和append在一起

(setq auto-mode-alist 
    (append '(("\\.rake" . ruby-mode) 
      ("\\.thor" . ruby-mode)) 
    auto-mode-alist)) 
+3

你應該調整你的榜樣,這樣的'返回值append'實際上被分配給'auto-mode-alist'。 –

+0

@MoritzBunkus我的例子是仿照原始帖子(他沒有分配cons的結果) – cobbal

+0

那麼,他不能使用'append'的結果作爲他的'add-to-list'的參數,所以你的論點對我來說沒有多大意義。爲什麼不提供一個完整的工作示例?這不是那麼多的工作。 –

1

我最喜歡的是

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