Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}
share|improve this question
4  
You may be interested in the xparse package and its verbatim argument type. E.g., try \DeclareDocumentCommand{\foo}{v}{\typeout{#1}}. –  Bruno Le Floch Oct 15 '11 at 3:17
2  
Also read: Why doesn’t verbatim work within...? –  Werner Oct 15 '11 at 6:28
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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