Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

What's the proper way to reference a section with a counter in the title? The TOC generates correctly, but the cross references aren't so lucky.

MWE:

\documentclass[letterpaper, 12pt, twoside]{exam}

\usepackage{hyperref}

\newcounter{KSRLessonNumberCounter}
\setcounter{KSRLessonNumberCounter}{1}
\newcommand{\KSRSection}[2][\value{KSRLessonNumberCounter}]{
        \setcounter{KSRLessonNumberCounter}{#1}
        \section*{Lesson \arabic{KSRLessonNumberCounter}: #2}
        \addcontentsline{toc}{section}{Lesson \arabic{KSRLessonNumberCounter}: {#2}}
        \stepcounter{KSRLessonNumberCounter}
}
\newcommand{\KSRSubsection}[1]{
        \subsection*{#1}
        \addcontentsline{toc}{subsection}{#1}
}
\newcommand{\KSRLessonNumber}{
}

\begin{document}

\KSRSection{Sample}

This is the first lesson. The second lesson is \nameref{sec:blah}.

\KSRSection{Blah}
\label{sec:blah}

This is the second section

\KSRSection{Lorem Ipsum}

Dollars are Set in \nameref{sec:blah}.

\end{document}

MWE: wrong section numbers

share|improve this question
add comment

2 Answers 2

up vote 9 down vote accepted

It is an expansion issue. The title string is not expanded and contains:

Lesson \arabic {KSRLessonNumberCounter}: Blah

Package hyperref loads nameref, which uses package gettitlestring to get a clean title string (removing \label, \index, ...). There are two methods, the traditional way without expansion or the version with expansion. The former is the default. By switching to method expand the problem is solved:

\usepackage{hyperref}
\usepackage{nameref}% loads gettitlestring
\GetTitleStringSetup{expand}
share|improve this answer
add comment

A different solution than Heiko's that uses standard names. You simply enter \subsection for subsections, without the need of *; for the reference to a section, use \lectref.

\documentclass[letterpaper, 12pt, twoside]{exam}

\usepackage[colorlinks]{hyperref}

\makeatletter
\renewcommand{\@seccntformat}[1]{Lesson \csname the#1\endcsname: }
\makeatother

\newcommand{\lectref}[1]{%
  \hyperref[#1]{Lesson~\ref*{#1}: \nameref*{#1}}%
}

\setcounter{secnumdepth}{1}

\begin{document}

\section{Sample}

This is the first lesson. The second lesson is \lectref{sec:blah}.

\section{Blah}\label{sec:blah}

This is the second section

\subsection{A subsection}

Here it is

\section{Lorem Ipsum}

Dollars are Set in \lectref{sec:blah}.

\end{document}

I used colorlinks to show them in the picture.

enter image description here

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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