user defined commands in verbatim environment
Question
is it possible to create a new command with a parameter in a verbatim environment and some indentation?
\newcommand{codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}}
This does not work. Is there an other way?
Solution
It looks like you want to have code in your document, in which case you're probably better served by the package listings than by verbatim. Listings also gives you nice features like line numbering and syntax highlighting for many common languages. See http://www.ctan.org/tex-archive/macros/latex/contrib/listings/ if it's not already installed with your LaTeX distribution.
OTHER TIPS
How \begin{verbatim}
works. briefly and roughly.
\begin{verbatim}
is expanded to\verbatim
.- Then
\verbatim
sets category code of each special characters to 12. Now all chars is like digits or puncts. - Then
\verbatim
sets font, parindent and calls\@xverbatim
. \@xverbatim
catches the end of verbatim using the following trick:\def\@xverbatim#1\end{#1\end}
Then
\end{verbatim}
finishes work.
How \newcommand{\codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}}
works.
- First of all
\codeblock{Some {}$&%^_}
reads its argument. #1 --> Some code {}$&%^_
Note:
{
,}
,$
,&
,%
,^
,_
have categories 1,2,3,4,6,7,8 rather than 11 or 12!!!)\codeblock
expands to\begin{quote}\begin{verbatim} Some {}$&%^_\end {verbatim}\end {quote}
. Important: backslash of\end
has category 0 rather than 11. Moreover{
and}
have categories 1 and 2 rather than 11. And$
,&
,%
,^
,_
have categories 3,4,6,7,8.\begin{quote}
expands to\quote
and\quote
executes.- Then
\begin{verbatim}
expands to\varbatim
.\varbatim
changes all categories and font. But (important) the category of backslash (in\end
) remains equal to 0. And the categories of{
,}
,$
,&
,%
,^
,_
typed afterSome
remains because of "argument reading" executes before\verbatim
changes all categories. But you need that all char has categories 11 o 12. - Then
\verbatim
calls\@xverbatim
. \@xverbatim
tries to catch your argument using the following trick:\def\@xverbatim#1\end{#1\end}
but it is impossible because of
\@xverbatim
tries to catch\end
where all letters (\
,e
,n
,d
) have the category 12 and 11. But in fact there are four letters with other category code:\
with category 0 ande
,n
,d
with category 11.It is possible (I am not sure) that trick is more masterly:
Red chars have category 12. Green chars have category 11.
\def
,\@xverbatim
,\end
are macros with\
(category 0) and letters (category 11).\@xverbatim
is trying and trying to find\end
where backslash (\
) has category 11 but....File ended while scanning use of \@xverbatim
If you want to create new macro \codeblock
you must do something like above text.