%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% tongjithesis -- Tongji University Thesis Template
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{tongjithesis}[v1.7.0 Tongji University Thesis Class] %x-release-please-version
%% TongjiThesis
%% Copyright 2023-2026 TJ-CSCCG
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
%   https://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions of LaTeX
% version 2008 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% The Current Maintainer of this work is R. Lin.
%
% This work consists of the files tongjithesis.cls and tongjithesis.cfg,
% and all accompanying *.tex files in
%   https://github.com/TJ-CSCCG/TongjiThesis

% ==========================================
% Option Declaration
% ==========================================
% 文档类选项用 LaTeX 内核的 l3keys 声明，由 \ProcessKeyOptions 处理。取值有限的
% 选项是选择键：写错的值直接报错并列出全部可用值，不再静默回退；布尔选项可写作
% blind、blind=true 或 blind=false。未声明的选项（oneside、twoside 等）原样传给
% ctexbook。解析结果存入 \tongjithesis@<选项> 与 \iftongjithesis@* 开关，供类文件
% 其余部分使用。
\ExplSyntaxOn
\prop_gput:Nnn \g_msg_module_type_prop { tongjithesis } { Class }
% 本类的版本号（\ProvidesClass 方括号中的第一个词，由 release-please 维护），
% 写入编译日志与 PDF 的 Creator 属性。
\cs_new:Npn \__tongjithesis_first_word:w #1 ~ #2 \q_stop {#1}
\tl_const:Ne \c__tongjithesis_version_tl
  {
    \exp_last_unbraced:Nv \__tongjithesis_first_word:w
      { ver@tongjithesis.cls } ~ \q_stop
  }
\cs_new_eq:NN \tj@version \c__tongjithesis_version_tl

\msg_new:nnnn { tongjithesis } { option-value }
  {
    Unknown~value~'#2'~for~class~option~'#1'.~Valid~values:~#3.
  }
  {
    Change~'#1~=~#2'~in~\iow_char:N \\documentclass[...]{tongjithesis}~
    to~one~of~the~values~above.
  }
\msg_new:nnnn { tongjithesis } { fontset-value }
  {
    Unknown~value~'#1'~for~class~option~'fontset'.~Valid~values:~#2.~
    A~font~set~of~your~own~needs~the~file~tongji-cjk-font-#1.def~
    in~the~folder~of~tongjithesis.cls.
  }
  {
    Change~'fontset~=~#1'~in~\iow_char:N \\documentclass[...]{tongjithesis}~
    to~one~of~the~values~above,~or~add~tongji-cjk-font-#1.def.
  }
\msg_new:nnnn { tongjithesis } { fontset-missing }
  { Missing~tongji-cjk-font-#1.def. }
  { Copy~every~tongji-cjk-font-*.def~file~into~the~folder~that~holds~tongjithesis.cls. }
\cs_generate_variant:Nn \msg_error:nnn { nne }
\cs_generate_variant:Nn \msg_error:nnnn { nnne }
\cs_generate_variant:Nn \msg_error:nnnnn { nnnne }
% \tj@fontsetmissing：字体集的 .def 找不到时报错。一个自定义字体集缺少 .def 时，
% fontset 选项已经报过错，此处不再重复。
\cs_new_protected:Npn \tj@fontsetmissing
  {
    \clist_if_in:NVT \c__tongjithesis_fontset_clist \tongjithesis@fontset
      { \msg_error:nne { tongjithesis } { fontset-missing } { \tongjithesis@fontset } }
  }
\cs_generate_variant:Nn \msg_warning:nnnn { nnVV }
\msg_new:nnn { tongjithesis } { field-graduate }
  {
    field~=~humanities~applies~to~bachelor~theses~only.~A~degree~=~#1~thesis~
    numbers~every~heading~in~Arabic~numerals,~so~field~=~science~is~used.
  }
\msg_new:nnn { tongjithesis } { degree-form }
  {
    doctype~=~#2~is~the~undergraduate~form,~so~degree~=~#1~does~not~change~it.
  }
\msg_new:nnn { tongjithesis } { language-form }
  {
    language~=~english~applies~to~the~thesis;~doctype~=~#1~is~one~of~the~
    university's~Chinese~forms~and~stays~in~Chinese.
  }
\msg_new:nnnn { tongjithesis } { pdfa-package }
  { pdfa~=~true~needs~the~TeX~Live~package~#1,~which~is~not~installed. }
  { Install~it~(tlmgr~install~pdfmanagement~colorprofiles),~or~set~pdfa~=~false. }
\msg_new:nnn { tongjithesis } { english-times }
  {
    language~=~english~sets~Latin~text~in~Times~New~Roman,~as~item~(14)~of~
    section~4~of~the~writing~specification~requires,~so~times~=~false~is~ignored.
  }

\clist_const:Nn \c__tongjithesis_fontset_clist
  { auto, windows, founder, adobe, mac, fandol, texlive }
\clist_const:Nn \c__tongjithesis_fullwidthstop_clist { circle, dot }
\clist_const:Nn \c__tongjithesis_degree_clist { bachelor, master, doctor }
\clist_const:Nn \c__tongjithesis_field_clist { science, humanities }
\clist_const:Nn \c__tongjithesis_algo_clist { algpseudocode, algorithm2e }
\clist_const:Nn \c__tongjithesis_doctype_clist
  { thesis, taskbook, proposal, midterm, spine }
\clist_const:Nn \c__tongjithesis_language_clist { chinese, english }
\clist_const:Nn \c__tongjithesis_bibstyle_clist { auto, numeric, authoryear }

% \__tongjithesis_option_choice:nNn {<选项>} {<可选值>} {<默认值>}：选中的值存入
% \tongjithesis@<选项>；其他值报错并列出可选值。只写选项名时取默认值（同 kvoptions）。
\cs_new_protected:Npn \__tongjithesis_option_choice:nNn #1#2#3
  {
    \keys_define:nn { tongjithesis / option }
      {
        #1 .choices:Vn = #2
          { \tl_set_eq:cN { tongjithesis@#1 } \l_keys_choice_tl } ,
        #1 .default:n = #3 ,
        #1 .usage:n = load ,
        #1 .initial:n = #3 ,
        #1 / unknown .code:n =
          \msg_error:nnnne { tongjithesis } { option-value } {#1} {##1}
            { \clist_use:Nn #2 { ,~ } } ,
      }
  }
% \__tongjithesis_option_bool:nn {<选项>} {<默认值>}：设置 \iftongjithesis@<选项>。
\cs_new_protected:Npn \__tongjithesis_option_bool:nn #1#2
  {
    \keys_define:nn { tongjithesis / option }
      {
        #1 .legacy_if_set:n = tongjithesis@#1 ,
        #1 .default:n = true ,
        #1 .usage:n = load ,
        #1 .initial:n = #2 ,
      }
  }

% fontset：auto（默认）依次选择已安装的、形状最接近官方 Word 模板中易字体的
% 字体集：windows、founder、fandol，最后是 texlive（TeX Live 自带的免费字体）；
% 也可直接指定 windows、founder、adobe、mac、fandol、texlive。其他名称须有类文件
% 能找到的 tongji-cjk-font-<名称>.def（自定义字体集），否则报错；报错后不改用 auto。
\__tongjithesis_option_choice:nNn { fontset } \c__tongjithesis_fontset_clist { auto }
\keys_define:nn { tongjithesis / option }
  {
    fontset / unknown .code:n =
      {
        \tl_set:Nn \tongjithesis@fontset {#1}
        \file_if_exist:nF { tongji-cjk-font-#1.def }
          {
            \msg_error:nnne { tongjithesis } { fontset-value } {#1}
              { \clist_use:Nn \c__tongjithesis_fontset_clist { ,~ } }
          }
      } ,
  }
% fontdir：字体文件所在的文件夹，以 / 结尾（默认 fonts/）。字体集的文件在其中时
% 从这里加载（Overleaf 上传的字体、`make fonts`），否则按字体名从系统查找。
\keys_define:nn { tongjithesis / option }
  {
    fontdir .tl_set:N = \tongjithesis@fontdir ,
    fontdir .value_required:n = true ,
    fontdir .usage:n = load ,
    fontdir .initial:n = fonts/ ,
  }
% fullwidthstop：circle（默认，保留 。）或 dot（替换为 ．）。
% 兼容 v1.3.1 及之前的布尔写法：true 同 dot，false 同 circle。
\__tongjithesis_option_choice:nNn { fullwidthstop }
  \c__tongjithesis_fullwidthstop_clist { circle }
\keys_define:nn { tongjithesis / option }
  {
    fullwidthstop / true  .code:n = \tl_set:Nn \tongjithesis@fullwidthstop { dot } ,
    fullwidthstop / false .code:n = \tl_set:Nn \tongjithesis@fullwidthstop { circle } ,
  }
% times：true 用系统的 Times New Roman（系统没有时用 TeX Gyre Termes），
% false（默认）用 newtx。记下 \documentclass 中是否写了 times：英文论文总用 Times New Roman，
% 写了 times=false 时警告。
\newif\iftongjithesis@times
\bool_new:N \l__tongjithesis_times_given_bool
\keys_define:nn { tongjithesis / option }
  {
    times .choices:nn = { true, false }
      {
        \bool_set_true:N \l__tongjithesis_times_given_bool
        \use:c { tongjithesis@times \l_keys_choice_tl }
      } ,
    times .default:n = true ,
    times .usage:n = load ,
    times / unknown .code:n =
      \msg_error:nnnnn { tongjithesis } { option-value } { times } {#1} { true,~false } ,
  }
% blind（默认 false）：true 排版盲审版本。封面保留各栏目，但学生姓名、学号与
% 指导教师留空，\tjblind{<正式版>}{<盲审版>} 输出第二个参数，PDF 不写作者。
\__tongjithesis_option_bool:nn { blind } { false }
% minted（默认 false）：true 用 minted 高亮代码（需 Python 与 Pygments）。
\__tongjithesis_option_bool:nn { minted } { false }
% biblatex（默认 true）：true 用 biblatex + biber，false 用 BibTeX + gbt7714。
\__tongjithesis_option_bool:nn { biblatex } { true }
% degree：bachelor（默认，本科毕业设计（论文））、master（硕士学位论文）、doctor（博士学位
% 论文）。研究生学位论文的版式见 tongji-graduate.def。
\__tongjithesis_option_choice:nNn { degree } \c__tongjithesis_degree_clist { bachelor }
% field：science（默认，理工科）、humanities（文科：人文、法学、外语、艺术）。
% 经管类属社科：编号要求依理工，撰写依理工模板。26 届为过渡期，可选 science 或
% humanities；自 27 届起统一使用 science。
\__tongjithesis_option_choice:nNn { field } \c__tongjithesis_field_clist { science }
% algo：algpseudocode（默认，algorithm + algorithmicx + algpseudocode）或
% algorithm2e（独立的 algorithm2e 宏包）。
\__tongjithesis_option_choice:nNn { algo } \c__tongjithesis_algo_clist { algpseudocode }
% doctype：\MakeDocument 排版的文档。thesis（默认）为论文正文，照常调用
% \MakeCover/\MakeInfoPage；taskbook 为毕业设计（论文）任务书，proposal 为开题报告，
% midterm 为中期报告；spine 为研究生学位论文印刷本的书脊。
\__tongjithesis_option_choice:nNn { doctype } \c__tongjithesis_doctype_clist { thesis }
% language：论文的撰写语言。chinese（默认）；english 按撰写规范（十四）“英文撰写毕业设计
% （论文）规范参考”排版：西文用 Times New Roman（同 times=true），章节名称、图表题注与
% 交叉引用用英文，标题、目录、摘要与参考文献按该条的格式。封面、信息说明页与中文摘要
% 仍为中文。
\__tongjithesis_option_choice:nNn { language } \c__tongjithesis_language_clist { chinese }
% bibstyle：参考文献的著录与引用方式。auto（默认）随 language 选择：chinese 为顺序编码制
% （numeric，撰写规范（九）），english 为著者-出版年制（authoryear，撰写规范（十四）要求
% 按作者姓氏字母顺序排列、不加序号）；也可直接指定 numeric 或 authoryear。
\__tongjithesis_option_choice:nNn { bibstyle } \c__tongjithesis_bibstyle_clist { auto }
% pdfa（默认 false）：true 输出符合 PDF/A-2b（ISO 19005-2，长期存档）的 PDF，不生成标签结构。
\__tongjithesis_option_bool:nn { pdfa } { false }
% 其他选项交给 ctexbook。
\keys_define:nn { tongjithesis / option }
  { unknown .code:n = \PassOptionsToClass { \CurrentOption } { ctexbook } }
\ProcessKeyOptions [ tongjithesis / option ]

% fontdir 须以 / 结尾，便于直接拼接文件名；省略时补上。
\tl_if_empty:NF \tongjithesis@fontdir
  {
    \str_if_eq:eeF { \str_item:Nn \tongjithesis@fontdir { -1 } } { / }
      { \tl_put_right:Nn \tongjithesis@fontdir { / } }
  }

% 由选项派生的开关
% \iftongjithesis@bachelor：本科；否则为研究生（master 或 doctor），\iftongjithesis@doctor 区分二者。
\newif\iftongjithesis@bachelor
\newif\iftongjithesis@doctor
\str_case:Vn \tongjithesis@degree
  {
    { bachelor } { \tongjithesis@bachelortrue }
    { doctor }   { \tongjithesis@doctortrue }
  }
% 研究生学位论文的层次标题一律用阿拉伯数字编号，不分理工与文科，field 只对本科生效。
\newif\iftongjithesis@humanities
\str_if_eq:VnT \tongjithesis@field { humanities }
  {
    \iftongjithesis@bachelor
      \tongjithesis@humanitiestrue
    \else
      \msg_warning:nnV { tongjithesis } { field-graduate } \tongjithesis@degree
      \tl_set:Nn \tongjithesis@field { science }
    \fi
  }
\newif\iftongjithesis@algorithmtwoe
\str_if_eq:VnT \tongjithesis@algo { algorithm2e } { \tongjithesis@algorithmtwoetrue }
\let\iftjalgorithmtwoe\iftongjithesis@algorithmtwoe
\newif\iftongjithesis@doctype@taskbook
\newif\iftongjithesis@doctype@proposal
\newif\iftongjithesis@doctype@midterm
\newif\iftongjithesis@doctype@spine
% \iftongjithesis@form：doctype 为 3 份行政表格之一（taskbook、proposal、midterm）。三者共享页边距、
% 封面版式等行为，凡“是否为行政表格”的判断都用本开关，避免同一条件写成三重嵌套。
\newif\iftongjithesis@form
\str_case:Vn \tongjithesis@doctype
  {
    { taskbook } { \tongjithesis@doctype@taskbooktrue \tongjithesis@formtrue }
    { proposal } { \tongjithesis@doctype@proposaltrue \tongjithesis@formtrue }
    { midterm }  { \tongjithesis@doctype@midtermtrue  \tongjithesis@formtrue }
    { spine }    { \tongjithesis@doctype@spinetrue }
  }
% 3 份表格是本科的表格，研究生学位不改变它们。
\iftongjithesis@form
  \iftongjithesis@bachelor \else
    \msg_warning:nnVV { tongjithesis } { degree-form }
      \tongjithesis@degree \tongjithesis@doctype
  \fi
\fi
% \iftongjithesis@english：language=english，只用于论文（doctype=thesis）：3 份表格与书脊是学校
% 的中文表格，language=english 时仍为中文，只在日志中说明。英文论文的西文字体按规范用
% Times New Roman，故同时打开 times；\documentclass 中写了 times=false 时警告。
\newif\iftongjithesis@english
\str_if_eq:VnT \tongjithesis@language { english }
  {
    \bool_lazy_or:nnTF
      { \legacy_if_p:n { tongjithesis@form } }
      { \legacy_if_p:n { tongjithesis@doctype@spine } }
      {
        \msg_info:nnV { tongjithesis } { language-form } \tongjithesis@doctype
        \tl_set:Nn \tongjithesis@language { chinese }
      }
      {
        \tongjithesis@englishtrue
        \bool_lazy_and:nnT
          { \l__tongjithesis_times_given_bool }
          { ! \legacy_if_p:n { tongjithesis@times } }
          { \msg_warning:nn { tongjithesis } { english-times } }
        \tongjithesis@timestrue
      }
  }
% \iftongjithesis@chinesenumbers：章节用中文数字编号（一、/（一）/ 1. /（1）），即文科的
% 中文论文。英文论文不论文理都用阿拉伯数字（1 / 1.1 / 1.1.1）：撰写规范（三）（四）
% “外语类论文的标题层次，可参照语言所在国通行的规则”。
\newif\iftongjithesis@chinesenumbers
\iftongjithesis@humanities
  \iftongjithesis@english \else \tongjithesis@chinesenumberstrue \fi
\fi
% bibstyle=auto 按语言取值：本科英文论文为著者-出版年制（撰写规范（十四）），其余为顺序编码制
% （研究生学位论文的参考文献按研究生院的指南，为顺序编码制）。\iftongjithesis@authoryear 为
% 著者-出版年制。
\newif\iftj@bibstyleauto
\str_if_eq:VnT \tongjithesis@bibstyle { auto }
  {
    \tj@bibstyleautotrue
    \bool_lazy_and:nnTF
      { \legacy_if_p:n { tongjithesis@english } }
      { \legacy_if_p:n { tongjithesis@bachelor } }
      { \tl_set:Nn \tongjithesis@bibstyle { authoryear } }
      { \tl_set:Nn \tongjithesis@bibstyle { numeric } }
  }
\newif\iftongjithesis@authoryear
\str_if_eq:VnT \tongjithesis@bibstyle { authoryear } { \tongjithesis@authoryeartrue }
\ExplSyntaxOff
\RequirePackage{etoolbox}
% \tj@lang{<中文>}{<英文>}：按 language 取其一（可展开），用于随语言变化的名称。
\newcommand\tj@lang{%
  \iftongjithesis@english\expandafter\@secondoftwo\else\expandafter\@firstoftwo\fi}

% ==========================================
% Class Loading
% ==========================================
% 加载 ctexbook 类
% pdfa=true：用 LaTeX 的 PDF 管理模块（pdfmanagement）声明 PDF/A-2b：写入 XMP 元数据、
% sRGB 输出意图（colorprofiles 的 sRGB.icc）与文档语言（language=chinese 为 zh-CN，english
% 为 en）。它不检查文档是否符合 PDF/A：模板的 CI 用 veraPDF 校验示例论文（XeLaTeX 与
% LuaLaTeX），写作者插入的图片等须自行校验。须在载入 ctexbook 与其他宏包之前设置。不用
% \DocumentMetadata：它同时载入标签（tagging）代码，而 LaTeX 团队不支持 XeLaTeX 下的标签，
% ctex 也被列为不兼容（LaTeX News 42 给出的不含标签代码的写法即下面两行）。
\iftongjithesis@pdfa
  \ExplSyntaxOn
  \clist_map_inline:nn { pdfmanagement, colorprofiles }
    { \file_if_exist:nF { #1.sty } { \msg_error:nnn { tongjithesis } { pdfa-package } {#1} } }
  \ExplSyntaxOff
  \RequirePackage{pdfmanagement}
  \expanded{\noexpand\SetKeys[document/metadata]
    {pdfversion=1.7, pdfstandard=a-2b, lang=\tj@lang{zh-CN}{en}}}
\fi
\LoadClass[UTF8,a4paper,zihao=-4,fontset=none]{ctexbook}  % zihao=-4 must match \tjfontbody (小四号)

% ------------------------------------------
% CJK fonts (fontspec is now available via ctexbook)
% ------------------------------------------
% 无真粗体的中文字体以描边模拟加粗。描边宽度取 Word 加粗宋体的值，即字号的 1/35；
% XeTeX 与 luaotfload 都把 AutoFakeBold 的值当作字号的百分数，故取 2.86。
\def\tj@fakebold{2.86}
% \tj@cjkload{<命令>}{<字体>}{<选项>}：先展开字体名与选项中的宏（Path=、描边宽度等），
% 再调用命令，使 fontspec 解析键值时看到的是实际的键与值。
\newcommand\tj@cjkload[3]{\edef\tj@next{\unexpanded{#1}{#2}[#3]}\tj@next}
% 字体集的文件在 fontdir 中时按文件加载，否则按字体名从系统加载。
\newif\iftj@cjkfiles
% \tj@cjkfonts{宋体名}{宋体文件}{黑体名}{黑体文件}{楷体名}{楷体文件}{仿宋名}{仿宋文件}
% 设置四种字体及 \songti、\heiti、\kaishu、\fangsong。宋体与黑体模拟加粗，楷体兼作宋体的斜体。
\NewDocumentCommand\tj@cjkfonts{mmmmmmmm}{%
  \IfFileExists{\tongjithesis@fontdir#2}{\tj@cjkfilestrue}{\tj@cjkfilesfalse}%
  \iftj@cjkfiles
    \edef\tj@cjkpath{Path=\tongjithesis@fontdir,}%
    \def\tj@song{#2}\def\tj@hei{#4}\def\tj@kai{#6}\def\tj@fang{#8}%
  \else
    \def\tj@cjkpath{}%
    \def\tj@song{#1}\def\tj@hei{#3}\def\tj@kai{#5}\def\tj@fang{#7}%
  \fi
  \tj@cjkload\setCJKmainfont{\tj@song}{\tj@cjkpath AutoFakeBold=\tj@fakebold,ItalicFont=\tj@kai}%
  \tj@cjkload\setCJKsansfont{\tj@hei}{\tj@cjkpath AutoFakeBold=\tj@fakebold}%
  \tj@cjkload\setCJKmonofont{\tj@fang}{\tj@cjkpath}%
  \tj@cjkload{\setCJKfamilyfont{zhsong}}{\tj@song}{\tj@cjkpath AutoFakeBold=\tj@fakebold,ItalicFont=\tj@kai}%
  \tj@cjkload{\setCJKfamilyfont{zhhei}}{\tj@hei}{\tj@cjkpath AutoFakeBold=\tj@fakebold}%
  \tj@cjkload{\setCJKfamilyfont{zhkai}}{\tj@kai}{\tj@cjkpath}%
  \tj@cjkload{\setCJKfamilyfont{zhfs}}{\tj@fang}{\tj@cjkpath}%
  \NewDocumentCommand{\songti}{}{\CJKfamily{zhsong}}%
  \NewDocumentCommand{\heiti}{}{\CJKfamily{zhhei}}%
  \NewDocumentCommand{\kaishu}{}{\CJKfamily{zhkai}}%
  \NewDocumentCommand{\fangsong}{}{\CJKfamily{zhfs}}%
}
% \tj@cjkfamily{<族>}{<字体名>}{<文件>}[<按名选项>][<按文件选项>]：附加字体族，
% 与同一字体集的 \tj@cjkfonts 采用同一种加载方式。字体不存在时跳过（如英文版 Windows
% 未安装补充字体时的隶书、幼圆），使用该族的命令才会报错。
\NewDocumentCommand\tj@cjkfamily{mmmO{}O{}}{%
  \iftj@cjkfiles
    \IfFileExists{\tongjithesis@fontdir#3}
      {\tj@cjkload{\setCJKfamilyfont{#1}}{#3}{\tj@cjkpath #5}}
      {\ClassInfo{tongjithesis}{#3 not found in \tongjithesis@fontdir; skipping CJK family #1}}%
  \else
    \IfFontExistsTF{#2}
      {\tj@cjkload{\setCJKfamilyfont{#1}}{#2}{#4}}
      {\ClassInfo{tongjithesis}{Font #2 not found; skipping CJK family #1}}%
  \fi
}
% fontset=auto：依次选择已安装的、形状最接近 Word 模板中易字体的字体集。
% 一个字体集的四种字体须全部存在（全在 fontdir 中，或全部可按字体名找到）才会被选中。
% \tj@iffontset{<字体集>}{<文件列表>}{<字体名列表>}{<否则>}
\newif\iftj@allfound
\newcommand\tj@checkfile[1]{\IfFileExists{\tongjithesis@fontdir#1}{}{\tj@allfoundfalse}}
\newcommand\tj@checkfont[1]{\IfFontExistsTF{#1}{}{\tj@allfoundfalse}}
\newcommand\tj@iffontset[4]{%
  \tj@allfoundtrue\forcsvlist\tj@checkfile{#2}%
  \iftj@allfound\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
    {\def\tongjithesis@fontset{#1}}%
    {\tj@allfoundtrue\forcsvlist\tj@checkfont{#3}%
     \iftj@allfound\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
       {\def\tongjithesis@fontset{#1}}{#4}}%
}
\newif\iftj@fontsetauto
\ifdefstring{\tongjithesis@fontset}{auto}{%
  \tj@fontsetautotrue
  \tj@iffontset{windows}
    {simsun.ttc,simhei.ttf,simkai.ttf,simfang.ttf}
    {SimSun,SimHei,KaiTi,FangSong}{%
  \tj@iffontset{founder}
    {FZSSK.TTF,FZHTK.TTF,FZKTK.TTF,FZFSK.TTF}
    {FZShuSong-Z01,FZHei-B01,FZKai-Z03,FZFangSong-Z02}{%
  \tj@iffontset{fandol}
    {FandolSong-Regular.otf,FandolHei-Regular.otf,FandolKai-Regular.otf,FandolFang-Regular.otf}
    {FandolSong-Regular.otf,FandolHei-Regular.otf,FandolKai-Regular.otf,FandolFang-Regular.otf}{%
  \def\tongjithesis@fontset{texlive}}}}%
  \ifdefstring{\tongjithesis@fontset}{windows}
    {\ClassInfo{tongjithesis}{fontset=auto chose windows}}
    {\ClassWarningNoLine{tongjithesis}{fontset=auto chose \tongjithesis@fontset:\MessageBreak
      the Zhongyi fonts of the official Word template\MessageBreak
      (SimSun, SimHei, KaiTi, FangSong) were not found.\MessageBreak
      To use them, run `make fonts' locally, or upload\MessageBreak
      the font files to \tongjithesis@fontdir\space on Overleaf}}%
}{}
\IfFileExists{tongji-cjk-font-\tongjithesis@fontset.def}
  {\input{tongji-cjk-font-\tongjithesis@fontset.def}}
  {\tj@fontsetmissing}
% 版本与选项摘要：写入编译日志，报告问题时附上的日志据此说明所用的版本与选项。
% 在选项之间换行，日志中每行不超过 79 列，不会在词中间折断。
\ExplSyntaxOn
\msg_new:nnn { tongjithesis } { summary }
  {
    TongjiThesis~\c__tongjithesis_version_tl :~
    fontset=\tongjithesis@fontset \legacy_if:nT { tj@fontsetauto } { ~(auto) } ,
    \\ doctype=\tongjithesis@doctype ,~
    degree=\tongjithesis@degree ,~
    field=\tongjithesis@field ,
    \\ language=\tongjithesis@language ,~
    bibstyle=\tongjithesis@bibstyle \legacy_if:nT { tj@bibstyleauto } { ~(auto) } ,
    \\ blind=\legacy_if:nTF { tongjithesis@blind } { true } { false } ,~
    biblatex=\legacy_if:nTF { tongjithesis@biblatex } { true } { false } ,~
    minted=\legacy_if:nTF { tongjithesis@minted } { true } { false } ,
    \\ algo=\tongjithesis@algo ,~
    times=\legacy_if:nTF { tongjithesis@times } { true } { false } ,
    \\ fullwidthstop=\tongjithesis@fullwidthstop ,~
    pdfa=\legacy_if:nTF { tongjithesis@pdfa } { true } { false }
  }
\msg_info:nn { tongjithesis } { summary }
\ExplSyntaxOff

% ==========================================
% Formatting Constants (官方规范)
% ==========================================
% 依据：《同济大学本科生毕业设计（论文）撰写规范》（2026 年 10 月修订版）；
% 规范未写明的数值沿用 2026 届官方 Word 模板。
% Font sizes
\newcommand{\tjfonttitle}{\zihao{-2}}        % 课题名称：小二号
\newcommand{\tjfontchapter}{\zihao{-3}}      % 章标题：小三号
\newcommand{\tjfontheading}{\zihao{4}}       % 摘要 / 目录 / 参考文献 / 谢辞标题：四号
\newcommand{\tjfontbody}{\zihao{-4}}         % 正文 / 二三级标题 / 关键词 / 摘要正文：小四号
\newcommand{\tjfontcaption}{\zihao{5}}       % 表题 / 图题：五号
\newcommand{\tjfontcover}{\zihao{-3}}        % 封面表格字段值：小三号（与 \tjfontchapter 同字号，语义分离）
\newcommand{\tjfonttable}{\fontsize{10.5bp}{18bp}\linespread{1}\selectfont} % 表内文字：五号 10.5 磅（撰写规范“表中文字原则上采用宋体五号”），行距 18 磅（沿用 Word 模板）；Word 的“磅”即 bp；\linespread{1} 隔离全文 1.625 倍行距
\newcommand{\tjfontinfotitle}{\zihao{3}}     % 信息说明页标题：三号（仅此页专用）
\newcommand{\tjfontformtitle}{\zihao{-0}}    % 任务书 / 开题报告 / 中期报告封面标题：小初号（36pt）
% Spacing
% Word 的 “0.5 行” 按单倍行距字体行高计算（≈ 字号 × 1.2 × 0.5 = 0.6em），
% 与段落自身行距无关；不能用 0.5\baselineskip（会被 \setstretch 拉伸）。
\newcommand{\tjskipbeforesec}{0.6em}            % 段前 0.5 行（Word 口径）
\newcommand{\tjskipaftersec}{0.6em}             % 段后 0.5 行（Word 口径）
% 行距（近似 Word 模板行距倍数；LaTeX 与 Word 的度量略有差异）
\newcommand{\tjlinespread}{1.625}            % 正文 / 摘要：Word 1.5 倍
\newcommand{\tjtoclinespread}{1.625}         % 目录：Word 1.5 倍
% 信息说明页行距（官方规范固定值，linespread = 目标磅数 ÷ (字号 × 1.2)）
\newcommand{\tjinfofieldspread}{1.6667}   % 四号宋体 28 磅：28÷(14×1.2)≈5/3
\newcommand{\tjinfoabstractspread}{1.25}  % 摘要小四 18 磅：18÷(12×1.2)=5/4（精确）
\newcommand{\tjinfotitlevspace}{0.8em}    % 多行课题名称后的间距补偿（在四号上下文中解析）
\newcommand{\tjcoverlinestretch}{0.8}   % 封面字段 parbox 行距倍率（压缩行距以适配窄框）
% Cover text：理工=毕业设计（论文）；文科=毕业论文（设计）
\iftongjithesis@humanities
  \newcommand{\tjcovertext}{毕业论文（设计）}
\else
  \newcommand{\tjcovertext}{毕业设计（论文）}
\fi
% Header text：理工=毕业设计（论文）；文科=毕业论文（设计）
\iftongjithesis@humanities
  \newcommand{\tjheadertext}{毕业论文（设计）}
\else
  \newcommand{\tjheadertext}{毕业设计（论文）}
\fi
% 任务书/开题报告/中期报告封面大标题专用：与 \tjheadertext 同义，但括号取半角，
% 使小初号（36pt）标题（如“毕业设计(论文)开题报告”）能在一行内排下。
\iftongjithesis@humanities
  \newcommand{\tjformheadertext}{毕业论文(设计)}
\else
  \newcommand{\tjformheadertext}{毕业设计(论文)}
\fi

% ==========================================
% Required Packages
% ==========================================
% Page layout
% headheight 43pt ≈ 1.14cm logo (≈32pt) + 小四号正文行 (≈11pt)；防止 fancyhdr headheight warning
\setlength{\headheight}{43pt}
% 页边距按同济本科毕业设计（论文）/毕业论文（设计）撰写规范设定；
% 任务书/开题报告/中期报告为 A4，上 2.3cm/下 1.0cm/左右各 3.17cm（左右对称），
% 与论文正文的装订页边距（左 3.3cm/右 1.8cm）不同。
\iftongjithesis@form
  \RequirePackage[a4paper,top=2.3cm,bottom=1.0cm,left=3.17cm,right=3.17cm]{geometry}
\else
  \RequirePackage[a4paper,top=4.0cm,bottom=2.7cm,left=3.3cm,right=1.8cm]{geometry}
\fi
\RequirePackage{fancyhdr}
\RequirePackage{lastpage}
\RequirePackage{eso-pic}
\RequirePackage{emptypage}

% Typography and text formatting
\RequirePackage[T1]{fontenc}
\RequirePackage{setspace}
\RequirePackage[inline]{enumitem}
\RequirePackage{alphalph}
\RequirePackage{circledsteps}
\RequirePackage[normalem]{ulem}
\RequirePackage{calc}
\RequirePackage{ifthen}
\RequirePackage{hologo}
\RequirePackage{graphicx}

% Table of contents
% [titles]: 让 ctex 保留其 \contentsname/\listfigurename 等中文名；tocloft 不会覆盖。
% 副作用：ToC 标题由 class 的 \chapter* 渲染，\cft*toctitle* 钩子失效。
\RequirePackage[titles]{tocloft}

% Mathematics
\RequirePackage{amsmath,amsthm,amsfonts,amssymb,amscd}
% @ is already a letter in a .cls file; no \makeatletter needed here or below.
\iftongjithesis@times
  \RequirePackage{fontspec}%
  % Times New Roman 是微软字体，只在装了它的系统上存在；Linux 与 Overleaf 上没有，
  % 直接 \setmainfont 会以 “Package fontspec Error: The font ... cannot be found”
  % 中止编译——times=true 因此在多数环境下完全不可用。
  % 回退到 TeX Gyre Termes：TeX Live 自带、与 Times 度量兼容，且带真正的小型大写
  % 字形（Times New Roman 没有，\TongjiThesis / \BibLaTeX 两处 \scshape 在它下面
  % 会静默退回常规体）。
  % 回退按文件名加载，不按字体名：TeX Live 自带的字体没有注册到 fontconfig，
  % Linux 上按名字找不到（“The font "TeX Gyre Termes" cannot be found”），
  % 按文件名走 kpathsea 才是各平台都可靠的方式。
  \IfFontExistsTF{Times New Roman}
    {\setmainfont{Times New Roman}}
    {\setmainfont{texgyretermes}[
       Extension     = .otf,
       UprightFont   = *-regular,
       BoldFont      = *-bold,
       ItalicFont    = *-italic,
       BoldItalicFont= *-bolditalic,
     ]}%
\else
  \RequirePackage{newtx}%
  \defaultfontfeatures{Ligatures = TeX}%
\fi

\RequirePackage{upgreek}

% Circled number rendering (Unicode 0–50 + circledsteps 51+)
\InputIfFileExists{tongji-circled.def}{}{\ClassError{tongjithesis}{Missing tongji-circled.def}{}}

% Tables and figures
\RequirePackage{float}
\RequirePackage{multirow}
\RequirePackage{array}
\RequirePackage{booktabs}
\RequirePackage{longtable}
\RequirePackage{threeparttable}
\RequirePackage{threeparttablex}
\RequirePackage{tabularx} % 三线表两端与页面对齐（官方规范）
% Caption customization (must load before subcaption, which internally loads caption)
\RequirePackage{caption}
\DeclareCaptionLabelSeparator{tj@twospace}{\ ~}
\DeclareCaptionFont{tj@songti}{\songti}
\DeclareCaptionFont{tj@caption}{\tjfontcaption}
\captionsetup{labelsep=tj@twospace,font={tj@caption,tj@songti}}
% 代码块标题与代码框之间留出呼吸空间（listings / minted）
\captionsetup[lstlisting]{skip=12pt}
\captionsetup[listing]{skip=12pt}

\RequirePackage{subcaption}
% Override subcaption default `font+=smaller` so sub-captions match main caption size.
% Other settings (labelsep, labelformat, skip) inherit defaults — labelsep follows the
% global tj@twospace from line above; labelformat=parens renders `(a)` style.
\captionsetup[sub]{font={tj@caption,tj@songti}}

% Algorithms and code listings
\iftongjithesis@algorithmtwoe
  \RequirePackage[ruled,linesnumbered,algochapter]{algorithm2e}
  \let\c@algorithm\c@algocf
  \renewcommand{\thealgocf}{\thealgorithm}
\else
  \RequirePackage{algorithm}
  \RequirePackage{algorithmicx}
  \RequirePackage{algpseudocode}
\fi

% Always load listings package first (mandatory)
\RequirePackage{listings}
\definecolor{bg}{rgb}{0.96,0.96,0.96}
\definecolor{commentcolor}{rgb}{0.24,0.48,0.48}
\definecolor{stringcolor}{rgb}{0.73,0.13,0.13}
\definecolor{keywordcolor}{rgb}{0.0,0.502,0.0}
\lstset{
  backgroundcolor=\color{bg},
  basicstyle=\small\ttfamily\linespread{1.0}\selectfont,
  keywordstyle=\color{keywordcolor}\bfseries,
  commentstyle=\color{commentcolor}\itshape,
  stringstyle=\color{stringcolor},
  numbers=left,
  numberstyle=\small\color{gray},
  numbersep=12pt,
  xleftmargin=2.5em,
  xrightmargin=2mm,     % equal to framesep; keeps frame right edge within text area
  frame=single,
  rulecolor=\color{gray!40},
  framesep=2mm,
  aboveskip=\baselineskip,
  belowskip=\smallskipamount,
  breaklines=true,
  showstringspaces=false,
  captionpos=b,
  tabsize=4,
  mathescape=true,
  escapeinside=||,
  belowskip=0pt,
}
\renewcommand{\lstlistingname}{\tj@lang{代码}{Listing}}
\renewcommand{\lstlistlistingname}{\tj@lang{代码列表}{List of Listings}}

% Enhanced verbatim support (pure TeX, no Python dependency).
% fvextra extends fancyvrb with breaklines/breakanywhere/\Verb/bgcolor/etc.
% Loaded BEFORE minted so minted (which pulls in fancyvrb internally) sees the extensions.
% \fvset aligned with \lstset and \setminted so Verbatim / lstlisting / minted
% blocks share one visual treatment: gray bg, thin frame, left line numbers, mathescape.
\RequirePackage{fvextra}
\fvset{
  frame=single,
  framesep=2mm,
  rulecolor=\color{gray!40},
  numbers=left,
  numbersep=12pt,
  xleftmargin=2.5em,
  fontsize=\small,
  baselinestretch=1,
  tabsize=4,
  breaklines=true,
  mathescape=true
}
% fvextra v1.8.0 (2024-09-14) introduced bgcolor; guard for older TeX Live
\@ifpackagelater{fvextra}{2024/09/14}{%
  \fvset{bgcolor=bg}%
}{}

% Conditionally load minted package (optional)
\iftongjithesis@minted
  \RequirePackage[chapter]{minted}
  \setminted{linenos,
    frame=single,
    framesep=2mm,
    rulecolor=\color{gray!40},
    fontsize=\small,
    breaklines,
    mathescape,
    escapeinside=||}
  % fvextra v1.8.0 (2024-09-14) introduced bgcolor; guard for older TeX Live
  \@ifpackagelater{fvextra}{2024/09/14}{%
    \setminted{bgcolor=bg}%
  }{}
  \renewcommand{\listingscaption}{\tj@lang{代码}{Listing}}

  % When using minted, DO NOT redefine the listing environment
  % It's already defined by the minted package
\else
  % When not using minted, create compatibility layer
  \newfloat{listing}{htbp}{lop}
  \floatname{listing}{\tj@lang{代码}{Listing}}

  % Define a minted-compatible environment that forwards to listings.
  % Must be \lstnewenvironment, not a plain \newenvironment wrapper around
  % lstlisting: lstlisting reads its body verbatim, scanning the source for the
  % literal string \end{lstlisting}. That string never appears when the writer
  % closes with \end{minted}, so a plain wrapper swallows the rest of the file
  % and aborts with "no legal \end found".
  \lstnewenvironment{minted}[2][]{\lstset{language=#2,#1}}{}

  % Define inputminted command
  \newcommand{\inputminted}[3][]{\lstinputlisting[language=#2,#1]{#3}}
\fi

% Non-float listing environment for cross-page code with captions.
% Normalise lstlisting's \belowskip inside this env so it matches minted's
% natural trailing (~10pt); combined with skip=2pt, both engines yield the
% same ~12pt gap between code and caption. The \lstset call is group-local
% to the environment, so regular (non-longlisting) lstlisting blocks keep
% their configured belowskip.
\newenvironment{longlisting}
  {\captionsetup{type=listing,skip=2pt}\lstset{belowskip=10pt}}
  {\medskip}

\RequirePackage{tcolorbox}
\RequirePackage{verbatim}  % kept for \comment / \verbatiminput; lowercase `verbatim` env is a kernel feature

% Cross-referencing and hyperlinks
\RequirePackage[colorlinks,allcolors=black,unicode=true]{hyperref}
% PDF 文档属性：Creator 写明模板与版本；标题与作者由 \tjsetup 的 title、author 键写入。
\hypersetup{pdfcreator={TongjiThesis \tj@version}}
% PDF 字符串（文档属性、书签）中，题名里常用的本类命令写作纯文本，\tjblind 按 blind 选项取值。
\pdfstringdefDisableCommands{%
  \def\TongjiThesis{TongjiThesis}%
  \def\XeTeX{XeTeX}%
  \def\LuaTeX{LuaTeX}%
  \def\BibTeX{BibTeX}%
  \def\BibLaTeX{BibLaTeX}%
  \def\tjblind{\iftongjithesis@blind\expandafter\@secondoftwo\else\expandafter\@firstoftwo\fi}%
}
% 盲审版本：PDF 文档属性中不写作者（author 键此时不写入，此处再显式清空，防止其他宏包或用户设置写入）。
\AtBeginDocument{\iftongjithesis@blind\hypersetup{pdfauthor={}}\fi}
\RequirePackage{nameref}
\RequirePackage[nameinlink,noabbrev]{cleveref}

% Units and graphics
\RequirePackage{siunitx}[=v2]
% 数字列表与数字范围的连接词：siunitx 默认输出英文“and”“to”。撰写规范（十三）要求标点按
% GB/T 15834—2011《标点符号用法》使用：并列词语用顿号，数值范围用浪纹线“～”（规范正文亦写作“3～5个”）。
% “和”两侧的 \tj@numsep 在 XeLaTeX 下补上数字与汉字之间的间距（LuaTeX 由 luatexja 处理）。
\sisetup{
  list-separator       = {、},
  list-final-separator = {\tj@numsep 和\tj@numsep},
  list-pair-separator  = {\tj@numsep 和\tj@numsep},
  range-phrase         = {～},
}
% 英文摘要中恢复 siunitx 的英文连接词
\newcommand*{\tj@siunitxenglish}{%
  \sisetup{list-separator = {, }, list-final-separator = { and },
            list-pair-separator = { and }, range-phrase = { to }}}
\newcommand*{\tj@siunitxchinese}{%
  \sisetup{list-separator = {、}, list-final-separator = {\tj@numsep 和\tj@numsep},
            list-pair-separator = {\tj@numsep 和\tj@numsep}, range-phrase = {～}}}
% 中西文共用的标点（弯引号、间隔号、连接号、破折号、省略号）：中文排版取中文字体的全角
% 字形，英文排版取西文字体。XeTeX 由 xeCJK 的字符类别决定（默认 FullLeft/FullRight，
% 改为 HalfLeft/HalfRight 即用西文字体），LuaTeX 由 luatexja 的字符范围 9 决定；两者的
% 设置都只在当前分组内有效。做法同 thuthesis，见 CTeX-org/ctex-kit#389。
\newcommand*{\tj@punctenglish}{%
  \ifdefined\XeTeXrevision
    \xeCJKDeclareCharClass{HalfLeft}{"2018, "201C}%
    \xeCJKDeclareCharClass{HalfRight}{"00B7, "2019, "201D, "2013, "2014, "2025, "2026, "2E3A}%
  \else
    \ltjsetparameter{jacharrange={-9}}%
  \fi}
\newcommand*{\tj@punctchinese}{%
  \ifdefined\XeTeXrevision
    \xeCJKDeclareCharClass{FullLeft}{"2018, "201C}%
    \xeCJKDeclareCharClass{FullRight}{"00B7, "2019, "201D, "2013, "2014, "2025, "2026, "2E3A}%
  \else
    \ltjsetparameter{jacharrange={+9}}%
  \fi}
% \tj@englishtext / \tj@chinesetext：在当前分组内按英文或中文排版正文（标点与 siunitx 的连接词）。
% 英文摘要用前者；英文论文（language=english）全文用前者，其中的中文部分（封面、信息说明页、
% 中文摘要、中文综述）用后者。
\newcommand*{\tj@englishtext}{\tj@siunitxenglish\tj@punctenglish}
\newcommand*{\tj@chinesetext}{\tj@siunitxchinese\tj@punctchinese}
\RequirePackage{pgf}
\RequirePackage{tikz}

% ==========================================
% Bibliography Configuration
% ==========================================
% 参考文献样式遵循 GB/T 7714-2025。所需宏包版本（均随 TeX Live 2026+ 分发）：
%   - biblatex 路径：biblatex-gb7714-2015 >= v1.1x（提供 gb7714-2025 样式；下方的覆盖定义按 v1.1x 编写）
%   - bibtex   路径：gbt7714 >= v2.2.0（提供 gbt7714-2025-numeric.bst）
% 版本过旧会报“style/bst not found”错误；升级步骤见 README“快速开始”提示。
% bibstyle=numeric 为顺序编码制（gb7714-2025 / gbt7714-2025-numeric），bibstyle=authoryear 为
% 著者-出版年制（gb7714-2025ay / gbt7714-2025-authoryear）；著者-出版年制的设置在本节末尾。
\iftongjithesis@biblatex
  \iftongjithesis@authoryear
    \PassOptionsToPackage{style=gb7714-2025ay}{biblatex}
    % 英文论文（撰写规范（十四））：按作者姓、年份、题名排序，中英文文献混排，不按语种分集
    % （sorting=nyt；中文文献的作者写作拼音即与英文文献一起按字母排序）；姓名写作
    % “Dowty, D. R.”（gbnamefmt=familyahead）；不著录文献类型标识（gbtype=false）；
    % 引用与文献表中的“et al.”“and”等一律用英文（gbcitelocal、gbbiblocal），两位作者的
    % 文献引用时写出两位（maxcitenames=2）。
    \iftongjithesis@english
      \PassOptionsToPackage{sorting=nyt, gbnamefmt=familyahead, gbtype=false,
        gbcitelocal=english, gbbiblocal=english, maxcitenames=2}{biblatex}
    \fi
  \else
    \PassOptionsToPackage{style=gb7714-2025}{biblatex}
  \fi
  \RequirePackage[
    backend=biber,
    gbpunctwidth=half,    % 撰写规范：参考文献与正文引用方括号内的标点统一采用半角
    natbib=true,
  ]{biblatex}
  % 参考文献序号左对齐至页边距，悬挂统一为 0.74cm（与 Word 模板一致）。
  % 0.74cm 为最小宽度；若实际最宽标签（如 [100]+ 三位数引用）超过 0.74cm，
  % 则使用实际宽度，避免标签溢出与正文首字符重叠。
  \defbibenvironment{bibliography}
    {\list
       {\printtext[labelnumberwidth]{%
          \printfield{labelprefix}%
          \printfield{labelnumber}}}
       {\setlength{\labelwidth}{\labelnumberwidth}%
        \ifdim\labelwidth<0.74cm \setlength{\labelwidth}{0.74cm}\fi
        \setlength{\labelsep}{0pt}%
        \setlength{\leftmargin}{\labelwidth}%
        \setlength{\itemindent}{0pt}%
        \setlength{\itemsep}{\bibitemsep}%
        \setlength{\parsep}{\bibparsep}%
        \renewcommand*{\makelabel}[1]{##1\hfill}}}
    {\endlist}
    {\item}
  % 以下四处改写 gb7714-2025 的默认输出，使其与 gbt7714 及 GB/T 7714—2025 的示例一致。
  % （1）DOI 与 CSTR：§7.8 示例写作“DOI:10.3760/…”，冒号后不留空格；
  %     样式原定义在冒号后加了 \addthinspace。
  \DeclareFieldFormat{doi}{%
    DOI\addcolon
    \ifhyperref
      {\href{https://doi.org/#1}{\nolinkurl{#1}}}
      {\nolinkurl{#1}}}
  \DeclareFieldFormat{cstr}{%
    CSTR\addcolon
    \ifhyperref
      {\href{https://cstr.cn/#1}{\nolinkurl{#1}}}
      {\nolinkurl{#1}}}
  % （2）更新或修改日期与引用日期：§7.6 示例写作“（2012-05-03）[2013-11-12]”，两者之间不留空格；
  %     样式原定义在引用日期前加了 \addthinspace。
  \renewbibmacro*{urldate}{%
    \printtext{\gbleftbracket}\printurldate\printtext{\gbrightbracket}}
  % （3）英文题名：§5.6 要求大小写“符合信息资源本身文种的习惯用法”，标准示例的题名与书名均为
  %     句首大写（sentence case），期刊名保留原样。与 gbt7714 的默认设置相同：title 与 booktitle
  %     改为句首大写，journal 不变；只处理英文文献（userd 是样式按题名判定的语种）。
  %     .bib 中需保持原样的专有名词与缩写须用花括号保护，如 {IEEE}、{LaTeX}，两种后端都会照录。
  %     副题名（subtitle、booksubtitle）整体小写，与 gbt7714 的 capitalizesubtitle=false 及示例
  %     “ARA：a flexible pipeline…”一致；\tj@mklowercase 沿用 biblatex 的花括号保护规则。
  %     含 \url 的题名原样输出：\url 按原文读取参数，无法再经过大小写转换。
  \newcommand*{\tj@mksentencecase}[1]{%
    \iffieldequalstr{userd}{english}
      {\tj@ifhasurl{#1}{#1}{%
         \ifboolexpr{test {\ifcurrentfield{subtitle}} or test {\ifcurrentfield{booksubtitle}}
                      or test {\ifcurrentfield{booktitleaddon}}}
           {\tj@mklowercase{#1}}
           {\MakeSentenceCase{#1}}}}
      {#1}}
  \ExplSyntaxOn
  \cs_new_protected:Npn \tj@mklowercase #1
    { \exp_args:No \text_lowercase:n { \biblatex_text_sentencecase_preprocess:n {#1} } }
  \cs_new_protected:Npn \tj@ifhasurl #1#2#3 { \tl_if_in:nnTF {#1} { \url } {#2} {#3} }
  \ExplSyntaxOff
  \renewcommand{\mktitlecase}{\tj@mksentencecase}
  \renewcommand{\mkbooktitlecase}{\tj@mksentencecase}
  % （4）姓名：§7.1.1 规定西文名可缩写为首字母（缩写名后不加点），汉语拼音名“宜用全称”。
  %     样式默认格式 gbnamefmt=lowercase 一律缩写名；全局改用 gbnamefmt=quanpin 又会把西文名
  %     也写成全称。因此逐个判断姓名：姓与名都是汉语拼音时改用样式的全拼格式 name:gbquanpin，
  %     其余仍按原格式缩写。判定规则照搬 gbt7714（gbt7714-2025-numeric.bst 的 is.name.pinyin）：
  %     没有前缀和后缀；姓是一个音节，或用连字符连接的两个音节；名是一个或两个音节，
  %     或用撇号隔开的两个音节；不区分大小写。音节表照录该文件的 pinyin.table1 至 table3，
  %     其中含 ü 的 4 个音节在 gbt7714 中永远不会匹配（它只接受 a 至 z），ka 与 sa 因该文件
  %     table2、table3 首项缺少前导空格也永远不会匹配，为与 gbt7714 输出一致均未列入。
  %     弯撇号 ’ 先换成 '，与 gbt7714 相同。两种后端的规则须同步维护。
  \ExplSyntaxOn
  \str_const:Nn \c__tj_pinyin_syllables_str
    {
      ,
      a,ai,an,ang,ao,
      ba,bai,ban,bang,bao,bei,ben,beng,bi,bian,biao,bie,bin,bing,bo,bu,
      ca,cai,can,cang,cao,ce,cen,ceng,cha,chai,chan,chang,chao,che,chen,cheng,chi,chong,chou,
      chu,chuai,chuan,chuang,chui,chun,chuo,ci,cong,cou,cu,cuan,cui,cun,cuo,
      da,dai,dan,dang,dao,de,dei,deng,di,dia,dian,diao,die,ding,diu,dong,dou,du,duan,dui,dun,
      duo,
      e,ei,en,eng,er,
      fa,fan,fang,fei,fen,feng,fo,fou,fu,
      ga,gai,gan,gang,gao,ge,gei,gen,geng,gong,gou,gu,gua,guai,guan,guang,gui,gun,guo,
      ha,hai,han,hang,hao,he,hei,hen,heng,hong,hou,hu,hua,huai,huan,huang,hui,hun,huo,
      ji,jia,jian,jiang,jiao,jie,jin,jing,jiong,jiu,ju,juan,jue,jun,
      kai,kan,kang,kao,ke,ken,keng,kong,kou,ku,kua,kuai,kuan,kuang,kui,kun,kuo,
      la,lai,lan,lang,lao,le,lei,leng,li,lia,lian,liang,liao,lie,lin,ling,liu,long,lou,lu,luan,
      lun,luo,lyu,lyue,
      ma,mai,man,mang,mao,me,mei,men,meng,mi,mian,miao,mie,min,ming,miu,mo,mou,mu,
      na,nai,nan,nang,nao,ne,nei,nen,neng,ni,nian,niang,niao,nie,nin,ning,niu,nong,nu,nuan,nuo,
      nyu,nyue,
      o,ou,
      pa,pai,pan,pang,pao,pei,pen,peng,pi,pian,piao,pie,pin,ping,po,pou,pu,
      qi,qia,qian,qiang,qiao,qie,qin,qing,qiong,qiu,qu,quan,que,qun,
      ran,rang,rao,re,ren,reng,ri,rong,rou,ru,ruan,rui,run,ruo,
      sai,san,sang,sao,se,sen,seng,sha,shai,shan,shang,shao,she,shei,shen,sheng,shi,shou,shu,
      shua,shuai,shuan,shuang,shui,shun,shuo,si,song,sou,su,suan,sui,sun,suo,
      ta,tai,tan,tang,tao,te,teng,ti,tian,tiao,tie,ting,tong,tou,tu,tuan,tui,tun,tuo,
      wa,wai,wan,wang,wei,wen,weng,wo,wu,
      xi,xia,xian,xiang,xiao,xie,xin,xing,xiong,xiu,xu,xuan,xue,xun,
      ya,yan,yang,yao,ye,yi,yin,ying,yong,you,yu,yuan,yue,yun,
      za,zai,zan,zang,zao,ze,zei,zen,zeng,zha,zhai,zhan,zhang,zhao,zhe,zhei,zhen,zheng,zhi,
      zhong,zhou,zhu,zhua,zhuai,zhuan,zhuang,zhui,zhun,zhuo,zi,zong,zou,zu,zuan,zui,zun,zuo,
    }
  \str_new:N \l__tj_pinyin_family_str
  \str_new:N \l__tj_pinyin_given_str
  \seq_new:N \l__tj_pinyin_seq
  \bool_new:N \l__tj_pinyin_bool
  \prg_new_protected_conditional:Npnn \__tj_pinyin_if_syllable:n #1 { T, F, TF }
    {
      \str_if_in:NnTF \c__tj_pinyin_syllables_str { , #1 , }
        { \prg_return_true: } { \prg_return_false: }
    }
  \prg_generate_conditional_variant:Nnn \__tj_pinyin_if_syllable:n { e } { T, F, TF }
  % 由 #2 中的分隔符切开的每一段都必须是一个音节，且至多 #3 段
  \cs_new_protected:Npn \__tj_pinyin_check_parts:nnn #1#2#3
    {
      \seq_set_split:Nnn \l__tj_pinyin_seq {#2} {#1}
      \bool_set_true:N \l__tj_pinyin_bool
      \int_compare:nNnT { \seq_count:N \l__tj_pinyin_seq } > {#3}
        { \bool_set_false:N \l__tj_pinyin_bool }
      \seq_map_inline:Nn \l__tj_pinyin_seq
        { \__tj_pinyin_if_syllable:nF {##1} { \bool_set_false:N \l__tj_pinyin_bool } }
    }
  % 不含撇号的名：一个音节，或能切成两个音节
  \cs_new_protected:Npn \__tj_pinyin_check_given:n #1
    {
      \__tj_pinyin_if_syllable:nTF {#1}
        { \bool_set_true:N \l__tj_pinyin_bool }
        {
          \bool_set_false:N \l__tj_pinyin_bool
          \int_step_inline:nn { \str_count:n {#1} - 1 }
            {
              \bool_if:NF \l__tj_pinyin_bool
                {
                  \__tj_pinyin_if_syllable:eT { \str_range:nnn {#1} { 1 } {##1} }
                    {
                      \__tj_pinyin_if_syllable:eT { \str_range:nnn {#1} { ##1 + 1 } { -1 } }
                        { \bool_set_true:N \l__tj_pinyin_bool }
                    }
                }
            }
        }
    }
  % \tj@ifpinyinname{<是拼音>}{<不是拼音>}：在 biblatex 姓名格式内判断当前姓名
  \cs_new_protected:Npn \tj@ifpinyinname #1#2
    {
      \bool_set_false:N \l__tj_pinyin_bool
      \bool_lazy_and:nnT
        { \tl_if_empty_p:o { \namepartprefix } }
        { \tl_if_empty_p:o { \namepartsuffix } }
        {
          \str_set:Ne \l__tj_pinyin_family_str { \exp_not:o { \namepartfamily } }
          \str_set:Ne \l__tj_pinyin_family_str { \str_casefold:V \l__tj_pinyin_family_str }
          \str_set:Ne \l__tj_pinyin_given_str { \exp_not:o { \namepartgiven } }
          \str_set:Ne \l__tj_pinyin_given_str { \str_casefold:V \l__tj_pinyin_given_str }
          \str_replace_all:Nnn \l__tj_pinyin_given_str { ’ } { ' }
          \__tj_pinyin_check_parts:Vnn \l__tj_pinyin_family_str { - } { 2 }
          \bool_if:NT \l__tj_pinyin_bool
            {
              \str_if_in:NnTF \l__tj_pinyin_given_str { ' }
                { \__tj_pinyin_check_parts:Vnn \l__tj_pinyin_given_str { ' } { 2 } }
                { \__tj_pinyin_check_given:V \l__tj_pinyin_given_str }
            }
        }
      \bool_if:NTF \l__tj_pinyin_bool {#1} {#2}
    }
  \cs_generate_variant:Nn \__tj_pinyin_check_parts:nnn { V }
  \cs_generate_variant:Nn \__tj_pinyin_check_given:n { V }
  \ExplSyntaxOff
  \letbibmacro{tj@name:gblowercase}{name:gblowercase}
  \renewbibmacro*{name:gblowercase}[4]{%
    \tj@ifpinyinname
      {\usebibmacro{name:gbquanpin}{#1}{\namepartgiven}{#3}{#4}}%
      {\usebibmacro{tj@name:gblowercase}{#1}{#2}{#3}{#4}}}
\else
  \RequirePackage[sort&compress, bibpunct=half]{gbt7714}   % 半角标点，与 biblatex 的 gbpunctwidth=half 对齐（撰写规范：参考文献标点统一采用半角）
  \iftongjithesis@authoryear
    \bibliographystyle{gbt7714-2025-authoryear}
  \else
    \bibliographystyle{gbt7714-2025-numeric}
  \fi
  \setlength{\bibsep}{3pt}
  % 目录条目写在“参考文献”标题之后，页码与跳转锚点才落在标题所在页（与 biblatex 的 heading=bibintoc 一致）。
  % 其余沿用 natbib 对 book 类的定义。
  \renewcommand{\bibsection}{%
    \chapter*{\bibname\@mkboth{\MakeUppercase{\bibname}}{\MakeUppercase{\bibname}}}%
    \addcontentsline{toc}{chapter}{\bibname}%
  }
  % 参考文献序号左对齐至页边距，悬挂统一为 0.74cm（与 Word 模板一致）。
  % gbt7714 已将 \@biblabel 改为 [#1]\hfill（左对齐）。natbib（gbt7714 内部加载）
  % 重写了 thebibliography，绕过 book.cls 的 \@openbib@code 钩子，因此须直接
  % 替换 numeric 模式下的列表参数宏 \@bibsetup（natbib 默认 \let 至 \NAT@bibsetnum）。
  % 0.74cm 为最小宽度；若实际最宽标签更宽（如 [100]+），则使用实际宽度。
  % \AtBeginDocument 确保替换在 natbib 自身 \NAT@set@cites 钩子（同样在 \AtBeginDocument）
  % 之后生效；用独立辅助宏 \tj@bibsetup 避免 \xdef 展开期 ## 参数歧义。
  \newcommand{\tj@bibsetup}[1]{%
    \settowidth\labelwidth{\@biblabel{#1}}%
    \ifdim\labelwidth<0.74cm \setlength{\labelwidth}{0.74cm}\fi
    \setlength{\leftmargin}{\labelwidth}%
    \setlength{\labelsep}{0pt}%
    \setlength{\itemsep}{\bibsep}%
    \setlength{\parsep}{\z@}}
  \iftongjithesis@authoryear\else\AtBeginDocument{\let\@bibsetup\tj@bibsetup}\fi
\fi

% \tjbibresource{file1,file2,...} — register bib files (preamble only)
\newcommand{\tj@bibfiles}{}
\iftongjithesis@biblatex
  \newcommand{\tjbibresource}[1]{%
    \def\do##1{\addbibresource{##1}}%
    \docsvlist{#1}%
  }
\else
  \newcommand{\tjbibresource}[1]{%
    \def\tj@bibfiles{#1}%
  }
\fi

% 未编号一级标题（目录、插图/表格清单、参考文献、附录、谢辞）：撰写规范要求四号黑体居中，
% 区别于正文章标题的小三号。目录、清单与参考文献在分组内调用，
% \appendix 与 \backmatter 之后则一直生效。
\newcommand{\tj@unnumberedheadingformat}{\ctexset{chapter/format={\centering\heiti\tjfontheading}}}

% \makereferences — output bibliography chapter
\iftongjithesis@biblatex
  \newcommand{\makereferences}{%
    \begingroup
    \tj@unnumberedheadingformat
    \printbibliography[heading=bibintoc,title=\tj@lang{参考文献}{Bibliography}]%
    \endgroup
  }
\else
  \newcommand{\makereferences}{%
    \begingroup
    \tj@unnumberedheadingformat
    \bibliography{\tj@bibfiles}%
    \endgroup
  }
\fi

% 著者-出版年制（bibstyle=authoryear）。中文论文沿用 GB/T 7714—2025 著者-出版年制的默认格式
% （按语种分集，中文在前），只取消上面为顺序编码制设置的序号标签：文献按悬挂缩进排列。
% 英文论文另按撰写规范（十四）“参考文献要求”与示例调整，两种后端都有的设置两边一致：
%   - 文献表：不著录文献类型标识；作者与年份之间用句点（“Dowty, D. R. 1986.”）；刊名与
%     论文集名用斜体；悬挂缩进“5 个空格”，取 MLA 对同一要求的写法“one-half inch (or five
%     spaces)”，即 0.5 英寸；题名的大小写照 .bib 原样（规范要求书名、刊名实词首字母大写，
%     期刊论文题名只大写首词与冒号后的首词，写 .bib 时按此书写）。
%   - 正文引用：“(Dowty, 1986: 37)”，页码在括号内，前加冒号（规范大段引文出处的格式）。
% 只有 biblatex 能做到的：中英文混排（gbt7714 总是按语种分集）、姓名“Dowty, D. R.”
% （gbt7714 为“Dowty D R”）、书名斜体、刊名与卷号之间不加逗号、最后两位作者之间用“&”、
% 同一（组）作者的后续文献以“——”代替作者，以及（十四）示例中论文集中的文章、整本论文集、
% 学位论文、会议论文、报纸与网络文献的格式（见下面的著录格式）。
% 英文论文的题名不论哪种著录方式都照 .bib 原样输出：顺序编码制原先的句首大写转换（见上文
% （3））会把题名中未加花括号的专有名词也改为小写。
\iftongjithesis@english
  \iftongjithesis@biblatex
    \renewcommand{\mktitlecase}[1]{#1}
    \renewcommand{\mkbooktitlecase}[1]{#1}
  \else
    \gbtsetup{sentencecase=false}
  \fi
\fi
\iftongjithesis@authoryear
  \iftongjithesis@biblatex
    \defbibenvironment{bibliography}
      {\list{}
         {\setlength{\leftmargin}{\bibhang}%
          \setlength{\itemindent}{-\leftmargin}%
          \setlength{\itemsep}{\bibitemsep}%
          \setlength{\parsep}{\bibparsep}}}
      {\endlist}
      {\item}
    \iftongjithesis@english
      \setlength{\bibhang}{0.5in}
      \DeclareDelimFormat[bib,biblist]{nameyeardelim}{\addperiod\space}
      \DeclareDelimFormat[bib,biblist]{finalnamedelim}{%
        \ifnumgreater{\value{liststop}}{2}{\addcomma}{}\addspace\&\space}
      % 引用中两位作者之间用“and”，与 gbt7714 的 citelang=english 一致（样式原为逗号，
      % 其 and 字符串也定义为逗号，故直接写出）。
      \DeclareDelimFormat{finalnamedelim}{\addspace and\space}
      \renewcommand{\jourdatevoldelim}{\addspace}
      % 斜体只用于西文：中文书名、刊名不排斜体（中文字体的“斜体”是楷体）。
      \newcommand*{\tj@mkbibemph}[1]{\iffieldequalstr{userd}{chinese}{#1}{\mkbibemph{#1}}}
      \DeclareFieldFormat{journaltitle}{\tj@mkbibemph{#1\isdot}}
      \DeclareFieldFormat{booktitle}{\tj@mkbibemph{#1}}
      \DeclareFieldFormat{maintitle}{\tj@mkbibemph{#1}}
      \DeclareFieldFormat
        [book,mvbook,collection,mvcollection,proceedings,mvproceedings,reference,mvreference]
        {title}{\tj@mkbibemph{#1}}
      % 同一（组）作者连续出现时，后续文献的作者写作“——”。gb7714-2025ay 在作者相同的分支
      % 里仍输出姓名，这里换成 \bibnamedash。
      \renewcommand*{\bibnamedash}{——}
      \patchcmd{\abx@macro@author}
        {\printnames{author}\setunit{\printdelim{nameyeardelim}}}
        {\printtext{\bibnamedash}\setunit{\printdelim{nameyeardelim}}}
        {}{\ClassError{tongjithesis}{Failed to patch the author macro of gb7714-2025ay}
             {The installed biblatex-gb7714-2015 differs from the version this class\MessageBreak
              was written for. Please report it with your log file.}}
      % 西文文献的译者前加“Trans.”（规范示例“Trans. Sheridan, A.”）；中文文献仍在译者后加“译”。
      \expandafter\patchcmd\csname abx@macro@bytranslator+others\endcsname
        {\printnames[bytranslator]{translator}}
        {\iffieldequalstr{usere}{chinese}{}{\printtext{Trans.}\setunit{\addspace}}%
         \printnames[bytranslator]{translator}}
        {}{\ClassError{tongjithesis}{Failed to patch the translator macro of gb7714-2025ay}
             {The installed biblatex-gb7714-2015 differs from the version this class\MessageBreak
              was written for. Please report it with your log file.}}
      % 中文文献（题名为中文）的标点用中文字体，如题名中的引号；其余文献用西文字体。
      \AtEveryBibitem{\iffieldequalstr{userd}{chinese}{\tj@punctchinese}{\tj@punctenglish}}
      % （十四）“参考文献书写格式示例”中 GB/T 7714 没有的格式：
      %   论文集中的文章 Labov, W. & Waletzky, J. 1967. Title. In Helm, J. ed., Book (pp. 12-44).
      %     Place: Publisher.（@incollection，及有编者的 @inproceedings）
      %   整本论文集     Davis, B. H. ed. 2005. Book. Place: Publisher.（@collection）
      %   学位论文       Chomsky, N. 1955. Title. Diss. Place: University.（@thesis）
      %   会议论文       Grice, H. P. 1967. Title. Conference. Place.（无编者的 @inproceedings）
      %   报纸           Lohr, S. “Title.” Newspaper 3 Apr. 1998, late ed.: C1+.
      %                  （@newspaper，或 entrysubtype = newspaper 的 @article；样式把两者都记作 news）
      %   网络文献       Knuth, D. E. Title. 28 Nov. 2026 <URL>.（@online）
      % 报纸与网络文献按示例（MLA 格式）在作者后不写年份，日期写在后面。
      \newcommand*{\tj@enmonth}[1]{%
        \ifcase\numexpr#1\relax\or Jan.\or Feb.\or Mar.\or Apr.\or May\or June\or
          July\or Aug.\or Sept.\or Oct.\or Nov.\or Dec.\fi}
      % tj@en:date{<前缀>}：“3 Apr. 1998”，<前缀> 为空（出版日期）或 url（访问日期）。
      \newbibmacro*{tj@en:date}[1]{%
        \iffieldundef{#1year}{}
          {\printtext{%
             \iffieldundef{#1day}{}{\thefield{#1day}\space}%
             \iffieldundef{#1month}{}{\tj@enmonth{\thefield{#1month}}\space}%
             \thefield{#1year}}}}
      % 作者，不写年份（报纸、网络文献）；同一作者连续出现时写作“——”。
      \newbibmacro*{tj@en:names}{%
        \ifnameundef{author}{}
          {\usebibmacro{bbx:dashcheck}
             {\printtext{\bibnamedash}}
             {\usebibmacro{bbx:savehash}\printnames{author}}}}
      \newbibmacro*{tj@en:publisher}{%
        \printlist{location}%
        \setunit{\addcolon\space}%
        \printlist{publisher}}
      \newbibmacro*{tj@en:in}{%
        \printtext{In}%
        \setunit{\addspace}%
        \ifnameundef{editor}{}
          {\printnames{editor}\setunit{\addspace}\printtext{ed\adddot}\setunit{\addcomma\space}}%
        \printfield{booktitle}%
        \iffieldundef{pages}{}
          {\setunit{\addspace}\printtext[parens]{pp\adddot\addspace\printfield{pages}}}}
      \DeclareFieldFormat{tj@angleurl}{\textless\url{#1}\textgreater}
      \DeclareFieldFormat{tj@quoted}{\mkbibquote{#1\addperiod}}
      \DeclareBibliographyDriver{incollection}{%
        \usebibmacro{bibindex}\usebibmacro{begentry}%
        \usebibmacro{author}\newunit\newblock
        \printfield{title}\newunit\newblock
        \usebibmacro{tj@en:in}\newunit\newblock
        \usebibmacro{tj@en:publisher}%
        \usebibmacro{finentry}}
      \DeclareBibliographyDriver{inproceedings}{%
        \usebibmacro{bibindex}\usebibmacro{begentry}%
        \usebibmacro{author}\newunit\newblock
        \printfield{title}\newunit\newblock
        \ifnameundef{editor}
          {\printfield[default]{booktitle}\newunit\newblock
           \iffieldundef{venue}{\printlist{location}}{\printfield{venue}}}
          {\usebibmacro{tj@en:in}\newunit\newblock
           \usebibmacro{tj@en:publisher}}%
        \usebibmacro{finentry}}
      \DeclareBibliographyDriver{collection}{%
        \usebibmacro{bibindex}\usebibmacro{begentry}%
        \ifnameundef{author}
          {\printnames{editor}\setunit{\addspace}\printtext{ed\adddot}%
           \setunit{\printdelim{nameyeardelim}}\usebibmacro{date+extradate}}
          {\usebibmacro{author}}%
        \newunit\newblock
        \printfield{title}\newunit\newblock
        \usebibmacro{tj@en:publisher}%
        \usebibmacro{finentry}}
      \DeclareBibliographyDriver{thesis}{%
        \usebibmacro{bibindex}\usebibmacro{begentry}%
        \usebibmacro{author}\newunit\newblock
        \printfield{title}\newunit\newblock
        \printtext{Diss\adddot}\newunit\newblock
        \printlist{location}\setunit{\addcolon\space}\printlist{institution}%
        \usebibmacro{finentry}}
      \DeclareBibliographyDriver{online}{%
        \usebibmacro{bibindex}\usebibmacro{begentry}%
        \usebibmacro{tj@en:names}\newunit\newblock
        \printfield{title}\newunit\newblock
        \usebibmacro{tj@en:date}{}\newunit\newblock
        \usebibmacro{tj@en:date}{url}\setunit{\addspace}%
        \printfield[tj@angleurl]{url}%
        \usebibmacro{finentry}}
      \csletcs{blx@bbx@tj@article}{blx@bbx@article}
      \DeclareBibliographyDriver{article}{%
        \iffieldequalstr{entrysubtype}{news}
          {\usebibmacro{bibindex}\usebibmacro{begentry}%
           \usebibmacro{tj@en:names}\newunit\newblock
           \printfield[tj@quoted]{title}\setunit{\addspace}%
           \printfield{journaltitle}\setunit{\addspace}%
           \usebibmacro{tj@en:date}{}%
           \iffieldundef{edition}{}
             {\setunit{\addcomma\space}\printtext{\thefield{edition}\addspace ed\adddot}}%
           \setunit{\addcolon\space}\printfield{pages}%
           \usebibmacro{finentry}}
          {\csuse{blx@bbx@tj@article}}}
      % 学位论文的题名与书名一样用斜体；网络文献的题名为网站或网页名，也用斜体（MLA）。
      \DeclareFieldFormat[thesis,online]{title}{\tj@mkbibemph{#1}}
      \DeclareFieldFormat[online]{labelurlyear}{#1}
      % 页码放进括号：\cite 与 \citep 原为“(Dowty, 1986)\textsuperscript{37}”。
      \DeclareFieldFormat{postnote}{#1}
      \DeclareFieldFormat{multipostnote}{#1}
      \DeclareDelimFormat{postnotedelim}{\addcolon\space}
      \DeclareCiteCommand{\cite}
        {\usebibmacro{cite:init}\mkbibleftborder\usebibmacro{prenote}}
        {\usebibmacro{citeindex}\usebibmacro{cite}}
        {}
        {\usebibmacro{postnote}\mkbibrightborder}
      \DeclareCiteCommand{\citep}
        {\usebibmacro{cite:init}\mkbibleftborder\usebibmacro{prenote}}
        {\usebibmacro{citeindex}\usebibmacro{cite}}
        {}
        {\usebibmacro{postnote}\mkbibrightborder}
      \renewbibmacro*{citet:postnote}{\usebibmacro{textcite:postnote}}
    \fi
  \else
    % 著者-出版年制的引用括号与标点也用半角（gbt7714 默认全角）。\cite 与 \parencite 同
    % \citep，为括号内的“(作者, 年份)”，与 gb7714-2025ay 一致（natbib 的 \cite 在著者-出版年制
    % 下同 \citet，gbt7714 的 \parencite 为顺序编码制而设）。
    \gbtsetup{citepunct=half}
    \let\cite\citep
    \let\parencite\citep
    \iftongjithesis@english
      \gbtsetup{
        citelang=english,
        maxcitenames=2,
        entrytypeid=false,
        entrymediumid=false,
        nameyeardelim=period,
        emphjournal=true,
        emphbooktitle=true,
        initializepinyin=true,
        locator-in-brackets=true,
      }
      \setlength{\bibhang}{0.5in}
      % 页码前用冒号；.aux 中的 \bibstyle 在 \begin{document} 读入时重设分隔符，故在其后设置。
      \AtBeginDocument{\setcitestyle{notesep={: }}}
    \fi
  \fi
\fi

% ==========================================
% General Configurations
% ==========================================

% Line spacing
\setstretch{\tjlinespread}  % 设置全文行距

% Display math spacing — 撰写规范（七）公式：“公式行行距1.5倍”，段前/段后 0 行。
%
% Word 里“段前 0 行 + 段后 0 行 + 行距 1.5 倍”指的是公式段落除 1.5 倍行距外不再
% 追加段间距——1.5 倍行距本身带来的行间留白仍然存在。LaTeX 的默认值正好对应这个
% 效果：\abovedisplayskip 12pt 对正文 \baselineskip 23.49pt 约为半行，与 Word 中
% 1.5 倍行距公式行的留白一致，因此正文公式沿用 LaTeX 默认值，不另行赋值。
%
% 注意不要把它写成 \abovedisplayskip 0\p@：TeX 在显示公式上下插入的是
% \abovedisplayskip / \belowdisplayskip 本身，而不是行距胶，置 0 会让公式紧贴上
% 一行，比规范要求更挤。（并且类文件层的一次性赋值本就无效——size1x.clo 把
% \normalsize、\small、\footnotesize 定义为「设置字号 + 重设这四个 skip」，
% \begin{document} 处的 \normalsize 会立刻改回默认值。）

% Table float spacing — 表格/图片上下与正文之间各空一行（官方规范）
\setlength{\textfloatsep}{\baselineskip}
\setlength{\intextsep}{\baselineskip}
\setlength{\floatsep}{0.5\baselineskip}

% 图居中（官方规范）
\AtBeginEnvironment{figure}{\centering}

% 禁止 twoside 模式下拉伸垂直间距
% book 文档类在 twoside 模式下默认启用 \flushbottom，强制所有页面底部对齐，
% 这会拉伸 \parskip 等带 stretch 的垂直间距，导致标题附近的空行行距不均匀。
% \raggedbottom 允许页面底部自然变化，保证全文行距一致。
% 使用 \AtEndOfClass 确保在所有 class 级代码执行完毕后覆盖。
\AtEndOfClass { \raggedbottom }

% ==========================================
% Page Layout
% ==========================================

% 画边界线（使用 eso-pic + savebox，避免 fancyput 与 listings 的跨页冲突）
% Pre-render binding line content into saved boxes, all centered in 1em width
\newlength{\bindwidth}
\setlength{\bindwidth}{1em}
\newsavebox{\tjbindpipe}
\newsavebox{\tjbindZ}
\newsavebox{\tjbindD}
\newsavebox{\tjbindX}
\AtBeginDocument{%
  \sbox{\tjbindpipe}{\makebox[\bindwidth][c]{\rule{0.4pt}{3mm}}}%
  \sbox{\tjbindZ}{\makebox[\bindwidth][c]{\zihao{5}装}}%
  \sbox{\tjbindD}{\makebox[\bindwidth][c]{\zihao{5}订}}%
  \sbox{\tjbindX}{\makebox[\bindwidth][c]{\zihao{5}线}}%
}

% Flag to suppress binding line on cover page
\newif\iftjbindingline
\tjbindinglinetrue

% Helper macro: draw binding line column at a given x position
% Coordinates empirically matched to the official Tongji thesis template.
% eso-pic \AtPageLowerLeft origin: (0,0) at bottom-left of A4 page.
\newcommand{\tj@bindingcolumn}[1]{%
  \put(\LenToUnit{#1},\LenToUnit{23.60cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{23.12cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{22.65cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{22.16cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{21.68cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{21.20cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{20.72cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{20.24cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{19.76cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{19.29cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{18.80cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{18.32cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{17.84cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{17.37cm}){\usebox{\tjbindZ}}%
  \put(\LenToUnit{#1},\LenToUnit{16.88cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{16.40cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{15.92cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{15.44cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{14.96cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{14.50cm}){\usebox{\tjbindD}}%
  \put(\LenToUnit{#1},\LenToUnit{14.00cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{13.52cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{13.04cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{12.56cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{12.07cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{11.60cm}){\usebox{\tjbindX}}%
  \put(\LenToUnit{#1},\LenToUnit{11.12cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{10.63cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{10.15cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{9.68cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{9.20cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{8.71cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{8.24cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{7.76cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{7.27cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{6.79cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{6.32cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{5.84cm}){\usebox{\tjbindpipe}}%
  \put(\LenToUnit{#1},\LenToUnit{5.35cm}){\usebox{\tjbindpipe}}%
}

% Oneside: x=1.6cm from left edge
% Twoside even page: binding on right side at 21 - 1.6 = 19.4cm
\@ifclasswith{tongjithesis}{twoside}{%
  \AddToShipoutPictureBG{%
    \iftjbindingline
      \AtPageLowerLeft{%
        \ifodd\value{page}%
          \tj@bindingcolumn{1.6cm}%
        \else
          \tj@bindingcolumn{19.4cm}%
        \fi
      }%
    \fi
  }%
}{%
  \AddToShipoutPictureBG{%
    \iftjbindingline
      \AtPageLowerLeft{%
        \tj@bindingcolumn{1.6cm}%
      }%
    \fi
  }%
}

% 双横线页眉：两条 0.5pt 细线替代默认的单粗线。
% fancyhdr 仅在 \headrulewidth>0pt 时调用 \headrule，故保留默认 0.4pt 即可触发，
% 实际线宽由 \tjdoubleheadrule 内部的 \hrule \@height 控制。
\newcommand{\tjdoubleheadrule}{%
  \hrule\@height0.5pt\@width\headwidth
  \vskip1pt
  \hrule\@height0.5pt\@width\headwidth}

% 设置摘要与目录页样式（如页眉、页脚等）
\fancypagestyle{firststyle}{
  \fancyhf{}
  \fancyhead[LO]{\hspace*{1cm}\includegraphics[height=1.14cm,alt={同济大学校名题字}]{figures/tongji-header.pdf}~}
  \fancyhead[RE]{~\includegraphics[height=1.14cm,alt={同济大学校名题字}]{figures/tongji-header.pdf}\hspace*{1cm}}
  \fancyhead[RO,LE]{\tjfontbody ~\tjheadertext~\\}
  \fancyfoot[C]{\tjfontbody \thepage}
  \renewcommand{\headrule}{\tjdoubleheadrule}
  \renewcommand{\footrulewidth}{0pt}
}

% 设置正文页样式（如页眉、页脚等）
\fancypagestyle{mainstyle}{
  \fancyhf{}
  \fancyhead[LO]{\hspace*{1cm}\includegraphics[height=1.14cm,alt={同济大学校名题字}]{figures/tongji-header.pdf}~}
  \fancyhead[RE]{~\includegraphics[height=1.14cm,alt={同济大学校名题字}]{figures/tongji-header.pdf}\hspace*{1cm}}
  \fancyhead[RO,LE]{\tjfontbody ~\tjheadertext~\\}
  \fancyfoot[RO]{{\tjfontbody 共\quad \pageref{LastPage}\quad 页\quad 第\quad \thepage \quad 页}}
  \fancyfoot[LE]{{\tjfontbody 第\quad \thepage \quad 页\quad 共\quad \pageref{LastPage}\quad 页}}
  \renewcommand{\headrule}{\tjdoubleheadrule}
  \renewcommand{\footrulewidth}{1.8pt}
}

% 自动设置前言和正文的页面样式
% ctexbook 的 \chapter 会将首页设为 plain 样式，需要重定义 plain 以匹配当前样式
\let\tj@origfrontmatter\frontmatter
\renewcommand{\frontmatter}{%
  \tj@origfrontmatter
  \pagenumbering{Roman}%
  \pagestyle{firststyle}%
  \fancypagestyle{plain}{\pagestyle{firststyle}}%
}
\let\tj@origmainmatter\mainmatter
\renewcommand{\mainmatter}{%
  \tj@origmainmatter
  \pagestyle{mainstyle}%
  \fancypagestyle{plain}{\pagestyle{mainstyle}}%
}
% 附录：
%   “附录”作为未编号 H1 章节标题（四号黑体居中），写入目录。
%   附录内的小节使用 A. B. C. 编号（与正文 chapter.section 解耦），
%   浮动体 (figure/table/equation/…) 随节编号为 A.1、A.2、B.1 …
%   \appendixsection / \appendixsubsection 是 \section / \subsection 的别名，
%   保持 chapters/appendix.tex 的语义；用户也可直接用 \section / \subsection。
\let\tj@origappendix\appendix
\renewcommand{\appendix}{%
  \tj@origappendix
  \tj@unnumberedheadingformat
  \chapter*{\appendixname}%
  \addcontentsline{toc}{chapter}{\appendixname}%
  % 附录内小节：A B C … Z AA AB …（alphalph 包提供，>26 自动延伸）
  \setcounter{section}{0}%
  \renewcommand{\thesection}{\AlphAlph{\value{section}}}%
  \renewcommand{\thesubsection}{\thesection.\arabic{subsection}}%
  % 浮动体随节编号 (A.1, A.2, B.1, …)
  \counterwithin{figure}{section}%
  \counterwithin{table}{section}%
  \counterwithin{equation}{section}%
  \counterwithin{algorithm}{section}%
  \counterwithin{listing}{section}%
  \@ifundefined{c@lstlisting}{}{\counterwithin{lstlisting}{section}}%
  \counterwithin{thm}{section}%
  \counterwithin{cor}{section}%
  \counterwithin{lem}{section}%
  \counterwithin{prop}{section}%
  \counterwithin{conj}{section}%
  \counterwithin{assume}{section}%
  \counterwithin{dfn}{section}%
  \counterwithin{exmp}{section}%
  \counterwithin{rem}{section}%
  % 理工科：“A. 节名”；文科：“（A） 节名”（括号来自正文 section/name 延续，无点号）
  \iftongjithesis@chinesenumbers
    \ctexset{section/number={\thesection},section/aftername={\hspace{0.5em}}}%
  \else
    \ctexset{section/name={,},section/number={\thesection},section/aftername={.\hspace{0.5em}}}%
  \fi
}
\newcommand{\appendixsection}{\section}
\newcommand{\appendixsubsection}{\subsection}
% Backmatter headings (acknowledgements) use 四号 per the spec.
% The \ctexset override is intentionally permanent for the rest of the document
% (backmatter is always the final structural division).
\let\tj@origbackmatter\backmatter
\renewcommand{\backmatter}{%
  \tj@origbackmatter
  \tj@unnumberedheadingformat
}

% ==========================================
% Typography and Font Settings
% ==========================================

% 表格内所有字体均为五号（\tjfonttable）
\AtBeginEnvironment{table}{\tjfonttable}
\AtBeginEnvironment{tabular}{\tjfonttable}
\AtBeginEnvironment{tabular*}{\tjfonttable}
\AtBeginEnvironment{tabularx}{\tjfonttable}
\AtBeginEnvironment{longtable}{\tjfonttable}
\AtBeginEnvironment{tablenotes}{\tjfonttable}

% 续表行：五号宋体，右对齐，右空2格（规范要求）
% 用法：在 longtable 的 \endhead 中，列头重复前调用 \tjlongtablecont{列数}
\newcommand{\tjlongtablecont}[1]{%
  \multicolumn{#1}{r@{\hspace{2em}}}{\zihao{5}\songti\tj@lang{续表~\thetable}{\tablename~\thetable\ (continued)}}\\%
}
% 转页处的表尾：横线与右对齐的“续下页”。用法：在 longtable 的 \endfoot 之前调用
% \tjlongtablefoot{列数}。研究生学位论文的续表与表尾见 tongji-graduate.def。
\newcommand{\tjlongtablefoot}[1]{\hline\multicolumn{#1}{r}{\tj@lang{续下页}{continued on next page}}}
% \tjifgraduate{<研究生>}{<本科>}：硕士、博士学位论文（degree=master|doctor）取第一个参数，本科取
% 第二个；供本科与研究生共用的文字（如示例章节）写出各自的规定。
\newcommand{\tjifgraduate}{%
  \iftongjithesis@bachelor\expandafter\@secondoftwo\else\expandafter\@firstoftwo\fi}

% 大段引文（撰写规范（十四））：超过 4 行的引文独立成段，不加引号，与正文上下各空一行，
% 整体左缩进 4 个字符、右侧与正文对齐，字体与行距同正文；出处在下一行右对齐，
% 写作“(作者姓氏, 出版年份: 页码)”。
% 用法：\begin{tjquote}[<出处>] <引文> \end{tjquote}；出处中有方括号时用花括号括起，
% 如 [{\parencite[37]{key}}]。中文论文同样可用。
\NewDocumentEnvironment{tjquote}{o}
  {\list{}{%
     \setlength{\leftmargin}{4em}%
     \setlength{\rightmargin}{\z@}%
     \setlength{\itemindent}{\z@}%
     \setlength{\listparindent}{\parindent}%
     \setlength{\topsep}{\baselineskip}%
     \setlength{\partopsep}{\z@}%
     \setlength{\parsep}{\z@}}%
   \item\relax}
  {\IfValueT{#1}{\par\nopagebreak{\raggedleft #1\par}}%
   \endlist}

% ==========================================
% Lists and Enumerations
% ==========================================

% 设置有序列表与无序列表格式
\setlistdepth{2}

\setlist[enumerate]{nosep,labelsep=0pt}
\setlist[enumerate,1]{label=（\arabic*）,left=2em,nosep,labelsep=0pt,wide=\parindent}
\setlist[enumerate,2]{label=\TJCircled{\tj@cval{enumii}},nosep,labelsep=0pt,labelwidth=1em,listparindent=0pt}

\setlist[itemize]{nosep}
\setlist[itemize,1]{wide=\parindent}
\setlist[itemize,2]{wide=2\parindent}

% ==========================================
% Table of Contents Formatting
% ==========================================

% 在上述修改基础上，符合模板标题对齐要求
% \renewcommand{\cftdot}{.}
\renewcommand{\cftdotsep}{1}
% 目录缩进：章无缩进，节 2em，小节 4em（与标题缩进保持一致）；目录行距由 \tjtoclinespread 控制
\setlength{\cftchapindent}{0em}
\setlength{\cftsecindent}{2em}
\setlength{\cftsubsecindent}{4em}
\setlength{\cftsecnumwidth}{1.5em}
\setlength{\cftsubsecnumwidth}{2em}
\setlength{\cftsubsubsecnumwidth}{2.5em}
\setlength{\cftbeforechapskip}{0pt}
\setlength{\cftbeforesecskip}{0pt}
\setlength{\cftbeforesubsecskip}{0pt}
\renewcommand{\contentsname}{\tj@lang{目\hspace{0.5em}录}{Contents}}
% 目录标题后留一空行
% tocloft[titles] 下 \cftaftertoctitleskip 无效——\tableofcontents 内部走 \chapter*，
% 所以直接在 \@starttoc 前注入 \vspace。
% 标题“前”的空行由页面上边距 + ctex chapter beforeskip 提供，此处不再额外注入以免产生孤儿页。
\patchcmd{\tableofcontents}{\@starttoc{toc}}{\vspace{\baselineskip}\@starttoc{toc}}%
  {}{\ClassWarning{tongjithesis}{Failed to patch \string\tableofcontents\space for title spacing}}
\renewcommand{\cftchapfont}{\songti\tjfontbody}
\renewcommand{\cftsecfont}{\songti\tjfontbody}
\renewcommand{\cftsubsecfont}{\songti\tjfontbody}
\renewcommand{\cftchapleader}{\cftdotfill{\cftchapdotsep}}
\renewcommand{\cftchapdotsep}{\cftdotsep}
\renewcommand{\cftsecleader}{\cftdotfill{\cftsecdotsep}}
\renewcommand{\cftsecdotsep}{\cftdotsep}
\renewcommand{\cftchappagefont}{\tjfontbody}
\renewcommand{\cftsecpagefont}{\tjfontbody}
\renewcommand{\cftsubsecpagefont}{\tjfontbody}

% 目录行距：对应 Word“1.5 倍行距”——使用 \tjtoclinespread
% 目录标题经 \chapter* 排出，spacing 分组内改用四号（\tj@unnumberedheadingformat）
\let\tj@origtableofcontents\tableofcontents
\renewcommand{\tableofcontents}{%
  \begin{spacing}{\tjtoclinespread}\tj@unnumberedheadingformat\tj@origtableofcontents\end{spacing}%
}
% 插图清单、表格清单（main.tex 中按需启用）的标题与目录一致，用四号
\let\tj@origlistoffigures\listoffigures
\renewcommand{\listoffigures}{\begingroup\tj@unnumberedheadingformat\tj@origlistoffigures\endgroup}
\let\tj@origlistoftables\listoftables
\renewcommand{\listoftables}{\begingroup\tj@unnumberedheadingformat\tj@origlistoftables\endgroup}

% ==========================================
% Chapter/Section Numbering and Formatting
% ==========================================

% 设置图表编号和章节相关联
\RequirePackage{chngcntr}
\counterwithin{figure}{chapter}
\counterwithin{table}{chapter}
\counterwithin{equation}{chapter}
\counterwithin{algorithm}{chapter}
% listing counter: created by minted (minted=true) or \newfloat (minted=false)
% lstlisting counter: created by listings package
% Both are bound to chapter, then lstlisting is aliased to listing.
\AtBeginDocument{%
  \counterwithin{listing}{chapter}%
  \@ifundefined{c@lstlisting}{}{%
    \counterwithin{lstlisting}{chapter}%
    \let\c@lstlisting\c@listing
  }%
}

% 设置正文页内章节标题格式
\ctexset{
  chapter={%
    format={\centering\heiti\tjfontchapter},
    nameformat={},
    name={},
    number={\arabic{chapter}},
    aftername={\quad},
    break={\cleardoublepage},  % oneside 下等同 \clearpage；twoside 下章首始于奇数页，由 emptypage 抑制页眉
    % Negative beforeskip: absolute value (16pt) is the vertical space above
    % the heading; the negative sign suppresses first paragraph indent (ctex convention).
    beforeskip={-16pt},
    afterskip={\tjskipaftersec},
  },
  section={%
    format={\heiti\tjfontbody},
    aftername={\hspace{0.5em}},
    beforeskip={\tjskipbeforesec},
    afterskip={\tjskipaftersec},
  },
  subsection={%
    format={\heiti\tjfontbody},
    aftername={\hspace{0.5em}},
    beforeskip={\tjskipbeforesec},
    afterskip={\tjskipaftersec},
    indent={2em},
  },
  subsubsection={%
    format={\heiti\tjfontbody},
    numbering=true,
    number={\AlphAlph{\value{subsubsection}}},
    aftername={.\hspace{0.5em}},
    beforeskip={\tjskipbeforesec},
    afterskip={\tjskipaftersec},
    indent={2em},
    aftertitle={\par},
  },
  paragraph={%
    format={\heiti\tjfontbody},
    numbering=true,
    number={\alphalph{\value{paragraph}}},
    aftername={.\hspace{0.5em}},
    beforeskip={\tjskipbeforesec},
    afterskip={\tjskipaftersec},
    indent={2em},
    aftertitle={\par},
    % ctex's chinese-book scheme makes paragraph run-in by default; with run-in the
    % afterskip is emitted as horizontal \hskip via \CTEX@heading@glue, which combines
    % with \parindent to give "parindent + afterskip" indent on the body. Force display.
    runin=false,
  },
  appendix/name={},
}

\setcounter{secnumdepth}{5}

% 文科类专业（field=humanities）：章节编号改用中文数字体系
% 理工科（science，默认）：1 / 1.1 / 1.1.1 / A. / a.
% 文科  （humanities）  ：一、/（一）/ 1. / （1） / ①②③（英文论文用理工科的编号，见 \iftongjithesis@chinesenumbers）
\iftongjithesis@chinesenumbers
  \renewcommand{\thechapter}{\chinese{chapter}}
  \renewcommand{\thesubsection}{\arabic{subsection}}
  \renewcommand{\thesubsubsection}{\arabic{subsubsection}}
  \ctexset{
    chapter/number    = {\chinese{chapter}},
    chapter/aftername = {、},
    % 括号写入 name 而非 number，使 \thesection 保持裸数字（供 tocloft/cref 使用）
    section/name      = {（,）},
    section/number    = {\chinese{section}},
    % section/aftername = {\hspace{0.5em}},
    subsection/number    = {\arabic{subsection}},
    subsection/aftername = {.\hspace{0.5em}},
    % 同理：括号写入 name，\thesubsubsection 保持裸数字
    subsubsection/name     = {（,）},
    subsubsection/number   = {\arabic{subsubsection}},
    subsubsection/aftername = {\hspace{0.5em}},
    paragraph/number    = {\TJCircled{\the\c@paragraph}},
    paragraph/aftername = {\hspace{0.5em}},
  }
  % TOC 目录列宽与分隔符
  % h1
  \renewcommand{\cftchapaftersnum}{\!、}
  \setlength{\cftchapnumwidth}{2.5em}
  % h2
  \setlength{\cftsecindent}{2.5em}
  \setlength{\cftsecnumwidth}{2.5em}
  % h3
  \renewcommand{\cftsubsecaftersnum}{.\hspace*{0.5em}}
  \setlength{\cftsubsecnumwidth}{1.5em}
  % 图、表、公式等按章编号（撰写规范：“以章分组编序号”，不分文理）。文科章号用汉字，
  % 编号中的章号仍用阿拉伯数字，如“图 2.1”“(2.2)”，与规范示例“(2.2) 表示第二章的第二个公式”一致。
  % 附录中 \appendix 改为按节编号（A.1），会覆盖这里的定义。
  \renewcommand{\thefigure}{\arabic{chapter}.\arabic{figure}}
  \renewcommand{\thetable}{\arabic{chapter}.\arabic{table}}
  \renewcommand{\theequation}{\arabic{chapter}.\arabic{equation}}
  \renewcommand{\thealgorithm}{\arabic{chapter}.\arabic{algorithm}}
  % listing/lstlisting 在 \AtBeginDocument 中才建立；定理类环境在 \newtheorem 后定义
  \AtBeginDocument{%
    \@for\tj@cnt:=listing,lstlisting,thm,cor,lem,prop,conj,assume,dfn,exmp,rem\do{%
      \@ifundefined{c@\tj@cnt}{}{%
        \expandafter\edef\csname the\tj@cnt\endcsname{%
          \noexpand\arabic{chapter}.\noexpand\arabic{\tj@cnt}}%
      }%
    }%
  }%
\fi

% 脚注编号使用①②③… (官方规范)
\renewcommand{\thefootnote}{\TJCircled{\the\c@footnote}}


% ==========================================
% Float Settings
% ==========================================

% 设置浮动体的 caption 位置
\floatstyle{plaintop}       % 表格的 caption 在表格上方
\restylefloat{table}
\floatstyle{plain}
\restylefloat{listing}      % minted 默认 ruled，\newfloat 默认 plain；统一为 plain
\sloppy

% ==========================================
% Math and Theorem Environments
% ==========================================
\theoremstyle{definition}

\newtheorem{thm}{\tj@lang{定理}{Theorem}\hspace{0.05pt}}[chapter]
\newtheorem{cor}{\tj@lang{推论}{Corollary}\hspace{0.05pt}}[chapter]
\newtheorem{lem}{\tj@lang{引理}{Lemma}\hspace{0.05pt}}[chapter]
\newtheorem{prop}{\tj@lang{命题}{Proposition}\hspace{0.05pt}}[chapter]
\newtheorem{conj}{\tj@lang{猜想}{Conjecture}\hspace{0.05pt}}[chapter]
\newtheorem{assume}{\tj@lang{假设}{Assumption}\hspace{0.05pt}}[chapter]
\newtheorem{dfn}{\tj@lang{定义}{Definition}\hspace{0.05pt}}[chapter]
\newtheorem{exmp}{\tj@lang{例}{Example}\hspace{0.05pt}}[chapter]
\newtheorem{rem}{\tj@lang{注}{Remark}\hspace{0.05pt}}[chapter]
\newtheorem*{pf}{\tj@lang{证明}{Proof}}

% Math commands
\providecommand{\dd}{\mathop{}\!\mathrm{d}}
\providecommand{\ee}{\mathrm{e}}
\providecommand{\ii}{\mathrm{i}}
\providecommand{\jj}{\mathrm{j}}
\DeclareRobustCommand\cs[1]{\texttt{\char`\\#1}}
\providecommand\pkg[1]{\href{https://ctan.org/pkg/#1}{\sffamily#1}}

% ==========================================
% Algorithm and Code Listing Settings
% ==========================================

% 算法环境把行距压回 \linespread{1.0}（\baselineskip 由 23.49pt 降到 14.45pt），
% 但 \abovedisplayskip / \belowdisplayskip 仍是正文行距下的 12pt——相对压缩后的
% 行距接近一整行空白，算法内的行间公式上下会多出明显空行。按正文里的同一比例
% （12pt ÷ 23.49pt ≈ 0.5 行）随当前行距缩放，两处算法实现都要挂。
\newcommand{\tj@algodisplayskips}{%
  \setlength\abovedisplayskip{0.5\baselineskip}%
  \setlength\abovedisplayshortskip{\z@}%
  \setlength\belowdisplayskip{0.5\baselineskip}%
  \setlength\belowdisplayshortskip{\z@}%
}

% 伪代码
\iftongjithesis@algorithmtwoe
  \SetAlgorithmName{\tj@lang{算法}{Algorithm}}{\tj@lang{算法}{Algorithm}}{\tj@lang{算法列表}{List of Algorithms}}
  \SetKwInput{KwIn}{\tj@lang{输入}{Input}}
  \SetKwInput{KwOut}{\tj@lang{输出}{Output}}
  \gdef\algocf@Vspace{\vskip\baselineskip\relax}
  \AtBeginEnvironment{algorithm}{\linespread{1.0}\selectfont\tj@algodisplayskips}
  \AfterEndEnvironment{algorithm}{\vspace{\baselineskip}}
\else
  \renewcommand{\algorithmicrequire}{\textbf{\tj@lang{输入}{Input}: }}
  \renewcommand{\algorithmicensure}{\textbf{\tj@lang{输出}{Output}: }}
  \AtBeginEnvironment{algorithmic}{\linespread{1.0}\selectfont\tj@algodisplayskips}
  \renewenvironment{algorithm}
  {
    \vskip\baselineskip
    \refstepcounter{algorithm}% New algorithm
    \hrule height.8pt depth0pt \kern2pt% \@fs@pre for \@fs@ruled
    \renewcommand{\caption}[2][\relax]{% 使用中文 caption
      {\raggedright\textbf{\tj@lang{算法}{Algorithm}~\thealgorithm} ##2\par}%
      \ifx\relax##1\relax % #1 is \relax
        \addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##2}%
      \else % #1 is not \relax
        \addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##1}%
      \fi
      \kern2pt\hrule\kern2pt
    }
  }{
    \kern2pt\hrule\relax
    \vskip\baselineskip
  }% \@fs@post for \@fs@ruled
\fi

% ==========================================
% Cross-Referencing Commands
% ==========================================

% 交叉引用
% \ref/\cref: Chinese numerals sit flush against Chinese chars — no ~ spacing needed
\iftongjithesis@chinesenumbers
  \newcommand*{\chapref}[1]{第\ref{#1}章}
  \newcommand*{\secref}[1]{第\ref{#1}节}
\else
  \newcommand*{\chapref}[1]{第~\ref{#1}~章}
  \newcommand*{\secref}[1]{第~\ref{#1}~节}
\fi
\newcommand*{\algoref}[1]{\tj@lang{算法}{Algorithm}~\ref{#1}\tj@refpeek}
\renewcommand*{\eqref}[1]{式~(\ref{#1})}
\newcommand*{\tabref}[1]{\tablename~\ref{#1}\tj@refpeek}
\newcommand*{\figref}[1]{\figurename~\ref{#1}\tj@refpeek}

% Cross-reference formats: 名字放进 #2…#3 让 nameinlink 全段可点（图/表/式 等整词都参与超链接）
\crefformat{listing}{#2代码~#1#3\tj@refnum}
\crefmultiformat{listing}{#2代码~#1#3\tj@refnum}{\tj@numsep 和#2代码~#1#3\tj@refnum}{、#2代码~#1#3\tj@refnum}{\tj@numsep 和#2代码~#1#3\tj@refnum}
\crefrangeformat{listing}{#3代码~#1#4~至#5代码~#2#6\tj@refnum}
\crefformat{lstlisting}{#2代码~#1#3\tj@refnum}
\crefmultiformat{lstlisting}{#2代码~#1#3\tj@refnum}{\tj@numsep 和#2代码~#1#3\tj@refnum}{、#2代码~#1#3\tj@refnum}{\tj@numsep 和#2代码~#1#3\tj@refnum}
\crefrangeformat{lstlisting}{#3代码~#1#4~至#5代码~#2#6\tj@refnum}
\newcommand*{\listingref}[1]{\lstlistingname~\ref{#1}\tj@refpeek}

% Configure references in Chinese
% “第X章/节” pattern: number is wrapped, needs full multi/range formats
\iftongjithesis@chinesenumbers
  \crefformat{chapter}{#2第#1章#3\tj@refnotnum}
  \crefmultiformat{chapter}{#2第#1章#3\tj@refnotnum}{和#2第#1章#3\tj@refnotnum}{、#2第#1章#3\tj@refnotnum}{和#2第#1章#3\tj@refnotnum}
  \crefrangeformat{chapter}{#3第#1章#4至#5第#2章#6\tj@refnotnum}
  \crefformat{section}{#2第#1节#3\tj@refnotnum}
  \crefmultiformat{section}{#2第#1节#3\tj@refnotnum}{和#2第#1节#3\tj@refnotnum}{、#2第#1节#3\tj@refnotnum}{和#2第#1节#3\tj@refnotnum}
  \crefrangeformat{section}{#3第#1节#4至#5第#2节#6\tj@refnotnum}
\else
  \crefformat{chapter}{#2第~#1~章#3\tj@refnotnum}
  \crefmultiformat{chapter}{#2第~#1~章#3\tj@refnotnum}{和#2第~#1~章#3\tj@refnotnum}{、#2第~#1~章#3\tj@refnotnum}{和#2第~#1~章#3\tj@refnotnum}
  \crefrangeformat{chapter}{#3第~#1~章#4至#5第~#2~章#6\tj@refnotnum}
  \crefformat{section}{#2第~#1~节#3\tj@refnotnum}
  \crefmultiformat{section}{#2第~#1~节#3\tj@refnotnum}{和#2第~#1~节#3\tj@refnotnum}{、#2第~#1~节#3\tj@refnotnum}{和#2第~#1~节#3\tj@refnotnum}
  \crefrangeformat{section}{#3第~#1~节#4至#5第~#2~节#6\tj@refnotnum}
\fi
\crefformat{subsection}{#2第~#1~小节#3\tj@refnotnum}
\crefmultiformat{subsection}{#2第~#1~小节#3\tj@refnotnum}{和#2第~#1~小节#3\tj@refnotnum}{、#2第~#1~小节#3\tj@refnotnum}{和#2第~#1~小节#3\tj@refnotnum}
\crefrangeformat{subsection}{#3第~#1~小节#4至#5第~#2~小节#6\tj@refnotnum}
% “名称~X” pattern: ~ separates CJK name from digit; whole reference wrapped in hyperlink.
% --- Common float/equation types ---
\crefformat{equation}{#2式~(#1)#3\tj@refnum}
\crefmultiformat{equation}{#2式~(#1)#3\tj@refnum}{\tj@numsep 和#2式~(#1)#3\tj@refnum}{、#2式~(#1)#3\tj@refnum}{\tj@numsep 和#2式~(#1)#3\tj@refnum}
\crefrangeformat{equation}{#3式~(#1)#4~至#5式~(#2)#6\tj@refnum}
\crefformat{figure}{#2图~#1#3\tj@refnum}
\crefmultiformat{figure}{#2图~#1#3\tj@refnum}{\tj@numsep 和#2图~#1#3\tj@refnum}{、#2图~#1#3\tj@refnum}{\tj@numsep 和#2图~#1#3\tj@refnum}
\crefrangeformat{figure}{#3图~#1#4~至#5图~#2#6\tj@refnum}
\crefformat{table}{#2表~#1#3\tj@refnum}
\crefmultiformat{table}{#2表~#1#3\tj@refnum}{\tj@numsep 和#2表~#1#3\tj@refnum}{、#2表~#1#3\tj@refnum}{\tj@numsep 和#2表~#1#3\tj@refnum}
\crefrangeformat{table}{#3表~#1#4~至#5表~#2#6\tj@refnum}
\crefformat{algorithm}{#2算法~#1#3\tj@refnum}
\crefmultiformat{algorithm}{#2算法~#1#3\tj@refnum}{\tj@numsep 和#2算法~#1#3\tj@refnum}{、#2算法~#1#3\tj@refnum}{\tj@numsep 和#2算法~#1#3\tj@refnum}
\crefrangeformat{algorithm}{#3算法~#1#4~至#5算法~#2#6\tj@refnum}
\crefformat{algocf}{#2算法~#1#3\tj@refnum}
\crefmultiformat{algocf}{#2算法~#1#3\tj@refnum}{\tj@numsep 和#2算法~#1#3\tj@refnum}{、#2算法~#1#3\tj@refnum}{\tj@numsep 和#2算法~#1#3\tj@refnum}
\crefrangeformat{algocf}{#3算法~#1#4~至#5算法~#2#6\tj@refnum}
\crefformat{FancyVerbLine}{#2第~#1~行#3\tj@refnotnum}
\crefmultiformat{FancyVerbLine}{#2第~#1~行#3\tj@refnotnum}{和#2第~#1~行#3\tj@refnotnum}{、#2第~#1~行#3\tj@refnotnum}{和#2第~#1~行#3\tj@refnotnum}
\crefrangeformat{FancyVerbLine}{#3第~#1~行#4至#5第~#2~行#6\tj@refnotnum}
% --- Theorem types (single + multi for consistency) ---
\crefformat{thm}{#2定理~#1#3\tj@refnum}
\crefmultiformat{thm}{#2定理~#1#3\tj@refnum}{\tj@numsep 和#2定理~#1#3\tj@refnum}{、#2定理~#1#3\tj@refnum}{\tj@numsep 和#2定理~#1#3\tj@refnum}
\crefformat{cor}{#2推论~#1#3\tj@refnum}
\crefmultiformat{cor}{#2推论~#1#3\tj@refnum}{\tj@numsep 和#2推论~#1#3\tj@refnum}{、#2推论~#1#3\tj@refnum}{\tj@numsep 和#2推论~#1#3\tj@refnum}
\crefformat{lem}{#2引理~#1#3\tj@refnum}
\crefmultiformat{lem}{#2引理~#1#3\tj@refnum}{\tj@numsep 和#2引理~#1#3\tj@refnum}{、#2引理~#1#3\tj@refnum}{\tj@numsep 和#2引理~#1#3\tj@refnum}
\crefformat{prop}{#2命题~#1#3\tj@refnum}
\crefmultiformat{prop}{#2命题~#1#3\tj@refnum}{\tj@numsep 和#2命题~#1#3\tj@refnum}{、#2命题~#1#3\tj@refnum}{\tj@numsep 和#2命题~#1#3\tj@refnum}
\crefformat{conj}{#2猜想~#1#3\tj@refnum}
\crefformat{assume}{#2假设~#1#3\tj@refnum}
\crefformat{dfn}{#2定义~#1#3\tj@refnum}
\crefformat{exmp}{#2例~#1#3\tj@refnum}
\crefformat{rem}{#2注~#1#3\tj@refnum}
\crefformat{pf}{#2证明~#1#3\tj@refnum}
\crefformat{proof}{#2证明~#1#3\tj@refnum}

% Configure connecting words
% 前一项以编号结尾时才在“和”前留间距（\tj@conjsep），“和”之后不留空
\newcommand{\crefpairconjunction}{\tj@conjsep 和}
\newcommand{\crefmiddleconjunction}{、}
\newcommand{\creflastconjunction}{\tj@conjsep 和}
\newcommand{\crefpairgroupconjunction}{\tj@conjsep 和}
\newcommand{\crefmiddlegroupconjunction}{、}
\newcommand{\creflastgroupconjunction}{\tj@conjsep 和}
\newcommand{\crefrangeconjunction}{ 至~}

% 超链接在编号后结束，链接结尾会打断 xeCJK 的中西文自动间距，“如图 1.1所示”缺少空格。
% 编号结尾的引用格式（图、表、式、算法、代码、定理等）之后若紧跟汉字，补上 xeCJK 的中西文间距
% \CJKecglue；紧跟标点、空格或命令时什么也不加。章、节、行以汉字结尾，不需要。
% LuaTeX 下由 luatexja 处理间距，这里不做任何事。
\ExplSyntaxOn
\bool_new:N \g__tj_ref_num_bool
\cs_new_protected:Npn \__tj_ref_cjk_space:
  {
    \sys_if_engine_xetex:T
      {
        \peek_regex:nT { [\x{3400}-\x{4DBF}\x{4E00}-\x{9FFF}\x{F900}-\x{FAFF}] }
          { \CJKecglue }
      }
  }
% 引用格式以编号结尾：记下这一点，并处理格式内部紧跟的“和”
\cs_new_protected:cpn { tj@refnum }
  { \bool_gset_true:N \g__tj_ref_num_bool \__tj_ref_cjk_space: }
% 同类多项引用中，编号与后一项的“和”之间（XeTeX）
\cs_new_protected:cpn { tj@numsep }
  { \sys_if_engine_xetex:T { \CJKecglue } }
\cs_new_protected:cpn { tj@refnotnum }
  { \bool_gset_false:N \g__tj_ref_num_bool }
% 整条引用结束后：最后一项以编号结尾时，按后面的字符补间距
\cs_new_protected:cpn { tj@refcjkspace }
  {
    \bool_if:NT \g__tj_ref_num_bool
      { \bool_gset_false:N \g__tj_ref_num_bool \__tj_ref_cjk_space: }
  }
% \figref 等不经 \cref：直接按后面的字符补间距，不动标记
\cs_new_eq:cN { tj@refpeek } \__tj_ref_cjk_space:
% 多项引用的“和”之前：前一项以编号结尾时留间距
\cs_new_protected:cpn { tj@conjsep }
  {
    \bool_if:NT \g__tj_ref_num_bool
      { \tj@numsep }
  }
% 用户自定义以编号结尾的 \crefformat 时，在 #3 之后加 \tjrefnum，在多项格式的“和”前加 \tjrefsep
\cs_new_eq:NN \tjrefnum \tj@refnum
\cs_new_eq:NN \tjrefsep \tj@numsep
\ExplSyntaxOff
\AtBeginDocument{%
  \NewCommandCopy\tj@cref@orig\cref
  \RenewDocumentCommand\cref{sm}{\tj@refnotnum\IfBooleanTF{#1}{\tj@cref@orig*{#2}}{\tj@cref@orig{#2}}\tj@refcjkspace}%
  \NewCommandCopy\tj@crefrange@orig\crefrange
  \RenewDocumentCommand\crefrange{smm}{\tj@refnotnum\IfBooleanTF{#1}{\tj@crefrange@orig*{#2}{#3}}{\tj@crefrange@orig{#2}{#3}}\tj@refcjkspace}%
}
% PDF 书签中不排版，这些钩子只留一个空格或什么也不输出
\pdfstringdefDisableCommands{%
  \def\tj@refnum{ }\def\tj@refpeek{ }\def\tjrefnum{ }\let\tjrefsep\relax%
  \let\tj@refnotnum\relax\let\tj@refcjkspace\relax\let\tj@conjsep\relax\let\tj@numsep\relax
}

% ==========================================
% Logo Commands
% ==========================================

\providecommand{\XeTeX}{\hologo{XeTeX}}
\providecommand{\BibTeX}{\hologo{BibTeX}}
\providecommand{\BibLaTeX}{\textsc{Bib}\LaTeX}
\providecommand{\LuaTeX}{\hologo{LuaTeX}}
\DeclareRobustCommand{\TongjiThesis}{%
  \texorpdfstring{%
    T{\scshape ongji}\kern.08em T{\scshape hesis}%
  }{TongjiThesis}%
}
% PDF/A（pdfa=true）的 XMP 元数据由 \text_purify:n 从题名等生成，其中的标志命令须写成纯文本，
% 否则被删去（PDF 文档属性由 hyperref 的 \texorpdfstring 处理）。
\ExplSyntaxOn
\text_declare_purify_equivalent:Nn \TongjiThesis { TongjiThesis }
\text_declare_purify_equivalent:Nn \TeX { TeX }
\text_declare_purify_equivalent:Nn \LaTeX { LaTeX }
\text_declare_purify_equivalent:Nn \XeTeX { XeTeX }
\text_declare_purify_equivalent:Nn \LuaTeX { LuaTeX }
\text_declare_purify_equivalent:Nn \BibTeX { BibTeX }
\text_declare_purify_equivalent:Nn \BibLaTeX { BibLaTeX }
\ExplSyntaxOff

% ==========================================
% Cover and User Information Commands
% ==========================================

% 设置封面信息盒子（information 环境）
\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}
\let\oldtabular\tabular
\let\endoldtabular\endtabular
\newenvironment{information}[1][h!]{
  \renewcommand{\arraystretch}{1.5}
  \setlength{\tabcolsep}{8pt}
  \tjfontcover\oldtabular[#1]
}{\renewcommand{\arraystretch}{1.2}\endoldtabular
}

\newlength{\covertextwidth}
\newlength{\covermaxwidth}
\newlength{\coverparwidth}

\newcommand{\ulinecentered}[1]{
  \bgroup
  \let\\\relax
  \setlength{\covertextwidth}{\widthof{#1}}
  \egroup
  \setlength{\covermaxwidth}{20em}
  \ifdim\covertextwidth > \covermaxwidth
    \ifdim\covertextwidth > 1.95\covermaxwidth
      \setlength{\coverparwidth}{0.53\covertextwidth}
      \pgfmathsetmacro{\coverscale}{\covermaxwidth / \coverparwidth}
      \uline{%
        \scalebox{\coverscale}[1]{%
          \parbox[b]{\coverparwidth}{%
            \centering
            \renewcommand{\baselinestretch}{\tjcoverlinestretch}\selectfont
            #1%
          }%
        }%
      }
    \else
      \uline{%
        \parbox[b]{\covermaxwidth}{%
          \centering
          \renewcommand{\baselinestretch}{\tjcoverlinestretch}\selectfont
          #1%
        }%
      }
    \fi
  \else
    \uline{%
      \makebox[\covermaxwidth][c]{%
        \parbox[b]{\covermaxwidth}{%
          \centering
          \renewcommand{\baselinestretch}{\tjcoverlinestretch}\selectfont
          #1%
        }%
      }%
    }
  \fi
}

\def\tj@titlecnbreak@opt[#1]{\unskip\ignorespaces}
\def\tj@titlecnbreak@star*{%
  \@ifnextchar[{\tj@titlecnbreak@opt}{\unskip\ignorespaces}%
}
\newcommand{\tjtitlecninlinebreak}{%
  \unskip
  \@ifnextchar*{\tj@titlecnbreak@star}{%
    \@ifnextchar[{\tj@titlecnbreak@opt}{\ignorespaces}%
  }%
}
\newcommand{\tjtitlecninline}[1]{%
  \begingroup
    \let\\\tjtitlecninlinebreak
    #1%
  \endgroup
}
\def\tj@titleenbreak@opt[#1]{\unskip\space\ignorespaces}
\def\tj@titleenbreak@star*{%
  \@ifnextchar[{\tj@titleenbreak@opt}{\unskip\space\ignorespaces}%
}
\newcommand{\tjtitleeninlinebreak}{%
  \unskip
  \@ifnextchar*{\tj@titleenbreak@star}{%
    \@ifnextchar[{\tj@titleenbreak@opt}{\space\ignorespaces}%
  }%
}
\newcommand{\tjtitleeninline}[1]{%
  \begingroup
    \let\\\tjtitleeninlinebreak
    #1%
  \endgroup
}

\newcommand{\tj@abstractblock}[2]{%
  \par\nointerlineskip
  \begingroup
    \setbox\@tempboxa\vbox{%
      \hsize=\linewidth
      \parindent=0pt
      \parbox[t]{\linewidth}{%
        \centering
        #1%
        \strut #2\strut\par
      }%
    }%
    \box\@tempboxa
  \endgroup
  \par\nointerlineskip
}

% 盲审：\tjblind{<正式版内容>}{<盲审版内容>}。正式版输出第一个参数，blind=true 时输出第二个参数，
% 用于封面上的学生姓名、学号与指导教师（盲审版留空），也供用户隐去谢辞、项目名称、本人成果等。
\NewDocumentCommand{\tjblind}{+m +m}{%
  \iftongjithesis@blind\expandafter\@secondoftwo\else\expandafter\@firstoftwo\fi{#1}{#2}%
}

% ------------------------------------------
% \tjsetup{<键> = <值>, ...}：论文信息
% ------------------------------------------
% 封面、信息说明页、摘要页与 3 份表格所需的信息都由 \tjsetup 设置，各键的说明见
% chapters/01_guide.tex。可在导言区或正文中多次调用，后设的值覆盖先设的值；值中有
% 西文逗号或等号时用花括号括起；键与键之间可以空行（含多段的值须括起）。值存入
% \tongji<字段> 宏（tongjithesis.cfg 中可预设），封面等页面读取这些宏。
% 写错的键报错并给出最接近的键；取值有限的键写错值时报错并列出可用值。
\ExplSyntaxOn
\msg_new:nnnn { tongjithesis } { setup-value }
  {
    Unknown~value~'#2'~for~\iow_char:N \\tjsetup~key~'#1'.~Valid~values:~#3.
  }
  { Change~'#1~=~#2'~to~one~of~the~values~above. }
\msg_new:nnnn { tongjithesis } { setup-unknown-key }
  {
    Unknown~\iow_char:N \\tjsetup~key~'#1'.~
    \tl_if_empty:nTF {#2}
      { Valid~keys:~\clist_use:Nn \c__tongjithesis_setup_keys_clist { ,~ } . }
      { Did~you~mean~'#2'? }
  }
  { Chapter~1~of~the~sample~thesis~(texdoc~tongjithesis)~describes~each~key. }
\msg_new:nnnn { tongjithesis } { setup-class-option }
  { '#1'~is~a~class~option,~not~a~\iow_char:N \\tjsetup~key. }
  { Set~it~in~\iow_char:N \\documentclass[#1~=~...]{tongjithesis}~instead. }
\msg_new:nnnn { tongjithesis } { setup-date }
  {
    \iow_char:N \\tjsetup~key~'#1'~needs~a~date~written~as~YYYY-MM-DD,~
    such~as~#1~=~2027-06-01;~got~'#2'.
  }
  {
    Write~the~year,~month~and~day~as~numbers~joined~by~hyphens.~
    For~the~current~date~write~#1~=~\iow_char:N \\the\iow_char:N \\year-
    \iow_char:N \\the\iow_char:N \\month-\iow_char:N \\the\iow_char:N \\day.
  }
\msg_new:nnnn { tongjithesis } { setup-date-invalid }
  { \iow_char:N \\tjsetup~key~'#1'~got~'#2',~which~is~not~a~calendar~date. }
  {
    The~year~starts~at~1,~the~month~runs~from~1~to~12~and~the~day~stays~
    within~the~month~(February~has~29~days~only~in~a~leap~year).
  }
\msg_new:nnn { tongjithesis } { deprecated-command }
  {
    \iow_char:N \\#1~is~deprecated;~use~
    \iow_char:N \\tjsetup \iow_char:N \{ #2 \iow_char:N \} ~instead~
    (\msg_line_context:).
  }

\clist_const:Nn \c__tongjithesis_setup_keys_clist
  {
    school, major, student-id, author, title, subtitle, title-en, subtitle-en,
    advisor, date, abstract-title, abstract-subtitle, abstract-title-en,
    abstract-subtitle-en, info-type, info-abstract, info-drawings, info-words,
    info-materials, start-date, end-date, midterm-decision, degree-type,
    school-en, author-en, advisor-en, co-advisor, co-advisor-en, category,
    category-en, discipline, discipline-en, subdiscipline, subdiscipline-en,
    research-direction, research-direction-en, joint-unit, joint-unit-en,
    funding, funding-en, secret-level, secret-years, logo, declarations-file,
    declarations
  }
\clist_const:Nn \c__tongjithesis_info_type_clist { thesis, design, engineering }
\clist_const:Nn \c__tongjithesis_degree_type_clist
  { academic, professional, equivalent-academic, equivalent-professional }
\clist_const:Nn \c__tongjithesis_secret_level_clist { none, secret, confidential }
\clist_const:Nn \c__tongjithesis_declarations_clist { keep, omit }
\clist_const:Nn \c__tongjithesis_midterm_decision_clist { none, agree, disagree }

\tl_new:N \l__tongjithesis_setup_tl
\tl_new:N \l__tongjithesis_date_tl
\seq_new:N \l__tongjithesis_date_seq
\tl_new:N \l__tongjithesis_pdf_tl
% 本次 \tjsetup 设置了任务书起讫日期：结束后重算周数。
\bool_new:N \g__tongjithesis_period_bool

\cs_generate_variant:Nn \regex_extract_once:nnNTF { nV }
\cs_generate_variant:Nn \keys_if_exist:nnTF { nV }
\cs_generate_variant:Nn \msg_error:nnnn { nnee }

% \__tongjithesis_date_if_valid:nnnTF {<年>} {<月>} {<日>}：年不小于 1，月在 1–12 之间，
% 日不超过该月的天数（闰年：能被 4 整除而不能被 100 整除，或能被 400 整除）。
\prg_new_conditional:Npnn \__tongjithesis_date_if_valid:nnn #1#2#3 { TF }
  {
    \bool_lazy_all:nTF
      {
        { \int_compare_p:nNn {#1} > { 0 } }
        { \int_compare_p:nNn {#2} > { 0 } }
        { \int_compare_p:nNn {#2} < { 13 } }
        { \int_compare_p:nNn {#3} > { 0 } }
        { \int_compare_p:nNn {#3} < { \__tongjithesis_month_days:nn {#1} {#2} + 1 } }
      }
      { \prg_return_true: }
      { \prg_return_false: }
  }
\prg_generate_conditional_variant:Nnn \__tongjithesis_date_if_valid:nnn { eee } { TF }
\cs_new:Npn \__tongjithesis_month_days:nn #1#2
  {
    \int_case:nnF {#2}
      {
        { 2 }
          {
            \bool_lazy_or:nnTF
              { \int_compare_p:nNn { \int_mod:nn {#1} { 400 } } = { 0 } }
              {
                \bool_lazy_and_p:nn
                  { \int_compare_p:nNn { \int_mod:nn {#1} { 4 } } = { 0 } }
                  { ! \int_compare_p:nNn { \int_mod:nn {#1} { 100 } } = { 0 } }
              }
              { 29 } { 28 }
          }
        { 4 } { 30 }
        { 6 } { 30 }
        { 9 } { 30 }
        { 11 } { 30 }
      }
      { 31 }
  }
% \__tongjithesis_date_gset:nnNNN {<键>} {<值>} <年> <月> <日>：<值> 先展开
% （以便写 \the\year-\the\month-\the\day；受保护的命令原样保留），再按 YYYY-MM-DD
% 拆为不带前导零的数字；空值清空三项。
\cs_new_protected:Npn \__tongjithesis_date_gset:nnNNN #1#2#3#4#5
  {
    \protected@edef \l__tongjithesis_date_tl {#2}
    \tl_if_blank:VTF \l__tongjithesis_date_tl
      { \tl_gclear:N #3 \tl_gclear:N #4 \tl_gclear:N #5 }
      {
        \regex_extract_once:nVNTF
          { \A \s* (\d{4}) - (\d{1,2}) - (\d{1,2}) \s* \Z }
          \l__tongjithesis_date_tl \l__tongjithesis_date_seq
          {
            \__tongjithesis_date_if_valid:eeeTF
              { \seq_item:Nn \l__tongjithesis_date_seq { 2 } }
              { \seq_item:Nn \l__tongjithesis_date_seq { 3 } }
              { \seq_item:Nn \l__tongjithesis_date_seq { 4 } }
              {
                \tl_gset:Ne #3 { \int_eval:n { \seq_item:Nn \l__tongjithesis_date_seq { 2 } } }
                \tl_gset:Ne #4 { \int_eval:n { \seq_item:Nn \l__tongjithesis_date_seq { 3 } } }
                \tl_gset:Ne #5 { \int_eval:n { \seq_item:Nn \l__tongjithesis_date_seq { 4 } } }
              }
              {
                \msg_error:nnne { tongjithesis } { setup-date-invalid } {#1}
                  { \exp_not:V \l__tongjithesis_date_tl }
              }
          }
          {
            \msg_error:nnne { tongjithesis } { setup-date } {#1}
              { \exp_not:V \l__tongjithesis_date_tl }
          }
      }
  }

% PDF 标题取中文题名：为封面换行写的 \\、\\* 与 \\[<间距>] 以及段落（\par、空行）
% 都改为一个空格，再交给 hyperref；题名中常用的本类命令在 PDF 字符串中写作纯文本
% （见 hyperref 之后的 \pdfstringdefDisableCommands）。
\cs_new_protected:Npn \__tongjithesis_pdf_title:n #1
  {
    \tl_set:Nn \l__tongjithesis_pdf_tl {#1}
    \regex_replace_all:nnN { \c{\\} \*? (?: \[ [^\]]* \] )? | \c{par} } { \x20 }
      \l__tongjithesis_pdf_tl
    \regex_replace_all:nnN { \s+ } { \x20 } \l__tongjithesis_pdf_tl
    \regex_replace_all:nnN { \A \s | \s \Z } { } \l__tongjithesis_pdf_tl
    \exp_args:Ne \hypersetup
      { pdftitle = { \exp_not:V \l__tongjithesis_pdf_tl } }
  }

% \__tongjithesis_setup_choice:nNn {<键>} {<可选值>} {<代码>}：取值有限的键，
% <代码> 中 \l_keys_choice_tl 为选中的值。
\cs_new_protected:Npn \__tongjithesis_setup_choice:nNn #1#2#3
  {
    \keys_define:nn { tongjithesis / setup }
      {
        #1 .choices:Vn = #2 {#3} ,
        #1 .value_required:n = true ,
        #1 / unknown .code:n =
          \msg_error:nnnne { tongjithesis } { setup-value } {#1} {##1}
            { \clist_use:Nn #2 { ,~ } } ,
      }
  }

\keys_define:nn { tongjithesis / setup }
  {
    school               .tl_gset:N = \tongjischool ,
    major                .tl_gset:N = \tongjimajor ,
    student-id           .tl_gset:N = \tongjiauthornumber ,
    % 作者同时写入 PDF 文档属性；盲审版本不写。
    author               .code:n    =
      {
        \tl_gset:Nn \tongjiauthor {#1}
        \iftongjithesis@blind \else \hypersetup { pdfauthor = {#1} } \fi
      } ,
    title                .code:n    =
      {
        \tl_gset:Nn \tongjithesistitle {#1}
        \__tongjithesis_pdf_title:n {#1}
      } ,
    subtitle             .tl_gset:N = \tongjithesissubtitle ,
    title-en             .tl_gset:N = \tongjithesistitleeng ,
    subtitle-en          .tl_gset:N = \tongjithesissubtitleeng ,
    advisor              .tl_gset:N = \tongjithesisadvisor ,
    date                 .code:n    =
      {
        \__tongjithesis_date_gset:nnNNN { date } {#1}
          \tongjithesisyear \tongjithesismonth \tongjithesisday
      } ,
    abstract-title       .tl_gset:N = \tongjiabstracttitle ,
    abstract-subtitle    .tl_gset:N = \tongjiabstractsubtitle ,
    abstract-title-en    .tl_gset:N = \tongjiabstracttitleeng ,
    abstract-subtitle-en .tl_gset:N = \tongjiabstractsubtitleeng ,
    info-abstract        .tl_gset:N = \tongjiinfoabstract ,
    info-drawings        .tl_gset:N = \tongjiinfodrawings ,
    % 正文总字数：毕业设计与毕业论文两行都读这一个值（\infowordcount 与
    % \infothesiswords 两个旧命令仍分别写入各自的一行）。
    info-words           .code:n    =
      {
        \tl_gset:Nn \tongjiinfowordcount {#1}
        \tl_gset:Nn \tongjiinfothesiswords {#1}
      } ,
    info-materials       .tl_gset:N = \tongjiinfomaterials ,
    start-date           .code:n    =
      {
        \__tongjithesis_date_gset:nnNNN { start-date } {#1}
          \tongjitaskbookstartyear \tongjitaskbookstartmonth \tongjitaskbookstartday
        \bool_gset_true:N \g__tongjithesis_period_bool
      } ,
    end-date             .code:n    =
      {
        \__tongjithesis_date_gset:nnNNN { end-date } {#1}
          \tongjitaskbookendyear \tongjitaskbookendmonth \tongjitaskbookendday
        \bool_gset_true:N \g__tongjithesis_period_bool
      } ,
    % 研究生学位论文的中英文封面（degree=master|doctor；本科不读取这些键）
    school-en            .tl_gset:N = \tongjischooleng ,
    author-en            .tl_gset:N = \tongjiauthoreng ,
    advisor-en           .tl_gset:N = \tongjithesisadvisoreng ,
    co-advisor           .tl_gset:N = \tongjicoadvisor ,
    co-advisor-en        .tl_gset:N = \tongjicoadvisoreng ,
    category             .tl_gset:N = \tongjicategory ,
    category-en          .tl_gset:N = \tongjicategoryeng ,
    discipline           .tl_gset:N = \tongjidiscipline ,
    discipline-en        .tl_gset:N = \tongjidisciplineeng ,
    subdiscipline        .tl_gset:N = \tongjisubdiscipline ,
    subdiscipline-en     .tl_gset:N = \tongjisubdisciplineeng ,
    research-direction   .tl_gset:N = \tongjiresearchdirection ,
    research-direction-en .tl_gset:N = \tongjiresearchdirectioneng ,
    joint-unit           .tl_gset:N = \tongjijointunit ,
    joint-unit-en        .tl_gset:N = \tongjijointuniteng ,
    funding              .tl_gset:N = \tongjifunding ,
    funding-en           .tl_gset:N = \tongjifundingeng ,
    % 封面校标的图片文件（含校徽的 2.6cm×10cm 正式校标），不设置时用校名字样。
    logo                 .tl_gset:N = \tongjilogo ,
    secret-years         .tl_gset:N = \tongjisecretyears ,
    % 研究生学位论文的原创性声明与版权使用授权书：签名后扫描的 PDF，\MakeDeclarations 插入
    % 它的全部页面代替生成的一页（盲审版本不用）。
    declarations-file    .tl_gset:N = \tongjideclarationsfile ,
    unknown              .code:n    = \__tongjithesis_setup_unknown: ,
  }
% 成果类型：thesis（毕业论文）、design（毕业设计）、engineering（工程设计类毕业设计，
% 摘要页标题为“设计总说明”）。
\__tongjithesis_setup_choice:nNn { info-type } \c__tongjithesis_info_type_clist
  { \tl_gset_eq:NN \tongjiinfotype \l_keys_choice_tl }
% 中期报告“专业审核意见”复选框：none（默认，两格留空，打印后手写）、agree、disagree。
\__tongjithesis_setup_choice:nNn { midterm-decision }
  \c__tongjithesis_midterm_decision_clist
  {
    \str_if_eq:VnTF \l_keys_choice_tl { none }
      { \tl_gclear:N \tongjimidtermdecision }
      { \tl_gset_eq:NN \tongjimidtermdecision \l_keys_choice_tl }
  }
% 学位类型（研究生）：academic（学术学位，默认）、professional（专业学位）、
% equivalent-academic（同等学力学术型）或 equivalent-professional（同等学力专业型），决定封面
% 学位类型一行与学科栏目的名称。
\__tongjithesis_setup_choice:nNn { degree-type } \c__tongjithesis_degree_type_clist
  { \tl_gset_eq:NN \tongjidegreetype \l_keys_choice_tl }
% 密级（研究生涉密学位论文）：none（默认，不标注）、secret（秘密）或 confidential（机密），
% 与 secret-years 一起标在封面左上角，如“秘密★2年”。
\__tongjithesis_setup_choice:nNn { secret-level } \c__tongjithesis_secret_level_clist
  {
    \str_if_eq:VnTF \l_keys_choice_tl { none }
      { \tl_gclear:N \tongjisecretlevel }
      { \tl_gset_eq:NN \tongjisecretlevel \l_keys_choice_tl }
  }
% 研究生学位论文盲审版本的原创性声明与版权使用授权书：keep（默认，排出未签名的一页）或
% omit（不排）。
\__tongjithesis_setup_choice:nNn { declarations } \c__tongjithesis_declarations_clist
  { \tl_gset_eq:NN \tongjideclarations \l_keys_choice_tl }
% 未设置的字段为空。
\clist_map_inline:nn
  {
    \tongjiauthor, \tongjithesistitle, \tongjithesisyear, \tongjithesismonth,
    \tongjithesisday, \tongjiinfotype, \tongjiinfowordcount, \tongjiinfothesiswords,
    \tongjitaskbookstartyear, \tongjitaskbookstartmonth, \tongjitaskbookstartday,
    \tongjitaskbookendyear, \tongjitaskbookendmonth, \tongjitaskbookendday,
    \tongjitaskbookweeks, \tongjimidtermdecision, \tongjisecretlevel
  }
  { \tl_if_exist:NF #1 { \tl_new:N #1 } }
\tl_new:N \tongjidegreetype
\tl_gset:Nn \tongjidegreetype { academic }
\tl_new:N \tongjideclarations
\tl_gset:Nn \tongjideclarations { keep }

% 未知的键：类选项提示写到 \documentclass；否则给出编辑距离最近的键（相差不超过
% 键长的三分之一，至少 1）。
\int_new:N \l__tongjithesis_distance_int
\int_new:N \l__tongjithesis_best_int
\tl_new:N \l__tongjithesis_nearest_tl
\str_new:N \l__tongjithesis_distance_a_str
\str_new:N \l__tongjithesis_distance_b_str
\intarray_new:Nn \g__tongjithesis_distance_back_intarray { 65 }
\intarray_new:Nn \g__tongjithesis_distance_prev_intarray { 65 }
\intarray_new:Nn \g__tongjithesis_distance_cur_intarray { 65 }
% \__tongjithesis_distance:nn {<a>} {<b>}：两串（各取前 64 个字符）的编辑距离
% （插入、删除、替换与相邻交换各计 1），存入 \l__tongjithesis_distance_int。
\cs_new_protected:Npn \__tongjithesis_distance:nn #1#2
  {
    \str_set:Ne \l__tongjithesis_distance_a_str { \str_range:nnn {#1} { 1 } { 64 } }
    \str_set:Ne \l__tongjithesis_distance_b_str { \str_range:nnn {#2} { 1 } { 64 } }
    \int_step_inline:nnn { 0 } { \str_count:N \l__tongjithesis_distance_b_str }
      { \intarray_gset:Nnn \g__tongjithesis_distance_prev_intarray { ##1 + 1 } {##1} }
    \int_step_inline:nn { \str_count:N \l__tongjithesis_distance_a_str }
      {
        \intarray_gset:Nnn \g__tongjithesis_distance_cur_intarray { 1 } {##1}
        \int_step_inline:nn { \str_count:N \l__tongjithesis_distance_b_str }
          {
            \intarray_gset:Nnn \g__tongjithesis_distance_cur_intarray { ####1 + 1 }
              {
                \int_min:nn
                  {
                    \int_min:nn
                      { \intarray_item:Nn \g__tongjithesis_distance_prev_intarray { ####1 + 1 } + 1 }
                      { \intarray_item:Nn \g__tongjithesis_distance_cur_intarray { ####1 } + 1 }
                  }
                  {
                    \intarray_item:Nn \g__tongjithesis_distance_prev_intarray { ####1 }
                    + \str_if_eq:eeTF
                        { \str_item:Nn \l__tongjithesis_distance_a_str {##1} }
                        { \str_item:Nn \l__tongjithesis_distance_b_str {####1} }
                        { 0 } { 1 }
                  }
              }
            \bool_lazy_all:nT
              {
                { \int_compare_p:nNn {##1} > { 1 } }
                { \int_compare_p:nNn {####1} > { 1 } }
                {
                  \str_if_eq_p:ee
                    { \str_item:Nn \l__tongjithesis_distance_a_str {##1} }
                    { \str_item:Nn \l__tongjithesis_distance_b_str { ####1 - 1 } }
                }
                {
                  \str_if_eq_p:ee
                    { \str_item:Nn \l__tongjithesis_distance_a_str { ##1 - 1 } }
                    { \str_item:Nn \l__tongjithesis_distance_b_str {####1} }
                }
              }
              {
                \intarray_gset:Nnn \g__tongjithesis_distance_cur_intarray { ####1 + 1 }
                  {
                    \int_min:nn
                      { \intarray_item:Nn \g__tongjithesis_distance_cur_intarray { ####1 + 1 } }
                      { \intarray_item:Nn \g__tongjithesis_distance_back_intarray { ####1 - 1 } + 1 }
                  }
              }
          }
        \int_step_inline:nn { \str_count:N \l__tongjithesis_distance_b_str + 1 }
          {
            \intarray_gset:Nnn \g__tongjithesis_distance_back_intarray {####1}
              { \intarray_item:Nn \g__tongjithesis_distance_prev_intarray {####1} }
            \intarray_gset:Nnn \g__tongjithesis_distance_prev_intarray {####1}
              { \intarray_item:Nn \g__tongjithesis_distance_cur_intarray {####1} }
          }
      }
    \int_set:Nn \l__tongjithesis_distance_int
      {
        \intarray_item:Nn \g__tongjithesis_distance_prev_intarray
          { \str_count:N \l__tongjithesis_distance_b_str + 1 }
      }
  }
\cs_generate_variant:Nn \__tongjithesis_distance:nn { V }
\cs_new_protected:Npn \__tongjithesis_setup_unknown:
  {
    \keys_if_exist:nVTF { tongjithesis / option } \l_keys_key_str
      { \msg_error:nne { tongjithesis } { setup-class-option } { \l_keys_key_str } }
      {
        \tl_clear:N \l__tongjithesis_nearest_tl
        \int_set:Nn \l__tongjithesis_best_int
          { \int_max:nn { 1 } { \int_div_truncate:nn { \str_count:N \l_keys_key_str } { 3 } } + 1 }
        \clist_map_inline:Nn \c__tongjithesis_setup_keys_clist
          {
            \__tongjithesis_distance:Vn \l_keys_key_str {##1}
            \int_compare:nNnT \l__tongjithesis_distance_int < \l__tongjithesis_best_int
              {
                \int_set_eq:NN \l__tongjithesis_best_int \l__tongjithesis_distance_int
                \tl_set:Nn \l__tongjithesis_nearest_tl {##1}
              }
          }
        \msg_error:nnee { tongjithesis } { setup-unknown-key }
          { \l_keys_key_str } { \exp_not:V \l__tongjithesis_nearest_tl }
      }
  }

\NewDocumentCommand \tjsetup { +m }
  {
    % 键与键之间的空行（顶层的 \par）去掉，花括号内的段落不受影响。
    \tl_set:Nn \l__tongjithesis_setup_tl {#1}
    \tl_remove_all:Nn \l__tongjithesis_setup_tl { \par }
    \bool_gset_false:N \g__tongjithesis_period_bool
    \keys_set:nV { tongjithesis / setup } \l__tongjithesis_setup_tl
    \bool_if:NT \g__tongjithesis_period_bool { \tj@taskbookweeks }
  }

% 旧的信息命令（v1.6.0 及之前）仍然有效，各在首次使用时警告一次，提示改用的键。
\cs_new_protected:Npn \__tongjithesis_deprecated:nn #1#2
  {
    \bool_if_exist:cF { g__tongjithesis_deprecated_#1_bool }
      {
        \bool_new:c { g__tongjithesis_deprecated_#1_bool }
        \msg_warning:nnnn { tongjithesis } { deprecated-command } {#1} {#2}
      }
  }
\NewDocumentCommand \school { m }
  {
    \__tongjithesis_deprecated:nn { school } { school~=~... }
    \tjsetup { school = {#1} }
  }
\NewDocumentCommand \major { m }
  {
    \__tongjithesis_deprecated:nn { major } { major~=~... }
    \tjsetup { major = {#1} }
  }
\NewDocumentCommand \student { m m }
  {
    \__tongjithesis_deprecated:nn { student } { student-id~=~...,~author~=~... }
    \tjsetup { student-id = {#1}, author = {#2} }
  }
\NewDocumentCommand \thesistitle { m m }
  {
    \__tongjithesis_deprecated:nn { thesistitle } { title~=~...,~subtitle~=~... }
    \tjsetup { title = {#1}, subtitle = {#2} }
  }
\NewDocumentCommand \thesistitleeng { m m }
  {
    \__tongjithesis_deprecated:nn { thesistitleeng } { title-en~=~...,~subtitle-en~=~... }
    \tjsetup { title-en = {#1}, subtitle-en = {#2} }
  }
\NewDocumentCommand \abstracttitle { m m }
  {
    \__tongjithesis_deprecated:nn { abstracttitle }
      { abstract-title~=~...,~abstract-subtitle~=~... }
    \tjsetup { abstract-title = {#1}, abstract-subtitle = {#2} }
  }
\NewDocumentCommand \abstracttitleeng { m m }
  {
    \__tongjithesis_deprecated:nn { abstracttitleeng }
      { abstract-title-en~=~...,~abstract-subtitle-en~=~... }
    \tjsetup { abstract-title-en = {#1}, abstract-subtitle-en = {#2} }
  }
\NewDocumentCommand \thesisadvisor { m }
  {
    \__tongjithesis_deprecated:nn { thesisadvisor } { advisor~=~... }
    \tjsetup { advisor = {#1} }
  }
% 旧命令的年、月、日原样保存（不要求数字），与 v1.6.0 的输出一致。
\NewDocumentCommand \thesisdate { m m m }
  {
    \__tongjithesis_deprecated:nn { thesisdate } { date~=~YYYY-MM-DD }
    \tl_gset:Nn \tongjithesisyear {#1}
    \tl_gset:Nn \tongjithesismonth {#2}
    \tl_gset:Nn \tongjithesisday {#3}
  }
\NewDocumentCommand \infotype { m }
  {
    \__tongjithesis_deprecated:nn { infotype } { info-type~=~... }
    \tl_if_blank:nTF {#1}
      { \tl_gclear:N \tongjiinfotype }
      { \tjsetup { info-type = {#1} } }
  }
\NewDocumentCommand \infoabstract { +m }
  {
    \__tongjithesis_deprecated:nn { infoabstract } { info-abstract~=~... }
    \tl_gset:Nn \tongjiinfoabstract {#1}
  }
\NewDocumentCommand \infodrawings { m }
  {
    \__tongjithesis_deprecated:nn { infodrawings } { info-drawings~=~... }
    \tjsetup { info-drawings = {#1} }
  }
\NewDocumentCommand \infowordcount { m }
  {
    \__tongjithesis_deprecated:nn { infowordcount } { info-words~=~... }
    \tl_gset:Nn \tongjiinfowordcount {#1}
  }
\NewDocumentCommand \infothesiswords { m }
  {
    \__tongjithesis_deprecated:nn { infothesiswords } { info-words~=~... }
    \tl_gset:Nn \tongjiinfothesiswords {#1}
  }
\NewDocumentCommand \infomaterials { +m }
  {
    \__tongjithesis_deprecated:nn { infomaterials } { info-materials~=~... }
    \tl_gset:Nn \tongjiinfomaterials {#1}
  }
\NewDocumentCommand \taskbookperiod { m m m m m m }
  {
    \__tongjithesis_deprecated:nn { taskbookperiod }
      { start-date~=~YYYY-MM-DD,~end-date~=~YYYY-MM-DD }
    \tl_gset:Nn \tongjitaskbookstartyear {#1}
    \tl_gset:Nn \tongjitaskbookstartmonth {#2}
    \tl_gset:Nn \tongjitaskbookstartday {#3}
    \tl_gset:Nn \tongjitaskbookendyear {#4}
    \tl_gset:Nn \tongjitaskbookendmonth {#5}
    \tl_gset:Nn \tongjitaskbookendday {#6}
    \tj@taskbookweeks
  }
\NewDocumentCommand \midtermdecision { m }
  {
    \__tongjithesis_deprecated:nn { midtermdecision } { midterm-decision~=~... }
    \tl_if_blank:nTF {#1}
      { \tjsetup { midterm-decision = none } }
      { \tjsetup { midterm-decision = {#1} } }
  }
\ExplSyntaxOff

% 设置封面
\newcommand{\MakeCover}{
  \begin{titlepage}
    \begin{center}
      \global\tjbindinglinefalse
      \pagestyle{empty}% 防止多页封面在第二页出现页码（titlepage 只 \thispagestyle empty）
      \vfill

      \includegraphics[height=2.5cm,alt={同济大学校名题字}]{figures/tongji.pdf}\\

      \tjfonttitle\MakeUppercase{\textbf{\tongjiuniversityeng}}\\
      % \vskip 20pt

      % 封面大标题：初号黑体（官方规范，理工/文科不同）
      \zihao{-0}\heiti{\tjcovertext}\\
      \vspace{60pt}

      \begin{information}{M{5em}M{22em}}
        \tjfonttitle\heiti{课题名称} & \ulinecentered{\tjfonttitle\heiti{\tongjithesistitle}} \\
        \tjfonttitle\heiti{副\enskip{}标\enskip{}题} & \ulinecentered{\tjfonttitle\heiti{\tongjithesissubtitle}} \\
        \tjfonttitle\heiti{学\quad{}\quad{}院} & \ulinecentered{\tjfonttitle\heiti{\tongjischool}} \\
        \tjfonttitle\heiti{专\quad{}\quad{}业} & \ulinecentered{\tjfonttitle\heiti{\tongjimajor}} \\
        \tjfonttitle\heiti{学生姓名} & \ulinecentered{\tjfonttitle\heiti{\tjblind{\tongjiauthor}{}}} \\
        \tjfonttitle\heiti{学\quad{}\quad{}号} & \ulinecentered{\tjfonttitle\heiti{\tjblind{\tongjiauthornumber}{}}} \\
        \tjfonttitle\heiti{指导教师} & \ulinecentered{\tjfonttitle\heiti{\tjblind{\tongjithesisadvisor}{}}} \\
        \tjfonttitle\heiti{日\quad{}\quad{}期} & \ulinecentered{\tjfonttitle\heiti{\tongjithesisyear{}年\tongjithesismonth{}月\tongjithesisday{}日}} \\
      \end{information}

      \vfill
    \end{center}
  \end{titlepage}
  \global\tjbindinglinetrue
}

% 设置信息说明页
\newsavebox{\tj@titlebox}
\newlength{\tj@titledp}
\newcommand{\infoline}[2]{%
  \noindent #1：#2\par\vspace{0.5em}
}

% 复选框渲染：\tjchecked/\tjunchecked 是勾选/未勾选的字形本身；\tjcheckbox
% 是信息说明页“成果类型”专用的判断逻辑（含 design/engineering 二选一映射，
% 不通用）；\tjcheckboxeq{当前值}{目标值} 是通用版本——当前值等于目标值时
% 打勾，否则留空，供 \midtermdecision 等其他“多选一”复选框场景复用。
% 方框尺寸：复选框的 □ 应与正文汉字等宽等高，而 amssymb 的 $\square$
% 明显小于周围汉字，故按当前字号缩放到 \tj@checkboxsize（相对 em，随字号自适应）
% 并整体下沉 0.1em，使方框与汉字视觉等高、基线一致。不直接使用 U+25A1 全角字符，
% 是因为该字形在 windows/founder/adobe/mac/fandol/texlive 各 fontset 下的覆盖与宽度并不一致。
% 勾号与方框分别装入等宽盒子后用 \llap 叠印，使勾号居中于方框（而非左对齐）；
% 下沉量作用于整组而非仅方框，否则方框下沉而勾号不动，勾号尖端会越出方框上边框。
% 勾号另按 \tj@checkmarksize（小于方框边长）限高，确保落在方框内部。pdfa=true 时勾号改取
% AMS 的 msam 字体（amssymb 的 \checkmark，字形相近但不同）：newtx 的 \checkmark 在 TFM 中
% 宽 774、在字体程序中宽 744，LuaLaTeX 把 TFM 宽度写入 PDF，违反 PDF/A 的 ISO 19005-2
% 6.2.11.5（字形宽度须一致）。不用 pdfa 时仍用 newtx 的勾号，输出不变。
% \mbox 包裹：\llap/\rlap 若为段首第一个盒子会触发 TeX 的伪断行（勾号脱落、方框变空），
% 故用 \mbox 强制水平模式，使复选框在段首（如中期报告审核意见框）也能正确渲染。
\newcommand{\tj@checkboxsize}{0.95em}
\newcommand{\tj@checkmarksize}{0.62em}
\newcommand{\tj@checkboxglyph}[1]{%
  \mbox{\raisebox{-0.1em}{%
    \makebox[\tj@checkboxsize][c]{\resizebox{\tj@checkboxsize}{!}{$\square$}}%
    \llap{\makebox[\tj@checkboxsize][c]{#1}}%
  }}%
}
\iftongjithesis@pdfa
  \newcommand{\tj@checkmark}{\usefont{U}{msa}{m}{n}\char"58}
\else
  \newcommand{\tj@checkmark}{$\checkmark$}
\fi
\newcommand{\tjchecked}{\tj@checkboxglyph{\resizebox{!}{\tj@checkmarksize}{\tj@checkmark}}}
\newcommand{\tjunchecked}{\tj@checkboxglyph{}}
\newcommand{\tjcheckbox}[1]{%
  \ifthenelse{\equal{\tongjiinfotype}{#1}\OR
              \(\equal{#1}{design}\AND\equal{\tongjiinfotype}{engineering}\)}%
    {\tjchecked}{\tjunchecked}%
}
\newcommand{\tjcheckboxeq}[2]{%
  \ifthenelse{\equal{#1}{#2}}{\tjchecked}{\tjunchecked}%
}
\newcommand{\ulinebox}[2][c]{%
  \uline{\makebox[#2][#1]{\phantom{X}}}%
}

\newcommand{\MakeInfoPage}{%
  \begin{titlepage}
    \global\tjbindinglinefalse
    \pagestyle{empty}% 防止信息页溢出到第二页时出现页码（titlepage 只 \thispagestyle empty）

    \begin{center}
      \tjfontinfotitle\heiti 同济大学本科\tjheadertext 信息说明页
    \end{center}

    \vspace{1em}

    {\tjfontheading\songti\linespread{\tjinfofieldspread}\selectfont  % 四号宋体，行距 28 磅
    \setlength{\parindent}{0pt}

    \savebox{\tj@titlebox}{\parbox[t]{\dimexpr\linewidth-5em\relax}{%
      \tjtitlecninline{\tongjithesistitle}%
      \ifx\tongjithesissubtitle\empty\else——\tjtitlecninline{\tongjithesissubtitle}\fi
    }}%
    \infoline{课题名称}{\usebox{\tj@titlebox}}%
    \settodepth{\tj@titledp}{\usebox{\tj@titlebox}}%
    \addtolength{\tj@titledp}{-\dp\strutbox}%
    \ifdim\tj@titledp>0pt\vspace{\tjinfotitlevspace}\fi

    \infoline{成果类型}{\tjcheckbox{design}\,毕业设计\quad \tjcheckbox{thesis}\,毕业论文}%

    \infoline{学科专业}{\tongjimajor}%

    \infoline{内容简述（请用300字以内简要概述）}{%
      \par\vspace{0.2em}
      % 摘要正文用小四号（规范正文字号），外层字段标签为四号
      {\tjfontbody\linespread{\tjinfoabstractspread}\selectfont% 小四 18 磅
       \setlength{\parindent}{2em}\tongjiinfoabstract\par}
    }

    % 按成果类型只显示对应行（成果类型二选一）
    \ifthenelse{\equal{\tongjiinfotype}{design}\OR\equal{\tongjiinfotype}{engineering}}{%
      \infoline{毕业设计}{主要图纸~\ifx\tongjiinfodrawings\empty \ulinebox{4em} \else \underline{\makebox[4em][c]{\tongjiinfodrawings}} \fi~张，正文总字数~\ifx\tongjiinfowordcount\empty \ulinebox{6em} \else \underline{\makebox[6em][c]{\tongjiinfowordcount}} \fi~字}%
    }{%
      \infoline{毕业论文}{正文总字数~\ifx\tongjiinfothesiswords\empty \ulinebox{6em} \else \underline{\makebox[6em][c]{\tongjiinfothesiswords}} \fi~字}%
    }%

    \infoline{随附资料}{%
      \ifx\tongjiinfomaterials\empty
        \par\vspace{0.5em}
      \else
        \begin{enumerate}[label=\arabic*.,leftmargin=2em,labelsep=0.5em,itemsep=0.2em,parsep=0pt,topsep=0pt] \tongjiinfomaterials \end{enumerate}
      \fi
    }%
    （请列出所有提交的支撑材料名称，如：毕业设计-全套图纸、毕业作品、计算书、程序代码、附录等）
    }
  \end{titlepage}
  \setstretch{\tjlinespread}
  \global\tjbindinglinetrue
}

% 设置中文摘要页（毕业设计时标题改为“设计总说明”）
\newcommand{\MakeAbstract}[2]{
  \vspace*{0.1em}
  \tj@abstractblock{\bfseries\heiti\tjfonttitle}{%
    \ifdefempty{\tongjiabstracttitle}{%
      \tjtitlecninline{\tongjithesistitle}%
    }{%
      \tongjiabstracttitle
    }%
  }
  \ifdefempty{\tongjiabstractsubtitle}{%
    \ifx\tongjithesissubtitle\empty\else
      \vspace{0.6em}%
      \tj@abstractblock{\bfseries\heiti\zihao{3}}{\tjtitlecninline{\tongjithesissubtitle}}% 副标题：三号（官方规范）
    \fi
  }{%
    \vspace{0.6em}%
    \tj@abstractblock{\bfseries\heiti\zihao{3}}{\tongjiabstractsubtitle}%
  }
  \vspace{0.8em}
  \tj@abstractblock{\heiti\tjfontheading}{%
    \ifthenelse{\equal{\tongjiinfotype}{engineering}}{设计总说明}{摘\hspace{0.5em}要}
  }
  \vspace{1.6em}

  \begin{spacing}{\tjlinespread}
    \setlength{\parindent}{2em}
    \songti\tjfontbody #1
    \par
  \end{spacing}

  \songti\tjfontbody
  \vspace{\baselineskip}
  {\noindent\textbf{关键词：}#2}\par
}

% 设置英文摘要页
\newcommand{\MakeAbstractEng}[2]{
  \clearpage
  \vspace*{0.1em}
  \tj@abstractblock{\tjfonttitle\bfseries}{%
    \ifdefempty{\tongjiabstracttitleeng}{%
      \tjtitleeninline{\tongjithesistitleeng}%
    }{%
      \tongjiabstracttitleeng
    }%
  }
  \ifdefempty{\tongjiabstractsubtitleeng}{%
    \ifx\tongjithesissubtitleeng\empty\else
      \vspace{0.6em}%
      \tj@abstractblock{\zihao{3}\bfseries}{\tjtitleeninline{\tongjithesissubtitleeng}}% 副标题：三号（官方规范）
    \fi
  }{%
    \vspace{0.6em}%
    \tj@abstractblock{\zihao{3}\bfseries}{\tongjiabstractsubtitleeng}%
  }
  \vspace{0.8em}
  \tj@abstractblock{\tjfontheading\bfseries}{\tj@lang{ABSTRACT}{Abstract}}
  \vspace{1.6em}

  \begin{spacing}{\tjlinespread}
    \tj@englishtext
    \setlength{\parindent}{2em}
    \tjfontbody #1
    \par
  \end{spacing}

  \tjfontbody
  \vspace{\baselineskip}
  {\tj@englishtext\noindent\textbf{\tj@lang{Key words}{Keywords}: }#2}\par
}

% ==========================================
% Task Book / Proposal / Mid-term Report Commands
% ==========================================
% 任务书（doctype=taskbook）、开题报告（doctype=proposal）、中期报告（doctype=midterm）
% 与正文论文共用 chapters/metadata.tex 中的学院/专业/学生/课题信息（指导教师
% 在 3 份表格中均为手写签字位，不预填，故不读取 \tongjithesisadvisor）；
% \MakeDocument 依据 doctype 分派到 \MakeTaskBook / \MakeProposal / \MakeMidterm，
% 三者仅渲染封面（任务书另含起讫时间与签字区，如 \MakeCover 之于论文封面），正文各段落内容
% 由 chapters/{taskbook,proposal,midterm}_body.tex 提供，写作者可直接编辑替换。

\definecolor{tjnotegray}{HTML}{ADADAD}
\definecolor{tjhintgray}{HTML}{747474}

% 任务书专用信息：起讫时间（\tjsetup 的 start-date、end-date；其余字段与论文共用）。
% 周数由起讫日期自动换算（向上取整），无需手动填写。
\RequirePackage{pgfcalendar}
\newcount\tj@julianstart
\newcount\tj@julianend
\newcount\tj@weeks
% 数值零填充（如 9 -> 09），供拼接 ISO 日期字符串（yyyy-mm-dd）使用；
% \numexpr 先规整输入（容忍调用方已自行补零，如 09 不会被重复补零）
\newcommand{\tj@zeropad}[1]{%
  \ifnum\numexpr#1\relax<10 0\the\numexpr#1\relax\else\the\numexpr#1\relax\fi
}
% \tj@taskbookweeks：起讫日期都已填写时换算周数，否则周数留空。
\newcommand{\tj@taskbookweeks}{%
  \ifboolexpr{test {\ifdefempty{\tongjitaskbookstartyear}} or test {\ifdefempty{\tongjitaskbookstartmonth}}
    or test {\ifdefempty{\tongjitaskbookstartday}} or test {\ifdefempty{\tongjitaskbookendyear}}
    or test {\ifdefempty{\tongjitaskbookendmonth}} or test {\ifdefempty{\tongjitaskbookendday}}}
    {\gdef\tongjitaskbookweeks{}}%
    {\tj@taskbookweeks@compute}%
}
\newcommand{\tj@taskbookweeks@compute}{%
  \pgfcalendardatetojulian{\tongjitaskbookstartyear-\tj@zeropad{\tongjitaskbookstartmonth}-\tj@zeropad{\tongjitaskbookstartday}}{\tj@julianstart}%
  \pgfcalendardatetojulian{\tongjitaskbookendyear-\tj@zeropad{\tongjitaskbookendmonth}-\tj@zeropad{\tongjitaskbookendday}}{\tj@julianend}%
  \ifnum\tj@julianend<\tj@julianstart
    \ClassError{tongjithesis}{The task book's end-date is before its start-date}{Swap the values of start-date and end-date in \string\tjsetup.}%
    \gdef\tongjitaskbookweeks{0}%
  \else
    % \numexpr's "/" rounds to nearest (ties away from zero), not truncates,
    % so a plain (delta+7-1)/7 ceiling-division trick silently over-counts by
    % one week for many date ranges. \divide truncates (unlike \numexpr's "/"),
    % so compute the sum with \numexpr and only then \divide.
    \tj@weeks=\numexpr\tj@julianend-\tj@julianstart+7\relax
    \divide\tj@weeks by 7
    \xdef\tongjitaskbookweeks{\the\tj@weeks}%
  \fi
}

% 中期报告专用信息：专业审核意见的“同意/不同意”复选框由 \tjsetup 的 midterm-decision
% 键设置（默认 none 两格留空，通常由专业负责人在打印后手写勾选；需要提前在电子版中
% 标注时设为 agree 或 disagree），中期报告正文读取 \tongjimidtermdecision。

% 表格环境：课题信息表 / 签字区专用，字段文字取四号宋体。
% 字体显式声明为 \songti：三份行政表格的课题信息表为四号宋体，与论文封面
% \MakeCover 的小二号黑体不同——两者共用版式（居中、定宽下划线）而非字体，
% 故此处不能依赖文档默认字族隐式生效。
% 本表不绘制边框，仅靠下划线呈现填空位置（与 \MakeCover 的 information
% 环境一致），故不设置任何竖线或 \hline。
% 可选参数为 tabcolsep（默认 8pt，与 information 一致）；必须在 \oldtabular
% 开始解析列格式前设定——tabcolsep 一旦用于构建列间距，在表格主体内再
% \setlength 为时已晚（且直接放在 tabular 主体内并非合法位置）。
\newenvironment{tjformtable}[2][8pt]{%
  \renewcommand{\arraystretch}{1.6}
  \setlength{\tabcolsep}{#1}
  \noindent\songti\zihao{4}\selectfont\oldtabular{#2}
}{%
  \endoldtabular
}

% 课题信息表：任务书/开题报告/中期报告共用。沿用论文封面 \MakeCover 的版式——
% 整体居中，每个字段独占一行，用 \ulinecentered 定宽下划线：下划线长度、位置
% 不随是否填写而变化（空则为纯下划线，内容过长则在定宽内居中换行），与论文
% 封面风格统一。blind=true 时学生姓名与学号留空，与论文封面一致。
\newcommand{\tj@formsubjecttable}{%
  \begin{center}
    \begin{tjformtable}{M{5em}M{22em}}
      课题名称 & \ulinecentered{\tongjithesistitle} \\
      副\enskip{}标\enskip{}题 & \ulinecentered{\tongjithesissubtitle} \\
      学\quad{}\quad{}院 & \ulinecentered{\tongjischool} \\
      专\quad{}\quad{}业 & \ulinecentered{\tongjimajor} \\
      学生姓名 & \ulinecentered{\tjblind{\tongjiauthor}{}} \\
      学\quad{}\quad{}号 & \ulinecentered{\tjblind{\tongjiauthornumber}{}} \\
    \end{tjformtable}
  \end{center}%
}

% 说明性文字（此项成稿删除）与提示性文字（内容提示，不删除）——两种灰色，语义不同
\newcommand{\tjformnote}[1]{{\tjfontbody\color{tjnotegray}\selectfont #1\par}}
\newcommand{\tjformhint}[1]{{\tjfontbody\color{tjhintgray}\selectfont #1\par}}

% 一级小节标题：四号黑体，缩进 2 字符（正文分节，不计入目录、不参与章节编号）
\newcommand{\tjformsection}[1]{%
  \par\vspace{\baselineskip}%
  \noindent{\zihao{4}\heiti\selectfont\hspace{2em}#1}\par
  \vspace{0.5\baselineskip}%
}

% 二级小节标题：小四号黑体，缩进 2 字符，段前/段后各 0.5 行
% （撰写规范：2 级标题小四号黑体，序号与题名之间空一格）。
% 与 \tjformsection 一样采用手工编号——两级标题均不进入目录、不参与章节编号，
% 故不使用 enumerate：列表环境无法把序号本身也置为黑体，且会额外引入列表缩进。
\newcommand{\tjformsubsection}[1]{%
  \par\vspace{0.5\baselineskip}%
  \noindent{\tjfontbody\heiti\selectfont\hspace{2em}#1}\par
  \vspace{0.5\baselineskip}%
}

% 居中的说明性大标题（如中期报告首页的“填写说明”）：小二号黑体加粗
\newcommand{\tjformnotice}[1]{%
  \begin{center}
    \vspace*{3\baselineskip}
    {\zihao{-2}\heiti\bfseries\selectfont #1}\par
    \vspace{2\baselineskip}
  \end{center}%
}

% 说明性正文（\tjformnotice 标题之下的条目）：四号宋体，比正文各节的小四号大一号
\newenvironment{tjformnoticebody}{%
  \par\zihao{4}\selectfont
}{%
  \par
}

% 审核意见框内的字段标签（如“指导教师意见：”）：小四黑体。
% 标签单独成组，使紧随其后的灰色提示文字（\tjformnote/\tjformhint）保持宋体。
\newcommand{\tjformlabel}[1]{{\tjfontbody\heiti\selectfont #1}}

% 日期空白（年/月/日下划线填空）
\newcommand{\tjdateblank}{\ulinebox{3em}~年~\ulinebox{2em}~月~\ulinebox{2em}~日}

% 签字行：签名标签 + 定宽下划线 + 日期填空，右对齐。整行（含年/月/日）取黑体——
% 正文中的签字行（任务书末尾、开题/中期报告的审核意见框内）为黑体，与同框内的
% 宋体提示文字不同；任务书封面的签字行则属于封面信息表的一部分，随 \tjformtable
% 取四号宋体，不走本命令。
% #1（可选）：字号，默认小四；任务书正文末尾的签字行为四号，故显式传 \zihao{4}。
% #2：标签文字（如“指导教师签名”）；#3：签名下划线宽度。
\newcommand{\tjformsignature}[3][\tjfontbody]{%
  \begin{flushright}
    {#1\heiti\selectfont #2：\ulinebox{#3}\qquad\tjdateblank}%
  \end{flushright}%
}

% 数字填空：定宽下划线 + 居中数字（#2 为空则为纯下划线），使起讫日期等数字字段
% 无论填写与否都保持等长下划线。用 ulem 的 \uline（同 \ulinebox/\ulinecentered），
% 使全表下划线的粗细与位置一致。
\newcommand{\tjnumline}[2]{\uline{\makebox[#1][c]{#2}}}

% 审核意见方框（指导教师/专业负责人意见 + 签名 + 日期）
% \fbox 的参数须一次性、完整地给出，不能跨 \newenvironment 的 begin/end 两段拆分
% （\fbox 按普通花括号参数扫描，而非 \begingroup/\endgroup 式分组）；
% 因此先用 lrbox 把 minipage 内容完整装入一个盒子寄存器，
% 再在 end 段一次性用 \fbox 包裹已装入完毕的盒子。
\newsavebox{\tj@reviewbox}
\newenvironment{tjreviewbox}{%
  \par\vspace{0.5\baselineskip}\noindent
  \begin{lrbox}{\tj@reviewbox}
  \begin{minipage}[t]{\dimexpr\linewidth-2\fboxsep-2\fboxrule-2pt\relax}\tjfontbody
}{%
  \end{minipage}
  \end{lrbox}
  \fbox{\usebox{\tj@reviewbox}}\par\vspace{0.5\baselineskip}
}

% 任务书/开题报告/中期报告全程不显示装订线：三者均为单独打印/提交的行政表格，
% 不与正文一同装订，且作为独立行政表格本无该装饰。这与 \MakeCover/\MakeInfoPage
% 形成对比——后两者的装订线仅在封面/信息页本身关闭，此后随论文正文恢复；此处
% 恢复为 true 没有意义（\clearpage 而非 titlepage 的 \newpage 触发首页 shipout，
% 若在 \clearpage 前恢复为 true 会导致装订线错误地出现在封面页本身）。
% 三个命令均不将 \tjbindingline 恢复为 true——同一次编译内不会再调用 \MakeCover
% 等其他封面命令，故无需担心状态泄漏到其他文档。

% 任务书封面：课题信息表 + 起讫时间 + 指导教师/教学院长签字区。
% 版式沿用论文封面 \MakeCover：整体居中、下划线定宽（\ulinecentered），风格统一。
\newcommand{\MakeTaskBook}{%
  \global\tjbindinglinefalse
  \begin{center}
    \vspace*{2\baselineskip}
    \includegraphics[height=1.7cm,alt={同济大学校名题字}]{figures/tongji.pdf}\\
    \vspace{1em}
    {\heiti\tjfontformtitle\selectfont \tjformheadertext 任务书}\par
    \vspace{3\baselineskip}
  \end{center}

  \tj@formsubjecttable

  \vspace{2\baselineskip}
  % 起讫时间：标签独占一行 + 日期区间另起一行，整体居中
  \begin{center}\zihao{4}\selectfont
    \tjformheadertext 起讫时间\\[0.5em]
    自~\tjnumline{2.4em}{\tongjitaskbookstartyear}~年~\tjnumline{1.5em}{\tongjitaskbookstartmonth}~月~\tjnumline{1.5em}{\tongjitaskbookstartday}~日至~\tjnumline{2.4em}{\tongjitaskbookendyear}~年~\tjnumline{1.5em}{\tongjitaskbookendmonth}~月~\tjnumline{1.5em}{\tongjitaskbookendday}~日共~\tjnumline{1.5em}{\tongjitaskbookweeks}~周
  \end{center}

  \vfill

  % 签字区：居中
  \begin{center}
    \begin{tjformtable}[2pt]{M{7em}M{8.6em}M{11.5em}}
      指导教师签名 & \ulinebox{8.6em} & \tjdateblank \\
      教学院长签名 & \ulinebox{8.6em} & \tjdateblank \\
    \end{tjformtable}
  \end{center}
  \vspace*{1.5cm}
  \clearpage
}

% 开题报告封面：课题信息表（无起讫时间）+ 填表日期
\newcommand{\MakeProposal}{%
  \global\tjbindinglinefalse
  \begin{center}
    \vspace*{2\baselineskip}
    \includegraphics[height=1.7cm,alt={同济大学校名题字}]{figures/tongji.pdf}\\
    \vspace{1em}
    {\heiti\tjfontformtitle\selectfont \tjformheadertext 开题报告}\par
    \vspace{3\baselineskip}
  \end{center}

  \tj@formsubjecttable

  \vfill
  \begin{center}\zihao{4}\selectfont \tjdateblank\end{center}
  \vspace*{1.3cm}
  \clearpage
}

% 中期报告封面：与开题报告共用同一表格结构（三者同源）
\newcommand{\MakeMidterm}{%
  \global\tjbindinglinefalse
  \begin{center}
    \vspace*{2\baselineskip}
    \includegraphics[height=1.7cm,alt={同济大学校名题字}]{figures/tongji.pdf}\\
    \vspace{1em}
    {\heiti\tjfontformtitle\selectfont \tjformheadertext 中期报告}\par
    \vspace{3\baselineskip}
  \end{center}

  \tj@formsubjecttable

  \vfill
  % 中期报告封面填表日期为三号——此处字号与开题报告（四号）不同
  \begin{center}\zihao{3}\selectfont \tjdateblank\end{center}
  \vspace*{1.3cm}
  \clearpage
}

% 书脊（doctype=spine，入口文件 spine.tex）：研究生学位论文印刷本的书脊，提交电子版时不需要。
% 《同济大学研究生学位论文写作参考指南》（2025 年 10 月）4.3：仿宋四号，行距 16 磅，段前段后 0 磅；
% 上方写论文题目，中间写研究生姓名，下方写“同济大学”，距上下边界均为 5cm 左右。
% 文字竖排，每个汉字占一行，排在页面的竖直中线上：题目上端与“同济大学”下端各距页边 5cm，
% 姓名居于两者之间。题目过长或含西文时，在 spine.tex 中用 \tjsetup{title = ...} 另写书脊上的题目。
% 盲审版本不写姓名。不画装订线。
% \tj@spinecolumn[<t|c|b>]{<文字>}：一列竖排文字；位置参数同 \parbox。“同济大学”一列以
% 末行对齐（b），整列落在距下边界 5cm 之内，不会因其余各行的深度伸出下边界。
\newcommand{\tj@spinecolumn}[2][t]{%
  \parbox[#1]{1.2em}{\centering\fangsong\fontsize{14bp}{16bp}\linespread{1}\selectfont #2}}
\newcommand{\MakeSpine}{%
  \global\tjbindinglinefalse
  \thispagestyle{empty}%
  \AddToShipoutPictureFG*{%
    \AtPageUpperLeft{\put(\LenToUnit{.5\paperwidth},\LenToUnit{-5cm}){%
      \makebox(0,0)[t]{\vbox to\dimexpr\paperheight-10cm\relax{%
        \offinterlineskip
        \hbox{\tj@spinecolumn{\tjtitlecninline{\tongjithesistitle}}}%
        \vfill
        \hbox{\tj@spinecolumn[c]{\tjblind{\tongjiauthor}{}}}%
        \vfill
        \hbox{\tj@spinecolumn[b]{\tongjiuniversity}}%
        \boxmaxdepth\z@}}}}%
  }%
  \null\clearpage
}

% \MakeDocument：按 doctype 分派封面渲染；正文由 chapters/{taskbook,proposal,midterm}_body.tex 提供；
% doctype=spine 只排书脊。
% doctype=thesis（默认）不使用本命令——论文封面/信息页仍由 \MakeCover/\MakeInfoPage 显式调用（main.tex 不变）。
\newcommand{\MakeDocument}{%
  \iftongjithesis@doctype@taskbook
    \MakeTaskBook
  \else\iftongjithesis@doctype@proposal
    \MakeProposal
  \else\iftongjithesis@doctype@midterm
    \MakeMidterm
  \else\iftongjithesis@doctype@spine
    \MakeSpine
  \else
    \ClassError{tongjithesis}{\string\MakeDocument\space requires doctype=taskbook|proposal|midterm|spine}{Set doctype in \string\documentclass[doctype=taskbook]{tongjithesis}, or call \string\MakeTaskBook/\string\MakeProposal/\string\MakeMidterm/\string\MakeSpine directly.}%
  \fi\fi\fi\fi
}

% ==========================================
% Graduate Theses
% ==========================================
% 硕士、博士学位论文（degree=master|doctor）的版式在 tongji-graduate.def 中：它在上面的本科
% 版式之上改写版心、页眉页脚、标题、图表题注、目录、摘要、附录与封面，并定义研究生论文
% 特有的部分（符号说明、致谢、个人简历及学术成果、原创性声明与版权使用授权书）。
% 3 份表格（本科）与书脊不读入它。
\iftongjithesis@bachelor\else\iftongjithesis@form\else\iftongjithesis@doctype@spine\else
  \InputIfFileExists{tongji-graduate.def}{}
    {\ClassError{tongjithesis}{Missing tongji-graduate.def}
      {Copy tongji-graduate.def into the folder that holds tongjithesis.cls.}}
\fi\fi\fi

% ==========================================
% Language
% ==========================================
% 中文综述（撰写规范（一）（二））：在国境外合作双学位项目中用外文撰写的论文，须附一份
% 不少于 5000 字的中文综述，对全稿内容进行综合阐述。规范未规定其位置；附于正文之后，
% 本模板将它排在附录之后、谢辞之前，使装订顺序（二）中谢辞仍在最后。
% 用法：\begin{tjsummary}[<标题>] <综述> \end{tjsummary}，标题默认“中文综述”。综述按中文排版
% （中文标点、黑体标题），其中的 \section 等不编号，以免接续附录的编号。
\NewDocumentEnvironment{tjsummary}{O{中文综述}}
  {\ctexset{
     chapter/format         = {\centering\heiti\tjfontheading},
     section/format+        = {\mdseries\heiti},
     subsection/format+     = {\mdseries\heiti},
     subsubsection/format+  = {\mdseries\heiti},
     paragraph/format+      = {\mdseries\heiti},
   }%
   \chapter*{#1}%
   \addcontentsline{toc}{chapter}{#1}%
   \tj@chinesetext
   \c@secnumdepth=\z@}
  {\par}

% 英文论文（language=english）：撰写规范（十四）“英文撰写毕业设计（论文）规范参考”。规范
% 未规定的项目沿用中文论文的格式（该条：“其余均依照中文撰写规范执行”）。研究生学位论文
% （degree=master|doctor）保留 tongji-graduate.def 的版式，只把名称、题注与交叉引用换成英文。
\iftongjithesis@english
  % 名称：目录（Contents）、参考文献（Bibliography，第十四条）在上文随语言设置；
  % 附录、插图与表格清单、图表题注用英文。
  \ctexset{
    listfigurename = List of Figures,
    listtablename  = List of Tables,
    figurename     = Figure,
    tablename      = Table,
    appendixname   = Appendix,
    bibname        = Bibliography,
    abstractname   = Abstract,
    indexname      = Index,
  }
  % 正文的标点用西文字体，siunitx 用英文连接词；中文部分（封面、信息说明页、中文摘要、
  % 中文综述、研究生学位论文的声明与授权书）在各自的分组内改回中文。
  \tj@englishtext
  \let\tj@MakeCover@chinese\MakeCover
  \renewcommand{\MakeCover}{\begingroup\tj@chinesetext\tj@MakeCover@chinese\endgroup}
  \let\tj@MakeInfoPage@chinese\MakeInfoPage
  \renewcommand{\MakeInfoPage}{\begingroup\tj@chinesetext\tj@MakeInfoPage@chinese\endgroup}
  \ifdefined\MakeDeclarations
    \let\tj@MakeDeclarations@chinese\MakeDeclarations
    \renewcommand{\MakeDeclarations}{\begingroup\tj@chinesetext\tj@MakeDeclarations@chinese\endgroup}
  \fi
  \let\tj@MakeAbstract@chinese\MakeAbstract
  \iftongjithesis@bachelor
    % 标题：一级标题（章、目录、参考文献等未编号标题）居中、四号、加粗；二级标题顶格、加粗；
    % 三级及以下规范未规定，沿用中文论文的字号与缩进，加粗。
    \ctexset{
      chapter/format       = {\centering\bfseries\tjfontheading},
      section/format       = {\bfseries\tjfontbody},
      subsection/format    = {\bfseries\tjfontbody},
      subsubsection/format = {\bfseries\tjfontbody},
      paragraph/format     = {\bfseries\tjfontbody},
    }
    \renewcommand{\tj@unnumberedheadingformat}{\ctexset{chapter/format={\centering\bfseries\tjfontheading}}}
    % 目录：标题四号居中加粗（同上）；章标题顶格、四号、加粗；节标题四号、不加粗；规范未提
    % 小节，与节相同。
    \renewcommand{\cftchapfont}{\bfseries\tjfontheading}
    \renewcommand{\cftchappagefont}{\bfseries\tjfontheading}
    \renewcommand{\cftsecfont}{\tjfontheading}
    \renewcommand{\cftsecpagefont}{\tjfontheading}
    \renewcommand{\cftsubsecfont}{\tjfontheading}
    \renewcommand{\cftsubsecpagefont}{\tjfontheading}
    % 摘要：中文摘要宋体四号、英文摘要 Times New Roman 四号，行距 1.5 倍，首行缩进 2 字符，
    % 各占一页（\MakeAbstractEng 另起一页）。题名与“摘要”“Abstract”标题的格式同中文论文。
    \renewcommand{\MakeAbstract}[2]{%
      \begingroup
        \tj@chinesetext
        \let\tjfontbody\tjfontheading
        \tj@MakeAbstract@chinese{#1}{#2}%
      \endgroup}
    \let\tj@MakeAbstract@english\MakeAbstractEng
    \renewcommand{\MakeAbstractEng}[2]{%
      \begingroup
        \let\tjfontbody\tjfontheading
        \tj@MakeAbstract@english{#1}{#2}%
      \endgroup}
  \else
    % 研究生学位论文：章标题写作“Chapter 1 ×××”，附录写作“Appendix A ×××”（中文为“第1章”
    % “附录A”）；目录、符号说明、致谢与个人简历的标题在 tongji-graduate.def 中随语言设置。
    \ctexset{
      chapter/name  = {Chapter\nobreakspace,},
      appendix/name = {Appendix\nobreakspace},
    }
    \renewcommand{\MakeAbstract}[2]{%
      \begingroup\tj@chinesetext\tj@MakeAbstract@chinese{#1}{#2}\endgroup}
  \fi
  % 正文分项：半角括号“(1)”，后空半个字符（中文论文的全角括号自带空白）。
  \setlist[enumerate,1]{label=(\arabic*),left=2em,nosep,labelsep=0.5em,wide=\parindent}
  % 交叉引用
  \renewcommand*{\chapref}[1]{Chapter~\ref{#1}}
  \renewcommand*{\secref}[1]{Section~\ref{#1}}
  \renewcommand*{\eqref}[1]{Equation~(\ref{#1})}
  % \tj@crefenglish{<类型>}{<单数>}{<复数>}：\cref 的英文格式，名称首字母大写（如“Figure 1.1”
  % “Figures 1.1 and 1.2”），名称与编号都在链接内。公式的编号加圆括号，单独定义。
  \newcommand*{\tj@crefenglish}[3]{%
    \crefformat{#1}{##2#2~##1##3}%
    \crefmultiformat{#1}{##2#3~##1##3}{ and~##2##1##3}{, ##2##1##3}{, and~##2##1##3}%
    \crefrangeformat{#1}{##3#3~##1##4 to~##5##2##6}}
  \tj@crefenglish{chapter}{Chapter}{Chapters}
  \tj@crefenglish{section}{Section}{Sections}
  \tj@crefenglish{subsection}{Section}{Sections}
  \tj@crefenglish{subsubsection}{Section}{Sections}
  \tj@crefenglish{appendix}{Appendix}{Appendices}
  \tj@crefenglish{subappendix}{Appendix}{Appendices}
  \tj@crefenglish{subsubappendix}{Appendix}{Appendices}
  \tj@crefenglish{figure}{Figure}{Figures}
  \tj@crefenglish{table}{Table}{Tables}
  \crefformat{equation}{#2Equation~(#1)#3}
  \crefmultiformat{equation}{#2Equations~(#1)#3}{ and~#2(#1)#3}{, #2(#1)#3}{, and~#2(#1)#3}
  \crefrangeformat{equation}{#3Equations~(#1)#4 to~#5(#2)#6}
  \tj@crefenglish{algorithm}{Algorithm}{Algorithms}
  \tj@crefenglish{algocf}{Algorithm}{Algorithms}
  \tj@crefenglish{listing}{Listing}{Listings}
  \tj@crefenglish{lstlisting}{Listing}{Listings}
  \tj@crefenglish{FancyVerbLine}{Line}{Lines}
  \tj@crefenglish{thm}{Theorem}{Theorems}
  \tj@crefenglish{cor}{Corollary}{Corollaries}
  \tj@crefenglish{lem}{Lemma}{Lemmas}
  \tj@crefenglish{prop}{Proposition}{Propositions}
  \tj@crefenglish{conj}{Conjecture}{Conjectures}
  \tj@crefenglish{assume}{Assumption}{Assumptions}
  \tj@crefenglish{dfn}{Definition}{Definitions}
  \tj@crefenglish{exmp}{Example}{Examples}
  \tj@crefenglish{rem}{Remark}{Remarks}
  \tj@crefenglish{pf}{Proof}{Proofs}
  \tj@crefenglish{proof}{Proof}{Proofs}
  \renewcommand{\crefpairconjunction}{ and~}
  \renewcommand{\crefmiddleconjunction}{, }
  \renewcommand{\creflastconjunction}{, and~}
  \renewcommand{\crefpairgroupconjunction}{ and~}
  \renewcommand{\crefmiddlegroupconjunction}{, }
  \renewcommand{\creflastgroupconjunction}{, and~}
  \renewcommand{\crefrangeconjunction}{ to~}
\fi

% ==========================================
% Configuration Input
% ==========================================

% 设置全角句号替换为全角点号
% fullwidthstop=dot：将句号（。U+3002）替换为全角句点（．U+FF0E）
% ctex/xeCJK 的 PunctStyle 仅控制标点间距，不做字符映射，故需 \catcode 方案
% （旧版布尔写法 fullwidthstop=true 在选项处理时已归为 dot）
% 先设开关再判断：\catcode 须在读入后面的 。 之前生效，故不能写在宏参数中。
\newif\iftongjithesis@fullwidth@active
\ifdefstring{\tongjithesis@fullwidthstop}{dot}{\tongjithesis@fullwidth@activetrue}{}
\iftongjithesis@fullwidth@active
  \catcode`\。=\active
  \newcommand{。}{\ifmmode\text{．}\else ．\fi}%
\fi

% 加载用户配置文件
% cfg is found via TEXINPUTS: locally via latexmkrc (./style//), or alongside cls on CTAN/texmf.
\AtEndOfPackage{
  \InputIfFileExists{tongjithesis.cfg}{}{}
}
