It’s now easier than ever to write major modes in Emacs. If you haven’t written a major mode in a while, or you’re just starting out, here are my three top tips:
As of Emacs 24,
regexp-opt takes a
'symbols option. You should write
your font-lock keywords like this:
This has two advantages. By whitelisting keywords, users can quickly spot mistakes when editing:
This also prevents a classic bug where Emacs highlights substrings that happen to be keywords:
(Don’t) use company
Company is excellent, and I highly recommend it. However, not all Emacsers use company. You don’t need to force company on your users.
Instead, you can use
completion-at-point-functions. Your completion functionality will
work in stock Emacs, and company users will benefit too through
Ah, but what about all the extra annotations you can supply to company? We can have our cake and eat it too:
Test with assess
Historically, it’s been rather awkward to test major modes. Many authors didn’t bother.
That’s all changed with the release of assess. Assess provides great assertions with readable error messages.
For example, here’s a simple indentation test from cask-mode:
Highlighting is particularly helped by assess:
If this test fails, we get a helpful message describing which faces were actually used:
These tips are all new things I’ve learnt writing a new major mode for Cask files. If you’re just getting started with Emacs development, check out adding a new language to Emacs. Finally, if I’ve missed your favourite tip, leave a comment on the /r/emacs discussion!