13

I know that emacs can recognize a file by the extension, a -*- mode -*- first line, and even by the shebang line, but what do I do if I want to override the shebang?

For example, a script that starts with

#!/usr/bin/env python2.7
...

won't be recognized by the shebang line alone. I also can't add in a -*-python-*- line, because then the shell tries to parse it. How do I deal with this?

Community
  • 1
  • 1
Shep
  • 7,990
  • 8
  • 49
  • 71

3 Answers3

14

You put the -*- mode: python -*- in the second line (special exception, added specifically for the shebang thingies).

Stefan
  • 27,908
  • 4
  • 53
  • 82
9

You can try putting something like

(add-to-list 'interpreter-mode-alist '("python2.7" . python-mode))

in your .emacs. See “Choosing File Modes” for more info.

KrzysiekJ
  • 186
  • 4
  • I can't get this to work by pasting this line directly into my `.emacs` file. Do you expect something _like_ this to work, or should this work? – Shep Aug 11 '13 at 14:52
  • I didn’t test it, but I did some experiments and I think it should work. You need to restart Emacs or evaluate that line to apply the change. – KrzysiekJ Aug 11 '13 at 16:04
  • This worked for me. I just had to evaluate it... naturally... since this is how all Emacs config works. – Tim Harper May 23 '18 at 21:38
  • Great, no need to add extra/special lines to the file. I needed this to open bash scrips in `sh-mode`: ``(add-to-list 'interpreter-mode-alist '("#!/bin/bash" . sh-mode))`` and found here how to do it. – AstroFloyd May 03 '20 at 09:34
3

Like this:

#!/usr/bin/env python2.7

print "test"

# Local Variables:
# mode: python
# End:

This information comes from Specifying File Variables node of info.

  1. Use f1 i to enter info.
  2. Use g (emacs) to jump to emacs info.
  3. Use g Specifying File Variables to jump to the page. You can use tab to complete node names.
abo-abo
  • 20,038
  • 3
  • 50
  • 71
  • is the `print "test"` line needed? – Shep Aug 11 '13 at 14:14
  • print "test" isn't needed, of course, it's just some python code to make sure that font-lock is on. If this doesn't work, you need to upgrade your Emacs. The current version is 24.3 – abo-abo Aug 11 '13 at 14:25
  • in what version of emacs was this added? I'm not sure if it's worth upgrading if I'm already running version where it should work. (I'm using 23.3) – Shep Aug 11 '13 at 14:37
  • Here's the link http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html. If this is not in your `info`, you don't have it. – abo-abo Aug 11 '13 at 14:38
  • if what is not in my info? What's my info? – Shep Aug 11 '13 at 14:53
  • it's there in my `info`, but I still can't get it working. Oddly a simple `-*- mode: python -*-` does the trick. – Shep Aug 11 '13 at 15:29