tags:

views:

288

answers:

3

I have to edit lots of grammar files in .bnf format. Is there a mode for this in Emacs?

I've looked at CEDET's semantic package, and it seems that it USED to have a bnf-mode, but not any more. This snippet is googlable, but semantic-bnf-mode doesn't seem to exist:

(autoload 'semantic-bnf-mode "semantic-bnf" "Mode for Bovine Normal Form." t)
(add-to-list 'auto-mode-alist '("\\.bnf$" . semantic-bnf-mode))
+6  A: 

The Semantic bnf mode was for its own internal parser format. The original 'bnf' name was a pun that ended up confusing people.

The existing Semantic modes such as wisent-grammar-mode and bovine-grammar-mode are for the grammars used by CEDET, and the original bnf-mode was similar, and did not represent a real BNF style grammar.

You are probably more interested in ebnf2ps, which translates ebnf grammars (yacc, etc) into syntax charts, though I haven't used it myself.

Eric
Thanks Eric for clearing that up. I decided to try implementing a really simple mode, just for syntax highlighting. I put this in my .emacs and it seems to work. (define-generic-mode 'bnf-mode '("#") nil '(("^<.*?>" . 'font-lock-variable-name-face) ("<.*?>" . 'font-lock-keyword-face) ("::=" . 'font-lock-warning-face) ("\|" . 'font-lock-warning-face) ) '("\\.bnf\\.pybnf\\'") nil "Major mode for BNF highlighting.")
jmmcd
+3  A: 

To be more readable and findable as an answer, jmmcd answered his own question with the following. You can find more in the emacs Help > elisp > 23.2.6 Generic Modes.


"I put this in my .emacs and it seems to work."

(define-generic-mode 'bnf-mode 
  '("#") 
  nil 
  '(("^<.*?>" . 'font-lock-variable-name-face) 
    ("<.*?>" . 'font-lock-keyword-face) 
    ("::=" . 'font-lock-warning-face) 
    ("\|" . 'font-lock-warning-face))
  '("\\.bnf\\.pybnf\\'") 
  nil 
  "Major mode for BNF highlighting.")
Don
+1  A: 

Thanks Don. I improved the code very slightly, here's a new version.

(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-const-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.")
jmmcd