
我編寫了一個包,它使用\@ifclassloaded{}
命令來處理文檔類,例如,
\RequirePackage{pgffor}
\makeatletter%
\@ifclassloaded{book}
{%
<code block>
}
\makeatother%
\makeatletter%
\@ifclassloaded{article}
{%
<code block>
}
\makeatother%
我想以相同的條件處理report
ormemoir
類,如下所示:book
\makeatletter%
\@ifclassloaded{book}
\else \@ifclassloaded{report}
\else \@ifclassloaded{memoir}
{%
<code block>
}
\makeatother%
但不工作。我怎樣才能實現這個目標?
答案1
您可以使用etoolbox
and 其\ifboolexpr
指令將多種形式的條件組合\<conditional [possibly with additional arguments]>{<true>}{<false>}
為一個。
請注意test
每個條件前面的關鍵字以及它們周圍的大括號。
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\test}{} % just to make sure \test is undefined
\makeatletter
\ifboolexpr{ test {\@ifclassloaded{book}}
or test {\@ifclassloaded{report}}
or test {\@ifclassloaded{memoir}}}
{\def\test{lorem}}
{\def\test{ipsum}}
\makeatother
\begin{document}
\test
\end{document}
在此範例中,您也可以直接測試該命令是否存在\chapter
。根據您想要做什麼,這實際上可能是更好的主意。
這裡我使用了\ifundef
from etoolbox
,這與第一個範例的邏輯相反。 (還有\ifdef
, 但它處理已定義的命令\relax
,這對於此應用程式來說沒有多大用處。)
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\test}{} % just to make sure \test is undefined
\ifundef\chapter
{\def\test{ipsum}}
{\def\test{lorem}}
\begin{document}
\test
\end{document}
答案2
的語法\@ifclassloaded
是
\@ifclassloaded{class}{yes code}{no code}
所以你不需要\else
。這兩個分支都內建在語法中。
你有
\@ifclassloaded{book}
{%
<code block>
}
\makeatother%
所以你的「無程式碼」參數是\makeatother
這樣你只有在該類別不是書的情況下才執行它。
你永遠不應該擁有\makeatletter
或\makeatother
在包代碼中
\RequirePackage{pgffor}
\@ifclassloaded{book}
{%
<code block>
}{%
else code
}
\@ifclassloaded{article}
{%
<code block>
}{%
else code
}
順便說一句,實際上並不建議按名稱檢查類,有數千個類,如果有人通過複製book.cls
和更改一些內容來創建一個類,您的包將不會將其識別為類似書本的類。通常最好測試特定功能,例如\chapter
定義),而不是檢查該類別是否被呼叫book
。