蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验交叉引用闭环、hyperref 末位加载顺序、.bib 解析与四步编译/BibLaTeX 规则

PYTHONWindows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。explore-latex-references.py
explore-latex-references.py211 行
"""Offline LaTeX verification lab for Chapter 10 (latex-references)."""
import json
import re

VERSION = "CPython 3.12.14 offline LaTeX cross-reference & BibTeX/BibLaTeX verifier"


def case_cross_reference_label_resolution():
    doc = r"""
\documentclass{ctexart}
\usepackage{amsmath, graphicx}
\begin{document}
\section{方法}\label{sec:method}
本节介绍模型结构,损失函数见式~\eqref{eq:loss},
实验分析见第~\ref{sec:result} 节。
\begin{equation}\label{eq:loss}
  L = \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right)^2
\end{equation}
\section{实验结果}\label{sec:result}
方法(第~\ref{sec:method} 节)的损失由式~\eqref{eq:loss} 度量,
曲线形态见图~\ref{fig:sin},所在页码见第~\pageref{sec:method} 页。
\begin{figure}[htbp]
  \centering
  \includegraphics[width=0.5\textwidth]{sin}
  \caption{正弦曲线}
  \label{fig:sin}
\end{figure}
\end{document}
"""
    labels = re.findall(r"\\label\{([^}]+)\}", doc)
    refs = re.findall(r"\\(?:ref|eqref|pageref)\{([^}]+)\}", doc)
    unresolved = sorted(set(refs) - set(labels))
    valid_prefixes = {"sec", "fig", "tab", "eq", "chap"}
    prefixes_used = sorted({lbl.split(":")[0] for lbl in labels if ":" in lbl})

    actual = {
        "label_count": len(labels),
        "ref_call_count": len(refs),
        "unresolved_refs": unresolved,
        "prefixes_used": prefixes_used,
        "all_prefixes_standard": set(prefixes_used) <= valid_prefixes,
    }
    expected = {
        "label_count": 4,
        "ref_call_count": 6,
        "unresolved_refs": [],
        "prefixes_used": ["eq", "fig", "sec"],
        "all_prefixes_standard": True,
    }
    return {
        "name": "cross_reference_label_resolution",
        "summary": "解析 \\label 与 \\ref/\\eqref/\\pageref 交叉引用闭环并检查前缀命名规范(sec:/fig:/eq:)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_hyperref_load_order_and_options():
    good_preamble = [
        r"\usepackage{amsmath}",
        r"\usepackage{graphicx}",
        r"\usepackage[colorlinks=true, linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref}",
    ]
    bad_preamble = [
        r"\usepackage{hyperref}",
        r"\usepackage{amsmath}",
        r"\usepackage{graphicx}",
    ]

    def hyperref_is_last(lines: list[str]) -> bool:
        pkgs = [re.search(r"\{([^}]+)\}", ln).group(1) for ln in lines]
        return "hyperref" in pkgs and pkgs[-1] == "hyperref"

    opt_str = re.search(r"\[([^\]]+)\]", good_preamble[-1]).group(1)
    opts = dict(kv.strip().split("=", 1) for kv in opt_str.split(","))
    actual = {
        "good_order_valid": hyperref_is_last(good_preamble),
        "bad_order_valid": hyperref_is_last(bad_preamble),
        "colorlinks": opts["colorlinks"],
        "link_colors": [opts["linkcolor"], opts["citecolor"], opts["urlcolor"]],
    }
    expected = {
        "good_order_valid": True,
        "bad_order_valid": False,
        "colorlinks": "true",
        "link_colors": ["blue", "blue", "blue"],
    }
    return {
        "name": "hyperref_load_order_and_options",
        "summary": "验证 hyperref 作为导言区末位加载宏包的顺序约束及 colorlinks/linkcolor/citecolor/urlcolor 参数",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bibtex_database_and_cite_matching():
    bib_src = r"""
@article{alexnet2012,
  author  = {Krizhevsky, Alex and Sutskever, Ilya and Hinton, Geoffrey E.},
  title   = {ImageNet Classification with Deep Convolutional Neural Networks},
  journal = {Communications of the ACM},
  year    = {2017},
  volume  = {60},
  pages   = {84--90}
}

@book{goodfellow2016,
  author    = {Goodfellow, Ian and Bengio, Yoshua and Courville, Aaron},
  title     = {Deep Learning},
  publisher = {MIT Press},
  year      = {2016}
}
"""
    tex_src = r"""
\documentclass{ctexart}
\begin{document}
深度学习的突破源于 AlexNet~\cite{alexnet2012},
系统教材可参考~\cite{goodfellow2016}。
\bibliographystyle{plain}
\bibliography{refs}
\end{document}
"""
    entries = {}
    for etype, key, body in re.findall(r"@(\w+)\{([^,]+),(.+?)\n\}", bib_src, re.S):
        fields = dict(re.findall(r"(\w+)\s*=\s*\{([^}]+)\}", body))
        entries[key.strip()] = {"type": etype.lower(), "fields": sorted(fields.keys())}
    cites = re.findall(r"\\cite\{([^}]+)\}", tex_src)
    missing_cites = [c for c in cites if c not in entries]
    bib_arg = re.search(r"\\bibliography\{([^}]+)\}", tex_src).group(1)

    actual = {
        "entry_keys": sorted(entries.keys()),
        "entry_types": {k: v["type"] for k, v in entries.items()},
        "cites_in_tex": cites,
        "missing_cites": missing_cites,
        "bibliography_omits_bib_ext": not bib_arg.endswith(".bib"),
    }
    expected = {
        "entry_keys": ["alexnet2012", "goodfellow2016"],
        "entry_types": {"alexnet2012": "article", "goodfellow2016": "book"},
        "cites_in_tex": ["alexnet2012", "goodfellow2016"],
        "missing_cites": [],
        "bibliography_omits_bib_ext": True,
    }
    return {
        "name": "bibtex_database_and_cite_matching",
        "summary": "解析 .bib 文献库条目类型与字段,核对正文 \\cite 键完整性及 \\bibliography 去扩展名规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_four_pass_pipeline_and_biblatex():
    bibtex_pipeline = [
        ("1", "xelatex main", "main.aux"),
        ("2", "bibtex main", "main.bbl"),
        ("3", "xelatex main", "main.pdf (with bbl)"),
        ("4", "xelatex main", "main.pdf (stable refs)"),
    ]
    biblatex_snippet = r"""
\usepackage[backend=biber, style=numeric]{biblatex}
\addbibresource{refs.bib}
\begin{document}
深度学习的突破源于 AlexNet~\cite{alexnet2012}。
\printbibliography[title=参考文献]
\end{document}
"""
    addres = re.search(r"\\addbibresource\{([^}]+)\}", biblatex_snippet).group(1)
    backend = re.search(r"backend=(\w+)", biblatex_snippet).group(1)

    actual = {
        "bibtex_pass_count": len(bibtex_pipeline),
        "step2_tool": bibtex_pipeline[1][1].split()[0],
        "biblatex_backend": backend,
        "addbibresource_includes_ext": addres.endswith(".bib"),
        "has_printbibliography": r"\printbibliography" in biblatex_snippet,
        "gb_style": "gb7714-2015",
    }
    expected = {
        "bibtex_pass_count": 4,
        "step2_tool": "bibtex",
        "biblatex_backend": "biber",
        "addbibresource_includes_ext": True,
        "has_printbibliography": True,
        "gb_style": "gb7714-2015",
    }
    return {
        "name": "four_pass_pipeline_and_biblatex",
        "summary": "验证四步编译流水线及 BibLaTeX + biber(\\addbibresource 带 .bib 与 gb7714-2015 国标配置)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_cross_reference_label_resolution(),
        case_hyperref_load_order_and_options(),
        case_bibtex_database_and_cite_matching(),
        case_four_pass_pipeline_and_biblatex(),
    ]
    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-references-lab/explore-latex-references.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-latex-references.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 LaTeX 语法、环境嵌套与工程依赖验证器(未调用本地 TeX 排版引擎)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LaTeX

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2303.zip

下载课程关联工程包:LaTeX

课程关联工程包(登记关联12章) · 含当前章节或实例 · mbskycom202612a2294.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习