Search code examples
emacselisp

Running a function before opening/finding a file


Im trying to make a function that should run before a file is opened/shown in the buffer. This function really only needs to run once.

I try to set a mode depending on the content of the file that is about to be viewed. I know about add-to-list 'auto-mode-alist <filename-regexp> . <mode>

But this is not enough. Ideally i would want to parse the file (or just a small part of it) and check the file content before setting the mode. Usually the view-file (think .js/.php etc. in a mvc framework) has the same extension as the files in "pure" code, so i cant just check for the file extension.

Why?

Basically when using any template language i normally want to use web-mode and when doing "pure" code i want to use the mode for the language.

So basically i would want to parse the file before, and check for some regexp, and if it matches i would set web-mode and if not i would set the language-mode i want to use.

I know i can easily change modes manually, but i would rather have this done by Emacs.


Solution

  • You can use magic-mode-alist for that. You'll probably want to use a MATCH-FUNCTION which checks the buffer's file-name and its content.