"""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()
本例需在 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。
入口文件:projects/latex-latex-structure-lab/explore-latex-structure.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-latex-structure.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2304.zip
课程关联工程包(登记关联12章) · 含当前章节或实例 · mbskycom202612a2294.zip