21

I'd like to run a hook for specific file extensions (i.e. not modes). I have zero experience with elisp, so I cargo-cult coded this:

(defun set_tab_mode ()
    (when (looking-at-p "\\.cat")
    (insert "OK")
    (orgtbl-mode)))

(add-hook 'find-file-hook 'set_tab_mode)

(Should set orgtbl minor mode for files with suffix .cat and insert text "OK", i.e. it's not only a mode setting question). Unfortunately it does not work.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
user673592
  • 2,090
  • 1
  • 22
  • 37

2 Answers2

28

You can use lambda in auto-mode-alist:

(add-to-list 'auto-mode-alist
             '("\\.cat\\'" . (lambda ()
                               ;; add major mode setting here, if needed, for example:
                               ;; (text-mode)
                               (insert "OK")
                               (turn-on-orgtbl))))
Victor Deryagin
  • 11,895
  • 1
  • 29
  • 38
  • 1
    He's trying to set a minor mode though, you're method only works for major modes unfortunately. – bneil Nov 06 '12 at 01:36
  • 3
    @bneil you can put arbitrary code in lambda, no matter if it sets major mode, minor mode or does some other thing. – Victor Deryagin Nov 06 '12 at 07:25
  • I was looking for a way to turn on two modes at once for a given file type, and while I knew about `auto-mode-alist`, I did not know you could use `lambda`s with it. This worked for me, thanks! – Scott Weldon Aug 31 '14 at 05:44
  • Even if you used this to set a minor mode, wouldn't it override the associated major mode? – Nick McCurdy Aug 25 '17 at 00:06
21

Try this:

(defun my-set-tab-mode ()
  (when (and (stringp buffer-file-name)
             (string-match "\\.cat\\'" buffer-file-name))
    (insert "OK")
    (orgtbl-mode)))

(add-hook 'find-file-hook 'my-set-tab-mode)
yibe
  • 3,939
  • 2
  • 24
  • 17