macroslatexspecial-characterslistingsverbatim

LaTeX newcommand with verbatim or listings : problem with `#` (hash key)


I'm trying to define a macro with \newcommand using verbatim or listings environment. It seems that the hash key in #1 (standing for the argument) is escaped, due to verbatim and listings.

I'm new to macros, so I tried something simple : it works with \begin{center} ... \end{center}.

\documentclass[a4paper,oneside,11pt]{report}
\newcommand{\script}[1]{
  \begin{center}
    #1
  \end{center}
}
\begin{document}
  \script{blabla}
  blibli
\end{document}

When I replace center with verbatim, I get this error :

File ended while scanning use of @xverbatim.

or lstlisting :

Text dropped after begin of listing

I didn't find anything on stackoverflow nor https://tex.stackexchange.com : what would you advise to use those environments in macros (\newcommand or maybe \newenvironment) ?

Thanks in advance


Solution

  • Verbatim content is tricky. You have to ask yourself what the intent is. If it's printing code, then king of the hill would be listings. I'd suggest that and define your own environment for large chunks of code-specific output.

    Here's an example:

    enter image description here

    \documentclass{article}
    
    \usepackage{listings}
    
    \lstnewenvironment{code}[1][]
      {\lstset{#1}}% Add/update settings locally
      {}
    
    \lstset{% Global options
      frame = single,
      basicstyle = \ttfamily\small,
      language = PHP
    }
    
    \begin{document}
    
    My first PHP ``Hello World'' page:
    
    \begin{code}
    <html>
     <head>
      <title>PHP Test</title>
     </head>
     <body>
     <?php echo '<p>Hello World</p>'; ?> 
     </body>
    </html>
    \end{code}
    
    When you write \lstinline!<title>PHP Test</test>!, it sets the \textit{title} of the page.
    
    \end{document}