3

I have a cheatsheet with a table that looks like

\begin{tabular}{l|l}
$k > 0$    &  \verb+k > 0+    \\
$k \geq 0$ &  \verb+k \geq 0+ \\
$\sum_l$   &  \verb+\sum_l+   \\
%etc
\end{tabular}

There is a lot of redundancy here since the argument to verb is the same as the first entry of the table. I tried to make a macro to remove the duplication

\newcommand\code[1]{$#1$& \verb+#1+\\}

but that gives an error. I also tried using detokenize

\newcommand\code[1]{$#1$&\texttt{\detokenize{#1}}\\}

but that introduces superfluous spaces. How can I define a macro that produces both the formula and its verbatim code?

1 Answers1

4

enter image description here

You need to read the argument verbatim, to see the spaces:

\documentclass{article}

\makeatletter
\def\code#1{%
\let\do\@makeother \dospecials
\verbatim@font\@noligs
\@vobeyspaces \frenchspacing 
\catcode`#1\active
\lccode`\~`#1%
\lowercase{\long\def\tmp##1~}{\$##1\$&$\scantokens{##1}$\\}%
\tmp
}

\makeatother

\begin{document}

\begin{tabular}{l|l}
\code|k > 0|
\code|k \geq 0|
\code|\sum_l|
\end{tabular}

\end{document}

or to swap the columns is a bit harder:-)

\makeatletter
\def\code#1{%
\bgroup
\let\do\@makeother \dospecials
\@vobeyspaces 
\catcode`#1\active
\lccode`\~`#1%
\lowercase{\long\def\tmp##1~}{\egroup$\scantokens{##1}$&%
\verbatim@font\@noligs
\@vobeyspaces\frenchspacing 
\$##1\$\\}%
\tmp
}

\makeatother
David Carlisle
  • 757,742