> 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/zhi-shi-ku/166-writing-markdown-in-latex-documents.md).

# 在 LaTeX 文档中编写 Markdown

## 简介

要在 LaTeX 文档中使用 markdown，你需要加载 [`markdown` 包](https://www.ctan.org/pkg/markdown) 到你的文档导言区：

```latex
\usepackage[settings]{markdown}
```

其中 `[settings]` 是一个 *可选的* 用于配置或启用特定宏包功能的一组参数。请参阅 `markdown` 包 [文档](https://anorien.csc.warwick.ac.uk/mirrors/CTAN/macros/generic/markdown/markdown.html) 以获取 [该宏包参数（选项）的说明](https://anorien.csc.warwick.ac.uk/mirrors/CTAN/macros/generic/markdown/markdown.html#options).

本文将简要介绍以下两种 *内联* markdown——写在文档内部——以及导入 *external* 文本文件中的 markdown。

* **提示说明**: 通常，在 LaTeX 文档中使用 markdown 应被视为编写文档内容某些元素的一种补充且方便的选项，而不是一种可完全取代 LaTeX 本身的替代语法。

## 使用外部 markdown 文件

使用命令

```latex
\markdownInput{filename}
```

来包含 markdown 文件 `filename`.

下面的示例插入了一个名为 `example.md`的文件。使用代码清单下方的链接将它们作为 Overleaf 项目打开：

**`main.tex`**

```latex
\documentclass{article}
\title{Using the markdown package}
\usepackage[smartEllipses]{markdown}
\begin{document}

\markdownInput{example.md}

\end{document}
```

**`example.md`**

```latex
%% example.md

# 我是一个 markdown 文件。

而且我可以做 *强调*。
## 带有小标题

> 引用块是
> 这样写的。
>
> 它们可以跨越多个段落，
> 如果你愿意的话。

使用 3 个短横线表示长破折号。使用 2 个短横线表示
范围（例如，“它都在第 12--14 章中”）。
三个点 ... 将被转换为省略号
（前提是你在导言区中包含 smartEllipses 选项
）。支持 Unicode。
```

[将这些文件作为 Overleaf 项目打开。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name\[]=main.tex\&snip\[]=%5Cdocumentclass%7Barticle%7D%0A%5Ctitle%7BUsing+the+markdown+package%7D%0A%5Cusepackage%5BsmartEllipses%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5CmarkdownInput%7Bexample.md%7D%0A%0A%5Cend%7Bdocument%7D\&snip_name\[]=example.md\&snip\[]=%25%25+example.md%0A%0A%23+I%27m+a+markdown+file.%0A%0AAnd+I+can+do+%2Aemphasis%2A.%0A%23%23+With+sub-headers%0A%0A%3E+Block+quotes+are%0A%3E+written+like+so.%0A%3E%0A%3E+They+can+span+multiple+paragraphs%2C%0A%3E+if+you+like.%0A%0AUse+3+dashes+for+an+em-dash.+Use+2+dashes+for+%0Aranges+%28ex.%2C+%22it%27s+all+in+chapters+12--14%22%29.+%0AThree+dots+...+will+be+converted+to+an+ellipsis+%0A%28provided+you+include+the+smartEllipses+option+%0Ain+your+preamble%29.+Unicode+is+supported.\&main_document=main.tex)

此示例生成如下输出：

![展示 markdown 宏包输出的图示](/files/a1aed4e8fcd886dbcb698c162b0218e865ef5268)

## 使用内联 markdown

使用 `markdown` 环境：

```latex
\begin{markdown}
...你的 markdown
放在这里...
\end{markdown}
```

来编写内联 markdown，正如下面的示例所示：

```latex
\documentclass{article}
\usepackage[hashEnumerators,smartEllipses]{markdown}
\begin{document}

使用内联 markdown：

\begin{markdown}
一个 h1 标题
============

段落之间用空行分隔。

第二段。*斜体*、**粗体**和`等宽字体`。项目列表
看起来像：

* 这个
* 那个
* 另一个

> 引用块是
> 这样写的。
>
> 它们可以跨越多个段落，
> 如果你愿意的话。

一个 h2 标题
------------

这是一个编号列表（如果你想使用井号，请使用 `hashEnumerators` 选项）：

#. 第一项
#. 第二项
#. 第三项

\end{markdown}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+markdown\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5BhashEnumerators%2CsmartEllipses%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%0AUsing+inline+markdown%3A%0A%0A%5Cbegin%7Bmarkdown%7D%0AAn+h1+header%0A%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%0A%0AParagraphs+are+separated+by+a+blank+line.+%0A%0A2nd+paragraph.+%2AItalic%2A%2C+%2A%2Abold%2A%2A%2C+and+%60monospace%60.+Itemized+lists%0Alook+like%3A%0A%0A%2A+this+one%0A%2A+that+one%0A%2A+the+other+one%0A%0A%3E+Block+quotes+are%0A%3E+written+like+so.%0A%3E%0A%3E+They+can+span+multiple+paragraphs%2C%0A%3E+if+you+like.%0A%0AAn+h2+header%0A------------%0A%0AHere%27s+a+numbered+list+%28use+%60hashEnumerators%60+option+if+you+want+to+use+hashes%29%3A%0A%0A%23.+first+item%0A%23.+second+item%0A%23.+third+item%0A%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![在 Overleaf 中排版的内联 markdown 示例](/files/4606c85a6910490f5862d6f808ca0c5b8762836d)

## Markdown 宏包的功能和选项

接下来我们将探讨其中的一些 [功能和选项](https://anorien.csc.warwick.ac.uk/mirrors/CTAN/macros/generic/markdown/markdown.html) 由 `markdown` 宏包提供。

### 在 markdown 中包含代码

在 markdown 中显示代码片段（代码块）有两种机制：

* 将代码块的每一行缩进至少四个空格或一个制表符，或者
* 使用所谓的 [围栏代码块](#using-fenced-code-blocks)

#### 使用缩进显示代码块

下面的示例在每行代码开头使用 4 个或更多空格字符——某些行根据所需缩进大小使用 6、8 或 10 个空格字符：

```latex
\documentclass{article}
\usepackage{markdown}
\begin{document}
这里有一些至少缩进了 4 个空格字符的代码片段。
\vspace{6mm}

\begin{markdown}

下面是一段 C 代码：

    /* Let me iterate ... */

    int i;
    for(i=0; i<10; i++)
    {
      do-something(i)
    }

下面是一些 HTML：

    <html>
      <head>
        <title>Page Title</title>
      </head>
      <body>
        <h1>This is a Heading</h1>
          <p>This is a paragraph.</p>
      </body>
    </html>

\end{markdown}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+markdown+code+snippets\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0AHere+are+some+code+fragments+indented+by+at+least+4+space+characters.%0A%5Cvspace%7B6mm%7D%0A%0A%5Cbegin%7Bmarkdown%7D%0A%0AHere+is+a+fragment+of+C%3A%0A%0A++++%2F%2A+Let+me+iterate+...+%2A%2F%0A%0A++++int+i%3B%0A++++for%28i%3D0%3B+i%3C10%3B+i%2B%2B%29%0A++++%7B%0A++++++do-something%28i%29%0A++++%7D%0A%0AHere+is+some+HTML%3A%0A%0A++++%3Chtml%3E%0A++++++%3Chead%3E%0A++++++++%3Ctitle%3EPage+Title%3C%2Ftitle%3E%0A++++++%3C%2Fhead%3E%0A++++++%3Cbody%3E%0A++++++++%3Ch1%3EThis+is+a+Heading%3C%2Fh1%3E%0A++++++++++%3Cp%3EThis+is+a+paragraph.%3C%2Fp%3E%0A++++++%3C%2Fbody%3E%0A++++%3C%2Fhtml%3E%0A%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![通过 markdown 排版代码的示例](/files/79cd99366a2ec5f33ac15341209bf40c3e52beec)

#### 使用围栏代码块

围栏代码块可以通过编写以下任一形式来创建

* 三个反引号（` ``` `），或者
* 三个波浪号（`~~~`)

在代码块前后的行中写入。使用这种方法，你不必缩进任何行，但你需要使用 `fencedCode` 导言区中的选项：

```latex
\usepackage[fencedCode]{markdown}
```

下面是一个使用 3 个反引号（` ``` `):

````latex
\documentclass{article}
\usepackage[fencedCode]{markdown}
\begin{document}
\begin{markdown}

```
if (a > 3) {
    moveShip(5 * gravity, DOWN);
}
```

```
    <html>
      <head>
        <title>Page Title</title>
      </head>
      <body>
        <h1>This is a Heading</h1>
          <p>This is a paragraph.</p>
      </body>
    </html>
```
\end{markdown}
\end{document}
````

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+markdown+fenced+code+blocks\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5BfencedCode%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bmarkdown%7D%0A%0A%60%60%60%0Aif+%28a+%3E+3%29+%7B%0A++++moveShip%285+%2A+gravity%2C+DOWN%29%3B%0A%7D%0A%60%60%60%0A%0A%60%60%60%0A++++%3Chtml%3E%0A++++++%3Chead%3E%0A++++++++%3Ctitle%3EPage+Title%3C%2Ftitle%3E%0A++++++%3C%2Fhead%3E%0A++++++%3Cbody%3E%0A++++++++%3Ch1%3EThis+is+a+Heading%3C%2Fh1%3E%0A++++++++++%3Cp%3EThis+is+a+paragraph.%3C%2Fp%3E%0A++++++%3C%2Fbody%3E%0A++++%3C%2Fhtml%3E%0A%60%60%60%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![在 markdown LaTeX 宏包中使用围栏代码块](/files/11a9af3cb94f563c9c0d537690d667d69abc7bc4)

#### 语法高亮

围栏代码块通过在第一组反引号（`` ` ``）之后写上语言名称来支持语法高亮。举例来说，下面的代码块通过将第一组反引号写成 ` ``` js `:

````latex
``` js
if (a > 3) {
    moveShip(5 * gravity, DOWN);
}
```
````

对于 LaTeX， `minted` 宏包可用于语法高亮，如下一个示例所示，其中包含一些 Javascript（` ``` js `）和 HTML（` ``` html `):

