Search code examples
latex

\newcommand / \newenvironment - optional parameters


I'm experimenting with my own commands and environments and now I'm facing those problems:

  1. How to create command \foo{parameter}[optional] or environment called \begin{bar}{parameter}[optional]?
  2. How to create command \foo[optional_1]...[optional_n]{parameter}

I've tried

\newcommand{\foo}[3][][]{#1#2#3}    - failed
\newcommand{\foo}[3][2][][]{#1#2#3} - failed

Does anyone know some hint? Thanks a lot.


Solution

  • Using the xparse package (part of the LaTeX3 development efforts):

    \usepackage{xparse}
    \NewDocumentCommand\foo{O{}O{}m}{%
      % Code with optional #1 and #2 with empty defaults
    }
    \NewDocumentCommand\foo{mO{}}{%
      % Code with optional #2 with empty default
    }
    \NewDocumentEnvironment{foo}{O{}}{%
    % Start code with optional #1
    }{%
    %  End code with optional #1
    }
    

    Optional arguments are a bit different in xparse to with \newcommand. You can detect whether one is given or not:

    \NewDocumentCommand\foo{mo}{%
      \IfNoValueTF{#2}
       {Code without #2}
       {Code with #2}%
    }
    

    You'll see that this works by using a lower case 'o', whereas the upper case 'O' then requires a default value (which I've made empty by including an empty group).