Programming

LaTeX 옵션 인수

procodes 2020. 7. 18. 23:11
반응형

LaTeX 옵션 인수


LaTeX에서 선택적 인수를 사용하여 명령을 작성하는 방법 다음과 같은 것 :

\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 프로그래밍을 사용하면 상당히 지루할 수 있습니다 (아직 어렵지는 않지만). LaTeX \@ifnextchar는 그러한 것들에 매우 유용합니다.

귀하의 질문에 가장 적합한 답변은 새 xparse패키지 를 사용하는 것 입니다. LaTeX3 프로그래밍 제품군의 일부이며, 임의의 선택적 인수로 명령을 정의하기위한 광범위한 기능을 포함합니다.

귀하의 예 \sec에서 하나 또는 두 개의 괄호 인수를 취하는 매크로가 있습니다. 이것은 xparse다음을 사용하여 구현됩니다 .

\ documentclass {article}
\ usepackage {xparse}
\ begin {document}
\ DeclareDocumentCommand \ sec {mg} {%
    {#1%
        \ IfNoValueF {# 2} {및 # 2} %
    } %
}
(\ sec {Hello})
(\ sec {Hello} {Hi})
\ end {문서}

이 인수 { m g }\sec; 의 인수를 정의합니다 . m"필수 인수"를 의미하고 g"선택적 중괄호"입니다. \IfNoValue(T)(F)그런 다음 두 번째 인수가 실제로 존재하는지 여부를 확인하는 데 사용할 수 있습니다. 허용되는 다른 유형의 선택적 인수에 대해서는 설명서를 참조하십시오.


All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

글쎄, 최근 (유연하지는 않지만) 최근의 개발을 추가하기 위해 논문 문서에서 최근에 사용한 내용은 다음과 같습니다.

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

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

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

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...


All you need is the following:

\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

I had a similar problem, when I wanted to create a command, \dx, to abbreviate \;\mathrm{d}x (i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.

\usepackage{ifthen}

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

Then

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

gives \dx with optional argument


Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.

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

참고URL : https://stackoverflow.com/questions/1812214/latex-optional-arguments

반응형