我想建立自己的 \ref 系统。
我写了 \Problem 命令来表示序列号和标题。我想要一个新的 \myref 命令,它通过引用标签来获取编号和标题。你能帮助我吗?
这是 MWE。
\documentclass{article}
\newcounter{cnt}
\setcounter{cnt}{1}
\def\Problem#1{
\noindent\textsf{\thecnt. #1}
\stepcounter{cnt}
}
\def\Answer#1{
\noindent\textsf{Ans. \myref{#1}}
}
\def\myref#1{
\ref{#1}
% I don't know.
}
\begin{document}
\section{Problems}
\Problem{Foo}\label{problem1}
\Problem{Bar}\label{problem2}
\section{Answers}
\Answer{problem1}
I want to display \textsf{Ans. 1. Foo}.
\Answer{problem2}
I want to display \textsf{Ans. 2. Bar}.
\end{document}
答案1
我建议使用定理,这样\label
就\ref
可以开箱即用,不要添加不需要的空格。
\documentclass{article}
\usepackage{amsthm}
\newtheoremstyle{problem}
{0pt} % ABOVESPACE
{0pt} % BELOWSPACE
{\upshape} % BODYFONT
{0pt} % INDENT (empty value is the same as 0pt)
{\sffamily} % HEADFONT
{.} % HEADPUNCT
{ } % HEADSPACE
% CUSTOM-HEAD-SPEC follows
{\thmnumber{#2}. \protect\problemname}
\providecommand{\problemname}{}
\newtheoremstyle{answer}
{0pt} % ABOVESPACE
{0pt} % BELOWSPACE
{\upshape} % BODYFONT
{0pt} % INDENT (empty value is the same as 0pt)
{\sffamily} % HEADFONT
{.} % HEADPUNCT
{ } % HEADSPACE
% CUSTOM-HEAD-SPEC follows
{Ans.\ \protect\answername}
\providecommand{\answername}{}
\theoremstyle{problem}
\newtheorem{innerproblem}{}
\makeatletter
\newenvironment{Problem}[1]
{%
\renewcommand{\problemname}{#1}%
\innerproblem
\edef\@currentlabel{\theinnerproblem.\ \unexpanded{#1}}%
}
{\endinnerproblem}
\makeatother
\theoremstyle{answer}
\newtheorem*{inneranswer}{}
\newenvironment{Answer}[1]
{\renewcommand{\answername}{\ref{#1}}\inneranswer}
{\endinneranswer}
\begin{document}
\section{Problems}
\begin{Problem}{Foo}\label{problem1}
Compute $1+1$.
\end{Problem}
\begin{Problem}{Bar}\label{problem2}
Compute $0+0$.
\end{Problem}
\section{Answers}
\begin{Answer}{problem1}
$1+1=2$.
\end{Answer}
\begin{Answer}{problem2}
$0+0=0$.
\end{Answer}
\end{document}
答案2
我找到了一种更简单的方法标记单词的答案。
\makeatletter
\def\Problem#1#2{
\stepcounter{cnt}
\noindent\textbf{\thecnt.} \textsf{#1}%
\def\@currentlabel{\thecnt. \unexpanded{#1}}\label{#2}}%
}
\makeatother
\def\Answer#1{
\noindent\textsf{Ans. \ref{#1}}
}
\Problem{FOOBAR}{foobar}
\Answer{foobar}
然后,\Answer 命令中的 \ref{foobar} 返回计数器和标签 foobar 标题的连接。
这对于我的工作来说已经足够了。但是,这种方法似乎对超链接不太管用。当我点击 Answer 中的标题时,它会转到第一页。