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{~}

hadley
  • 530

2 Answers2

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

Henri Menke
  • 109,596
  • 1
    And how badly does this blow up if you do things like \code{1 != 0}? – kahen May 19 '13 at 18:00
  • 1
    Feel free to suggest a better delimiting character than ! – Henri Menke May 19 '13 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 07 '13 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

  • 1
    Won't work with for example \fauxverb|%{| – Joseph Wright Jun 06 '13 at 19:03
  • 1
    Remark: \detokenize is documented in eTeX manual. -- See https://tex.stackexchange.com/questions/150767/strange-behaviour-with-detokenize-and-underscore for why T1 fontenc is necessary. (also it's not necessary for other engines such as XeLaTeX) – user202729 Sep 07 '21 at 03:56