\newcommand: 한 매개변수를 다른 매개변수의 기본값으로 사용

\newcommand: 한 매개변수를 다른 매개변수의 기본값으로 사용

두 개의 인수(그 중 하나는 선택 사항)를 사용하는 매크로를 정의하고 싶습니다. 지정되지 않은 경우 다른 값을 기본값으로 사용해야 합니다.

안타깝게도,

\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}

여기에 이미지 설명을 입력하세요

관련 정보