
Я пишу документ, используя scrreprt
класс KOMAscript, и пишу пользовательский макрос ( \xref
) для форматирования текста, используемого для перекрестных ссылок.
Этот макрос принимает имя метки в качестве аргумента:\xref{mylabel}
Я хочу сгенерировать разный текст в зависимости от того, относится ли метка к главе/разделу/подразделу (по умолчанию пронумерованным) или к подподразделу/абзацу (по умолчанию не пронумерованным).
Как это проверить? Подойдет любой из следующих двух вариантов:
- Проверьте, относится ли метка к главе/разделу/подразделу (или наоборот: проверьте, относится ли метка к подподразделу/абзацу)
- Проверьте, относится ли этикетка к пронумерованному элементу.
решение1
См. обновление для ссылки на unnumbered/numbered
структурную единицу и проверку в конце.
Без использования дополнительных пакетов, \renewcommand, \let, \pdfstrcmp
используются только etc. и запись \@namedef
в .aux
файл.
Для этого требуется два прогона (которые необходимы в любом случае, поскольку мы имеем дело с этикетками!)
Используйте \extractlabeltype{labelname}
and \checklabeltype
с ветвью true/false.
Предполагается, что никакой другой пакет не участвует в работе \label
и \ref
, т. е. hyperref
или не cleveref
поддерживается.
\documentclass{book}
\makeatletter
\let\latex@@refstepcounter\refstepcounter
\let\latex@@label\label%
\renewcommand{\refstepcounter}[1]{%
\gdef\lastrefsteppedcounter{#1}%
\latex@@refstepcounter{#1}%
}
\renewcommand{\label}[1]{%
\immediate\write\@auxout{\string\global\string\@namedef{label#1}{\lastrefsteppedcounter}}
\latex@@label{#1}%
}
\newcommand{\extractlabeltype}[1]{%
\@nameuse{label#1}%
}
\makeatother
\newcommand{\checklabeltype}[4]{%
\ifnum0=\pdfstrcmp{\extractlabeltype{#1}}{#2}
#3%
\else
#4%
\fi
}
\begin{document}
\chapter{Foo} \label{foo}
\section{Foosection}\label{foosection}
\checklabeltype{foosection}{section}{Yes, it is section}{No, it is something different}
\checklabeltype{foo}{section}{Yes, it is section}{No, it is something different}
\end{document}
Обновлятьс проверкой на наличие ненумерованных/нумерованных выпусков.
Обратите внимание, что это намеренно основано на предположении, что имя якоря ненумерованной структурной единицы содержит *
в себе , поэтому играть с \theH...
макросами — не очень хорошая идея ;-)
\documentclass{book}
\usepackage{xparse}
\usepackage[hyperref,counter]{zref}% Using the counter mechanism behind `nameref`
\usepackage{hyperref}
\makeatletter
\AtBeginDocument{%
\let\latex@@label\label%
\renewcommand{\label}[1]{%
\zref@label{#1}%
\latex@@label{#1}%
}
% Get the underlying counter type
\newcommand{\extractlabelcounter}[1]{%
\zref@ifrefundefined{#1}{%
???????}{%
\zref@extract{#1}{counter}%
}%
}
% Get the anchor name for hyperref or nameref -> has a `*` inside if it is unnumbered
\newcommand{\extractlabelanchor}[1]{%
\zref@ifrefundefined{#1}{%
???????}{%
\zref@extract{#1}{anchor}%
}%
}
}
% Check if there's a `*` inside of the anchor name
\ExplSyntaxOn
\cs_new:Npn \checkifnumbered#1#2#3{%
\tl_set:Nx \l_tmpa_tl {\extractlabelanchor{#1}}
\tl_if_in:NnTF \l_tmpa_tl {*} {#2} {#3}
}
\ExplSyntaxOff
\makeatother
\newcommand{\checklabeltype}[4]{%
\ifnum0=\pdfstrcmp{\extractlabelcounter{#1}}{#2}
#3%
\else
#4%
\fi
}
\begin{document}
\chapter{Foo} \label{foo}
\section*{An unnumbered section} \label{unnumbered}
\section{Foosection}\label{foosection}
\checklabeltype{foosection}{section}{Yes, it is section}{No, it is something different}
\checklabeltype{foo}{section}{Yes, it is section}{No, it is something different}
\begin{enumerate}
\item First \label{enumfirst}
\item Second \label{enumsecond}
\end{enumerate}
\checklabeltype{enumsecond}{enumi}{It is a numbered item and has the value \ref{enumsecond}}{}
In \nameref{unnumbered} we have an \checkifnumbered{unnumbered}{unnumbered}{numbered} \extractlabelcounter{unnumbered}
In \nameref{foo} we have an \checkifnumbered{foo}{unnumbered}{numbered} \extractlabelcounter{foo} whereas
\nameref{foosection} is a \checkifnumbered{foosection}{unnumbered}{numbered} \extractlabelcounter{foosection}.
\end{document}