0

I want to build a macro with the tcblisting enviroment from tcolorbox, as shown below, but fail. What's the reason and how to deal with this?

Code:

\documentclass[a4paper]{article}
\usepackage{geometry,tcolorbox}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\tcbuselibrary{listings}
\parindent0pt

\begin{document}
This works all right as expected.
\begin{tcblisting}{}
  \rule{1in}{5pt}\\\parbox{1in}{some text}
\end{tcblisting}


Construct a macro with the above code, but the macro does not work, why and what is the solution?
\newcommand\qa[2][]{
  \begin{tcblisting}{#1}
  #2
  \end{tcblisting}
}
\qa{\rule{1in}{5pt}\\\parbox{1in}{some text}}
\end{document}
3
  • Verbatim environments often can't be hidden inside commands. Mar 19, 2022 at 8:17
  • Besides \qa not working because you can't have verbatim in the argument to a command, what would be the advantage of \qa over the environment form?
    – egreg
    Mar 19, 2022 at 9:38
  • @egreg Sometimes simple verbatim may be used in which an enviroment is too heavy. And verbatim not working as an argument to a command is very annoying in some cases.
    – lyl
    Mar 19, 2022 at 13:39

1 Answer 1

1

Verbatim mode requires disabling or modifying a lot of TeX features and conventions.

For instance, you don't want to interpret the backslash as introducing a command, but also interpret newlines to actually produce a new line; and so on.

What happens when TeX reads the argument to a command? Well, it forms tokens using its standard way of doing things and in your case you'd need to undo this work, which is impossible in full generality. You might “stringify” the input, but this would add spaces after control sequences and newlines would not be preserved, because they've already been converted to spaces or even to \par. For instance the input

\ttfamily
\detokenize{a\xyz\uvw b

c}

would produce

enter image description here

Not what you'd like, I guess. There are tricks around this, see for instance \lstinline{<verbatim material>} but you can't have braces in the verbatim material; listings offers \lstinline<char><verbatim material><char> where the <char> stands for a character not appearing in the verbatim material, but newlines would not be honored (they'd cause an error message actually).

The only safe method for general verbatim material is to use an environment form.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .