# Define command so that \label works properly

I have something like this:

\newcounter{Def}
\newcommand{\printDef}{\thechapter.\thesection.\theDef}
\newenvironment{Expl}
{\small\narrower\medskip\stepcounter{Def}\noindent\ignorespaces \textsc{Example \printDef.}}
{\par\normalsize\medskip}


And then:

\begin{Expl} \label{myref}
blahblahblah
\end{Expl}


Suppose the current section is 2.4, then it will print something like:

Example 2.4.1.

However, when I do \ref{myref}, it will just print 2.4. The 1 is totally gone! Could anyone please help? Thanks!

-
Wow, thank Caramdir for editing it!!! It looks amazing now. – brian Mar 18 '11 at 21:19
You are welcome. It was just a matter of selecting text and pressing the code (marked with 101010) and quote buttons. – Caramdir Mar 18 '11 at 21:43
For your immediate example, it might be easier to use a theorem environment (e.g. from amsmath or ntheorem). – Caramdir Mar 18 '11 at 23:02

## 1 Answer

You need to change some of the code to make it work:

• You should redefine \theDef instead of using \printDef. It is used in internal code. You can add the old definition as \arabic{Def} which prints the counter value as normal (i.e. arabic) number.
• Use \refstepcounter instead of \stepcounter. This sets the internal macro \@currentlabel which is used by \label. Then the then current value of \theDef will be used in the \ref.

Also:

• Note that depending on the used document-class the \thesection macro already includes \thechapter. With e.g. report the chapter number would be printed twice. (I disabled it therefore in the example).
• The \ignorespaces should be at the very end to be effective.
• You don'y need to change the font back to normal at the end because all changes are only local to the environment content anyway.
• You should add an explicit \par at the beginning and place the \medskip and \noindent just after it. They work at the current locations as well but this way it is much cleaner.

The working code looks like this:

\documentclass{report}

\newcounter{Def}
\renewcommand{\theDef}{%\thechapter.
\thesection.\arabic{Def}}
\newenvironment{Expl}
{\par\medskip\noindent\small\narrower\refstepcounter{Def}\textsc{Example~\theDef.}\ignorespaces}
{\par\medskip}

\begin{document}
\chapter{Test}
\chapter{Test}
\section{A}

\begin{Expl}\label{test}
Test
\end{Expl}

See \ref{test}.

\begin{Expl}\label{test2}
Test2
\end{Expl}

See \ref{test2}.

\end{document}

-
Thanks a lot!!! It works. – brian Mar 18 '11 at 22:20
It is probably better to add it also to the section counter reset list: \newcounter{Def}[section] – Danie Els Mar 19 '11 at 2:55