Am overview of writing your own major mode

This is not meant to be a full guide on writing your own major mode but a starting point covering the main points and providing info links to further reading.

In emacs there are two kinds of modes, a major mode and minor modes, You can think of major modes as file types and minor modes as plugins. You can only have one major mode active at a time in a single buffer. [1] In your case you want a major mode that implements some kind of special functionality for your input files.

You implement modes using the define-derived-mode [2] which defines a new major mode off of some other mode, say your defining a new book format you would derive from text-mode a new programming language would derive from prog-mode and some kind of special latex mode would derive from TeX-mode for example. This means you can inherit a lot of functionality and also means a lot of things can be generalised to all modes (such as you want diagnostics in all programming modes, just add to the prog mode hook) [3]

Like I mentioned we use define-derived-mode to define our mode, It has too many arguments for me to describe so Ill leave it to the info node to describe [4] But something of importance is the syntax table [5] Essentially this is a table that tells emacs what certain chars can mean, for example we can say that ; is a comment. You can make a new syntax table using make-syntax-table [6] which then takes in a list of syntax classes [7]. This classify characters and character sets.

To get syntax highlighting we use font lock, which looks up regexes and then highlights them according to a face. [8]

TLDR I think all of this would be well illustrated by a good example though so here is one for ini mode ini-mode/ini-mode.el at 5472abc94e564edc6b469c48d2324519a044a77c · Lindydancer/ini-mode · GitHub Its 25 lines long so I think It should be somewhat accessible.

This is a lot of reading but should allow you to learn how these work in a little more depth. If not you can always look at the example and tweak it if the reading is overwhelming.

Hope this helps and if I got something wrong call me out on it please

[1]: (emacs)Top > Modes

[2]: (elisp)Top > Modes > Major Modes

[3]: (elisp)Top > Modes > Major Modes > Basic Major Modes

[4]: (elisp)Top > Modes > Major Modes > Derived Modes

[5]: (elisp)Top > Syntax Tables > Syntax Basics

[6]: (elisp)Top > Syntax Tables > Syntax Table Functions

[7]: (elisp)Top > Syntax Tables > Syntax Descriptors > Syntax Class Table

[8]: (elisp)Top > Modes > Font Lock Mode (edited)

1 Like