````latex
\documentclass{article}
\usepackage{minted}
\usepackage[fencedCode]{markdown}
\begin{document}
\begin{markdown}

``` js
if (a > 3) {
    moveShip(5 * gravity, DOWN);
}
```

``` html
    <html>
      <head>
        <title>Page Title</title>
      </head>
      <body>
        <h1>This is a Heading</h1>
          <p>This is a paragraph.</p>
      </body>
    </html>
```
\end{markdown}
\end{document}
````

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+markdown+fenced+code+blocks\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bminted%7D%0A%5Cusepackage%5BfencedCode%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bmarkdown%7D%0A%0A%60%60%60+js%0Aif+%28a+%3E+3%29+%7B%0A++++moveShip%285+%2A+gravity%2C+DOWN%29%3B%0A%7D%0A%60%60%60%0A%0A%60%60%60+html%0A++++%3Chtml%3E%0A++++++%3Chead%3E%0A++++++++%3Ctitle%3EPage+Title%3C%2Ftitle%3E%0A++++++%3C%2Fhead%3E%0A++++++%3Cbody%3E%0A++++++++%3Ch1%3EThis+is+a+Heading%3C%2Fh1%3E%0A++++++++++%3Cp%3EThis+is+a+paragraph.%3C%2Fp%3E%0A++++++%3C%2Fbody%3E%0A++++%3C%2Fhtml%3E%0A%60%60%60%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![使用 minted 和 markdown 进行语法高亮](/files/7e6f94273d423d6aaf7bb180b15d9cb936649c63)

