# Reference an environment counter through label in another counter

I have an implications environment impl whose counter works as intended (1,2...). In a subsequent chapter, I develop a series of hypotheses for each implication, and I want the hypothesis environment hypo to recognize the counter of the implication that it belongs to. So far what I have is:

\documentclass{article}
\usepackage{amsmath}
%% Implications
\newcounter{implcounter}
\newenvironment{impl}{
\refstepcounter{implcounter}
\textbf{Implication \theimplcounter:}
}{\par}

%% Hypotheses
\newcounter{hypcounter}
\newenvironment{hypo}{
\refstepcounter{hypcounter}
\textbf{Hypothesis \thehypcounter:}
}{\par}
\numberwithin{hypcounter}{implcounter}

\begin{document}

This is one implication:

\begin{impl} \label{impl:a}
Hello
\end{impl}

This is another implication:

\begin{impl}
Bye bye
\end{impl}

But then:

\begin{hypo}
Not the numberwithin I would like!
% I would like for this to be implication 1.1
\end{hypo}

\end{document}


I would like to have a hypo environment for which the number within is the one referenced by \label{impl:a}, in this case 1.

• Welcome to TeX.SX! Can you please add as comment to the code the numbering you wish to get? – egreg Jun 15 '17 at 23:24
• Why should it be 1 when it is the second implication? Shouldn't it be 2? – cfr Jun 15 '17 at 23:29
• You are right, I just switched the label to the first implication, so the number should be one. Also added the comment to the code. – Milo Jun 15 '17 at 23:30

## 5 Answers

Try this:

\documentclass{article}
\usepackage{amsmath}
%% Implications
\newcounter{implcounter}
\newenvironment{impl}{
\refstepcounter{implcounter}
\textbf{Implication \theimplcounter:}
}{\par}

