
我想創建具有兩個可選參數的環境,如下所示:
\begin{myenvir}[]
Title
#1
\end{myenvir}
\begin{myenvir}[s]
Titles
#1
\end{myenvir}
\begin{myenvir}[a]
Title (with something)
#1
\end{myenvir}
\begin{myenvir}[sa]
Titles (with something)
#1
\end{myenvir}
我怎樣才能做到這一點 ?我在互聯網上找不到任何東西可以做到這一點
編輯:我正在考慮類似的事情:
% Pseudo-Declaration
\begin{envir}[#1]
if #1 == a:
Title (admis) % or admise but it depends of the envir
elif #1 == s:
Titles
else:
Titles (admis) % or admise
% And then the text
\end{envir}
答案1
目前尚不清楚您想要什麼,因為您#1
在範例中使用的就好像將在環境中使用一樣,而該符號僅在以下情況下使用定義環境。
但我對情況的理解是正確的,至少在你對gernot的回應中,根據每次使用的環境,需要做的改變會有所不同。
因此,下面描述一種方法。在環境內部,您可以使用具有兩個替代選項的特殊命令來回應環境中設定的選項。它使用xstring
套件來解析選項,以及\NewDocumentEnvironment
新添加到核心中的命令(請參閱xparse 套件的文檔如果需要的話),
\documentclass{article}
\usepackage{xstring}% for \IfSubStr command
% set booleans for the options
\newif\ifmysoption
\newif\ifmyaoption
% define commands that respond to the options
\newcommand{\IfAOption}[2]{\ifmyaoption{#1}\else{#2}\fi}
\newcommand{\IfSOption}[2]{\ifmysoption{#1}\else{#2}\fi}
% define environment that sets the values of the booleans
\NewDocumentEnvironment{myenvir}{o}{%
\IfValueTF{#1}{% check if optional argument exists
\IfSubStr{#1}{a}% check if it contains an a
{\myaoptiontrue}% if so, set a option boolean true
{\myaoptionfalse}% if not, set it false
\IfSubStr{#1}{s}% check if it contains an s
{\mysoptiontrue} % if so, set s option boolean true
{\mysoptionfalse} % if not, set it false
}{
% no option given, so both are false
\mysoptionfalse\myaoptionfalse
}
}{%
}
\begin{document}
With no option:
\begin{myenvir}
Title\IfSOption{s}{}\IfAOption{ (Something)}{}
\end{myenvir}
\bigskip
With just ``a'':
\begin{myenvir}[a]
Title\IfSOption{s}{}\IfAOption{ (Something)}{}
\end{myenvir}
\bigskip
With just ``s'':
\begin{myenvir}[s]
Title\IfSOption{s}{}\IfAOption{ (Something)}{}
\end{myenvir}
\bigskip
With both:
\begin{myenvir}[sa]
Title\IfSOption{s}{}\IfAOption{ (Something)}{}
\end{myenvir}
\end{document}
答案2
也許遵循以下幾行(儘管我不確定您#1
在環境的範例使用中的意思)?
對於X
代表選項的每個字母(此處a
和s
),定義一個\OptX
給出預設值的命令(如果未選擇該選項則使用),以及一個\setOptX
重新定義\OptX
為選擇該選項時應表示的任何內容的命令。例如,定義
\newcommand\Opts{}% default value
\newcommand\setOpts{\renewcommand\Opts{s}}
定義一個選項s
,使其\Opts
擴展為s
;如果沒有這個選項,\Opts
就會擴展為空。
選項的處理方式是\processOptions
將一串選項字母作為參數並呼叫相應的\setOpt
命令。
\documentclass{article}
\newcommand\processOptions[1]{\processOptionsX#1\relax}
\newcommand\processOptionsX[1]{%
\ifx\relax#1\relax
\let\tmp\relax
\else
\csname setOpt#1\endcsname
\let\tmp\processOptionsX
\fi
\tmp
}
\newcommand\Opta{}% default value
\newcommand\setOpta{\renewcommand\Opta{ (with something)}}
\newcommand\Opts{}% default value
\newcommand\setOpts{\renewcommand\Opts{s}}
\newenvironment{myenvir}[1][]{%
\processOptions{#1}%
\begin{center}
}{%
\end{center}
}
\begin{document}
\begin{myenvir}
Title\Opts\Opta
\end{myenvir}
\begin{myenvir}[s]
Title\Opts\Opta
\end{myenvir}
\begin{myenvir}[a]
Title\Opts\Opta
\end{myenvir}
\begin{myenvir}[sa]
Title\Opts\Opta
\end{myenvir}
\end{document}