### 列表

前面的示例 [演示了如何创建无序列表](#using-inline-markdown) 在 markdown 中使用 `*` 字符。可以使用 `#` 字符创建有序列表，如果 `hashEnumerators` 选项已被指定：

```latex
\usepackage[hashEnumerators]{markdown}
```

也可以创建嵌套列表，如下一个示例所示：

```latex
\documentclass{article}
\usepackage[hashEnumerators]{markdown}
\begin{document}
\begin{markdown}
这是一个包含嵌套列表的编号列表：

#. 首先，准备以下食材：

      * 胡萝卜
      * 芹菜
      * 扁豆

#. 烧一些水。

#. 把所有东西倒进锅里，并遵循以下算法：

        找到木勺
        揭开锅盖
        搅拌
        盖上锅盖
        把木勺摇摇晃晃地架在锅柄上
        等待 10 分钟
        转到第一步（或者完成后关掉炉火）

    不要碰到木勺，否则它会掉下来。
\end{markdown}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Creating+a+nested+list+in+markdown\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5BhashEnumerators%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bmarkdown%7D%0AHere+is+a+numbered+list+that+contains+a+nested+list%3A%0A%0A%23.+First%2C+get+these+ingredients%3A%0A%0A++++++%2A+carrots%0A++++++%2A+celery%0A++++++%2A+lentils%0A%0A%23.+Boil+some+water.%0A%0A%23.+Dump+everything+in+the+pot+and+follow+this+algorithm%3A%0A%0A++++++++find+wooden+spoon%0A++++++++uncover+pot%0A++++++++stir%0A++++++++cover+pot%0A++++++++balance+wooden+spoon+precariously+on+pot+handle%0A++++++++wait+10+minutes%0A++++++++goto+first+step+%28or+shut+off+burner+when+done%29%0A%0A++++Do+not+bump+wooden+spoon+or+it+will+fall.%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![使用 LaTeX markdown 宏包创建编号列表](/files/8ecf3054c009846482fa126a7b5606d35ba691c9)

### 在 markdown 中包含 LaTeX

如果你启用 `hybrid` 选项，就可以在 Markdown 中混合 LaTeX 代码！

```latex
\documentclass{article}
\usepackage[hybrid]{markdown}
\begin{document}

\begin{markdown}
可以像这样创建行内数学公式：$\omega = d\phi / dt$。
显示数学公式可以写成：

\begin{equation}
I = \int \rho R^{2} dV
\end{equation}

\end{markdown}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+LaTeX+code+in+markdown\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bhybrid%5D%7Bmarkdown%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cbegin%7Bmarkdown%7D%0AInline+math+equations+can+be+created+like+this%3A+%24%5Comega+%3D+d%5Cphi+%2F+dt%24.+%0ADisplay+math+can+be+written+as%3A%0A%0A%5Cbegin%7Bequation%7D%0AI+%3D+%5Cint+%5Crho+R%5E%7B2%7D+dV%0A%5Cend%7Bequation%7D%0A%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![在 markdown 中使用 LaTeX 代码](/files/4f00ee605b2318387b5787ec1bb55155921d50bd)

### 包含图像

* **注意**：下一个示例使用了一个图形文件（`example-image.pdf`）由 `mwe` 宏包提供。这些图形文件由 TeX Live 分发，因此存储在 Overleaf 的服务器上，可作为图像占位符使用，例如下面的示例。

可以通过编写以下格式的标记在 markdown 中包含图像：

```latex
![alt-text](file-name "image caption")
```

希望这些参数名 `alt-text`, `file-name` 和 `"image caption"` 能说明它们的作用。这里有一个示例来演示：

```latex
\documentclass{article}
\usepackage[hybrid]{markdown}
% The mwe package provides example images. Loading it is
% not essential because those images are in LaTeX's search path.
% Here, we load it for clarity in this example.
\usepackage{mwe}
\begin{document}
\begin{markdown}
这个示例展示了如何导入图形文件。这里我们使用的是一个
由 `mwe` 宏包提供的示例图像。

% Use \setkeys{Gin} if you need to change an image's display size

\setkeys{Gin}{width=.5\linewidth}
![This is alt text to describe my image.](example-image.jpg "An example image provided by the \texttt{mwe} package.")
\end{markdown}
\end{document}
```

[在 Overleaf 中打开此示例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Using+images+in+markdown\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bhybrid%5D%7Bmarkdown%7D%0A%25+The+mwe+package+provides+example+images.+Loading+it+is%0A%25+not+essential+because+those+images+are+in+LaTeX%27s+search+path.+%0A%25+Here%2C+we+load+it+for+clarity+in+this+example.%0A%5Cusepackage%7Bmwe%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bmarkdown%7D%0AThis+example+shows+how+to+import+a+graphics+file.+Here+we+are+using+an%0Aexample+image+provided+by+the+%60mwe%60+package.%0A%0A%25+Use+%5Csetkeys%7BGin%7D+if+you+need+to+change+an+image%27s+display+size%0A%0A%5Csetkeys%7BGin%7D%7Bwidth%3D.5%5Clinewidth%7D%0A%21%5BThis+is+alt+text+to+describe+my+image.%5D%28example-image.jpg+%22An+example+image+provided+by+the+%5Ctexttt%7Bmwe%7D+package.%22%29%0A%5Cend%7Bmarkdown%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![展示如何在 markdown 中导入图像](/files/0883cd708558061ff26b67991fbb636314f30d4b)

#### 关于图像宽度的说明

与大多数宏包一样， `markdown` 会加载其他宏包，包括 [`keyval`](https://ctan.org/pkg/keyval?lang=en) 和 [`graphicx`](https://ctan.org/pkg/graphicx?lang=en)，以便使用它们提供的命令和功能。这里，图像宽度是通过以下方式设置的： `\setkeys` 命令，它由 `keyvals`. `Gin` 是由“键族”定义的 `graphicx` 宏包提供。

* **注意**：因为这里使用了一个 LaTeX 命令， `\setkeys`，被使用 *在* 该 `markdown` 环境中， `hybrid` markdown 宏包的选项是必需的。

## 延伸阅读

Overleaf 还发布了其他关于使用 markdown 的文章：

* [如何在 Overleaf 中使用 Markdown 写作](/latex/zh-cn/shen-du-wen-zhang/30-how-to-write-in-markdown-on-overleaf.md)
* [将 Markdown 以优雅样式转换为 LaTeX](/latex/zh-cn/shen-du-wen-zhang/32-markdown-into-latex-with-style.md)


---

# 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/zhi-shi-ku/166-writing-markdown-in-latex-documents.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.
