> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/ming-ling/02-environments.md).

# 环境

LaTeX 环境用于对文档内容中的某一部分应用特定的排版效果。本文介绍如何使用现有环境并定义新环境。

## 引言

一个环境以 `\begin{name}` 并以 `\end{name}`:

```
\begin{name}
你的内容写在这里...
...放在这里...
\end{name}
```

其中“`名称`”是所使用的环境名称——例如下面使用“`center`”来格式化（居中）一段文本：

```latex
\documentclass{article}
\begin{document}
\begin{center}
这是 \texttt{center} 环境的演示。
这段文字将会被 \textit{居中}，因为它
被包含在一个特殊环境中。环境提供了
一种高效的方法来修改文档中的文本块。
\end{center}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Simple+environment+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bcenter%7D%0AThis+is+a+demonstration+of+the+%5Ctexttt%7Bcenter%7D+environment.+%0AThis+paragraph+of+text+will+be+%5Ctextit%7Bcentred%7D+because+it+is+%0Acontained+within+a+special+environment.+Environments+provide+%0Aan+efficient+way+to+modify+blocks+of+text+within+your+document.%0A%5Cend%7Bcenter%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![显示居中对齐的图片](/files/a14d4310fceff904920d2891446bb00f1feb40f2)

## 环境

下面的示例使用 `tabular` 环境来排版一个小表格。 `tabular` 需要额外的参数 `{ c c c }` 用以定义单元格的对齐方式——更多信息请参见 [表格](/latex/zh-cn/tu-xing-he-biao-ge/01-tables.md) 文章。

```latex
\documentclass{article}
\begin{document}
\begin{tabular}{ c c c }
  cell1 & cell2 & cell3 \\
  cell4 & cell5 & cell6 \\
  cell7 & cell8 & cell9 \\
 \end{tabular}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Simple+tabular+environment+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btabular%7D%7B+c+c+c+%7D+%0A++cell1+%26+cell2+%26+cell3+%5C%5C+%0A++cell4+%26+cell5+%26+cell6+%5C%5C+%0A++cell7+%26+cell8+%26+cell9+%5C%5C+%0A+%5Cend%7Btabular%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![tabular 环境示例](/files/f82918780091978cbd9f4f686d4ac062271227a0)

某些环境接受可选参数，这些参数通常放在方括号中（`[...]`).

## 定义新环境

要定义一个新环境，请使用 `\newenvironment` 命令，其一般形式为：

```
\newenvironment{name}[numarg][optarg_default]{begin_def}{end_def}
```

其中：

