25

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.

5 Answers 5

23
  1. You can't create a \foo{parameter}[optional] command simply; you can, however, create a \foo[optional]{parameter} command with

    \newcommand{\foo}[2][default]{Mandatory: #2; optional: #1}
    

    If you call it as \foo{given}, it will produce Mandatory: given, optional: default; if you call it as \foo[bonus]{given}, it will produce Mandatory: given, optional: bonus. This is probably how you should do it—that will look better with the rest of your LaTeX code. Creating a new environment with optional parameters is done similarly with

    \newenvironment{env}[2][def]{(#1,#2)\begingroup}{\endgroup}
    

    where #1 is again the optional argument; this is again written as \begin{env}[opt]{req}...\end{env}. If you really want a command in the other form, see the end of my answer.

  2. The TeX FAQ has an answer about writing commands with more than one optional argument. There are two options to how to do it. The underlying idea is to define a command which takes an optional argument, and then runs another command which itself takes an optional argument, etc.; the twoopt package encapsulates this.


If you really want a command like \reversed{mandatory}[optional], you can do it like so. First, you define a command which takes a required argument, stores it in a macro, and then forward it onto another command. This second command takes an optional argument, and uses the defined command and the optional argument. Putting this all together, we get

\makeatletter
\newcommand{\reversed}[1]{\def\reversed@required{#1}\reversed@opt}
\newcommand{\reversed@opt}[1][def]{Required: \reversed@required; optional: #1}
\makeatother

You can then use \reversed{mandatory}[optional] or just \reversed{mandatory}, and everything should work.

3
  • 2
    +1 nice summary. A particular issue is if the macro is used incorrectly, with the optional arg being ommitted: "\reversed[optarg]". The error messages will have poor readability with your code: it's worth testing for \reversed@opt being equal to "[" and flagging this as a fatal error if it is. Commented May 26, 2010 at 8:31
  • 1
    Thanks. I'm not sure what I think about checking for [—you're right that it will behave unexpectedly, but it actually has a perfectly well-defined behavior (printing Required: [; optional: def, and then typesetting optarg]). The actual advice I would give is "don't use this technique"—while it's technically possible, it's probably a bad idea. Commented May 26, 2010 at 9:08
  • Thank you very much for your time spent on this issue.
    – Crowley
    Commented Jun 3, 2010 at 11:09
19

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).

1
  • 2
    I'm sorry for late reply, I did't have time to try it. Thanks a lot for sloving my problem with multiple parameters
    – Crowley
    Commented Jun 3, 2010 at 11:10
7

Consider also the xargs package. The following is an example from its documentation.

Set it up in the usual way,

\usepackage{xargs}

and then if you define

\newcommandx*\coord[3][1=1, 3=n]{(#2_{#1},\ldots,#2_{#3})}

(which means to use "1" for the first argument, if it is not specified, and to use "n" for the third). Then

$\coord{x}$

yields (sans subscripts)

(x1, . . . , xn)

and

$\coord[0]{y}$

yields (again, sans subscripts, and y replaces the mandatory parameter)

(y0, ..., yn)

0

I know there are already comprehensive answers, but is some cases, I want to give different definitions for different situations. There is a still very basic yet simple solution for this. I write it down in case any other need it.

% ----------------------------------
%! TEX program = XeLaTeX
% !TeX encoding = UTF-8
% Author:       Troy_Daniel 
% Email:        [email protected]
% ----------------------------------
\documentclass{article}
\usepackage{xcolor}

\newcommand{\Caption}[3]{%
    \textcolor[rgb]{0.36, 0.72, 0.80}{\Large #1}
    {\def\tmp{#3}
    \ifx\tmp\empty                                  % the third parameter is not provieded
        \textcolor[rgb]{0.96, 0.66, 0.35}{\small#2}
    \else                                           % non-empty third parameter
        \textcolor[rgb]{0.96, 0.66, 0.35}{\small[#3]#2}
    \fi}}
\begin{document}

\Caption{First}{Second}{}

\Caption{First}{Second}{Third}

\end{document}

And the result is shown below, different definitions for optional parameter(s): Different definitions for optional parameter(s)

1
  • This doesn't make the third argument optional, since you have to supply an empty {}. Optional means "don't supply anything" usually.
    – Werner
    Commented Dec 31, 2019 at 7:13
-1

Troy Daniel's solution worked perfectly for me. This custom 'example' environment allows to name your examples or not using an optional parameter.

\newcounter{example}[section]
\newenvironment{examplex}[1][]{
\def\optpar{#1}
\refstepcounter{examplex}\par\medskip\noindent\textbf{
    Example~\thesection.\theexample
    \ifx\optpar\empty
    {.}
    \else
    { - }#1.
    \fi
    } 
    \rmfamily
    \begin{adjustwidth}{2em}{0em}}{
    \medskip
    \end{adjustwidth}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.