2010-01-27 94 views
35

我試圖寫一個簡單的示例命令,沒有參數,但沒有打印任何東西,但它與它圍繞它的東西。LaTeX newcommand默認參數:是空的嗎?

我讀過的默認值應該是\@empty和簡單\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。一個想法?

回答

40

嘗試使用以下測試:

\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 package提供\ifthenelse構建體和\isempty測試。

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

+0

作品很有魅力,謝謝! :) – kolypto

8

在用LaTeX編寫的底層TeX引擎中,命令可以採用的參數數量是固定的。你使用默認[\@empty]所做的事情是要求LaTeX檢查下一個標記,看它是否是一個空心方括號[。如果是這樣,LaTeX將方括號的內容作爲參數,否則,下一個標記將放回到輸入流中,並使用默認的\@empty參數。所以,讓你的想法來工作,你必須使用括號來界定的可選參數時存在:

\optarg 
\optarg[] 
\optarg[test] 

你應該有這種表示更好的運氣。

令人討厭的是,您不能爲可選參數使用相同的括號,因爲您用於必需的參數,但事實就是如此。

+0

哇,謝謝!從來沒有想過括號是如此重要。然而,問題仍然存在:'\ optarg'仍然給我'(((空)))'和'\ optarg [] =((()))(afaik這不應該工作)。按照預期,只有'\ optarg [test]'現在是'(((test)))'。 – kolypto

+1

嘗試'\ ifx!#!\ else(((#1)))\ fi'並設置默認的arg'!'。如果這樣做的話,你可以將'!'改成某人不太可能偶然使用的東西。 –

11

使用LaTeX3 xparse包:

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

謝謝,這也適用,但設計用於包AFAIK。 – kolypto

+1

xparse的目的是爲\ newcommand提供一個完整的替代方案。在文檔的序言中沒有理由不能使用它作爲一次性命令:我當然會這麼做(但是我確實編寫了當前大部分xparse的實現,儘管我強調這些想法不是真的是我的)。文檔中的示例主要是關於當前的軟件包,但我已經爲下一個有「文檔」用途的問題編寫了TUGBoat文章。 –

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