1

I would like an environment that optionally numbers based on the current section. I currently have:

\newcounter{example}[section]
\newenvironment{example}[1][]{\refstepcounter{example}\par\medskip
   \emph{Example~\theexample. #1} \rmfamily}{\medskip}

But what I would like is:

% In section X.

\begin{example}[1]
foo
\end{example}

\begin{example}[1]
bar
\end{example}

\begin{example}[0]
qux
\end{example}

\begin{example}[1]
wat
\end{example}

which produces

Example X.1: foo
Example X.2: bar
Example: qux
Example X.3: wat

The blocks are ultimately going to be more complex (consistent formatting, etc.) and I'd like to just use one environment. I could also achieve this with two.

1 Answer 1

2

This is a possible way to achieve your requested input:

enter image description here

\documentclass{article}

\newcounter{example}[section]
\renewcommand{\theexample}{\thesection.\arabic{example}}
\newenvironment{example}[1][]{%
  \par\medskip
  \noindent\emph{Example%
    \ifnum#1=0\else
      ~\refstepcounter{example}\theexample
    \fi:} \rmfamily}
    {\medskip}

\begin{document}

\setcounter{section}{6}
\section{A section}

\begin{example}[1]
foo
\end{example}

\begin{example}[1]
bar
\end{example}

\begin{example}[0]
qux
\end{example}

\begin{example}[1]
wat
\end{example}

\end{document}

The typical way this style of numbering works is usually via a theorem-style environment, or using starred versions. Here's an example of the latter:

\documentclass{article}

\newcounter{example}[section]
\renewcommand{\theexample}{\thesection.\arabic{example}}
\newenvironment{example}{%
  \par\medskip
  \refstepcounter{example}%
  \noindent\emph{Example~\theexample:} \rmfamily}
  {\medskip}
\newenvironment{example*}{%
  \par\medskip
  \noindent\emph{Example:} \rmfamily}
  {\medskip}

\begin{document}

\setcounter{section}{6}
\section{A section}

\begin{example}
foo
\end{example}

\begin{example}
bar
\end{example}

\begin{example*}
qux
\end{example*}

\begin{example}
wat
\end{example}

\end{document}

You must log in to answer this question.

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