Search code examples
latextexnewenvironment

Using optional arguments for \newenvironment in Latex


I defined two new environments (nmlist and nmlistf) in Latex as follows. The former creates a list with a title at the first line introduced by \paragraph, and the latter creates a list starting at the first line without any title. How should I modify the former such that, in addition to its own output, it can also be used to create an output like that of the latter? Thank you for your contributions!

Here is the code:

\documentclass[final,3p,times]{elsarticle}
\usepackage{enumitem}

\newenvironment{nmlist}[1]{% list with title
  \paragraph{#1}
  \begin{enumerate}[align=parleft,itemsep=-4pt,labelwidth=20mm,leftmargin=22mm]}
  {\end{enumerate}}

\newenvironment{nmlistf}{% list without title
  \begin{enumerate}[align=parleft,itemsep=-4pt,labelwidth=20mm,leftmargin=22mm]}
  {\end{enumerate}}


\begin{document}

 % With a title at the first line and with a list starting at the second line 
 \begin{nmlist}{Others}
  \item[{$a$}]{distances to x-axis}%
  \item[{$b$}]{distances to y-axis}%
 \end{nmlist}

 % Without a title and with a list starting at the first line
 \begin{nmlistf}
  \item[{$a$}]{distances to x-axis}%
  \item[{$b$}]{distances to y-axis}%
 \end{nmlistf}

\end{document}

Solution

  • Instead of a mandatory argument {...} you could use an optional argument [...] and test if it is empty:

    \documentclass[final,3p,times]{elsarticle}
    \usepackage{enumitem}
    
    \newenvironment{nmlist}[1][]{% list with title
      \ifstrempty{#1}{}{\paragraph{#1}}%
      \begin{enumerate}[align=parleft,itemsep=-4pt,labelwidth=20mm,leftmargin=22mm]}
      {\end{enumerate}}
    
    \begin{document}
    
     % With a title at the first line and with a list starting at the second line 
     \begin{nmlist}[Others]
      \item[{$a$}] distances to x-axis
      \item[{$b$}] distances to y-axis
     \end{nmlist}
    
     % Without a title and with a list starting at the first line
     \begin{nmlist}
      \item[{$a$}] distances to x-axis
      \item[{$b$}] distances to y-axis
     \end{nmlist}
    
    \end{document}
    

    enter image description here