emacsmajor-modeminor-mode

How to use the same file extension with different modes?


I have files with a .new extension that contain LaTeX code (they are the output of a program that does things on the original .tex source).

In order to check them I need that they have the LaTeX syntax highlighted and that they can be opened in read-only mode to avoid introducing errors. So I put these lines in my .emacs:

(setq auto-mode-alist
      (append '(("\\.new\\'" . read-only-mode)
                ("\\.new\\'" . latex-mode))
          auto-mode-alist))

But it does not work as expected because only the first mode is applied. How can I force emacs to apply both read-only-mode and latex-mode to the same file extension?


Solution

  • An easy solution is to associate your file extension with a custom derived major mode:

    (define-derived-mode read-only-latex-mode latex-mode "LaTeX"
      "Major mode for viewing files of input for LaTeX."
      (read-only-mode 1))
    
    (add-to-list 'auto-mode-alist '("\\.new\\'" . read-only-latex-mode))
    

    The new read-only-latex-mode does everything that latex-mode does (including running latex-mode-hook if you're already using that), but it additionally enables read-only-mode after all of the parent mode's actions have taken place.

    Any other code which cares about the major mode being latex-mode should already be testing that using the standard approach of (derived-mode-p 'latex-mode) which is still true for this new mode; so in principle this approach should Just Work.