2

I made a simple macro called \cmd{} which detokenizes the input. I would like to print the contents exactly as shown, and it works as I desire, except that it seems to produce a space between an inputted command sequence and the curly braces.

\documentclass{article}
\newcommand{\cmd}[1]{\texttt{\detokenize{#1}}}
\begin{document}
\cmd{\test{}}
\end{document}

results in \test {}

enter image description here

Edit: I would like a verbatim-like macro called \cmd{} that does the following:

\cmd{\test{}}\test{}

Edit: I did try the solutions posed in Detokenizing without extra spaces?, but have had no luck. I am using LuaLaTeX.

5
  • 1
    It looks to me like you actually want \verb, but this sounds like an XY problem: what exactly are you after?
    – campa
    Sep 1, 2022 at 14:06
  • That is what \detokenize does. If your argument is a single control sequence, \string can produce it without the space. What is your actual use case? Sep 1, 2022 at 14:06
  • Are you aware of the posting Detokenizing without extra spaces?
    – Mico
    Sep 1, 2022 at 14:11
  • @Mico did not see that post--perhaps this should be flagged as duplicate. Sep 1, 2022 at 14:13
  • \detokenize is like writing tokens unexpanded to an external file and then inputting the external file under a category code régime where the space character has category code 10 (space) and all other characters have category code 12(other) and \endlinechar has a negative value. \newlinechar is obeyed with the writing-part. When writing a control word token, TeX automatically appends a space character. Another peculiarity of TeX's way of writing tokens is: When writing an explicit hash of category 6(parameter) that gets doubled. Sep 2, 2022 at 15:02

1 Answer 1

2

When the paramater \test{} is scanned then it is tokenized to three tokens: \test, { and }. The \detokenize primitive always prints the token which is a control sequence separated by a space, so, it prints \test {}.

If you want to keep the spacing like it is written in the parameter, you must to read it in verbatim mode. It means that the { and } must be read asn normal characters in the text \test{}. But the parameter is separeted by { and } and they cannot be normal characters in this case. This is nearly impossible to read internal {} as normal characters and use {...} around the parameter. So, I suggest to use different parentheses for parameter separators:

\def\cmd{\bgroup\def\do##1{\catcode`##1=12}\dospecials \cmdA}
\def\cmdA[#1]{\egroup{\tt#1}}

\cmd[\test{}]

Another approach is to set only \ and as normal characters, read the parameter (with balanced braces) and do \detokenize after it:

\def\cmd{\bgroup\catcode`\\=12 \catcode`\ =12 \cmdA}
\def\cmdA#1{\egroup{\tt\detokenize{#1}}}

second test: \cmd{\test{}}

You must log in to answer this question.

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