簡體   English   中英

LaTeX \ newcommand默認參數:是空的?

[英]LaTeX \newcommand default argument: is empty?

我正在嘗試編寫一個簡單的示例命令,在沒有參數的情況下打印任何內容,但是使用參數將其包圍起來。

我已經讀過默認值應該是\\@empty而simple \\ifx\\@empty#1條件應該可以完成這項工作:

\newcommand{\optarg}[1][\@empty]{%
\ifx\@empty#1  {}  \else  {(((#1)))}  \fi
}

\optarg % (((empty)))
\optarg{} % (((empty)))
\optarg{test} % (((empty))) test

后三個命令都出於某種原因打印empty字,我希望前兩個打印沒有,最后打印(((test)))

我正在使用TeXLive / Ubuntu。 一個想法?

嘗試以下測試:

\documentclass{article}

\usepackage{xifthen}% provides \isempty test

\newcommand{\optarg}[1][]{%
  \ifthenelse{\isempty{#1}}%
    {}% if #1 is empty
    {(((#1)))}% if #1 is not empty
}

\begin{document}

Testing \verb|\optarg|: \optarg% prints nothing

Testing \verb|\optarg[]|: \optarg[]% prints nothing

Testing \verb|\optarg[test]|: \optarg[test]% prints (((test)))

\end{document}

xifthen提供了\\ifthenelse結構和\\isempty測試。

另一個選擇是使用ifmtarg包(請參閱ifmtarg.sty文件以獲取文檔)。

使用LaTeX3 xparse包:

\usepackage{xparse}
\NewDocumentCommand\optarg{g}{%
  \IfNoValueF{#1}{(((#1)))}%
}

在用於編寫LaTeX的底層TeX引擎中,命令可以采用的參數數量是固定的。 您使用默認[\\@empty]所做的是要求LaTeX檢查下一個標記,看它是否是一個開放的方括號[ 如果是這樣,LaTeX將方括號的內容作為參數,如果不是,則將下一個標記放回到輸入流中,而使用默認的\\@empty參數。 因此,為了讓您的想法發揮作用,您必須使用括號來界定可選參數(如果存在):

\optarg
\optarg[]
\optarg[test]

你應該用這種表示法獲得更好的運氣。

令人討厭的是,您不能使用相同的括號作為可選參數,因為您使用了必需的參數,但這就是它的方式。

\documentclass{article}

\usepackage{ifthen} % provides \ifthenelse test  
\usepackage{xifthen} % provides \isempty test

\newcommand{\inlinenote}[2][]{%
    {\bfseries{Note:}}%  
    \ifthenelse{\isempty{#1}}  
            {#2}               % if no title option given
            {~\emph{#1} #2}    % if title given
}

\begin{document}

\inlinenote{
    simple note
}

\inlinenote[the title]{
    simple note with title
}

\end{document}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM