> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-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-biao-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}
%我们可以在导言区定义该环境
\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}
    参数 1 (\#1)=#1\\[1ex]
    \begin{tabular}{{{!}}p{0.9\textwidth}{{!}}}
    \hline\\
    参数 2 (\#2)=#2\\[2ex]
    }
    {
    \\\\\hline
    \end{tabular}
    \end{center}
    }
```

增强版与原版的不同之处如下：

* 包含 \[numarg]，其值为 2；
* 也包含 \[optarg\_default]，使第一个参数成为带默认值的可选参数 `这是一个盒子`.

下面的示例演示了我们升级后的某些用法 `boxed` 环境：

```latex
\documentclass{article}
% 注意第一个的默认值
% 参数由 [This is a box] 提供
\newenvironment{boxed}[2][This is a box]
    {\begin{center}
    参数 1 (\#1)=#1\\[1ex]
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline\\
    参数 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}
% 在导言区定义我们的编号环境
\newcounter{example}[section]
\newenvironment{example}[1][]{\refstepcounter{example}\par\medskip
   \noindent \textbf{示例~\theexample. #1} \rmfamily}{\medskip}

% 另一个使用 \newtheorem 定义的编号环境
\usepackage{amsmath} % 用于 \newtheorem 命令
\newtheorem{SampleEnv}{示例环境}[section]
\begin{document}

\section{用户定义的编号环境}

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

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

\section{更多用户定义的编号环境}
注意示例编号如何重新从 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)

#### 一些说明

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