Mathtools: using substack to align limits

I want to align the limits of a sequence at the equal sign but have an optional modifier before the substack. When I add this optional modifier, the limits are distorted since the modifier is placed in the middle. If I remover it, the limits are okay.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
Distortion
$\sum_{k:\substack{ \mathllap{X(S_k)} = \mathrlap{x_i,}\\ \mathllap{Y(S_k)} = \mathrlap{y_j}}$
Okay
$\sum_{\substack{ \mathllap{X(S_k)} = \mathrlap{x_i,}\\ \mathllap{Y(S_k)} = \mathrlap{y_j}}$
\end{document}

Without k With k You could just use the aligned environment to do the alignment: Notes:

• The difference in the first two is where the k: is located.
• There must be a better way to enforce \scriptstyle.

Code:

\documentclass{article}
\usepackage{mathtools}
\begin{document}
Ok?
S_1 = \sum_{\mathclap{k:~\substack{\setlength{\jot}{-0.8\baselineskip}\everymath{\scriptstyle}\begin{aligned} X(S_k) &\scriptstyle= x_i,\\ Y(S_k) &\scriptstyle= y_j, \end{aligned} }}} x_i + y_i \quad\text{or } S_1 = \sum_{\mathclap{\substack{\setlength{\jot}{-0.8\baselineskip}\everymath{\scriptstyle}\begin{aligned} k:~ X(S_k) &\scriptstyle= x_i,\\ Y(S_k) &\scriptstyle= y_j, \end{aligned} }}} x_i + y_i
Okay
S_2 = \sum_{\mathclap{\substack{\setlength{\jot}{-0.8\baselineskip}\begin{aligned} X(S_k) &\scriptstyle= x_i,\\ Y(S_k) &\scriptstyle= y_j, \end{aligned} }}} x_i + y_i
\end{document}

A variant of my answer to Align in Substack

\documentclass{article}
\usepackage{mathtools}

\makeatletter
\newcommand{\subalign}[c]{%
\if#1c\vcenter\else\vtop\fi{%
\Let@ \restore@math@cr \default@tag
\baselineskip\fontdimen10 \scriptfont\tw@
\lineskip\thr@@\fontdimen8 \scriptfont\thr@@
\lineskiplimit\lineskip
\ialign{\hfil$\m@th\scriptstyle##$&$\m@th\scriptstyle{}##$\hfil\crcr
#2\crcr
}%
}%
}
\makeatother

\begin{document}

\sum_{\mathclap{ k:\;\subalign[t]{ X(S_k) &= x_i,\\ Y(S_k) &= y_j} }}f(k)+g(k)+h(k) \qquad \sum_{\mathclap{ k:\;\subalign{ X(S_k) &= x_i,\\ Y(S_k) &= y_j} }}f(k)+g(k)+h(k)
\end{document}

The \subalign command has an optional argument, which can be t or c (default c) for setting the vertical alignment. As far as I understand the following correction will be sufficient:

\documentclass{article}
\usepackage{mathtools}
\begin{document}
Distortion
$\sum_{k:\substack{ \mathllap{X(S_k)} = \mathrlap{x_i,}\\ \mathllap{Y(S_k)} = \mathrlap{y_j,}} } % closing - PS$

Distortion corrected
$\sum_{k:\ \substack{ {X(S_k)} = \mathrlap{x_i,}\\ {Y(S_k)} = \mathrlap{y_j,}} } % closing - PS$

\end{document} • My document doesn't change when I put k:\ \substack{} Oct 10 '14 at 17:30
• @dustin Please observe the additional closing }'s in my solution. Oct 10 '14 at 18:27