2

I've been working on a command that will typeset snippets of code within a paragraph. I'm aware of listings and company, but I want something that will just typeset the code verbatim and also allow me to do other things with it (like save to an external file and then execute).

I've created a macro that typesets its argument using \verb and also could make its argument available for other purposes. But in the process of creating it, I keep reading about how verb isn't meant to take arguments (even though I seem to have gotten it to do so). So two questions:

  • Is there anything that can go terribly wrong with this code? Is there some deep reason that \verb is not to be tampered with?
  • What is going on with the catcodes? It seems that \verb's delimiting character must be active. This leads to some really strange behavior. For example, I can use "=" as my delimiter, and typeset code that contains "=", so long as the delimiter isn't the last character in my \createverb macro.

Minimal working example:

\documentclass[11pt]{article}
\usepackage{xstring}

\makeatletter
\begingroup
\catcode`\==\active
\gdef\delimchar{=}
\gdef\delimchardetok{\detokenize{=}}
\endgroup
\verbtocs{\cmd}|\verb|
\def\createverb{%
    \begingroup
    \let\do\@makeother
    \dospecials
    %Reset the \, {, and } so they're special
    \catcode`\\=0
    \catcode`\{=1
    \catcode`\}=2
    %Obey spaces
    \frenchspacing\@vobeyspaces
    \createverb@finish}
\def\createverb@finish#1{%
    %Deactiveate { and } 
    \catcode`\{=12
    \catcode`\}=12
    \tokenize{\verbtext}{\cmd\delimchardetok\detokenize{#1}}%
    \endgroup
    \verbtext\delimchar%
}%
\makeatother

\begin{document}

Pseudo-Perl:

\createverb{$f=$_[0]+$a{$b[2]}+$c*$d  #Comment here}

\end{document}
1

Following Bruno's suggestion, here is an example

\documentclass[a4paper]{article}
\usepackage{xparse}

\NewDocumentCommand{\createverb}{ov}{
  \IfNoValueTF{#1}
    {{\fontencoding{T1}\ttfamily#2}}
    {\def#1{#2}}
}

\begin{document}

\createverb{$f=$_[0]+$a{$b[2]}+$c*$d  #Comment here}

\createverb[\xyz]{$f=$_[0]+$a{$b[2]}+$c*$d  #Comment here}

\xyz

\end{document}

I don't see anything "dangerous" in your code; but it's quite awkward.

| 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.