문제

라텍스에서 선택적인 인수로 명령을 어떻게 작성합니까? 같은 것 :

\newcommand{\sec}[2][]{
    \section*{#1
        \ifsecondargument
            and #2
        \fi}
    }
}

그런 다음처럼 부를 수 있습니다

\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi
도움이 되었습니까?

해결책

예제 가이드:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

다른 팁

"옵션 인수"를 만들어 낸 일반적인 아이디어는 먼저 토큰 스트림에서 다음에 어떤 캐릭터가 나오는지 감지하기 위해 미리 스캔 한 중간 명령을 정의한 다음 관련 매크로를 삽입하여 인수를 적절하게 처리하는 것입니다. 일반적인 TEX 프로그래밍을 사용하는 것은 매우 지루할 수 있습니다 (어렵지는 않지만). 라텍스 \@ifnextchar 그런 것들에 매우 유용합니다.

질문에 대한 가장 좋은 대답은 새로운 것을 사용하는 것입니다. xparse 패키지. 라텍스 프로그래밍 스위트의 일부이며 임의의 선택적 인수가있는 명령을 정의하기위한 광범위한 기능이 포함되어 있습니다.

당신의 예에서 당신은 a \sec 하나 또는 두 개의 브레이스 논쟁을 취하는 매크로. 이것은 사용하여 구현됩니다 xparse 다음과 함께 :

\documentclass{article}
\usepackage{xparse}
\begin{document}
\DeclareDocumentCommand\sec{ m g }{%
    {#1%
        \IfNoValueF {#2} { and #2}%
    }%
}
(\sec{Hello})
(\sec{Hello}{Hi})
\end{document}

논쟁 거리 { m g } 논쟁을 정의합니다 \sec; m "필수 주장"을 의미합니다 g "옵션 브레이스 인수"입니다. \IfNoValue(T)(F) 그런 다음 두 번째 인수가 실제로 존재했는지 여부를 확인하는 데 사용될 수 있습니다. 허용되는 다른 유형의 선택 인수에 대한 문서를 참조하십시오.

위의 모든 것은 열심히 보여줍니다. 라텍스에서 멋지고 유연한 (또는 과부하가 금지 된) 기능을 만드는 것입니다 !!! (그 텍스 코드는 나에게 그리스어처럼 보입니다)

글쎄요

\usepackage{ifthen}  % provides conditonals...

기본적으로 "옵션"명령을 공백으로 설정 한 명령을 시작하십시오.

\newcommand {\figHoriz} [4] []  {

그런 다음 매크로가 선택적 인수가 비어 있는지 여부에 따라 다르게 임시 변수 temp {}를 설정했습니다. 이것은 통과 된 주장으로 확장 될 수 있습니다.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

그런 다음 두 경우에 temp {} 변수를 사용하여 매크로를 실행합니다. (여기서는 사용자가 지정하지 않은 경우 단락을 긴 캡션과 동일하게 설정합니다).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

이 경우 newCommand {}가 제공하는 단일 "선택적"인수 만 확인합니다. 3 "옵션"Args를 설정하려면 여전히 3 개의 빈 아르를 보내야합니다 ... 예를 들어.

\MyCommand {first arg} {} {} {}

꽤 어리석은 일이지만, 나는 라텍스와 함께 갈 수있는 한입니다. 텍스 코드를보기 시작하면 그렇게 감각적이지는 않습니다. '시도 해보세요 ...

필요한 것은 다음과 같습니다.

\makeatletter
\def\sec#1{\def\tempa{#1}\futurelet\next\sec@i}% Save first argument
\def\sec@i{\ifx\next\bgroup\expandafter\sec@ii\else\expandafter\sec@end\fi}%Check brace
\def\sec@ii#1{\section*{\tempa\ and #1}}%Two args
\def\sec@end{\section*{\tempa}}%Single args
\makeatother

\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi

명령을 만들고 싶을 때 비슷한 문제가있었습니다. \dx, 약식 \;\mathrm{d}x (즉, 적분의 차동 전에 추가 공간을두고 "d"도 똑바로 세워집니다). 그러나 나는 또한 통합 변수를 선택적 인수로 포함시킬 정도로 유연하게 만들고 싶었습니다. 다음 코드를 서문에 넣었습니다.

\usepackage{ifthen}

\newcommand{\dx}[1][]{%
   \ifthenelse{ \equal{#1}{} }
      {\ensuremath{\;\mathrm{d}x}}
      {\ensuremath{\;\mathrm{d}#1}}
}

그 다음에

\begin{document}
   $$\int x\dx$$
   $$\int t\dx[t]$$
\end{document}

주어진 선택적 인수가있는 dx

여기 내 시도가 있습니다. 그래도 사양을 정확히 따르지 않습니다. 완전히 테스트되지 않았으므로 조심하십시오.

\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top