%% Hypotheses
\newcounter{hypcounter}
\newenvironment{hypo}[1][\theimplcounter]{
\refstepcounter{hypcounter}
\textbf{Hypothesis #1.\thehypcounter:}
}{\par}

\begin{document}

This is one implication:

\begin{impl} \label{impl:a}
Hello
\end{impl}

This is another implication:

\begin{impl}
Bye bye
\end{impl}

But then:

\begin{hypo}[\ref{impl:a}]
Not the numberwithin I would like!
% I would like for this to be implication 1.1
\end{hypo}

\end{document}


You just need a second parameter (optional) in your environment to refer to the Implication you choose to refer... If you don't give the parameter it will refer to the last one impl

Edit:

What you want can be done like this:

\documentclass{article}
\usepackage{amsmath}
\usepackage{verbatim}

\usepackage{refcount}
\usepackage{stringstrings}
\usepackage{xstring}

%% Implications
\newcounter{implcounter}
\newenvironment{impl}{
\refstepcounter{implcounter}
\textbf{Implication \theimplcounter:}
}{\par}

%% Hypotheses
\makeatletter
\newcommand\andrea@test@count[1]{%
\@ifundefined{c@#1}
{% the counter doesn't exist so I define it
\expandafter\newcounter{#1}
}
{% the counter exists and I do nothing
\relax
}%
}

\newenvironment{hypo}[1][\theimplcounter]{
\ifnum #1=\theimplcounter
{ %this is the default case for not given argument
\andrea@test@count{counter\theimplcounter}
\refstepcounter{counter\theimplcounter}
\textbf{Hypothesis \theimplcounter.\csname thecounter\theimplcounter\endcsname:}
}
\else
{ %this is tha case with given argument
\andrea@test@count{counter#1}
\refstepcounter{counter#1}
\textbf{Hypothesis #1.\csname thecounter#1\endcsname:}
}
\fi
}{\par}
\makeatother

\begin{document}

This is one implication:

\begin{impl} \label{impl:a}
Hello this Implication has label \getrefnumber{impl:a}
\end{impl}\quad

This is another implication:

\begin{impl} \label{impl:b}
Hello this Implication has label \getrefnumber{impl:b}
\end{impl}\quad

This is a third implication without label:

\begin{impl}
Bye bye
\end{impl}\quad

And then:\par

\begin{hypo}[\getrefnumber{impl:b}]
This hypothesis is refered to label \getrefnumber{impl:b}.
So I want 2.1
\end{hypo}\quad

\begin{hypo}
This Hypothesis is refered to no label.
So I want it 3.1
\end{hypo}\quad

\begin{hypo}[\getrefnumber{impl:a}]
This hypothesis is refered to label \getrefnumber{impl:a}.
I want it 1.1
\end{hypo}\quad

\begin{hypo}[\getrefnumber{impl:a}]
This hypothesis is refered to label \getrefnumber{impl:a}.
I want 1.2
\end{hypo}\quad

\begin{hypo}
This last hypothesis has no label. So I want it 3.2
\end{hypo}

\end{document}


You have this result:

• Thanks so much. Now is there a way to add a within counter so that: I can write somethig like: \begin{hypo}[\ref{impl:a}] I would like for this to be implication 1.1 \end{hypo} \begin{hypo}[\ref{impl:b}] I would like for this to be implication 2.1 \end{hypo} \begin{hypo}[\ref{impl:a}] I would like for this to be implication 1.2 \end{hypo} – Milo Jun 16 '17 at 0:07
• Sorry for the delay in my answer... I didn't realize you needed more help. Also my code if you give any undefined label gives the number 0 and continues like 0.1, 0.2... etc – koleygr Jun 16 '17 at 6:29
• Hello, this solution is nice and works with my other packages. thanks! – Milo Jun 19 '17 at 19:31
• When using your first example with hyperref, you get links to referenced numbers, e.g., "Hypothesis {link to 1}1{end of link}.2 . Also anchors from \refstepcounter{hypcounter} might not wind up in the right places. Is that really what you want? – Ulrich Diez Jun 28 '18 at 10:45

This is based on Christian Hupfer's answer, but tries to adhere to the guidelines for working with expl3 code and issues warnings in case an implication context has not been defined.

It reimplements the two environments as xparse wrappers around expl3 functions, which adhere to the standard syntax. It also uses \cs_new_protected_nopar in preference to \cs_new, and tries to use more efficient options for handling property lists, where possible.

The implementation no longer relies on the \label/\ref system provided by LaTeX 2e. Instead, a tag can be given as an optional argument to the impl environment, and must be given as a mandatory argument to the hypo one.

Two property lists are used: one for each type of environment. If an implication context is not defined, zeroes will be used in the output and warnings written to the console with details.

One standard, as I understand it, is that user-level commands and environments should be defined using \NewDocumentEnvironment etc. rather than \newenvironment etc., and that this should be minimal wrappers which simply parse user input and pass it to lower-level expl3 functions.

However, I'm not sure I've understood all this correctly, especially since people seem generally not to do this. So this could be all wrong.

# Caveat emptor

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

% based on ateb Christian Hupfer: https://tex.stackexchange.com/a/375209/
\ExplSyntaxOn

\prop_new:N \g_milo_hypcounter_prop
\prop_new:N \g_milo_implcounter_prop

% these are the counters
\int_new:N \g_milo_hypo_int
\int_new:N \g_milo_impl_int

\msg_new:nnn { milo } { undef }
{
milo ~::~reference~#1~is~unknown.~0~will~be~used~instead.~\msg_line_context:.
}

\cs_new_protected_nopar:Nn \milo_storehypcounter:n {
\prop_gput:Nnx \g_milo_implcounter_prop { #1 } { \int_to_arabic:n { \g_milo_impl_int } }
\prop_gput:Nnn \g_milo_hypcounter_prop { #1 } { 0 }
}

\cs_new_protected_nopar:Nn \milo_extracthypcounter:n {
\prop_get:NnNTF \g_milo_implcounter_prop { #1 } \l_tmpa_tl
{
\l_tmpa_tl
}
{
0
\msg_warning:nnn { milo } { undef } { #1 }
}
.
\prop_get:NnNTF \g_milo_hypcounter_prop { #1 } \l_tmpa_tl
{
\prop_gput:Nnx \g_milo_hypcounter_prop { #1 } { \int_eval:n { \l_tmpa_tl + 1 } }
\prop_item:Nn \g_milo_hypcounter_prop { #1 }
}
{
0
\msg_warning:nnn { milo } { undef } { #1 }
}
}

\NewDocumentEnvironment { impl } { o }
{
\int_gincr:N \g_milo_impl_int
\IfValueT { #1 }
{
\milo_storehypcounter:n { #1 }
}
\textbf{Implication ~ \int_to_arabic:n {\g_milo_impl_int} : }
}{
\par
}

\NewDocumentEnvironment { hypo } { m }
{
\textbf{ Hypothesis ~ \milo_extracthypcounter:n { #1 } }
}{
\par
}

\ExplSyntaxOff

\begin{document}

This is one implication:

\begin{impl}[impl:a]
Hello
\end{impl}

This is another implication:

\begin{impl}[impl:b]
Bye bye
\end{impl}

But then:

\begin{hypo}{impl:a}
Foo a
\end{hypo}

\begin{hypo}{impl:a}
Impl a cont.
\end{hypo}

\begin{hypo}{impl:b}
Foo b
\end{hypo}

\begin{hypo}{impl:a}
Foo a cont.
\end{hypo}

\begin{hypo}{impl:u}
Undefined case.
\end{hypo}

\end{document}


Note the last case is undefined, so produces warnings and zeroes:

Here is a way using something akin to property lists:

\documentclass{article}

\usepackage{xfp}

%% Implications
\newcounter{implcounter}
\newenvironment{impl}{%
\par\noindent
\refstepcounter{implcounter}%
\textbf{Implication \theimplcounter:}%
}{\par}

%% Hypotheses
\makeatletter
\newenvironment{hypo}[1]{%
\par\noindent
\ifcsname c@impl@#1\endcsname\else
\@namedef{c@impl@#1}{0}% First hypothesis for implication #1
\fi
\begingroup\edef\x{\endgroup
\noexpand\global\noexpand\@namedef{c@impl@#1}{\noexpand\fpeval{\csname c@impl@#1\endcsname+1}}}\x% Increment hypothesis
\textbf{Hypothesis \ref{#1}.\csname c@impl@#1\endcsname:}%
}{\par}
\makeatother

\begin{document}

This is one implication:

\begin{impl} \label{impl:a}
Hello
\end{impl}

This is another implication:

\begin{impl}  \label{impl:b}
Bye bye
\end{impl}

But then:

\begin{hypo}{impl:a}
Foo a
\end{hypo}

\begin{hypo}{impl:a}
Impl a cont.
\end{hypo}

\begin{hypo}{impl:b}
Foo b
\end{hypo}

\begin{hypo}{impl:a}
Foo a cont.
\end{hypo}

\end{document}


An expl3 way by storing the number of hypo calls for a specific label in an expl3 \prop list.

It does not check whether the label is valid, however.

Just define the label, say, \label{foo} as usual and say \begin{hypo}{foo}...\end{hypo}.

This can be done at any time in the document, even before the relevant implication has been defined, the first compilation run will give ?? and some warnings about the undefined references, however then.

\documentclass{article}
\usepackage{amsmath}

\usepackage{xparse}

\makeatletter
\ExplSyntaxOn

\prop_new:N \g_milo_hypcounter_prop% The global prop list

\cs_new:Npn \storehypcounter#1 {
% Test if the label #1 is contained already, if so, increase the current number by one
\prop_if_in:NnTF  \g_milo_hypcounter_prop  {#1}  {
\prop_gput:Nnx \g_milo_hypcounter_prop {#1} {\int_eval:n {\prop_item:Nn \g_milo_hypcounter_prop {#1} +1}}
}{
% First call, set the per label - specific counting value to 1
\prop_gput:Nnn \g_milo_hypcounter_prop {#1} {1}
}
}

\cs_new:Npn \extracthypcounter#1 {%
% Extract the current value of the property (i.e. the label #1)
\prop_item:Nn \g_milo_hypcounter_prop {#1}
}

\ExplSyntaxOff
\makeatother

\usepackage{refcount}
%% Implications
\newcounter{implcounter}
\newenvironment{impl}{%
\refstepcounter{implcounter}
\textbf{Implication \theimplcounter:}
}{\par}

%% Hypotheses
\newenvironment{hypo}[1]{%
\storehypcounter{#1}%
\textbf{Hypothesis  \ref{#1}.\extracthypcounter{#1}}
}{\par}

\begin{document}

This is one implication:

\begin{impl} \label{impl:a}
Hello
\end{impl}

This is another implication:

\begin{impl}  \label{impl:b}
Bye bye
\end{impl}

But then:

\begin{hypo}{impl:a}
Foo a
\end{hypo}

\begin{hypo}{impl:a}
Impl a cont.
\end{hypo}

\begin{hypo}{impl:b}
Foo b
\end{hypo}

\begin{hypo}{impl:a}
Foo a cont.
\end{hypo}

\end{document}


• @Milo: You're welcome. Happy TeXing – user31729 Jun 16 '17 at 0:42
• Shouldn't you be using \NewDocumentCommand to wrap the expl3 functions? And \cs_new_protected_nopar works fine here. – cfr Jun 16 '17 at 1:45
• @cfr: Actually, it was a preliminary test solution that works as well. – user31729 Jun 16 '17 at 6:46
• @Milo: Please unaccept my answer -- I want to delete it which is impossible as long as it is the accepted answer. – user31729 Jun 16 '17 at 19:24
• @ChristianHupfer Already unaccepted – Milo Jun 17 '17 at 0:57

For some reason the question Reference to a counter was marked as a duplicate of this one.

There you can read:

Certainly a stupid question. I have a newcounter defined normaly, that is

\newcounter{sharc}


How can I call a specific value of this counter with a command like label/ref ?

Exemple

blabla  \thesharc  blala
blabla  \thesharc  blabla
blabla  \thesharc  blabla <- I want to refer to this value
blabla  \thesharc  blabla


Seems finding questions marked as duplicate and answers to them is not easy in StackExchange. Therefore I post my answer to that question here as well:

What do you mean by "refer to a value"?

Do you wish to obtain only the plain counter value in arabic numerals even if the counter in question is subordinated to whatsoever other counters and thus \the<counter> is defined to prepend whatsoever prefix and apply whatsoever formatting when printing the value?

What about automatic creation of hyperlinks in case of using the hyperref-package?

Be that as it may.

For obtaining only the plain value in arabic numerals of the last counter that was incremented via \refstepcounter, Heiko Oberdiek's zref package might be of interest.
(Within almost all the sectioning commands of documentclasses for LaTeX, \refstepcounter is used for stepping counters. That's because \refstepcounter is the macro which makes values of counters available to the \label..\ref-mechanism.)

For obtaining the expansion of \the<counter> without hyperlinks in situations where the hyperref bundle/package is in use, Heiko Oberdiek's refcount package might be of interest.

(The example below requires to be compiled at least twice/requires at least two LaTeX-runs between which auxiliary files are not deleted.)

\documentclass[a4paper]{article}

% --- Layout of MWE.Has nothing to do with
%     referencing-techniques.
\setlength\textwidth{\paperwidth}
\setlength\oddsidemargin{1.5cm}
\setlength\marginparwidth{\oddsidemargin}
\addtolength\marginparwidth{-2\marginparsep}%
\setlength\topmargin{\oddsidemargin}
\addtolength\textwidth{-1.5\oddsidemargin}
\addtolength\oddsidemargin{-1in}
\addtolength\oddsidemargin{-\hoffset}
\setlength\evensidemargin{\oddsidemargin}
\setlength\textheight\paperheight
\setlength\footnotesep{.333\topmargin}
\addtolength\textheight{-2\topmargin}
\addtolength\topmargin{-1in}
\addtolength\topmargin{-\voffset}
\setlength\headheight{0ex}
\setlength\headsep{0ex}
\pagestyle{empty}
\parindent=0ex
\parskip=.85\ht\strutbox
\topskip=0ex
% --- Layout done. ---

\usepackage{hyperref}
\usepackage[counter,user]{zref}
\usepackage{refcount}
\makeatletter
%% This will establish a new zref-property holding just the
%% plain value of the counter that was \refstep'ped as the
%% last one in arabic numerals:
%% (\refstepcounter is used internally by all the
%%   sectioning-commands of LaTeX-documentclasses.)
\zref@newprop{MyPlainCntValue}{\the\value{\zref@getcurrent{counter}}}%
%
%% This will place both a normal label and a zref-label.
%% The zref-label will store the value of the new property.
%% Both kinds of labels are needed as zref does not yet
%% have hyperref-features.
\newcommand\Mylabel[1]{%
\zref@labelbyprops{#1}{MyPlainCntValue}%
\label{#1}%
}%
%
%% This is used for referencing saved MyPlainCntValue-property-values
%% of zref-labels:
\newcommand\MyPlainCntValueRef[1]{%
\zref[MyPlainCntValue]{#1}%
}%
\makeatother

\newcounter{sharc}[section]
\renewcommand\thesharc{\thesection.\arabic{sharc}}

\begin{document}

\section{Within the preamble define the label-placement- and
referencing-macros for referencing the plain values
of counters in arabic numerals.}
\begin{verbatim}
\usepackage{hyperref}
\usepackage[counter,user]{zref}
\usepackage{refcount}
\makeatletter
%% This will establish a new zref-property holding just the
%% plain value of the counter that was \refstep'ped as the
%% last one in arabic numerals:
%% (\refstepcounter is used internally by all the
%%   sectioning-commands of LaTeX-documentclasses.)
\zref@newprop{MyPlainCntValue}{\the\value{\zref@getcurrent{counter}}}%
%
%% This will place both a normal label and a zref-label.
%% The zref-label will store the value of the new property.
%% Both kinds of labels are needed as zref does not yet
%% have hyperref-features.
\newcommand\Mylabel[1]{%
\zref@labelbyprops{#1}{MyPlainCntValue}%
\label{#1}%
}%
%
%% This is used for referencing saved MyPlainCntValue-property-values
%% of zref-labels:
\newcommand\MyPlainCntValueRef[1]{%
\zref[MyPlainCntValue]{#1}%
}%
\makeatother
\end{verbatim}

\section{Define the \texorpdfstring\texttt\empty{sharc}-counter
and just for fun bind it to the
\texorpdfstring\texttt\empty{section}-counter}
\begin{verbatim}
\newcounter{sharc}[section]
\renewcommand\thesharc{\thesection.\arabic{sharc}}
\end{verbatim}

\section{Within the document-environment step the
\texorpdfstring\texttt\empty{sharc}-counter via
\texorpdfstring{\protect\newline}\empty
\texorpdfstring{\texttt{\string\refstepcounter}}%
{\textbackslash refstepcounter},
and via
\texorpdfstring{\texttt{\string\Mylabel}}%
{\textbackslash Mylabel}
place the referencing-labels.}%
(\verb|\refstepcounter| is used internally by all the
sectioning-commands of \LaTeX-documentclasses.)

\verb|blabla \refstepcounter{sharc}\thesharc\ blabla|:\\
blabla \refstepcounter{sharc}\thesharc\ blabla

\verb|blabla \refstepcounter{sharc}\thesharc\ blabla|:\\
blabla \refstepcounter{sharc}\thesharc\ blabla

\verb|blabla \refstepcounter{sharc}\thesharc\Mylabel{INeedReferenceToThis} blabla|:\\
blabla \refstepcounter{sharc}\thesharc\Mylabel{INeedReferenceToThis} blabla
\\\emph{(This is to be referenced/linked. Therefore the}
\verb|\Mylabel|\emph{-command was used for placing both a
normal label and a} \textsf{\textbf{zref}}\emph{-label.
For testing the links view the resulting pdf at a
magnification/zoom-factor where scrolling within the window
where the pdf is displayed is needed.)}

\verb|blabla \refstepcounter{sharc}\thesharc\ blabla|:\\
blabla \refstepcounter{sharc}\thesharc\ blabla

\newpage
\section{Referencing the label}%

\verb|\ref{INeedReferenceToThis}|

yields:

\ref{INeedReferenceToThis}

{(\verb|\ref| comes from the \LaTeXe-kernel but may be
redefined by some package. This produces the number with all
prefixes from other counters. When using the
\textsf{\textbf{hyperref}}-bundle, this also does
produce a hyperlink to the anchor automatically produced by
\verb|\refstepcounter|.)}

\hrulefill

\verb|\makeatletter|\\
\verb|\getrefbykeydefault{INeedReferenceToThis}%|\\
\verb|                   {}%|\\
\verb|                   {\refused{INeedReferenceToThis}\nfss@text{\reset@font\bfseries??}}%|\\
\verb|\makeatother|

yields:

\makeatletter
\getrefbykeydefault{INeedReferenceToThis}%
{}%
{\refused{INeedReferenceToThis}\nfss@text{\reset@font\bfseries??}}%
\makeatother

{(\verb|\getrefbykeydefault| comes from the
\textsf{\textbf{refcount}}-package. This produces the number
with all prefixes from other counters. Even when using the
\textsf{\textbf{hyperref}}-bundle, this does not produce a
hyperlink to the anchor automatically produced by
\verb|\refstepcounter|.)}

\hrulefill

\verb|\MyPlainCntValueRef{INeedReferenceToThis}|

yields:

\MyPlainCntValueRef{INeedReferenceToThis}

{(\verb|\MyPlainCntValueRef| is defined by
means of macros from the \textsf{\textbf{zref}}-package.
This produces just the plain number in arabic numerals without
any prefixes from other counters. Even when using the
\textsf{\textbf{hyperref}}-bundle, this does not produce
a hyperlink to the anchor automatically produced by
\verb|\refstepcounter|.)}

\hrulefill

\verb|\hyperref[INeedReferenceToThis]{\MyPlainCntValueRef{INeedReferenceToThis}}|

yields:

\hyperref[INeedReferenceToThis]{\MyPlainCntValueRef{INeedReferenceToThis}}

{\sloppy(\verb|\hyperref| comes from the
\textsf{\textbf{hyperref}}-bundle. Therefore this only works
when the \textsf{\textbf{hyperref}}-bundle is loaded.
\verb|\MyPlainCntValueRef| is defined by means of macros
from the \textsf{\textbf{zref}}-package. This produces just
the plain number in arabic numerals without any prefixes from
other counters. This does also produce a hyperlink to the
anchor automatically produced by
\verb|\refstepcounter|.)

}
\hrulefill

In expansion contexts you can use \textsf{\textbf{zref}}'s \verb|\zref@extractdefault|
for obtaining just the plain number - here the plain number delivered by
\verb|\zref@extractdefault| will be used by \verb|\romannumeral| for delivering
roman numerals instead of arabic numerals:

\verb|\makeatletter|\\
\verb|\expandafter\@firstofone|\\
\verb|\expandafter{%|\\
\verb|  \romannumeral|\\
\verb|  \zref@extractdefault{INeedReferenceToThis}%|\\
\verb|                      {MyPlainCntValue}%|\\
\verb|                      {0 \zref@refused{INeedReferenceToThis}\nfss@text{\reset@font\bfseries??}}%|\\
\verb|}%|\\
\verb|\makeatother|

yields:

\makeatletter
\expandafter\@firstofone
\expandafter{%
\romannumeral
\zref@extractdefault{INeedReferenceToThis}%
{MyPlainCntValue}%
{0 \zref@refused{INeedReferenceToThis}\nfss@text{\reset@font\bfseries??}}%
}%
\makeatother

\end{document}