[Tex/LaTex] Enclose an entry in an enumerate list in parentheses

#enumeratelists

I'd like to enclose one entry of an enumerate list in parentheses, with the opening parenthesis appearing before the index number. I can do this manually by using \item[(3.] Item text), but this requires hard-coding the item number. Is there a way to do this automatically?

\documentclass{article}

\begin{document}
\begin{enumerate}
  \item Really important
  \item Quite important
  \item[(3.] If we have time)
\end{enumerate}
\end{document}

In the answer to Modifying labels on some enumerated items, an approach is suggested for modifying the item label, which gets me quite close to the goal. The opening parenthesis is added and the counter is still automatic. I only need to add the closing parenthesis by hand. Could that be automated as well?

\documentclass{article}

\begin{document}
\newcommand{\parenitem}{\stepcounter{enumi}\item[(\theenumi.]}

\begin{enumerate}
  \item Really important
  \item Quite important
  \parenitem If we have time)
\end{enumerate}
\end{document}

Best Answer

Another attempt, counting the open parentheses.

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newcounter{item@paren@depth}
\newcommand{\insert@item@paren}{%
\ifnum\value{item@paren@depth}>0
\addtocounter{item@paren@depth}{-1}\unskip) %
\fi%
}
\newcommand{\pitem}{%
\@noitemargtrue \item[\llap{(}\@itemlabel ]%
\stepcounter{item@paren@depth}%
}
\pretocmd{\endenumerate}{\insert@item@paren}{\relax}{\relax}
\pretocmd{\item}{\insert@item@paren}{\relax}{\relax}
\makeatother

\begin{document}

\begin{enumerate}
  \item  Really important
  \item  Quite important
  \pitem If we have time
  \item  Whatever it takes
  \begin{enumerate}
    \pitem maybe
    \item definitely
  \end{enumerate}
  \pitem first
  \pitem second

  \pitem third
\end{enumerate}

\end{document}

The result is the following

enter image description here

As shown in the example, empty lines still cause a deserted parenthesis. Right now I have no idea how to fix this.


EDIT (2012-09-16)

Just had time to look into the TeXbook: the end-of-line character \endlinechar can be set to a negative value to ignore empty lines (or actually line breaks). If one includes this in the \pitem macro, the lonesome paren artefact is fixed:

\newcommand{\pitem}{%
\@noitemargtrue \item[\llap{(}\@itemlabel ]%
\stepcounter{item@paren@depth}%
\ifnum\endlinechar>0\endlinechar=-1\fi
}

enter image description here

The behavior will only be activated when the \pitem macro is used and the effect will be limited to the scope of the enumerate environment. Note that explicit line breaks using \newline or \\ ans explicit paragraphs with \par still work.

Related Question