LaTeX 文档结构与排版
系统讲解标题区声明、多级章节自动编号与脚注、两遍目录生成与深度控制、geometry 页面边距、fancyhdr 页眉页脚六槽位及换页断行控制。
学完这一章,你能够
- 系统讲解标题区声明、多级章节自动编号与脚注、两遍目录生成与深度控制、geometry 页面边距、fancyhdr 页眉页脚六槽位及换页断行控制。
文档骨架概览与标题区声明
本章聚焦长文档的整体“骨架”设计,依次解决标题区排布、多级章节自动编号、目录自动提取、页面版心边距以及页眉页脚定制问题。这些机制共同遵循“一次配置、全局自动生效”的理念,正是 LaTeX 在论文与专著排版中大幅降低维护成本的核心优势。
构建规范标题区分为声明与渲染两步:先在导言区用 `\title{...}`(必填,内部可用 `\\` 断行)、`\author{张三 \and 李四}`(多作者用 `\and` 分隔,可附 `\thanks{...}` 标注单位脚注)和 `\date{\today}`(填固定日期或留空 `{}` 隐藏日期)登记元信息;随后在正文区开头调用 `\maketitle`,编译器即自动居中渲染完整标题块(详见标题区命令表)。
多级章节自动编号、星号命令与连续脚注
章节命令是组织结构化文档的基本单元,覆盖从 `\part`、`\chapter`(仅 `report`/`book` 可用)到 `\section`、`\subsection`、`\subsubsection` 及不编号的 `\paragraph` 共六个层级(详见章节层级表)。其自动化价值突出体现在两点:在文中任意位置增删章节后,后续编号全部自动顺延重排;若某节(如致谢、前言)不需要编号也不必进入目录,只需在命令名后加星号写成 `\section*{...}`。
在示例文档编译结果中,一级至三级标题会自动获得 `1`、`1.1`、`2.1.1` 的递进编号。插入注释性说明时,在正文对应词句后紧跟 `\footnote{脚注内容}` 即可在原位标注上标序号并将说明文字排至本页底部,全篇编号连续自增;切忌在 `\footnote{...}` 内部再嵌套 `\footnote`,以免引发排版与计数器错乱。
自动目录生成与深度计数器控制
生成带页码的目录仅需在正文合适位置(通常位于 `\begin{document}` 之后并搭配 `\newpage` 让目录独占一页)写入 `\tableofcontents`。由于目录内容与页码经由 `.aux` 与 `.toc` 辅助文件传递,新增或改动章节后首次编译结果可能滞后,再编译一遍即可同步最新页码。若需精细限制目录收录层级或正文编号深度,可在导言区设置计数器:例如 `\setcounter{tocdepth}{2}` 表示目录仅收录到 `\subsection`,配合 `\setcounter{secnumdepth}{2}` 可同步控制正文编号止于二级小节。
页面几何布局(geometry)与页眉页脚(fancyhdr)
纸张规格、四边页边距与版心尺寸统一交由 `geometry` 宏包管理。配置支持两种完全等价的写法:选项较少时直接置于方括号中(`\usepackage[a4paper, margin=2.5cm]{geometry}`);选项较多时先 `\usepackage{geometry}` 再通过 `\geometry{a4paper, margin=2.5cm, includefoot}` 分行声明(`includefoot` 可将页脚纳入版心,防止页脚悬出底边距)。务必牢记宏包选项始终使用方括号 `[ ]` 而非花括号 `{ }`。针对国内双面装订论文,还可追加 `bindingoffset=1cm` 为装订侧预留额外空白。
页眉与页脚定制采用 `fancyhdr` 宏包,它将页眉和页脚各自划分为左(`L`)、中(`C`)、右(`R`)三个槽位。经典学术配置先声明 `\pagestyle{fancy}` 并执行 `\fancyhf{}` 清空默认样式避免页码残留,再用 `\fancyhead[L]{\nouppercase\leftmark}` 显示当前一级章节名、`\fancyhead[R]{第 \thepage 页}` 显示页码、`\fancyfoot[C]{...}` 填充页脚文字,并以 `\renewcommand{\headrulewidth}{0.4pt}` 调整页眉分隔线粗细。其中 `\leftmark` 与 `\rightmark` 相当于动态书签,会在翻页时自动更新为当前页所属章节标题。
换页断行控制与本章结构小结
段落内强制换行使用 `\\`,而页面级分页则主要依靠 `\newpage` 与 `\clearpage`(两者及 `\linebreak`、`\pagebreak` 的差异见下表)。写作时应尽量信任 LaTeX 的自动分页算法,不要为了凑齐视觉页面而频繁手动插入 `\newpage`,否则稍改前文便会引发全篇空页错位;手动换页仅建议保留给目录结尾、章节收尾等结构性断点(尤其在含浮动图表处优先使用 `\clearpage` 冲刷未排浮动体)。末表汇总了本章全部文档骨架命令及其导言区/正文区归属。
标题区声明与渲染命令
| 命令 | 作用 | 常用写法 |
| \title{...} | 在导言区声明文档主标题 | 长标题内部可用 \\ 手动换行 |
| \author{...} | 在导言区声明作者信息 | 多位作者用 \and 分隔,\thanks 可附注单位脚注 |
| \date{...} | 在导言区声明日期 | \today 取编译当天;可手写固定日期;{} 隐藏日期 |
| \maketitle | 在正文区渲染居中标题块 | 通常紧跟 \begin{document} 之后调用 |
LaTeX 章节层级与适用文档类
| 命令 | 层级 | 适用文档类 |
| \part{...} | 部分(0 级,独立编号体系) | article / report / book |
| \chapter{...} | 章(1 级,默认独立新起一页) | 仅 report / book(含 ctexrep / ctexbook) |
| \section{...} | 节(在 article 中为最高 1 级标题) | 全部标准文档类 |
| \subsection{...} | 小节(2 级) | 全部标准文档类 |
| \subsubsection{...} | 小小节(3 级) | 全部标准文档类 |
| \paragraph{...} | 带加粗小标题的段落(默认不编号) | 全部标准文档类 |
geometry 宏包常用页面布局选项
| 选项 | 含义 | 示例 |
| margin | 一次性统一设置上下左右四边页边距 | margin=2.5cm |
| top / bottom / left / right | 分别精确控制单个方向的页边距 | left=3cm, right=3cm |
| a4paper / a5paper / letterpaper | 指定目标印刷纸张规格 | a4paper |
| landscape | 切换为横向页面排版 | 宽幅表格或横向讲义 |
| textwidth / textheight | 直接限定正文版心的宽度或高度 | textwidth=15cm |
fancyhdr 页眉页脚六槽位控制命令
| 命令 | 控制的槽位 |
| \fancyhead[L]{...}(\lhead) | 页眉左侧区域 |
| \fancyhead[C]{...}(\chead) | 页眉居中区域 |
| \fancyhead[R]{...}(\rhead) | 页眉右侧区域 |
| \fancyfoot[L]{...}(\lfoot) | 页脚左侧区域 |
| \fancyfoot[C]{...}(\cfoot) | 页脚居中区域 |
| \fancyfoot[R]{...}(\rfoot) | 页脚右侧区域 |
换页与强制断行命令对比
| 命令 | 作用 | 使用建议 |
| \newpage | 立即结束当前页,从新页面顶部继续排版 | 用于目录后等常规结构换页 |
| \clearpage | 换页并强制先输出所有排队的浮动图表 | 章节收尾、附录前与文档末尾更稳妥 |
| \linebreak | 在当前位置强制断行并拉伸本行至两端对齐 | 尽量少用,优先交给 TeX 自动断行算法 |
| \pagebreak | 建议引擎在此处换页并垂直拉伸当前页内容 | 日常少用,可与 \newpage 的底部留白行为对比 |
文档结构与页面排版命令小结
| 需求 | 命令 | 所属位置 |
| 标题区 | \title、\author、\date + \maketitle | 导言区声明,正文区渲染 |
| 章节 | \section / \subsection / \subsubsection | 正文区 |
| 脚注 | \footnote{...} | 正文区 |
| 目录 | \tableofcontents | 正文区(常紧跟 \begin{document}) |
| 页面边距 | geometry 宏包 | 导言区 |
| 页眉页脚 | fancyhdr 宏包 | 导言区 |
离线校验多级章节编号、两遍目录深度、geometry 等价配置与 fancyhdr 六槽位
展开查看收起
"""Offline LaTeX verification lab for Chapter 04 (latex-structure)."""
import json
import re
VERSION = "CPython 3.12.14 offline LaTeX document structure & page-layout verifier"
def case_title_area_and_section_numbering():
doc = r"""
\documentclass{ctexart}
\title{论文标题}
\author{张三 \and 李四}
\date{\today}
\begin{document}
\maketitle
\section{引言}
\subsection{研究背景}
这里介绍研究背景\footnote{这是一条脚注,编号与排版都是自动的。}。
\subsection{研究意义}
\section{方法}
\subsection{数据采集}
\subsubsection{样本选择}
\subsection{模型设计}
\section*{致谢}
\section{结论}
\end{document}
"""
authors = [a.strip() for a in re.search(r"\\author\{([^}]+)\}", doc).group(1).split(r"\and")]
counters = [0, 0, 0]
numbered = []
unnumbered = []
for cmd, star, title in re.findall(r"\\(section|subsection|subsubsection)(\*)?\{([^}]+)\}", doc):
if star:
unnumbered.append(title)
continue
if cmd == "section":
counters[0] += 1
counters[1] = 0
counters[2] = 0
num = f"{counters[0]}"
elif cmd == "subsection":
counters[1] += 1
counters[2] = 0
num = f"{counters[0]}.{counters[1]}"
else:
counters[2] += 1
num = f"{counters[0]}.{counters[1]}.{counters[2]}"
numbered.append(f"{num} {title}")
footnotes = re.findall(r"\\footnote\{([^}]+)\}", doc)
nested_footnote = any(r"\footnote" in fn for fn in footnotes)
actual = {
"authors": authors,
"numbered_outline": numbered,
"unnumbered_sections": unnumbered,
"footnote_count": len(footnotes),
"has_nested_footnote": nested_footnote,
}
expected = {
"authors": ["张三", "李四"],
"numbered_outline": [
"1 引言",
"1.1 研究背景",
"1.2 研究意义",
"2 方法",
"2.1 数据采集",
"2.1.1 样本选择",
"2.2 模型设计",
"3 结论",
],
"unnumbered_sections": ["致谢"],
"footnote_count": 1,
"has_nested_footnote": False,
}
return {
"name": "title_area_and_section_numbering",
"summary": "解析标题区多作者 \\and、三级章节自动编号、星号不编号章节及连续脚注规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_toc_depth_and_two_pass_aux():
outline = [
(1, "1", "引言"),
(2, "1.1", "研究背景"),
(1, "2", "方法"),
(2, "2.1", "数据采集"),
(3, "2.1.1", "样本选择"),
(1, "3", "结论"),
]
tocdepth = 2
pass1_toc_entries = [] # first pass has empty .aux/.toc
pass2_toc_entries = [f"{num} {title}" for lvl, num, title in outline if lvl <= tocdepth]
actual = {
"tocdepth": tocdepth,
"pass1_count": len(pass1_toc_entries),
"pass2_entries": pass2_toc_entries,
"excluded_level3": [title for lvl, _, title in outline if lvl > tocdepth],
}
expected = {
"tocdepth": 2,
"pass1_count": 0,
"pass2_entries": ["1 引言", "1.1 研究背景", "2 方法", "2.1 数据采集", "3 结论"],
"excluded_level3": ["样本选择"],
}
return {
"name": "toc_depth_and_two_pass_aux",
"summary": "模拟 .aux/.toc 两遍编译目录生成机制并校验 tocdepth=2 深度过滤结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_geometry_options_equivalence():
form1 = r"\usepackage[a4paper, margin=2.5cm, includefoot]{geometry}"
form2 = r"""
\usepackage{geometry}
\geometry{
a4paper,
margin=2.5cm,
includefoot
}
"""
def parse_geometry(src: str) -> dict:
m = re.search(r"\\usepackage\[([^\]]+)\]\{geometry\}", src)
if not m:
m = re.search(r"\\geometry\{([^}]+)\}", src, re.S)
opts = {}
for tok in m.group(1).split(","):
tok = tok.strip()
if not tok:
continue
if "=" in tok:
k, v = [x.strip() for x in tok.split("=", 1)]
opts[k] = v
else:
opts[tok] = True
return opts
cfg1 = parse_geometry(form1)
cfg2 = parse_geometry(form2)
# A4 is 21.0cm x 29.7cm; with margin=2.5cm and bindingoffset=1.0cm -> textwidth = 21.0 - 5.0 - 1.0 = 15.0cm
a4_w = 21.0
margin = 2.5
binding = 1.0
effective_textwidth_cm = round(a4_w - 2 * margin - binding, 2)
actual = {
"forms_equivalent": cfg1 == cfg2,
"parsed_options": cfg1,
"a4_with_bindingoffset_textwidth_cm": effective_textwidth_cm,
}
expected = {
"forms_equivalent": True,
"parsed_options": {"a4paper": True, "margin": "2.5cm", "includefoot": True},
"a4_with_bindingoffset_textwidth_cm": 15.0,
}
return {
"name": "geometry_options_equivalence",
"summary": "验证 geometry 方括号与 \\geometry{} 两种写法的参数等价性及 bindingoffset 版心宽度计算",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fancyhdr_slots_and_page_breaks():
doc = r"""
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\nouppercase\leftmark}
\fancyhead[R]{第 \thepage 页}
\fancyfoot[C]{蓝色天空网 LaTeX 教程}
\renewcommand{\headrulewidth}{0.4pt}
"""
slots = {"HL": None, "HC": None, "HR": None, "FL": None, "FC": None, "FR": None}
cleared = r"\fancyhf{}" in doc
for pos, val in re.findall(r"\\fancyhead\[([LCR])\]\{(.+)\}", doc):
slots[f"H{pos}"] = val.strip()
for pos, val in re.findall(r"\\fancyfoot\[([LCR])\]\{(.+)\}", doc):
slots[f"F{pos}"] = val.strip()
rule_w = re.search(r"\\renewcommand\{\\headrulewidth\}\{([^}]+)\}", doc).group(1)
break_semantics = {
r"\newpage": {"flushes_floats": False, "scope": "page"},
r"\clearpage": {"flushes_floats": True, "scope": "page"},
r"\linebreak": {"flushes_floats": False, "scope": "line"},
r"\pagebreak": {"flushes_floats": False, "scope": "page_suggest"},
}
actual = {
"cleared_defaults": cleared,
"slots": slots,
"headrulewidth": rule_w,
"flush_float_command": [k for k, v in break_semantics.items() if v["flushes_floats"]],
}
expected = {
"cleared_defaults": True,
"slots": {
"HL": r"\nouppercase\leftmark",
"HC": None,
"HR": r"第 \thepage 页",
"FL": None,
"FC": "蓝色天空网 LaTeX 教程",
"FR": None,
},
"headrulewidth": "0.4pt",
"flush_float_command": [r"\clearpage"],
}
return {
"name": "fancyhdr_slots_and_page_breaks",
"summary": "解析 fancyhdr 六槽位配置与 \\headrulewidth,并核对 \\newpage/\\clearpage/\\linebreak/\\pagebreak 语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_title_area_and_section_numbering(),
case_toc_depth_and_two_pass_aux(),
case_geometry_options_equivalence(),
case_fancyhdr_slots_and_page_breaks(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`\newpage` 仅把后续正文切到下一页,队列中尚未排出的浮动图或表可能继续滞后;`\clearpage` 不仅换页,还会强制先把所有未处理的浮动体全部输出,避免前一章的图表漂移到下一章。