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?

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

| improve this answer | |
  • ...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 8:19
  • 1
    @Henri Could you please explain the need for \noexpand? It seems to work without it too. – AlexG Aug 28 '19 at 8:40
  • @Henri Is \scantokens a kind of reverse operation to \detokenize? – AlexG Aug 28 '19 at 8:47
  • 1
    @AlexG mirrors.ctan.org/systems/doc/etex/etex_man.pdf 3.7 Input Handling – Henri Menke Aug 28 '19 at 9:22
  • 1
    @AlexG See also tex.stackexchange.com/questions/117906/…. 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
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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.