3

Similar to New command to display a symbol and its command I would like to have a command to display and execute code. The code should be displayed with the listings package.

For example something like

\documentclass{scrartcl}
\usepackage{amsmath,listings}
\newcommand*{\codeExample}[1]{Code: \lstinline!\string{#1}! yields #1}
\begin{document}
  \codeExample{$\lVert a\rVert$}
\end{document}

should for best of cases display $\lVert a \rVert$ as verbatim (\lstinline!...!) code and after that the rendered math code. Is something like that possible? The code above yields several mistakes. I think I miss something to avoid #1 being tokenised?

siracusa
  • 13,411
Ronny
  • 6,110

2 Answers2

6

You can use xparse verbatim arguments for that.

\documentclass{scrartcl}
\usepackage{amsmath,xparse}
\NewDocumentCommand\codeExample{v}{%
    Code: \texttt{#1} yields \scantokens{#1\noexpand}%
}
\begin{document}
  \codeExample{$\lVert a\rVert$}
\end{document}

enter image description here

Henri Menke
  • 109,596
  • ...and that again also works with \lstinline[language={[LaTeX]TeX}]{#1} instead of the \texttt (which I prefer for further markup). Great! – Ronny Aug 28 '19 at 08:19
  • 1
    @Henri Could you please explain the need for \noexpand? It seems to work without it too. – AlexG Aug 28 '19 at 08:40
  • @Henri Is \scantokens a kind of reverse operation to \detokenize? – AlexG Aug 28 '19 at 08:47
  • 1
    @AlexG http://mirrors.ctan.org/systems/doc/etex/etex_man.pdf 3.7 Input Handling – Henri Menke Aug 28 '19 at 09:22
  • 1
    @AlexG See also https://tex.stackexchange.com/questions/117906/use-of-everyeof-and-endlinechar-with-scantokens. The effect of that here is that the version with \noexpand doesn't add an extra space when the \scantokens is processed. – siracusa Aug 28 '19 at 22:58
  • @siracusa Thank you for sharing the link! Interesting read. Now I understand better. – AlexG Aug 29 '19 at 06:59
  • Please note that this usage of \scantokens might break things (e.g., try \codeExample|abc|\\). While the \noexpand is supposed to fix the \scantokens eof-leakage, it also breaks immediately following macros, you can use \scantokens{#1\noexpand}\relax as a quick-fix for this instead. – Skillmon Dec 08 '19 at 11:01
  • That should have been \codeExample|abc|\\. – Skillmon Dec 08 '19 at 11:23
1

Since \scantokens is really hard to use right, I'd advocate to use the expl3 implementation of it that takes care of all the pitfalls. So all in all, this is the same as @HenriMenke's answer, but more robust:

\documentclass{scrartcl}
\usepackage{amsmath,xparse}
\ExplSyntaxOn
\NewDocumentCommand\codeExample{v}
  {
    Code:~\texttt{#1}~yields~\tl_rescan:nn {} {#1}
  }
\ExplSyntaxOff
\begin{document}
  \codeExample{$\lVert a\rVert$}
\end{document}

enter image description here

Skillmon
  • 60,462