This code compiles correctly as long as I don't put spaces around arguments #3 and #4 in the definition of \vec. I can't find anything about this in the xparse documentation, and I have been under the impression that spaces in such places are the preferred style in LaTeX3 so I'd like to know why this happens. I have a feeling it may be trivial, but I'm not seeing it.
My MWE (contains code originally by @egreg):
\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}
\usepackage{esvect}
% A smarter \vec command.
% Why doesn't it work when I put spaces around #3 or #4?
\RenewDocumentCommand{\vec}{ s m e{_^} }{%
\ensuremath{%
\IfBooleanTF {#1}
{\vv{#2}}
{\boldsymbol{#2}}
_{\IfValueT{#3}{#3}\vphantom{\smash[b]{|}}}
^{\IfValueT{#4}{#4}\vphantom{\smash[t]{\big|}}}
}%
}%
\begin{document}
[
\vec{E}{\textup{ball}}
\qquad
\vec{E}{{\textup{ball}}}
]
[
\vec{p}{\textup{ball}}
\qquad
\vec{p}{{\textup{ball}}}
\qquad
]
[
\vec{F}
\qquad
\vec{F}{\textup{proton}}
\qquad
\vec{F}^{\textup{elec}}
\qquad
\vec{F}^{\textup{elec}}{\textup{proton}}
\qquad
\vec{F}{\textup{proton}}^{\textup{elec}}
]
[
\vec{F}
\qquad
\vec{F}{21}
\qquad
\vec{F}{21}^{\textup{contact}}
\qquad
\vec{F}{\textup{table on ball}}^{\textup{contact}}
\qquad
\vec{F}^{\textup{contact}}_{\textup{table on ball}}
]
\end{document}
Here is the result without the spaces in question:
And here is the result WITH the spaces in question:


\IfValueT{ #3 }{<true code>}, then you need to surround definition of\vecin between\ExplSyntaxOnand\ExplSyntaxOffpair. You can find the documentation of them in manual ofexpl3. – muzimuzhi Z Jul 23 '20 at 02:59\dnisn't defined. I'll just do without the spaces for now. – LaTeXereXeTaL Jul 23 '20 at 04:01\ExplSyntaxOnchanges the category code of_, hence the_used in definition of\vebin between\ExplSyntaxOnand...Offnow has catcode 11 (letter) while the_used in document has its normal catcode 8 (subscript). This makes\vecexpecting a_(letter) but actually_(subscript) is met. – muzimuzhi Z Jul 23 '20 at 05:24\textis the wrong command to use to make those -scripts upright.\textdoes not do what you think it does (it will be italic if the text outside math is italic, not what you wanted). In this case\textupis probably better. Sadly we see a lot of people misusing\textlike this. You should only use it for textual comments in displayed math. This is not a comment but a textual sup-/superscript – daleif Jul 23 '20 at 06:31\textis the wrong choice here as it does not do what people expect. In some context textup is a good replacement some mention textnormal – daleif Aug 14 '20 at 16:52