\newcommand: 1つのパラメータを他のパラメータのデフォルトとして使用する

\newcommand: 1つのパラメータを他のパラメータのデフォルトとして使用する

2 つの引数を取るマクロを定義したいと思います。そのうちの 1 つはオプションです。指定されていない場合は、もう 1 つをデフォルト値として使用する必要があります。

残念ながら、

\newcommand{\mycommand}[2][#1]{ ... }

機能しない、機能しない

\newcommand{\mycommand}[2][#2]{ ... }

誰かこれをどうやってやるのか知っていますか?

答え1

良いニュースです: 次のようにすれば簡単にできますxparse:

\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand{\foo}{O{#2}m}{%
  Optional=``#1'', mandatory=``#2''\par
}
\NewDocumentCommand{\oof}{mO{#1}}{%
  Mandatory=``#1'', optional=``#2''\par
}

\begin{document}

\foo{x}

\foo[y]{x}

\oof{x}

\oof{x}[y]

\end{document}

引数指定子は、O{...}呼び出し時に引数自体が表示されない場合に、デフォルトで何を置き換えるかを引数として受け取ります。これは、別の引数を参照するパラメーター トークンである可能性があります。

ここに画像の説明を入力してください

答え2

使用できますxparseオプションの引数が存在するかどうかを簡単に条件付けし、適切な組み合わせを別の(補助)関数に提供します。次に例を示します。

ここに画像の説明を入力してください

\documentclass{article}

\usepackage{xparse}

\newcommand{\printthis}[2]{%
  Optional: #1; Mandatory: #2%
}

\NewDocumentCommand{\mycommand}{o m}{%
  \IfValueTF{#1}
    {\printthis{#1}{#2}}% \mycommand[..]{...}
    {\printthis{#2}{#2}}% \mycommand{...}
}

\begin{document}

\mycommand{first}

\mycommand[first]{second}

\end{document}

これの少し異なるバージョンは、 の使用から生じます\caption。ここでは、LoT/LoF にオプションの引数を指定できますが、指定しない場合は、代わりに必須の引数が送信されます (ToC にオプションの引数が指定されたセクション単位の場合も同様)。これは、カーネル\@dblarg:

\documentclass{article}

\newcommand{\printthis}[2][]{%
  Optional: #1; Mandatory: #2%
}

\makeatletter
\newcommand{\mycommand}{%
  \@dblarg\printthis
}
\makeatother

\begin{document}

\mycommand{first}

\mycommand[first]{second}

\end{document}

答え3

これは、オプションの引数を処理する他のマクロと同様に保護を追加する試みです。

%%\errorcontextlines=1000
\documentclass[a4paper]{article}

\makeatletter
\newcommand\makefirstmandatorytheoptional[1]{%
  \expandafter\innermakefirstmandatorytheoptional
  \expandafter{\csname\string#1\endcsname}{#1}%
}%
\newcommand\innermakefirstmandatorytheoptional[2]{%
  \def#2{%
    \ifx\protect\@typeset@protect
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
    \fi
    {\kernel@ifnextchar[{#1}{\@dblarg{#1}}}%
    {\protect#2}%
  }%
}%
\newcommand\mycommand[2][dummyoptional]{%
  This is taken for the optional argument: #1.\\
  This is taken for the mandatory argument: #2.
}%
\makefirstmandatorytheoptional{\mycommand}%
\makeatother

\parindent=0ex
\parskip=\medskipamount

\begin{document}

No optional argument given---\verb|\mycommand{A}|:

\mycommand{A}

Optional argument "B" given---\verb|\mycommand[B]{A}|:

\mycommand[B]{A}

\end{document}

ここに画像の説明を入力してください

関連情報