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?

Was it helpful?

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.

  1. \begin{verbatim} is expanded to \verbatim.
  2. Then \verbatim sets category code of each special characters to 12. Now all chars is like digits or puncts.
  3. Then \verbatim sets font, parindent and calls \@xverbatim.
  4. \@xverbatim catches the end of verbatim using the following trick:

    \def\@xverbatim#1\end{#1\end}
    
  5. Then \end{verbatim} finishes work.

How \newcommand{\codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}} works.

  1. First of all \codeblock{Some {}$&%^_} reads its argument.
  2. #1 --> Some code {}$&%^_

    Note: {,},$,&,%,^,_ have categories 1,2,3,4,6,7,8 rather than 11 or 12!!!)

  3. \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.
  4. \begin{quote} expands to \quote and \quote executes.
  5. 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 after Some remains because of "argument reading" executes before \verbatim changes all categories. But you need that all char has categories 11 o 12.
  6. Then \verbatim calls \@xverbatim.
  7. \@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 and e,n,d with category 11.

    It is possible (I am not sure) that trick is more masterly:

    alt text

    Red chars have category 12. Green chars have category 11. \def, \@xverbatim, \end are macros with \ (category 0) and letters (category 11).

  8. \@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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top