I'm not an expert on TeX and I've run into a problem. I've been able to condense it into the following minimal working (or rather not working) example:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amssymb}
\makeatletter
\newcommand{\E}{
\@ifnextchar[{\Ea}{\mathbb{E}}
}
\newcommand{\Ea}[1][]{
\@ifnextchar\bgroup{\Eb{#1}}{\mathbb{E}\left[#1\right]}
}
\newcommand{\Eb}[2]{
\mathbb{E}\left[#1\,\middle|\, #2\right]
}
\makeatother
\begin{document}
\begin{equation}
\E[\E[X]{Y}]{Y}=\E[X]{Y}
\end{equation*}
\end{document}
I want this command \E to be usable as just \mathbb{E}. I want the first optional argument to be in square brackets and the second (even more optional) argument to be in curly brackets. I don't quite understand, why the above example doesn't work. I get the error "Missing delimiter (. inserted)." and the output looks like:
E[E[X|Y]]Y=E[X|Y]
where it is supposed to look like this
E[E[X|Y]|Y]=E[X|Y]
I also had some problems passing
\E[X_{n+1}]{X_1,\dots,X_n}
where I could identify \dots as the problem. This was fixable (why, I don't entirely understand) by writing
\newcommand{\Eb}[2]{
\mathbb{E}\left[\nonexpanded{#1\,\middle|\, #2\right}]
}
However, this also doesn't solve the nesting-issue. I'm completely lost at this point, as to what is happening. Is there some way to solve this?

gtype for optional{}arguments.gis deprecated and not supported built in format version of xparse as it breaks all latex syntax conventions. – David Carlisle Nov 07 '21 at 15:23