tags:

views:

82

answers:

4

how can I write, as a comment within a file, the mode that this particular file should be opened with in emacs? for example, suppose I have a script called "foo". In the body of foo, I'd like to put something like:

# sh-mode
# rest of my script here...

to emacs that "sh-mode" should be used when "foo" is opened in emacs. Note, I don't want to do this by file extension from .emacs. The point here is that the filename of "foo" does not say what type of file it is -- I want that to be specified from within the file itself. Is there a way to do this?

Thanks.

+7  A: 

I usually add something like:

# -*- mode: sh -*-

at the top of the file. See the emacs documentation for more information.

Zach Hirsch
you can also add ### Local Variables: ### mode: latex ### End:`at the end of the file
Rémi
+1  A: 

Also see magic-mode-alist.

magic-mode-alist is a variable defined in `files.el'.

Documentation:
Alist of buffer beginnings vs. corresponding major mode functions.
Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
After visiting a file, if REGEXP matches the text at the beginning of the
buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
major mode.

If FUNCTION is nil, then it is not called.  (That is a way of saying
"allow `auto-mode-alist' to decide for these files.")
Cheeso
+3  A: 

you can specify file local variable that emacs uses in either the first or second line of any file(and more).

For more details see: http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables

So for your case you can use:

# -*- mode: sh; -*-

Enjoy!

Anatoly Fayngelerin
+4  A: 

Note also that Emacs will also correctly identify the type of the file if the first line is a hash-bang comment, e.g.

#!/bin/sh
sanityinc