Make Emacs use Racket mode for files with non-standard extensions
Emacs just doesn’t get it
When I hack Racket code, if I’m not in DrRacket you can find me using Greg Hendershott’s racket-mode in Emacs. Upon installing this package, Emacs automatically enables Racket mode for files, provided their file extension is
.rktl. That’s quite sensible and works nearly all the time.
But what if the Racket file you’re hacking doesn’t have one of these standard Racket extensions? Emacs has no clue. It lands you in fundamental mode, or some unintended mode. You have do manually do M-x racket-mode. There’s got to be a better way.
Non-standard Racket file extensions
Consider Pollen. Standard file extensions there are
.pm. In most cases, these files are straightforward Pollen files; they begin with
#lang pollen, which, for me, triggers Junsong Li’s
pollen-mode. This works, again, nearly all the time.
But sometimes I code Prolog, and I’ve already got things set up so that
.p files are opened in
prolog-mode. Likewise, in Pollen,
.pm files come up all the time. But, since I’m also a Perl hacker, I’ve set up Emacs to turn on perl-mode (because
.pm is often used for Perl modules).
Perhaps you’re not a Pollen writer but you do use another one of Racket’s domain-specific languages, but your code there is, more or less, Racket code (at least from a text editor’s point of view). You use a file extension other than
What to do?
Magical thinking to the rescue
Here’s a simple way to turn on Racket mode based not on the file extension, but on the presence of
#lang racket at the beginning of a line somewhere in the file. The trick is to use the
(add-to-list 'magic-mode-alist '("^#lang racket" . racket-mode))
Add that code to your
.emacs file. The next time Emacs starts up and finds
at the beginning of a line in your file, it will switch to Racket mode.
Bonus Emacs hackery: If you want your change to take effect without restarting Emacs, evaluate that little code snippet: put your cursor just after the two right parentheses
)), type C-x C-e, and you’re ready to rock.