> 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-tw/zhi-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/1cb943e76f284a50146d53d999d074cc251cdc83)

## 環境

以下範例使用了 `tabular` 環境，用來排版一個小表格。 `tabular` 需要額外的參數 `{ c c c }` ，用來定義儲存格的對齊方式——請參見 [表格](/latex/zh-tw/tu-biao-yu-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/a6fa91f24b688d7029501aa929fe0d766353852f)

有些環境接受可選參數，通常會放在括號中（`[...]`).

## 定義新的環境

要定義一個新的環境，請使用 `\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/b4eb35ca822ff45d3788ff7740bac2eecf68e639)

如果我們將 `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/97dc7c341dd5b83ed075183dd0464a017a0fe40a)

### 帶編號的環境

帶編號的環境可以手動建立，或直接使用命令 `\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/c9305f718d091f180748877ac7803382f5eedfac)

#### 一些注意事項

* 在手動定義的 `範例` 環境中，命令 `\newcounter{example}[section]` 會建立一個計數器，也稱為 `範例`。 `範例` 計數器是：
  * 會透過使用 `\refstepcounter{example}` 於環境定義中；
  * 每當新的 `\section{...}` 開始時重設；
  * 一個變數，其目前值可以使用 `\theexample`。請參見 [關於計數器的文章](/latex/zh-tw/ge-shi-hua/10-counters.md) 以了解更多。
* 命令 `\newtheorem` 會直接建立一個帶編號的環境，並接受三個參數：
  * 新環境的名稱： `SampleEnv` 在我們的範例中；
  * 要在行首以粗體印出的文字： `範例環境` 在我們的範例中；
  * 一個可選參數，用來決定何時計數器重設；若使用它，計數器前面會加上該重設計數器的值： `section` 在我們的範例中。

該 [`amsthm` 套件](https://ctan.org/pkg/amsthm?lang=en)，再加上 `amsmath`，可提供與 `\newtheorem`搭配的實用額外定義；請參見 [定理與證明](/latex/zh-tw/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/14abd0535ab6330fab60cb862cdfd35780e569b5)

## 延伸閱讀

詳情請見：

* [命令](/latex/zh-tw/zhi-ling/01-commands.md)
* [了解套件與類別檔](/latex/zh-tw/lei-bie-dang/01-understanding-packages-and-class-files.md)
* [撰寫你自己的套件](/latex/zh-tw/lei-bie-dang/03-writing-your-own-package.md)
* [撰寫你自己的類別](/latex/zh-tw/lei-bie-dang/04-writing-your-own-class.md)
* [LaTeX 中的長度](/latex/zh-tw/ge-shi-hua/01-lengths-in-latex.md)
* [在 LaTeX 中使用顏色](/latex/zh-tw/ge-shi-hua/13-using-colors-in-latex.md)
* [頁面大小與邊界](/latex/zh-tw/ge-shi-hua/07-page-size-and-margins.md)
* [套件與類別檔清單](/latex/zh-tw/lei-bie-dang/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-tw/zhi-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.
