我最终想要的是标题到目录的可点击反向链接。目标是点击标题并进入目录中的确切标题。就我的搜索努力而言,没有简单的方法可以实现这一点。所以我尝试从链接到目录开始,例如这里。但我已经无法在标题中放置链接,这似乎是不可能的,并导致此错误消息:
pdfTeX error (ext1): \pdfendlink cannot be used in vertical mode.
只是为了澄清这一点,因为网络上的其他讨论似乎存在潜在的误解:我不想改变标题的样式!链接应该像使用该hidelinks
选项时一样不可见。我将链接保留在 MWE 中以便更好地概览。
以下是 MWE,其中一条产生错误的行没有被注释掉:
\documentclass{scrreprt}
\usepackage{hyperref}
% \usepackage[hidelinks]{hyperref}%Works like a charm
% And I would like to do something like that too:
% \renewcommand{\chapter}[1]{\hyperlink{toc}{\chapter{#1}}}
\begin{document}
\hypertarget{toc}{\tableofcontents}
\chapter{This is a great headline}%Working
% \chapter{This \hyperlink{toc}{is} a great headline}%Not working
% \chapter{\hyperlink{toc}{This is a great headline}}%Also not working
\hyperlink{toc}{\chapter{This is a great headline}}%Also not working
Here is some text to prove, that \hyperlink{toc}{links} to toc work, if they're not in headings\ldots
\section{This is a section heading}
% \section{This is a \hyperlink{toc}{section} heading}%Also not working
\section{and another}
\chapter{This is a bad headline!}
\section{last section}
\end{document}
最后,如果能自动获取每个标题中的链接就太好了,就像我尝试的那样renewcommand
。
答案1
我将重新定义放在了\contentsline
后面\begin{document}
,因为 hyperref 似乎将重新定义的内容放在了 aux 文件中。但仔细检查后发现,这段代码实际上什么也没做。
\documentclass{scrreprt}
\usepackage{hyperref}
\makeatletter
\let\hyperchapter\chapter
\def\chapter{\@ifstar\starchapter\mychapter}
\def\starchapter{\hyperchapter*}
\newcommand{\mychapter}[2][\@empty]% #1=optional (toc and top of page), #2=title
{\ifx#1\@empty \hyperchapter[#2]{\hyperlink{toc.chapter.\thechapter}{#2}}
\else \hyperchapter[#1]{\hyperlink{toc.chapter.\thechapter}{#2}}
\fi}
\let\hypersection\section
\def\section{\@ifstar\starsection\mysection}
\def\starsection{\hypersection*}
\newcommand{\mysection}[2][\@empty]% #1=optional (toc), #2=title
{\ifx#1\@empty \hypersection[#2]{\hyperlink{toc.section.\thesection}{#2}}
\else \hypersecton[#1]{\hyperlink{toc.section.\thesection}{#2}}
\fi}
\makeatother
\begin{document}
\let\hypercontentsline=\contentsline
\renewcommand{\contentsline}[4]{\hypertarget{toc.#4}{}\hypercontentsline{#1}{#2}{#3}{#4}}
\tableofcontents
\chapter{This is a great headline}
\section{and another}
\chapter{This is a bad headline!}
\section{last section}
\end{document}