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

离线校验字体样式与 \emph 切换、字号作用域泄漏、嵌套列表及对齐模式

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

VERSION = "CPython 3.12.14 offline LaTeX typography & list-environment verifier"


def case_font_styles_and_emph_toggle():
    snippet = (
        r"\textbf{加粗文字}、\textit{斜体文字}、\underline{下划线文字}、\texttt{等宽文字}。"
        r"\emph{重点} \textbf{加粗且\textit{斜体}} \texttt{代码里也可以\textbf{加粗}}"
    )
    commands_used = sorted(set(re.findall(r"\\(textbf|textit|underline|texttt|emph)\{", snippet)))

    def resolve_emph(in_italic: bool, is_chinese: bool) -> str:
        if in_italic:
            return "upright_songti" if is_chinese else "upright_roman"
        return "kaiti_mapping" if is_chinese else "italic"

    actual = {
        "commands_used": commands_used,
        "emph_in_upright_cn": resolve_emph(False, True),
        "emph_in_italic_cn": resolve_emph(True, True),
        "emph_in_upright_en": resolve_emph(False, False),
        "emph_in_italic_en": resolve_emph(True, False),
    }
    expected = {
        "commands_used": ["emph", "textbf", "textit", "texttt", "underline"],
        "emph_in_upright_cn": "kaiti_mapping",
        "emph_in_italic_cn": "upright_songti",
        "emph_in_upright_en": "italic",
        "emph_in_italic_en": "upright_roman",
    }
    return {
        "name": "font_styles_and_emph_toggle",
        "summary": "校验五种字体样式命令识别、嵌套组合及 \\emph 在中英文正/斜体上下文的智能切换",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_font_size_scope_and_zihao():
    western_scale = [
        r"\tiny", r"\scriptsize", r"\footnotesize", r"\small", r"\normalsize",
        r"\large", r"\Large", r"\LARGE", r"\huge", r"\Huge",
    ]
    zihao_pt = {"5": 10.5, "-4": 12.0, "4": 14.0}

    def check_size_leak(src: str) -> bool:
        depth = 0
        leaked = False
        i = 0
        while i < len(src):
            if src[i] == "{":
                depth += 1
            elif src[i] == "}":
                depth = max(0, depth - 1)
            elif src.startswith(r"\large", i) or src.startswith(r"\zihao", i):
                if depth == 0:
                    leaked = True
            i += 1
        return leaked

    actual = {
        "western_levels": len(western_scale),
        "normalsize_index": western_scale.index(r"\normalsize") + 1,
        "xiaosi_pt": zihao_pt["-4"],
        "wuhao_pt": zihao_pt["5"],
        "scoped_leaks": check_size_leak(r"{\large 大字} 后续正文 {\zihao{-4}小四}"),
        "unscoped_leaks": check_size_leak(r"\large 大字 后续正文被放大"),
    }
    expected = {
        "western_levels": 10,
        "normalsize_index": 5,
        "xiaosi_pt": 12.0,
        "wuhao_pt": 10.5,
        "scoped_leaks": False,
        "unscoped_leaks": True,
    }
    return {
        "name": "font_size_scope_and_zihao",
        "summary": "核对西文十级字号序列、ctex \\zihao 字号磅值及声明型字号命令的花括号作用域泄漏检测",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_list_environments_and_nesting():
    doc = r"""
\begin{itemize}
  \item 第一项
  \item 第二项
    \begin{itemize}
      \item 嵌套的子项,符号自动变化
      \item 又一个子项
    \end{itemize}
\end{itemize}
\begin{enumerate}
  \item 安装发行版
  \item 选择编辑器
  \item 编译第一个文档
\end{enumerate}
\begin{description}
  \item[LaTeX] 一套基于 TeX 的排版系统
  \item[宏包] 即插即用的功能扩展包
\end{description}
"""
    stack = []
    max_depth = 0
    envs_seen = []
    for kind, env in re.findall(r"\\(begin|end)\{(itemize|enumerate|description)\}", doc):
        if kind == "begin":
            stack.append(env)
            envs_seen.append(env)
            max_depth = max(max_depth, len(stack))
        else:
            assert stack and stack[-1] == env
            stack.pop()
    desc_terms = re.findall(r"\\item\[([^\]]+)\]", doc)
    enumitem_cfg = r"\begin{itemize}[label=\textsquare, noitemsep] \begin{enumerate}[label=(\alph*)]"
    enumitem_opts = re.findall(r"\\begin\{(?:itemize|enumerate)\}\[([^\]]+)\]", enumitem_cfg)

    actual = {
        "balanced": len(stack) == 0,
        "envs_seen": envs_seen,
        "max_itemize_depth": max_depth,
        "max_latex_list_depth_limit": 4,
        "description_terms": desc_terms,
        "enumitem_options": enumitem_opts,
    }
    expected = {
        "balanced": True,
        "envs_seen": ["itemize", "itemize", "enumerate", "description"],
        "max_itemize_depth": 2,
        "max_latex_list_depth_limit": 4,
        "description_terms": ["LaTeX", "宏包"],
        "enumitem_options": [r"label=\textsquare, noitemsep", r"label=(\alph*)"],
    }
    return {
        "name": "list_environments_and_nesting",
        "summary": "解析 itemize/enumerate/description 三种列表与嵌套深度,并校验 enumitem 定制选项",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_alignment_environments_vs_centering():
    doc = r"""
正文默认两端对齐。
\begin{center}
居中的文字\\第二行仍然居中
\end{center}
\begin{flushright}
右对齐的文字\\署名常用右对齐
\end{flushright}
"""
    envs = re.findall(r"\\begin\{(center|flushleft|flushright)\}", doc)
    alignment_modes = {
        "center_env": {"adds_vertical_space": True, "recommended_in_float": False},
        "centering_decl": {"adds_vertical_space": False, "recommended_in_float": True},
        "flushright_env": {"adds_vertical_space": True, "typical_use": "signature_or_date"},
    }
    actual = {
        "envs_in_doc": envs,
        "default_body_alignment": "justified",
        "float_preferred": [k for k, v in alignment_modes.items() if v.get("recommended_in_float")],
        "center_adds_vspace": alignment_modes["center_env"]["adds_vertical_space"],
    }
    expected = {
        "envs_in_doc": ["center", "flushright"],
        "default_body_alignment": "justified",
        "float_preferred": ["centering_decl"],
        "center_adds_vspace": True,
    }
    return {
        "name": "alignment_environments_vs_centering",
        "summary": "核对正文默认两端对齐、center/flushright 环境与浮动体内 \\centering 声明的间距差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_font_styles_and_emph_toggle(),
        case_font_size_scope_and_zihao(),
        case_list_environments_and_nesting(),
        case_alignment_environments_vs_centering(),
    ]
    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-text-lab/explore-latex-text.py

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

下载课程关联工程包:LaTeX

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

下载课程关联工程包:LaTeX

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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