3

The code below doesn't compile logically:

Verbatim-like command '\test' illegal in argument...

Is there a way to "fix" this? If not, can I at least use a m parameter, and then replace all the underscores by :: for example, like if the user has typed \section{\test{txt::example}}?

\documentclass[12pt]{article}

\usepackage{color}

\NewDocumentCommand{\test}{v}{%
  \textcolor{red}{\fbox{\texttt{#1}}}%
}

\begin{document}

\section{\test{txt_example}}

The smallest \test{txt_example} in the world.

\end{document}
2
  • 1
    This is a documented restriction. But what would be the reason of defining \test that way and then asking to replace _ with :: as a fallback possibility? My impression is that you want to do something else.
    – egreg
    Jan 7 at 20:51
  • I am working on jinjaNG. I need to type \test{txt_example} in a template file such as to build a new one from data. During the templating phase, it is not a problem to see txt::example instead of txt_example. One short use case here.
    – projetmbc
    Jan 7 at 20:56

1 Answer 1

4

Do a regex replacement.

\documentclass[12pt]{article}
\usepackage{xcolor}

\ExplSyntaxOn

\NewDocumentCommand{\test}{m}
 {
  \formattest { \projetmbc_test:n { #1 } }
 }

\tl_new:N \l__projetmbc_test_tl

\cs_new_protected:Nn \projetmbc_test:n
 {
  \tl_set:Nn \l__projetmbc_test_tl { #1 }
  \regex_replace_all:nnN { _ } { \c{textunderscore} } \l__projetmbc_test_tl
  \tl_use:N \l__projetmbc_test_tl
 }

\ExplSyntaxOff

\NewDocumentCommand{\formattest}{m}{%
  \textcolor{red!90!blue}{\fbox{\ttfamily #1}}%
}

\begin{document}

\section{\test{txt_example}}

The smallest \test{txt_example} in the world.

\end{document}

enter image description here

3
  • Thanks for this. I should at least try this by myself... I will point to this post in my code.
    – projetmbc
    Jan 7 at 22:29
  • What is the need to use cs_new_protected?
    – projetmbc
    Jan 9 at 8:24
  • 1
    @projetmbc The function performs an assignment, hence it should be protected.
    – egreg
    Jan 9 at 9:13

You must log in to answer this question.

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