创建自定义环境

创建自定义环境

我的代码片段使用了以下语法

\begin{minipage}{\textwidth}
\begin{lstlisting}[caption=<something>, label=<something>]
The REST Endpoint URL 
   is http://api.flickr.com/services/rest/

To request the flickr.test.echo service, 
   invoke like this:
   http://api.flickr.com/services/rest/
      ?method=flickr.test.echo&name=value

By default, REST requests will send a REST response.
\end{lstlisting}
\end{minipage}

我希望

\begin{code}[<caption>, <label>]
... code ...
\end{code}

其行为将完全相同。

所以我尝试了这个东西,但它无法编译,我找不到问题所在

\newenvironment{code}[2][]%
    {
        \minipage{\textwidth} 
        \lstset{
            basicstyle=\ttfamily,
            breaklines=true,
            captionpos=b,
            frame=bottomline,
            extendedchars=true
        }
        \begin{lstlisting}[caption=#1, label=#2]
    }
    {
        \end{lstlisting}
        \endminipage
    }

运行时出错pdflatex

! Package inputenc Error: Unicode char \u8:�\expandafter not set up for use with LaTeX.

See the inputenc package documentation for explanation.
Type  H <return>  for immediate help.

答案1

您需要使用\lstnewenvironment由提供的listings专门为此目的(见listings文档; 部分4.16 环境,第 40 页):

在此处输入图片描述

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\lstnewenvironment{code}[2][]%
  {%
    %\minipage{\textwidth} 
    \lstset{
      basicstyle=\ttfamily,
      breaklines=true,
      captionpos=b,
      frame=bottomline,
      extendedchars=true,
      caption=#1,
      label=#2
    }
  }
  {
    %\endminipage
  }
\begin{document}
\begin{code}[My code]{mycode}
  Here is some code
\end{code}

Here is some text. Also see Listing~\ref{morecode}.

\begin{code}[More code]{morecode}
  Here is some more code
\end{code}
\end{document}

不需要使用minipage宽度\textwidth,除非您想避免跨页中断。

相关内容