I am trying to make a reference-able environment with its own counter, that I later refer to in text. I want the counter of my environment to have the style Chapter.Number . I have been able to make it work within a new environment and a new counter with this code (MWE in the end of the question):
\newcounter{code}[chapter]
\definecolor{bg}{rgb}{0.975,0.95,1.0}
\newenvironment{code}[3][hbp]
{\VerbatimEnvironment \refstepcounter{code}
\begin{listing}[#1]
\label{#3}
\textbf{Code~\arabic{chapter}.\arabic{code}} #2
\centering
\begin{minted}[bgcolor =bg, frame=lines,framesep=2mm,linenos]{julia}}
{\end{minted}\end{listing}}
(notice the maybe incorrect use of \label)
In my document I use the environment like so:
It is possible to compute this histogram with a naive approach.
This is shown in Code~\ref{code1}.
A much smarter approach is instead presented in Code~\ref{code2}.
\begin{code}{Naive calculation}{code1}
function naivehist(data, ε)
Δ += sin(ε) # lalala
m = rand(1000,1000)
end
\end{code}
Everything seems to work nicely, except when referencing the code blocks:
I suspect that my usage of \label inside my custom environment is probably incorrect. What is the way to do this, so that when using \ref{...} I would correctly get the number 2.1 instead of 1?
MWE
\documentclass{book}
\usepackage[utf8]{inputenc}
\usepackage{minted} % for making code snippets
\usepackage{amsmath}
\begin{document}
\chapter{Title of chapter.}
\newcounter{code}[chapter]
\definecolor{bg}{rgb}{0.975,0.95,1.0}
\newenvironment{code}[3][hbp]
{\VerbatimEnvironment \refstepcounter{code}
\begin{listing}[#1]
\label{#3}
\textbf{Code~\arabic{chapter}.\arabic{code}} #2
\centering
\begin{minted}[bgcolor =bg, frame=lines,framesep=2mm,linenos]{julia}}
{\end{minted}\end{listing}}
the histogram equation:
\begin{equation}
\label{eq1}
p = \sum p_i + \int_0^1 \omega d\epsilon
\end{equation}
It is possible to compute this histogram with a naive approach. This is shown in Code~\ref{code1}.
\begin{code}{Naive, memory-inefficient calculation of eq.~\eqref{eq1}.}{code1}
function naivehist(data, a)
x += sin(a) # lalala
m = rand(1000,1000)
end
\end{code}
\end{document}

