How to display code snippets in plain TeX
A version that breaks ligatures and obeys blank lines:
\def\verbatim{%
\begingroup
\def\do##1{\catcode`##1=12 }%
\dospecials
\otherspecial\ {\ }%
\otherspecial\-{-\kern0pt }%
\otherspecial\`{\lq\kern0pt }%
\otherspecial\'{\rq\kern0pt }%
\otherspecial\^^M{\endgraf\ifblankline\vskip\baselineskip\fi\blanklinetrue}%
\parindent0pt\medskip
\everypar{\blanklinefalse}
\tt\verbatimaux
}
\newif\ifblankline
\begingroup\endlinechar=-1
\catcode`\|=0 %
\catcode`\\=12 %
|gdef|verbatimaux#1\endverbatim#2{#1|endgroup|par|medskip}%
|endgroup%
\def\otherspecial#1#2{%
\begingroup\lccode`~=`#1\relax
\lowercase{\endgroup\def~}{#2}%
\catcode`#1=\active
}
Some text some text some text some text some text some text.
Some text some text some text some text some text some text.
Some text some text some text some text some text some text.
\verbatim
void dfs(int p){
if(o[p]) return;
o[p]=1;
c[p] = t++;
for(int i=0; i<s[p].size(); ++i){
dfs(s[p][i]);
}
}
-- --- `` '' `? `!
\endverbatim
Some text some text some text some text some text some text.
Some text some text some text some text some text some text.
Some text some text some text some text some text some text.
\bye
Something like
\def\verbatim{%
\begingroup
\def\do##1{\catcode`##1=12 }%
\dospecials
\obeylines
\obeyspaces
\tt
\verbatimaux
}
\begingroup
\catcode`\|=0 %
\catcode`\\=12 %
|gdef|verbatimaux#1\endverbatim{#1|endverbatim}%
|endgroup
\def\endverbatim{\endgroup}
{\obeyspaces\gdef {\ }}% Omit this for 'explicit' spaces
\verbatim
void dfs(int p){
if(o[p]) return;
o[p]=1;
c[p] = t++;
for(int i=0; i<s[p].size(); ++i){
dfs(s[p][i]);
}
}
\endverbatim
\bye
should do you: a simplified version of LaTeX's verbatim
environment. Also see Appendix E of The TeXbook (page 421), which described how Knuth did this for the book itself. (He requires every line is marked up using |
... |
.)
When opmac is used then \begtt
...\endtt
environment is ready to use:
\input opmac
aha
\begtt
void dfs(int p){
if(o[p]) return;
o[p]=1;
c[p] = t++;
for(int i=0; i<s[p].size(); ++i){
dfs(s[p][i]);
}
}
// -- --- `` '' `? `!
\endtt
\bye
Moreover, you can copy the code from this Opmac trick and you can add
\hisyntax{C}
before \begtt
and you get the following result: