You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LaTeX自定义环境的自定义长引用实现需求

实现LaTeX自定义环境的\longref命令

核心思路

要生成包含编号、标题和状态的长引用,需在自定义环境的条目命令中额外存储每个条目的标题和状态信息,再通过\longref读取这些信息并组合成指定格式。

具体代码实现

\documentclass{article}
\usepackage{xparse} % 简化带参数命令的定义,可选但更灵活

% 定义条目计数器
\newcounter{itemdesc}
\renewcommand{\theitemdesc}{\arabic{itemdesc}}

\makeatletter
% 辅助命令:存储每个标签对应的标题和状态
\newcommand{\storeitemtitle}[2]{\@namedef{itemtitle@#1}{#2}}
\newcommand{\storeitemstatus}[2]{\@namedef{itemstatus@#1}{#2}}

% 重定义\itemdescription命令:添加标签、标题、状态的存储逻辑
\NewDocumentCommand{\itemdescription}{O{} m m +m O{}}{%
  % 参数说明:O{}=可选备注,m=必填标签,m=必填标题,+m=必填描述,O{}=可选状态
  \refstepcounter{itemdesc}
  \label{#2} % 保留原有的标签引用
  \storeitemtitle{#2}{#3} % 存储当前条目标题
  \storeitemstatus{#2}{#5} % 存储当前条目状态

  % 条目内容输出(可根据你的原有格式调整)
  \par\noindent\textbf{Item \theitemdesc - #3}
  \ifx\empty#5\empty\else\space(\textit{#5})\fi\\
  #4 % 描述文本
  \ifx\empty#1\empty\else\\\textit{备注:#1}\fi\\[1em]
}

% 定义\longref命令
\NewDocumentCommand{\longref}{m}{%
  Item \ref{#1} - \@nameuse{itemtitle@#1}%
  \ifx\empty\@nameuse{itemstatus@#1}\empty\else\space(\@nameuse{itemstatus@#1})\fi
}
\makeatother

\begin{document}

% 使用示例
\itemdescription[e]{This is the title}{This is the description text.}[pending]

% 引用测试
直接引用编号:\ref{e}\\
长引用效果:\longref{e}

\end{document}

代码说明

  • 用\@namedef和\@nameuse实现动态存储/读取每个标签对应的标题和状态,这是LaTeX处理动态命名内容的常规方法。
  • xparse的\NewDocumentCommand让参数定义更清晰,支持可选参数(如备注、状态);若不需要可选参数,也可替换为普通\newcommand。
  • \longref会自动判断状态是否为空,仅当状态存在时才显示括号内的内容。

效果验证

编译后,\longref{e}会输出:Item 1 - This is the title (pending),完全符合需求。

内容的提问来源于stack exchange,提问作者Bant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 11:26:03