コマンドまたは環境のスター付き/スターなしバージョンのメンテナンスを改善する方法

コマンドまたは環境のスター付き/スターなしバージョンのメンテナンスを改善する方法

私が読んだスター付き/スターなしバージョンのコマンドに関するすべてのドキュメントでは、多かれ少なかれ次のような方法を推奨しています(たとえば、TeX FAQのリスト):

\newcommand{\mycommand}{\@ifstar\mycommandStar\mycommandNoStar}
\newcommand{\mycommandStar}{%
  <few lines of code only for starred mycommand>
  <many lines of code common to starred/non starred mycommand>
}
\newcommand{\mycommandNoStar}{%
  <few lines of code only for non starred mycommand>
  <many lines of code common to starred/non starred mycommand>
}

環境の場合も同様のスキームになります(たとえば、この答え):

\newenvironment{myenvironment}{%
  <few lines of code only for non starred myenvironment>
  <many lines of code common to starred/non starred myenvironment>
}{%
  <few lines of code only for non starred myenvironment>
  <many lines of code common to starred/non starred myenvironment>
}
\newenvironment{myenvironment*}{%
  <few lines of code only for starred myenvironment>
  <many lines of code common to starred/non starred myenvironment>
}{%
  <few lines of code only for starred myenvironment>
  <many lines of code common to starred/non starred myenvironment>
}

しかし、ほとんどの場合、星付きバージョンと星なしバージョンの違いはわずかであり、この方法では 2 つのバージョン間で共通コードのすべての変更をコピーする必要があり、メンテナンスが面倒になります (特に共通コードが長い場合)。

もっと効率的な方法はありますか?

答え1

それは主に、コマンドが何を実行するかによって決まります。 が、開始時にいくつかの異なるコードを実行する必要があるという理由だけ\mycommand*で異なる場合は、次のアプローチが機能するはずです。\mycommand

\newcommand{\mycommand}{\@ifstar{\@tempswatrue\@mycommand}{\@tempswafalse\@mycommand}}
\newcommand{\@mycommand}{%
  \if@tempswa
    <few lines of code only for starred mycommand>
  \else
    <few lines of code only for non starred mycommand>
  \fi
  <many lines of code common to starred/non starred mycommand>
}

これにより、xparse次のことが簡単になります。

\usepackage{xparse}
\NewDocumentCommand{\mycommand}{s}
 {\IfBooleanTF{#1}
    {<few lines of code only for starred mycommand>}
    {<few lines of code only for non starred mycommand>}%
  <many lines of code common to starred/non starred mycommand>%
 }

環境フォームの場合、\@ifstar利用できるものがないため、さらに複雑になります。

\newenvironment{myenvironment}{%
  <few lines of code only for non starred myenvironment>
  \@myenvironmentstart
}{%
  <few lines of code only for non starred myenvironment>
  \@myenvironmentfinish
}
\newenvironment{myenvironment*}{%
  <few lines of code only for starred myenvironment>
  \@myenvironmentstart
}{%
  <few lines of code only for starred myenvironment>
  \@myenvironmentfinish
}

\newcommand{\@myenvironmentstart}{%
  <many lines of code common to starred/non starred myenvironment>
}
\newcommand{\@myenvironmentfinish}{%
  <many lines of code common to starred/non starred myenvironment>
}

では実際の簡略化は不可能ですxparse

答え2

xparseLaTeX3 バンドルの一部であるこのパッケージは、この点で非常に便利です。たとえば、次のようになります。

\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\foo}{s}{This is the \IfBooleanTF{#1}{starred }{}foo command.}
\begin{document}
\foo{}

\foo*{}
\end{document}

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

関連情報