"""Offline LaTeX verification lab for Chapter 03 (install)."""
import json
import re
VERSION = "CPython 3.12.14 offline LaTeX toolchain & document-class verifier"
def case_platform_install_and_package_managers():
platforms = {
"Windows": {"distributions": ["MiKTeX", "TeX Live"], "path_subdir": "bin", "pkg_tools": ["MiKTeX Console", "tlmgr"]},
"macOS": {"distributions": ["MacTeX"], "installer_ext": ".pkg", "path_subdir": "bin", "pkg_tools": ["tlmgr"]},
"Linux": {"distributions": ["TeX Live"], "apt_cmd": "sudo apt-get install texlive-full", "pkg_tools": ["tlmgr"]},
}
tlmgr_cmd = "tlmgr install geometry"
actual = {
"platform_count": len(platforms),
"macos_installer": platforms["macOS"]["installer_ext"],
"linux_apt_pkg": platforms["Linux"]["apt_cmd"].split()[-1],
"tlmgr_valid": bool(re.fullmatch(r"tlmgr\s+install\s+[a-z0-9-]+", tlmgr_cmd)),
"all_have_tlmgr": all("tlmgr" in v["pkg_tools"] for v in platforms.values()),
}
expected = {
"platform_count": 3,
"macos_installer": ".pkg",
"linux_apt_pkg": "texlive-full",
"tlmgr_valid": True,
"all_have_tlmgr": True,
}
return {
"name": "platform_install_and_package_managers",
"summary": "校验 Windows/macOS/Linux 三平台 TeX 发行版安装路径、apt 包名与 tlmgr 宏包管理命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_compiler_engines_and_aux_artifacts():
engines = {
"pdflatex": {"output": ".pdf", "native_unicode_cjk": False},
"xelatex": {"output": ".pdf", "native_unicode_cjk": True},
"lualatex": {"output": ".pdf", "native_unicode_cjk": True},
}
src = "mydocument.tex"
stem = src.removesuffix(".tex")
aux_files = [f"{stem}{ext}" for ext in (".aux", ".log", ".toc")]
chinese_doc = r"\documentclass[UTF8]{ctexart}\begin{document}你好,世界!\end{document}"
has_cjk = bool(re.search(r"[\u4e00-\u9fff]", chinese_doc))
recommended = [k for k, v in engines.items() if v["native_unicode_cjk"]] if has_cjk else ["pdflatex"]
actual = {
"engine_count": len(engines),
"output_pdf": f"{stem}.pdf",
"aux_files": aux_files,
"has_cjk": has_cjk,
"recommended_engines": recommended,
}
expected = {
"engine_count": 3,
"output_pdf": "mydocument.pdf",
"aux_files": ["mydocument.aux", "mydocument.log", "mydocument.toc"],
"has_cjk": True,
"recommended_engines": ["xelatex", "lualatex"],
}
return {
"name": "compiler_engines_and_aux_artifacts",
"summary": "验证 pdflatex/xelatex/lualatex 引擎能力、中文文档编译选型及 .aux/.log/.toc 辅助文件",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_document_classes_and_options_parser():
class_catalog = {
"article": {"has_chapter": False, "chinese_variant": "ctexart"},
"report": {"has_chapter": True, "chinese_variant": "ctexrep"},
"book": {"has_chapter": True, "chinese_variant": "ctexbook"},
"letter": {"has_chapter": False, "chinese_variant": None},
"beamer": {"has_chapter": False, "chinese_variant": "ctexbeamer"},
}
lines = [
r"\documentclass[12pt, a4paper]{article}",
r"\documentclass[12pt, a4paper]{ctexart}",
]
parsed = []
for ln in lines:
m = re.match(r"\\documentclass(?:\[([^\]]+)\])?\{([^}]+)\}", ln)
opts = [x.strip() for x in m.group(1).split(",")] if m.group(1) else []
parsed.append({"class": m.group(2), "options": opts})
actual = {
"standard_classes": sorted(class_catalog.keys()),
"chapter_classes": sorted(k for k, v in class_catalog.items() if v["has_chapter"]),
"parsed_headers": parsed,
}
expected = {
"standard_classes": ["article", "beamer", "book", "letter", "report"],
"chapter_classes": ["book", "report"],
"parsed_headers": [
{"class": "article", "options": ["12pt", "a4paper"]},
{"class": "ctexart", "options": ["12pt", "a4paper"]},
],
}
return {
"name": "document_classes_and_options_parser",
"summary": "解析五大标准文档类与中文 ctex 对应类,校验方括号字号与纸张选项(12pt, a4paper)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_first_complete_doc_and_troubleshooting():
doc = r"""
\documentclass{ctexart}
\usepackage{geometry}
\geometry{a4paper, margin=2.5cm}
\title{我的第一份完整文档}
\author{林远}
\date{\today}
\begin{document}
\maketitle
你好,\LaTeX{}!这份文档由 XeLaTeX 编译生成。
\begin{itemize}
\item 写数学公式,例如勾股定理 $a^2 + b^2 = c^2$;
\item 自动生成章节编号和目录;
\item 让长文档保持格式统一。
\end{itemize}
\end{document}
"""
pkgs = re.findall(r"\\usepackage(?:\[[^\]]*\])?\{([^}]+)\}", doc)
geom_pos = doc.find(r"\usepackage{geometry}")
geom_cfg_pos = doc.find(r"\geometry{")
items = re.findall(r"\\item\s+(.+)", doc)
def diagnose(symptom: str) -> str:
if "Undefined control sequence" in symptom:
return "check_spelling_or_usepackage"
if "not found" in symptom and ".sty" in symptom:
return "tlmgr_install_package"
if "??" in symptom:
return "recompile_second_pass"
if "中文" in symptom:
return "switch_to_xelatex"
if "超时" in symptom:
return "simplify_or_compile_locally"
return "unknown"
actual = {
"packages": pkgs,
"geometry_loaded_before_config": 0 <= geom_pos < geom_cfg_pos,
"item_count": len(items),
"has_today": r"\today" in doc,
"diagnostics": {
"cjk": diagnose("中文显示空白或直接报错"),
"undef": diagnose("Undefined control sequence"),
"sty": diagnose("File 'geometry.sty' not found"),
"ref": diagnose("目录、引用显示为 ??"),
"timeout": diagnose("Overleaf 编译超时"),
},
}
expected = {
"packages": ["geometry"],
"geometry_loaded_before_config": True,
"item_count": 3,
"has_today": True,
"diagnostics": {
"cjk": "switch_to_xelatex",
"undef": "check_spelling_or_usepackage",
"sty": "tlmgr_install_package",
"ref": "recompile_second_pass",
"timeout": "simplify_or_compile_locally",
},
}
return {
"name": "first_complete_doc_and_troubleshooting",
"summary": "检验首份完整中文文档宏包加载顺序、列表条目,并测试五类高频新手编译故障诊断器",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_platform_install_and_package_managers(),
case_compiler_engines_and_aux_artifacts(),
case_document_classes_and_options_parser(),
case_first_complete_doc_and_troubleshooting(),
]
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-install-lab/explore-install.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-install.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2295.zip
课程关联工程包(登记关联12章) · 含当前章节或实例 · mbskycom202612a2294.zip