6

I'm not quite sure how to describe this, but I want to create a custom command that treats its input as verbatim and allows some control of the output.

In pseudocode, I want:

\newcommand{\code}[1]{\verb{!#1!}}
\newcommand{\samp}[1]{{\normalfont\textsl{\verb!#1!}}}

(But that obviously doesn't work)

newverbs gets me close to what I need, but e.g.

\RequirePackage{newverbs}
\newverbcommand{\code}{}{}

requires \code!~! rather than \code{~}

8
  • The main problem is that \verb can never be used in the argument to another command.
    – egreg
    May 18, 2013 at 20:57
  • @egreg Exactly - what's the workaround?
    – hadley
    May 18, 2013 at 21:16
  • There's no workaround. What's wrong in typing \verb|something| instead of \code|something|? Can you make some examples of usage of your command? Maybe there's a different way to accomplish the task.
    – egreg
    May 18, 2013 at 21:19
  • 1
    @egreg it's less semantic - e.g. in the future I might want to automatically syntax highlight code chunks.
    – hadley
    May 18, 2013 at 21:23
  • 5
    Does this answer your question? Can you interpret macro parameters as verbatim?
    – user202729
    Dec 25, 2021 at 9:39

2 Answers 2

5

I prepared something using the listings package. You can adjust the appearance by customizing the \lstset and \lstdefinestyle commands. See the documentation for further information.

\documentclass{standalone}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
    basicstyle=\color{red}\itshape
}
\lstdefinestyle{inline}{
    columns=fullflexible,
    breaklines=false
}
\newcommand{\code}[1]{\lstinline[style=inline]!#1!}
\begin{document}
Here is some \code{verbatim} text.
\end{document}

The output will looks something like this

Verbatim text using lstlisting

3
  • 1
    And how badly does this blow up if you do things like \code{1 != 0}?
    – kahen
    May 19, 2013 at 18:00
  • 1
    Feel free to suggest a better delimiting character than ! May 19, 2013 at 18:20
  • 1
    Note that newer versions of listings also support \lstinline{#1} which would not need the character-marker !. Also, in case if anyone is interested, I wanted to have the style like \mathnormal. You can do that via basicstyle=\usefont{OML}{cmm}{m}{it}.
    – Albert
    Jun 7, 2013 at 10:06
2

This will give inline conversion of the argument to catcode 12 tokens, except for spaces and percents (%), which it still takes as ignore-the-rest-of-the-line-characters. Thus, it will wrap. But what it will not do is honor linefeeds in the argument. But as an inline command, you wouldn't want it to.

As Joseph Wright points out, unbalanced braces will also break this version.

\documentclass{article}
\usepackage[T1]{fontenc}
\def\fauxverb#1{\textsl{\detokenize{#1}}}
\begin{document}
This is \fauxverb{\verbatim} text.
\end{document}

enter image description here

2

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