# verbatim text in tables and macros [duplicate]

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?

• Can we assume that the input is essentially math mode material: no % tokens, etc.? – Joseph Wright Sep 11 '14 at 14:11
• @Wright Yes these are just math formulas between . – stackman Sep 11 '14 at 15:49

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

• @StevenB.Segletes not so novel as it turns out: same as egreg's answer in other question but he just uses an xparse v argument (which is same thing, really) – David Carlisle Sep 11 '14 at 14:32
• For one who doesn't speak L3, it qualifies as "novel". Kind of like "verboten" is a novel term for English speakers. Who would have guessed? Those Germans have a different word for everything. – Steven B. Segletes Sep 11 '14 at 14:35
• @stackman updated answer – David Carlisle Sep 11 '14 at 15:54
• oh that's \verb* rather than \verb I put the \@vobeyspaces in the wrong place:-) update coming up... – David Carlisle Sep 11 '14 at 16:29
• @stackman updated – David Carlisle Sep 11 '14 at 16:34