# \mathcal gives different output where it should not

I have multiple occurences of mathcal in my document and they do not use the same style. Consider this MWE:

\documentclass{standalone}

\usepackage{mathtools}

\usepackage{unicode-math}
\setmainfont[Ligatures=TeX]{STIX}

\setmathfont{XITS Math}
\setmathfont[range={\mathcal},StylisticSet=1]{XITS Math}

\begin{document}

$\operatorname{O}$
$\mathcal{S}$
$\text{$P$}$
$\mathcal{S}$

\end{document}


As you can see the two "S" charcters are different, which they should not be.

What have I done wrong?

Versions used:

• XeTeX, Version 3.14159265-2.6-0.99996 (TeX Live 2016)
• mathtools 2015/11/12 v1.18
• amsmath 2016/06/28 v2.15d
• unicode-math 2015/09/24 v0.8c

Loading mathtools after unicode-math solves this problem, but messes up other things. For example \underbrace{X}_{0} then gives:
• Looks okay in texlive 2017. I get the second S in both places. It works in texlive 2016 with unicode-math 2017/01/27 v0.8d too. – Ulrike Fischer Oct 1 '17 at 9:55
This was a bug in unicode-math. See for example https://github.com/wspr/unicode-math/issues/356.