Article View: comp.emacs
Article #8372Re: mode by file contents
From: Ashwin Ram
Date: Wed, 25 Jan 1989 19:45
Date: Wed, 25 Jan 1989 19:45
54 lines
2779 bytes
2779 bytes
In article <GHH.89Jan25110326@thought.princeton.edu>, ghh@thought.princeton.edu (Gilbert Harman) writes:
> I would like to put something in my .emacs that would
> determine the major mode of a buffer on the basis of the
> contents of the file read into the buffer rather than on the
> basis of something about the name of the file.
>
> For example, if the file began with "\documentstyle... "
> the buffer would be automatically put into latex mode.
See if you like this. To use, put this in your ~/.emacs file:
(setq find-file-hooks '(infer-file-mode))
The function infer-file-mode uses infer-mode-alist (analogous to
auto-mode-alist) to search for a regexp within the first infer-mode-limit
characters (nil means search entire buffer). In your example, you would use:
(setq infer-mode-alist '(("\\documentstyle" . latex-mode)))
-----------------------------------------------------------------------------
;; INFER-MODE.EL -- Infer file mode based on contents.
;; Ashwin Ram, 11/5/88.
(defvar infer-mode-alist '(("\\documentstyle" . latex-mode))
"Alist of file content patterns vs corresponding major mode functions.
Each element looks like (REGEXP . FUNCTION).
Visiting a file whose which contains REGEXP within the first infer-mode-limit
characters causes FUNCTION to be called.")
(defvar infer-mode-limit 1000
"Number of characters to search when inferring mode based on file contents.
Nil means search entire buffer. See infer-mode-alist.")
(defun infer-file-mode ()
"Infer mode of file based on its contents.
To use, add this function to find-file-hooks.
To customize, see the variable infer-mode-alist."
(let ((mode-alist infer-mode-alist))
(catch 'found
(while mode-alist
(if (save-excursion
(goto-char (point-min))
(re-search-forward (caar mode-alist) infer-mode-limit t))
(throw 'found t)
(setq mode-alist (cdr mode-alist)))))
(if mode-alist
(funcall (cdar mode-alist)))))
-----------------------------------------------------------------------------
-- Ashwin.
ARPA: Ram-Ashwin@cs.yale.edu
UUCP: {decvax,ucbvax,harvard,cmcl2,...}!yale!Ram-Ashwin
BITNET: Ram@yalecs
Technical Details
Message-ID:
<48686@yale-celray.yale.UUCP>Path:
arc1-ca.pugleaf.net!utzoo!attcan!uunet!mfci!yale!Ram-AshwinReferences:
<GHH.89Jan25110326@thought.princeton.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!mfci!yale!Ram-Ashwin From: Ram-Ashwin@cs.yale.edu (Ashwin Ram) Newsgroups: comp.emacs Subject: Re: mode by file contents Message-ID: <48686@yale-celray.yale.UUCP> Date: 25 Jan 89 19:45:04 GMT References: <GHH.89Jan25110326@thought.princeton.edu> Sender: root@yale.UUCP Reply-To: Ram-Ashwin@cs.yale.edu (Ashwin Ram) Organization: Computer Science, Yale University, New Haven, CT 06520-2158 Lines: 54 In-reply-to: ghh@thought.princeton.edu (Gilbert Harman)