2

Referencing this question: Hyperref refer chapter and page in text and its possible duplicate Clickable Link back to the Table of Contents

This is basically the second question all over again, but bear with me.

I used the first questions' answer, but shightly edited. I now have every chapter name linking back to the TOC (just the name, not the 'Chapter #' part above it. Not a big problem, if you know how to solve it, lemmeknow :) )

Problem is: this also alters the TOC line itself to link to the TOC. So if I now click a chapter in the TOC, that also links to the TOC.

MWE:

\documentclass[11pt]{report}

\usepackage{hyperref}
\usepackage{lipsum}

\usepackage{xparse}
\AtBeginDocument{
    \let\oldchapter\chapter
    \RenewDocumentCommand{\chapter}{s o m}{%
    \clearpage
    \IfBooleanTF{#1}
        {\oldchapter*{\hyperref[toc]{#3}}}% \chapter*[..]{...}
        {\IfValueTF{#2}
            {\oldchapter[#2]{\hyperref[toc]{#3}}}% \chapter[..]{...}
            {\oldchapter{\hyperref[toc]{#3}}}% \chapter{...}
        \label{chapter-\thechapter}% \label this chapter
        }%
    }
}

\begin{document}

\chapter*{Preface}
\lipsum[1-1]
\tableofcontents\label{toc}
\chapter{Introduction}
\lipsum[2-2]
\end{document}

What I did was take the solution with the support for unnumbered chapters, and add a \hyperref[toc]{} to them.

1

The easiest solution is to use \oldchapter[#3]{\hyperref[toc]{#3}}}%, i.e. explicitly writing the #3 again to the toc and setting the \hyperref command in the chapter title. This will preserve the the correct hyperanchors and prevents ugly [toc] prefixes in the bookmark panel!

\documentclass[11pt]{report}

\usepackage{hyperref}
\usepackage{lipsum}

\usepackage{xparse}
\AtBeginDocument{
  \let\oldchapter\chapter
  \RenewDocumentCommand{\chapter}{s o m}{%
    \clearpage
    \IfBooleanTF{#1}
    {\oldchapter*{\hyperref[toc]{#3}}}% \chapter*[..]{...}
    {\IfValueTF{#2}
      {\oldchapter[#2]{\hyperref[toc]{#3}}}% \chapter[..]{...}
      {\oldchapter[#3]{\hyperref[toc]{#3}}}% \chapter{...}
      \label{chapter-\thechapter}% \label this chapter
    }%
  }
}

\begin{document}

\chapter*{Preface}
\lipsum[1-1]
\tableofcontents\label{toc}
\chapter{Introduction}
\lipsum[2-2]

\chapter{Results}
\lipsum[2-4]
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.