Create an environment with optional arguments

argumentsenvironments

I want to create environments with two optional arguments like that :

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

How can I do that ? I don't find anything on Internet to do that

EDIT : I was thinking about something like that :

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

Best Answer

It's not that clear exactly what you want, as you're using #1 in your example as if that would be used inside the environment, whereas that notation would only be used when defining the environment.

But I understand the situation correctly, at least in your response to gernot, the changes that need to be made will be different depending on each use of the environment.

So one approach is described below. Inside the environment you could use a special command with two alternatives that responds to the options set with the environment. It uses the xstring package for parsing the option, and \NewDocumentEnvironment command newly added to the kernel (see the documentation for the xparse package if need be),

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

options output

Related Question