Problem: I want to create an environment named Example, and the environment has a counter (number within chapter). I want to refer to the counter for illustration just as the table, figure and equation environment.
When using \newenvironment
, the command \refstepcounter
works. However, since the new environment includes a TikZ code, I can not use \newenvironment
to create the environment.
Alternatively, I used environ package. The only problem is that the cross-reference of the counter doesn't work, even though I use \refstepcounter
in my customized environment.
Example Minimal Example is given as follows:
\documentclass{book}
\usepackage{lipsum}
\usepackage{mathpazo}
\newcounter{exam}[chapter]
\setcounter{exam}{0}
\renewcommand{\theexam}{\thechapter.\arabic{exam}}
% % Method 1
% \newenvironment{example}[1][]{\refstepcounter{exam}\par\medskip\noindent%
% \textbf{Example \theexam~ #1} \rmfamily}{\medskip}
% Method 2
\usepackage{environ,tikz}
\tikzstyle{title}=[right=10pt,fill=gray,text=green!50]
\tikzstyle{context}=[thick,rectangle,draw=gray,inner sep=10pt, inner ysep=10pt]
\NewEnviron{example}[1][{}]{%
\par\noindent\centering
\begin{tikzpicture}
\node[context](box){
\begin{minipage}{0.93\textwidth}
\BODY
\end{minipage}};
\node[title] at (box.north west){
\refstepcounter{exam}\par\medskip\noindent \textbf{Example \theexam~ #1}};
\end{tikzpicture}}
\begin{document}
\setcounter{chapter}{2}
\begin{example}[First]\label{exam:1}
\lipsum[4]
\end{example}
\lipsum[2]
\begin{example}[Second]\label{exam:2}
\lipsum[5]
\end{example}
Example ~\ref{exam:1} and ~\ref{exam:2} are the new environments!
\end{document}
Method 1 works, but method 2 does not work. How can I make it work?
Additional information: if possible I would try to not use ntheorem or tcolorbox.
Thank you!