* `名称` 是这个用户自定义参数的名称；
* `numarg` 是环境接受的参数个数，从 1 到 9。若 `[numarg]` 被省略，则该环境不接受任何参数——例如下一示例中的 [`boxed` 环境](#defining-simple-environments);
* `optarg_default` 使第一个参数变为可选，并提供一个默认值——也就是说，如果未提供可选参数值，就使用该值；
* `begin_def` 是当环境开始（打开）时执行的 LaTeX 代码，也就是当你写 `\begin{name}`时。在这段代码中，你可以使用环境接受的参数——注意，可选参数是 #1，其余参数通过 #2 到 #numarg 访问；
* `end_def` 是当环境结束（关闭）时执行的 LaTeX 代码；也就是说，当你写 `\end{name}`时。你不能在这段代码中使用任何参数。

### 定义简单环境

在第一个示例中，我们定义 `boxed` 环境，它不接受任何参数。它会在环境内的文本周围绘制一个框：

```latex
\documentclass{article}
%We can define the environment in the preamble
\newenvironment{boxed}
    {\begin{center}
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline\\
    }
    {
    \\\\\hline
    \end{tabular}
    \end{center}
    }
%
\begin{document}
现在我们可以在文档中使用 \texttt{boxed} 环境：

\begin{boxed}
这段文字是在 \texttt{boxed} 环境中排版的。
\end{boxed}

这段文字是在 \texttt{boxed} 环境之外排版的。
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Creating+a+new+environment\&snip=%5Cdocumentclass%7Barticle%7D%0A%25We+can+define+the+environment+in+the+preamble%0A%5Cnewenvironment%7Bboxed%7D%0A++++%7B%5Cbegin%7Bcenter%7D%0A++++%5Cbegin%7Btabular%7D%7B%7Cp%7B0.9%5Ctextwidth%7D%7C%7D%0A++++%5Chline%5C%5C%0A++++%7D%0A++++%7B+%0A++++%5C%5C%5C%5C%5Chline%0A++++%5Cend%7Btabular%7D+%0A++++%5Cend%7Bcenter%7D%0A++++%7D%0A%25%0A%5Cbegin%7Bdocument%7D%0ANow+we+can+use+the+%5Ctexttt%7Bboxed%7D+environment+in+our+document%3A%0A%0A%5Cbegin%7Bboxed%7D%0AThis+text+is+formatted+within+the+%5Ctexttt%7Bboxed%7D+environment.%0A%5Cend%7Bboxed%7D%0A%0AThis+text+is+typeset+outside+the+%5Ctexttt%7Bboxed%7D+environment.%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![演示一个自定义 LaTeX 环境](/files/fc3ac0663e254dcb15f3a3501a7115b1f98a5a03)

如果我们将对 `boxed` 的定义与 `\newenvironment` 的一般形式进行比较，就能看出：

* `名称` 是 `boxed`;
* 既不是 `[numarg]` 或 `[optarg_default]` ，因为这个环境不接受任何参数；
* `begin_def` 是 LaTeX 代码——提供在一对大括号 `{...}`之间——它会在环境 *开始* （打开）时执行：

```latex
\begin{center}
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline\\
```

* `end_def` 是 LaTeX 代码——提供在一对大括号 `{...}`之间——它会在环境 *停止* （关闭）时：

```latex
    \\\\\hline
    \end{tabular}
    \end{center}
```

在这个示例中， `begin_def` 开始一个 `center` 环境，而在其内部又打开一个 `tabular` 环境，用于在我们放入环境中的文本周围绘制垂直线和一条水平线。 `end_def` 再绘制一条水平线，然后关闭这些 `tabular` 和 `center` 环境。

### 定义接受参数的环境

让我们扩展示例，完成以下操作：

* 使用一个可选参数来排版标题。如果未提供标题，则使用默认值 `这是一个框`;
* 使用第二个参数，其中包含要在我们在环境内部提供的文本之前排版的内容。

因此我们有 2 个参数：

* 第一个（参数 1）是可选的；
* 第二个（参数 2）不是。

这意味着 `numarg`=2.

我们可以使用更新后的 `boxed` 环境：

```latex
\newenvironment{boxed}[2][This is a box]
    {\begin{center}
    Argument 1 (\#1)=#1\\[1ex]
    \begin{tabular}{{{!}}p{0.9\textwidth}{{!}}}
    \hline\\
    Argument 2 (\#2)=#2\\[2ex]
    }
    {
    \\\\\hline
    \end{tabular}
    \end{center}
    }
```

这个增强版与原始版本的不同之处如下：

* \[numarg] is present and has the value 2;
* \[optarg\_default] is also present, making the first argument optional with a default value `这是一个框`.

以下示例演示了我们升级后的 `boxed` 环境：

```latex
\documentclass{article}
% Note the default value for the first
% argument is provided by [This is a box]
\newenvironment{boxed}[2][This is a box]
    {\begin{center}
    Argument 1 (\#1)=#1\\[1ex]
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline\\
    Argument 2 (\#2)=#2\\[2ex]
    }
    {
    \\\\\hline
    \end{tabular}
    \end{center}
    }
\begin{document}
\textbf{示例 1}：为第一个参数使用默认值：

\begin{boxed}{Some preliminary text}
这段文字位于环境\textit{内部}。
\end{boxed}

这段文字位于环境\textit{外部}。

\vskip12pt

\textbf{示例 2}：为第一个参数提供一个值：

\begin{boxed}[This is not the default value]{Some more preliminary text}
这段文字仍然位于环境\textit{内部}。
\end{boxed}

这段文字也位于环境\textit{外部}。
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Environment+with+an+optional+argument\&snip=%5Cdocumentclass%7Barticle%7D%0A%25+Note+the+default+value+for+the+first%0A%25+argument+is+provided+by+%5BThis+is+a+box%5D%0A%5Cnewenvironment%7Bboxed%7D%5B2%5D%5BThis+is+a+box%5D%0A++++%7B%5Cbegin%7Bcenter%7D%0A++++Argument+1+%28%5C%231%29%3D%231%5C%5C%5B1ex%5D%0A++++%5Cbegin%7Btabular%7D%7B%7Cp%7B0.9%5Ctextwidth%7D%7C%7D%0A++++%5Chline%5C%5C%0A++++Argument+2+%28%5C%232%29%3D%232%5C%5C%5B2ex%5D%0A++++%7D%0A++++%7B+%0A++++%5C%5C%5C%5C%5Chline%0A++++%5Cend%7Btabular%7D+%0A++++%5Cend%7Bcenter%7D%0A++++%7D%0A%5Cbegin%7Bdocument%7D%0A%5Ctextbf%7BExample+1%7D%3A+Use+the+default+value+for+the+first+argument%3A%0A+%0A%5Cbegin%7Bboxed%7D%7BSome+preliminary+text%7D%0AThis+text+is+%5Ctextit%7Binside%7D+the+environment.%0A%5Cend%7Bboxed%7D%0A%0AThis+text+is+%5Ctextit%7Boutside%7D+the+environment.%0A%0A%5Cvskip12pt%0A%0A%5Ctextbf%7BExample+2%7D%3A+Provide+a+value+for+the+first+argument%3A%0A+%0A%5Cbegin%7Bboxed%7D%5BThis+is+not+the+default+value%5D%7BSome+more+preliminary+text%7D%0AThis+text+is+still+%5Ctextit%7Binside%7D+the+environment.%0A%5Cend%7Bboxed%7D%0A%0AThis+text+is+also+%5Ctextit%7Boutside%7D+the+environment.%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![带可选参数的环境](/files/a54a4a212ef7002c1f08938d6448673188508015)

### 编号环境

编号环境可以手动创建，也可以直接使用命令 `\newtheorem`创建，如下例所示：

```latex
\documentclass{article}
% Define our numbered environment within the preamble
\newcounter{example}[section]
\newenvironment{example}[1][]{\refstepcounter{example}\par\medskip
   \noindent \textbf{Example~\theexample. #1} \rmfamily}{\medskip}

% Another numbered environment defined with \newtheorem
\usepackage{amsmath} % For the \newtheorem command
\newtheorem{SampleEnv}{Sample Environment}[section]
\begin{document}

\section{User-defined numbered environments}

\begin{example}
第一个用户自定义编号环境（编号 \theexample）。
\end{example}

\begin{example}
第二个用户自定义编号环境（编号 \theexample）。
\end{example}

\section{More user-defined numbered environments}
注意示例编号已重新从 1 开始：

\begin{example}
第一个用户自定义编号环境（编号 \theexample）。
\end{example}

\begin{SampleEnv}
使用 \verb|\newtheorem| 命令创建的用户自定义环境。
\end{SampleEnv}
\end{document}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Creating+a+numbered+environment\&snip=%5Cdocumentclass%7Barticle%7D%0A%25+Define+our+numbered+environment+within+the+preamble%0A%5Cnewcounter%7Bexample%7D%5Bsection%5D%0A%5Cnewenvironment%7Bexample%7D%5B1%5D%5B%5D%7B%5Crefstepcounter%7Bexample%7D%5Cpar%5Cmedskip%0A+++%5Cnoindent+%5Ctextbf%7BExample%7E%5Ctheexample.+%231%7D+%5Crmfamily%7D%7B%5Cmedskip%7D%0A%0A%25+Another+numbered+environment+defined+with+%5Cnewtheorem%0A%5Cusepackage%7Bamsmath%7D+%25+For+the+%5Cnewtheorem+command%0A%5Cnewtheorem%7BSampleEnv%7D%7BSample+Environment%7D%5Bsection%5D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Csection%7BUser-defined+numbered+environments%7D%0A%0A%5Cbegin%7Bexample%7D%0AFirst+user-defined+numbered+environment+%28number+%5Ctheexample%29.%0A%5Cend%7Bexample%7D%0A%0A%5Cbegin%7Bexample%7D%0ASecond+user-defined+numbered+environment+%28number+%5Ctheexample%29.%0A%5Cend%7Bexample%7D%0A%0A%5Csection%7BMore+user-defined+numbered+environments%7D%0ANote+how+the+example+numbering+has+restarted+at+1%3A%0A%0A%5Cbegin%7Bexample%7D%0AFirst+user-defined+numbered+environment+%28number+%5Ctheexample%29.%0A%5Cend%7Bexample%7D%0A%0A%5Cbegin%7BSampleEnv%7D%0AUser-defined+environment+created+with+the+%5Cverb%7C%5Cnewtheorem%7C+command.%0A%5Cend%7BSampleEnv%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![用户自定义编号环境示例](/files/f5fa08f142edd554115f8ec363ff52f9d151d37f)

#### 一些说明

* 在手动定义的 `example` 环境中，命令 `\newcounter{example}[section]` 会创建一个计数器，也称为 `example`。 `example` 计数器：
  * 通过使用 `\refstepcounter{example}` 在环境定义中被增加 1；
  * 每次新的 `\section{...}` 开始时重置；
  * 一个变量，其当前值可通过 `\theexample`进行排版。参见 [有关计数器的文章](/latex/zh-cn/ge-shi-hua/10-counters.md) 以了解更多。
* 命令 `\newtheorem` 直接创建一个编号环境，并接受三个参数：
  * 新环境的名称： `SampleEnv` 在我们的示例中；
  * 在行首以粗体打印的文本： `Sample Environment` 在我们的示例中；
  * 一个可选参数，用于决定何时重置计数器；如果使用它，则计数器前面会加上该重置计数器的值： `section` 在我们的示例中。

该 [`amsthm` 宏包](https://ctan.org/pkg/amsthm?lang=en)，以及 `amsmath`，提供了与 `\newtheorem`配套的有用附加定义；参见 [定理与证明](/latex/zh-cn/te-ding-ling-yu/01-theorems-and-proofs.md) 以了解更多细节。

## 重新定义现有环境

环境可以使用 `\renewenvironment` 重新定义，其语法与 `\newenvironment`相同——参见 [定义新环境](#defining-a-new-environment) 部分以了解各参数的说明：

```
\newenvironment{name}[numarg][optarg_default]{begin_def}{end_def}
```

下面的示例重新定义 `itemize` 环境——这只是一个用来说明过程的示例，不应在真实文档中照搬。新的 `itemize` 环境不再生成项目符号列表；相反，它会将其中的文本居中并强调（斜体化）（使用 `\em` 命令）。

```latex
\documentclass{article}
% Redefine the environment in the preamble
\renewenvironment{itemize}
{\begin{center}\em}
{\end{center}}
\begin{document}

\begin{itemize}
我们已重新定义 \texttt{itemize} 环境，使其中的任何文本
都会居中并强调（斜体化）。它不再创建
项目符号列表——这仅仅是一个示例，并不打算用于
真实文档中！
\end{itemize}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Redefining+an+existing+environment\&snip=%5Cdocumentclass%7Barticle%7D%0A%25+Redefine+the+environment+in+the+preamble%0A%5Crenewenvironment%7Bitemize%7D%0A%7B%5Cbegin%7Bcenter%7D%5Cem%7D%0A%7B%5Cend%7Bcenter%7D%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cbegin%7Bitemize%7D%0AWe+have+redefined+the+%5Ctexttt%7Bitemize%7D+environment+so+that+any+text+%0Awithin+it+is+centred+and+emphasised+%28italicized%29.+It+no+longer+creates%0Aa+bulleted+list---this+is+only+an+example+and+not+intended+for+use+%0Ain+real+documents%21%0A%5Cend%7Bitemize%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![重新定义 itemize 环境的示例](/files/fb5eee12d15bb7e81e8def335a841a51d487cc84)

## 进一步阅读

更多信息请参见：

* [命令](/latex/zh-cn/ming-ling/01-commands.md)
* [理解宏包和类文件](/latex/zh-cn/lei-wen-jian/01-understanding-packages-and-class-files.md)
* [编写你自己的宏包](/latex/zh-cn/lei-wen-jian/03-writing-your-own-package.md)
* [编写你自己的类](/latex/zh-cn/lei-wen-jian/04-writing-your-own-class.md)
* [LaTeX 中的长度](/latex/zh-cn/ge-shi-hua/01-lengths-in-latex.md)
* [在 LaTeX 中使用颜色](/latex/zh-cn/ge-shi-hua/13-using-colors-in-latex.md)
* [页面大小和页边距](/latex/zh-cn/ge-shi-hua/07-page-size-and-margins.md)
* [宏包和类文件列表](/latex/zh-cn/lei-wen-jian/02-overleaf-and-tex-live.md)
* [LaTeX2ε 的不算太短的介绍](http://www.ctan.org/tex-archive/info/lshort/)
* [WikiBooks 上的 LaTeX/Creating\_Packages](http://en.wikibooks.org/wiki/LaTeX/Creating_Packages)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/ming-ling/02-environments.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
