7

I would like to increment a counter every time a particular style is applied. The MWE below compiles just fine, but the counter is not incremented.

enter image description here

I would like to have the counter value be 3 after the tikzpicture.

Code:

\documentclass{article}
\usepackage{tikz}

\newcounter{MyCounter}

\tikzset{My Style/.style={draw=red, .code={\stepcounter{MyCounter}}}}

\begin{document}
\stepcounter{MyCounter}
BEFORE MyCounter=\the\value{MyCounter}

\begin{tikzpicture}
\draw [My Style] (0,0) -- (3,0);
\draw [My Style] (0,0) -- (3,2) -- (4,0);
\end{tikzpicture}

AFTER MyCounter=\the\value{MyCounter}
\end{document}
0

1 Answer 1

14

With My Style/.style={draw=red, .code={\stepcounter{MyCounter}}}, your style My Style defines an unused blank key linked to your code.

You may use :

\tikzset{My Style/.style={draw=red,inc/.code={\stepcounter{MyCounter}},inc}}

to define and use the inc key.

Or you may use .code handler instead of .style handler:

\tikzset{My Style/.code={\stepcounter{MyCounter}\tikzset{draw=red}}}

Or you may use the predefined key /utils/exec:

\documentclass{article}
\usepackage{tikz}

\newcounter{MyCounter}

\tikzset{My Style/.style={draw=red,/utils/exec={\stepcounter{MyCounter}}}}

\begin{document}
\stepcounter{MyCounter}
BEFORE MyCounter=\the\value{MyCounter}

\begin{tikzpicture}
\draw [My Style] (0,0) -- (3,0);
\draw [My Style] (0,0) -- (3,2) -- (4,0);
\end{tikzpicture}

AFTER MyCounter=\the\value{MyCounter}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .