BNF-mode

I do a lot of writing and editing of context-free grammars in BNF format, eg for my work on Grammatical Evolution (examples here and here).

I was amazed to find that there’s no Emacs mode for editing BNF. Here’s a small contribution which does some syntax highlighting. It also lives at EmacsWiki.

(define-generic-mode 'bnf-mode
  () ;; comment char: inapplicable because # must be at start of line

  nil ;; keywords

  '(
    ("^#.*" . 'font-lock-comment-face) ;; comments at start of line

    ("^<.*?>" . 'font-lock-function-name-face) ;; LHS nonterminals

    ("<.*?>" . 'font-lock-builtin-face) ;; other nonterminals

    ("::=" . 'font-lock-warning-face) ;; "goes-to" symbol

    ("\|" . 'font-lock-warning-face) ;; "OR" symbol

    ("\{:\\|:\}" . 'font-lock-keyword-face) ;; special pybnf delimiters

    )
  '("\\.bnf\\'" "\\.pybnf\\'") ;; filename suffixes

  nil ;; extra function hooks

  "Major mode for BNF highlighting.")

Installation

Paste it into your .emacs file and execute it with C-x C-e. When you edit a .bnf file, it will automatically go into BNF-mode.