TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to represent a grammar where rules are numbered (for example, the following grammar: http://en.wikipedia.org/wiki/LR_parser#Additional_Example_1.2B1), in order to refer to those rules later in an action table. However, I don't find any way to do this properly. Ideally, the rules numbers would be right-aligned, like in a alignat environment.

Currently, I simply put the numbers directly in the grammar, and the output is not really readable.

My code:



\setlength{\grammarparsep}{20pt plus 1pt minus 1pt}
<E> ::= <E> \lit{*} <B>    (1)
    \alt <E> \lit{+} <B>   (2)
    \alt <B>               (3)

<B> ::= \lit{0}            (4)
    \alt \lit{1}           (5)


(note that the E and B were between 'less than' and 'greater than' symbols, I removed them from the listing because they seem to badly interact with stackexchange).

share|improve this question
Welcome to TeX.sx! A tip: If you indent lines by 4 spaces, they'll be marked as a code sample. You can also highlight the code and click the "code" button (with "{}" on it). About the E and B, please edit your code now, there should be no problem with those symbols any more. – egreg Mar 16 '13 at 17:44
Edited, thanks! – acieroid Mar 16 '13 at 17:51
up vote 5 down vote accepted

This should work for many cases; I'm no expert in these kinds of grammars.

I suggest you to define a new environment, patching the grammar environment to add line numbers.

\usepackage[pass,showframe]{geometry} % just to show the margins


\usepackage{etoolbox} % for patching
% define the main command on the model of the original one
% we add stepping the counter and typesetting the number
\def\gr@implnumbereditem<#1> #2 {%
    \rlap{\hskip\dimexpr\linewidth+\grammarindent\relax %% add the number
% copy the grammar environment under a new name
% now patch the new environment

% the command for numbering the \alt lines
        \llap{(\thegrammarline)}}% add the number



\setlength{\grammarparsep}{20pt plus 1pt minus 1pt}
Some text above
<E> ::= <E> \lit{*} <B>
  \alt <E> \lit{+} <B>
  \alt <B>

<B> ::= \lit{0}
  \alt \lit{1}
Some text below
\item a
<E> ::= <E> \lit{*} <B>
  \alt <E> \lit{+} <B>
  \alt <B>

<B> ::= \lit{0}
  \alt \lit{1}

enter image description here

share|improve this answer
Works perfectly, thanks! – acieroid Mar 16 '13 at 21:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.