6

I'm using the bnf package to format a context-free grammar in one of my documents. I'm finding that any whitespace will be reflected in the output. I would like to keep the whitespace in the code for readability but have it removed in the output. Is there a way to make this happen?

\documentclass[leqno,fleqn,12pt]{report}

\usepackage{bnf}

\begin{document}

\begin{grammar}
[(colon){$\rightarrow$}]
[(semicolon)$|$]
[(comma){}]
[(period){\\}]
[(quote){\begin{bf}}{\end{bf}}]
[(nonterminal){$\langle$}{$\rangle$}]

<rule-working>:<formats>,<correctly>;<without>,<whitespace>.
<rule-not-working> : <formats> , <incorrectly> ; <with> , <whitespace> .

\end{grammar}

\end{document}

Example

1 Answer 1

7

The command \catcode32=9\relax (or \catcode`\ =9\relax) will make TeX ignore all spaces in the current group/environment. You could define your own environment and add it and {grammar} to it.

\documentclass[leqno,fleqn,12pt]{report}

\usepackage{bnf}

\newenvironment{Grammar}{%
\catcode32=9\relax
\begin{grammar}%
}{%
\end{grammar}
}

\begin{document}

% Either
\begin{grammar}
[(colon){$\rightarrow$}]
[(semicolon)$|$]
[(comma){}]
[(period){\\}]
[(quote){\begin{bf}}{\end{bf}}]
[(nonterminal){$\langle$}{$\rangle$}]
\catcode32=9\relax

<rule-working>:<formats>,<correctly>;<without>,<whitespace>.
<rule-not-working> : <formats> , <incorrectly> ; <with> , <whitespace> .

\end{grammar}

% or
\begin{Grammar}
[(colon){$\rightarrow$}]
[(semicolon)$|$]
[(comma){}]
[(period){\\}]
[(quote){\begin{bf}}{\end{bf}}]
[(nonterminal){$\langle$}{$\rangle$}]

<rule-working>:<formats>,<correctly>;<without>,<whitespace>.
<rule-not-working> : <formats> , <incorrectly> ; <with> , <whitespace> .

\end{Grammar}

\end{document}

Result

As Joseph Wright pointed out there are more space-like characters you might also want to ignore:

\catcode9=9\relax     % Horizontal Tab
\endlinechar=-1\relax % No line endings

A space or non-expandable TeX command like \relax must follow the number so TeX knows to stop reading digits.

and maybe these (just to be on the save side):

\catcode10=9 %   New line
\catcode11=9 %   Vertical Tab 
\catcode12=9 %   Form Feed
\catcode13=9 %   Carriage Return
4
  • 1
    You'd probably want to cover tabs as well, plus make line-ends disappear (\endlinechar=-1\relax).
    – Joseph Wright
    Commented Mar 5, 2011 at 21:58
  • @Joseph: Indeed, I added these now plus some more. Commented Mar 5, 2011 at 22:05
  • @Joseph why not enclose it in ExplSyntaxOn ...ExplSyntaxOff, it is much simpler.
    – yannisl
    Commented Mar 6, 2011 at 3:26
  • @Yiannis, in case you don't know: Joseph wasn't notified of your comment; only the first "@" does this. If your had exchanged Martin und Joseph, both would have gotten a notification since the author of the post is always notified. Commented Mar 6, 2011 at 7:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .