creating custom modes the easy way with generic-mode





Syntax highlighting is useful when editing configuration files, programs and
so on, as it helps to prevent errors and makes it easier to quickly scan
documents.



Emacs supports syntax highlighting (font locking in emacs lingo) for many
different file types. For many common cases (e.g. editing for many programming
languages, org-mode), emacs' support goes much further than merely
colorizing keywords, and offers all kinds of 'magic' (auto-completion,
'electricity', special key bindings, …). For some other file types, at least
keywords are given some different color.



Still, there are files that are not recognized by emacs as having some
special format; these are displayed as plain text. This may be the case for
less-common configuration files, or your own specific formats.



Defining a full 'mode' for such file types can be a lot of work. Fortunately,
emacs offers a easier way: generic-mode. generic-mode defines a whole lot
of mode of modes for common formats, but also defines the
define-generic-mode macro to create your own modes.



Suppose we have a little language called foo; a typical foo-file might
look something like:




!! this is a comment
account=foo; !! another comment
user=jimmy;
password=$3cre7;





Using define-generic-mode, we can easily define a mode for this:




(require 'generic-x) ;; we need this

(define-generic-mode
'foo-mode ;; name of the mode to create
'("!!") ;; comments start with '!!'
'("account" "user"
"password") ;; some keywords
'(("=" . 'font-lock-operator) ;; '=' is an operator
(";" . 'font-lock-builtin)) ;; ';' is a a built-in
'("\\.foo$") ;; files for which to activate this mode
nil ;; other functions to call
"A mode for foo files" ;; doc string for this mode
)




Now, this will look something like this (if necessary, see the colorized version):




!! this is a comment
account = foo; !! another comment
user = jimmy;
password = $3cre7;




No comments:

Post a Comment

Followers

Popular Posts