1

I use the PDFLaTeX to design the exercise template. I want the labels of exercises are automatically given according to the Chapter number and the Exercise number, and I also want to show the Exercise number in the bookmark of the PDF files. Inspired by What’s the most straightforward way to typeset theorems etc. when the numbering is entirely manual?, I try the following codes:

\documentclass{book}

\usepackage{amsthm}
\usepackage{hyperref}

\makeatletter
\newtheorem{ex}{Exercise}[chapter]
\newenvironment{exx}[1]{\def\@currentlabel{#1}
\ex\label{\@currentlabel}
\pdfbookmark[1]{Exercise~~\@currentlabel}{\@currentlabel}
}{\endex}
\makeatother

\newcommand{\exref}[1]{Exercise~\textup{\ref{#1}}}

\begin{document}
\setcounter{chapter}{3}
\chapter{Hello Chapter 4}

\begin{exx}
Exercise A.
\end{exx}

\begin{exx}
Exercise B.
\end{exx}

By \exref{4.1} and \exref{4.2}

\end{document}

It works, but some problems occur, which shows

Exercise 4.1. xercise A.
Exercise 4.2. xercise B.
By Exercise 4.1 and Exercise 4.2

i.e., the first letters of the Exercises are missing!!! Of course, we can avoid this by replacing \begin{exx}{} with \begin{exx}, but I don't want this unless I want redefine new lables for the Exercises, namely,

\begin{exx}
Exercise A.
\end{exx}
\exref{4.1}

and

\begin{exx}{newLabel41}
Exercise A.
\end{exx}
\exref{newLabel41}

give the same results. Any help?

Werner
  • 603,163

1 Answers1

2

You are probably interested in an optional argument rather than a mandatory one. With the latter - your current setup using \newenvironment{exx}[1] - it gobbles the first letter in the environment body as the mandatory argument. With an optional argument - using \newenvironment{exx}[1][] - you can test whether it was used or not and use a different \label.

enter image description here

\documentclass{book}

\usepackage{amsthm}
\usepackage{hyperref}

\makeatletter
\newtheorem{ex}{Exercise}[chapter]
\newenvironment{exx}[1][]{% 
  \begin{ex}
    % https://tex.stackexchange.com/q/53068/5764
    \if\relax\detokenize{#1}\relax
      \label{\@currentlabel}%
    \else
      \label{#1}%
    \fi
    \pdfbookmark[1]{Exercise~~\@currentlabel}{\@currentlabel}
}{%
  \end{ex}
}
\makeatother

\newcommand{\exref}[1]{Exercise~\textup{\ref{#1}}}

\begin{document}
\setcounter{chapter}{3}
\chapter{Hello Chapter 4}

\begin{exx}
Exercise A.
\end{exx}

\begin{exx}
Exercise B.
\end{exx}

See \exref{4.1} and \exref{4.2}, but also \exref{ex:next}.

\begin{exx}[ex:next]
Exercise C.
\end{exx}

\end{document}
Werner
  • 603,163