# newcommand for verbatim

I'm trying to write a \newcommand for verbatim:

\newcommand{\codeline}[1]{\begin{verbatim}{#1}\end{verbatim}}


and use it as

\codeline{int foo;}


but it gives an error "File ended while scanning use of \@xverbatim". How to fix it?

-
You would have to use other means to include verbatim content inside a macro. See Verbatim inside a command. You may be interested in what the listings package has to offer instead. It also provides the means to create your own environments. For example, see Creating a custom environment. –  Werner Dec 8 '12 at 6:18
@Werner Thanks for your reply. Why can't I include verbatim inside a macro the way I did it? –  Paul S. Dec 8 '12 at 6:26
An environment should be used for verbatim text. Take a loot at the fancyvrb package; it provides the \DefineVerbatimEnvironment for defining your own verbatim environment. There is also \DefineShortVerb for creating short verbatim texts like this |int foo;|. –  Stephan Lehmke Dec 8 '12 at 6:26
If you don't want to use TeX stuff like \  or % in code lines, maybe \newcommand{\codeline}[1]{\par{\ttfamily#1\par}} is enough? –  Stephan Lehmke Dec 8 '12 at 6:36
@PaulS.: See Why doesn’t verbatim work within …? –  Werner Dec 8 '12 at 7:04

If you want a simple implementation, go with

\newcommand[1]{{\small\texttt{#1}}}


If you want more detailed control, you should go with fancyvrb or minted packages.

-
Oh, btw, I like to put a \small in there because the default monospace font is a little too big for my taste. I like my code snippets relatively equal to or smaller than my main font. –  recluze Dec 8 '12 at 11:45
This "dirty" command does not work for special caracters as _, &, etc. I.e. \codeline{a_b_c} will result in an error. –  strpeter Jan 4 at 16:20
@strpeter I use the underscore package by default in my docs and your example works perfectly with that. –  recluze Jan 5 at 13:04

For my example below the following code from the listings package was the solution:

\newcommand{\codeline}[1]{\lstinline|#1|}


Of course this is only reasonable if you are using short inline code examples without vertical line |.

## Example

MWE in which this implementation makes sense:

\documentclass[landscape]{article}
\usepackage{listings}
\newcommand{\includegraphicswithtitle}[1]{%
\clearpage%
\section*{\lstinline|#1|}%
\includegraphics{#1}}

\title{All graphics of my thesis}

\begin{document}
\maketitle
\centering
\includegraphicswithtitle{Image08_a_1.pdf}
\includegraphicswithtitle{Image08_b_1.pdf}
\includegraphicswithtitle{Image08_c_1.pdf}
\end{document}

-
What's the advantage of \codeline{text} over \lstinline|text|? –  egreg Jan 4 at 16:47
@egreg: You can crop several lines together in order to reduce repeating code. Is this not advantage enough? If there is a more efficient answer, please feel free to correct me. –  strpeter Jan 4 at 17:06