The following answer builds closely on the OP's original code, only adding some low-level TeX code in the preamble to set the width of the hanging indents. Basically, it defines a length variable called \alength
and then sets its value to the width of a "box" filled by "(\theexamplectr)
" (plus a minute fudge factor, determined empirically). The environment example
is instructed to hang-indent all but the first line of its paragraph by the amount of \alength
. Note that the amount of the indent is adjusted automatically as the counter variable switches from 1 to 2, 3, etc digits.
This code is, by design, not as "elegant" as simply setting some of the options of the enumitem
package. In contrast, it has the advantage (IMHO) of not depending on this package and, instead, demonstrating how one may go about achieving the OP's objective by setting the \hangafter
and \hangindent
parameters. :-)
Addendum: I edited the code, following the OP's comment, to allow the possibility that the maximum number of examples is known in advance, so that the bodies of the examples may all be set to the same (hanging) indent. This is implemented by defining a counter
variable named maxexamplectr
; if this variable is greater than zero, its value is taken to be the largest number of any example environment. Conversely, if its value is zero the value of the hang-indent is calculated separately for each label.
\documentclass{article}
\usepackage{lipsum,ifthen}
\newcounter{maxexamplectr} %% largest possible number of examples
\setcounter{maxexamplectr}{1002}
\newcounter{examplectr} %% counter of current example environment
\setcounter{examplectr}{0} %% initialize this counter
\newlength\alength
\makeatletter
% if maxexamplectr>0, calculate \alength only once
\ifthenelse{\themaxexamplectr>0}{
\sbox\@tempboxa{(\themaxexamplectr)\ \ }
\setlength{\alength}{\the\wd\@tempboxa}}{}
\newenvironment{example}{%
\refstepcounter{examplectr}%
\ifthenelse{\themaxexamplectr=0}{% calculate \alength if maxexamplectr=0
\sbox\@tempboxa{(\theexamplectr)\ \ }
\setlength{\alength}{\the\wd\@tempboxa}}{}
% start a "generic list" with a single, numbered item
\begin{list}{{}(\theexamplectr)}%
{\leftmargin\alength
\labelwidth\alength
\topsep0pt}
\ignorespaces\item }
{\unskip \end{list}}
\makeatother
\begin{document}
\noindent
The quick brown fox \ldots
\begin{example}
\lipsum[2]
\end{example}
\setcounter{examplectr}{20}
\begin{example}
\lipsum[2]
\end{example}
\setcounter{examplectr}{1001}
\begin{example}
\lipsum[2]
\end{example}
\noindent
The quick brown fox \ldots
\end{document}