是否可以使用lineno
包中的数字作为 中的计数器imakeidx
?如下面的 MWE 所示,我尝试使用xpatch
将索引的计数器更改为thelinenumber
,但没有成功:
\documentclass{article}
\usepackage{lineno}
\usepackage{imakeidx}
\usepackage{xpatch}
\makeindex
\makeatletter
\makeatletter
\patchcmd{\@wrindex}{\thepage}{\thelinenumber}{}{}
\makeatother
\begin{document}
\linenumbers
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus
facilisis magna, id sodales ante convallis vitae. In a porttitor nibh,
eget vehicula dui\index{test}. Integer feugiat dui nec neque porttitor, non eleifend
erat lobortis. Sed varius malesuada nisi, id vulputate ante commodo vitae.
Nam non felis at ante mollis commodo eget porttitor ex. Donec in quam diam.
Maecenas fringilla, turpis a egestas pulvinar, massa lacus molestie enim,
vel vulputate lorem ante ac velit. Nam ex nulla, venenatis et tortor at,
efficitur fringilla ante.
\clearpage \printindex
\end{document}
答案1
您不能直接使用\thelinenumber
,因为这将引用段落已分成行时计算的行号。
使用补丁后,您得到的数字是 1,因为\thelinenumber
在错误的时间进行了扩展;但是使用补丁后,\noexpand\thelinenumber
您会得到 8,因为这是处理段落时的值(它有七行)。
您需要使用该\linelabel
机制。
\documentclass{article}
\usepackage{lineno,refcount}
\usepackage{imakeidx}
\usepackage{xpatch}
\makeindex
\makeatletter
\newcommand{\lineindex}[1]{\linelabel{#1}\index{#1}}
\patchcmd{\@wrindex}{\thepage}{\getrefnumber{#2}}{}{}
\makeatother
\begin{document}
\linenumbers
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus
facilisis magna, id sodales ante convallis vitae. In a porttitor nibh,
eget vehicula dui\lineindex{dui}. Integer feugiat dui nec neque porttitor, non eleifend
erat lobortis. Sed varius malesuada nisi, id vulputate ante commodo vitae.
Nam non felis at ante mollis commodo eget porttitor ex. Donec in quam diam.
Maecenas fringilla, turpis a egestas pulvinar, massa lacus molestie enim\lineindex{enim},
vel vulputate lorem ante ac velit. Nam ex nulla, venenatis et tortor at,
efficitur fringilla ante.
\printindex
\end{document}
这需要运行两次,因为它使用\ref
(实际上是可扩展版本\getrefnumber
)。