Onner Irotsab
Onner Irotsab

Reputation: 125

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?

Upvotes: 1

Views: 95

Answers (2)

phils
phils

Reputation: 73246

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.

Upvotes: 3

Stefan Kamphausen
Stefan Kamphausen

Reputation: 1665

Not sure I can really provide an answer, but here's some things to consider:

  1. read-only-mode is a minor mode, while
  2. auto-mode-alist is meant to turn on major modes. For major modes, it makes sense that you can have only one.
  3. You can put something like -*- buffer-read-only: t; -*- on your first line in the file (possibly behind some comments or shebangs, depending on the file type) which would turn on read-only-mode. Maybe automate this using auto-insert-alist and match the .new filename pattern.
  4. There's some good suggestions over at https://www.reddit.com/r/emacs/comments/jqxgiz/how_can_i_make_some_files_automatically_readonly/ , namely try file local variables and use find-file-hook

Hope some of that helps.

Upvotes: 3

Related Questions