Suppose that I have defined two commands
\newcommand\parens[1]{(\begin{array}[t]{@{}l@{}}#1)\end{array}}
\newcommand\stmts[2]{\begin{array}[t]{@{}l@{}}#1;#2\end{array}}
which attempt to allow for optional linebreaks while keeping the markup semantic. Each of these commands works well on its own. For example, $\parens{X_1 \\ X_2}$ produces
and $\stmts{Y_1}{\\ Y_2}$ produces
.
However, in certain combinations, the two commands don't play nicely together. For example, $\parens{\stmts{Y_1}{\\ Y_2}}$ produces 
Instead, I would want the output to be
, i.e., visually the same as if
$(\begin{array}[t]{@{}l@{}}
\begin{array}[t]{@{}l@{}}
Y_1;
\\ Y_2)
\end{array}
\end{array}$
had been used. Is there any way to accomplish this without requiring the user to manually place the )? In other words, can I redefine \parens and \stmts to give the desired behavior - without changing the user interface of those commands?
I suppose one solution might check if the next token is ) and, if so, commute it with \end{array}. But, in general, I would like a solution that works for all closing delimiters, not just ). Even better would be a solution that works for arbitrary next tokens.
Here is some starter code.
\documentclass{article}
\usepackage{amsmath}
\newcommand\parens[1]{(\begin{array}[t]{@{}l@{}}#1)\end{array}}
\newcommand\stmts[2]{\begin{array}[t]{@{}l@{}}#1;#2\end{array}}
\begin{document}
\begin{tabular}{l@{\enspace}l}
\verb`\parens{\stmts{Y_1}{\\ Y_2}}` & $\parens{\stmts{Y_1}{\\ Y_2}}$ \\
\\
manual construction & $(\begin{array}[t]{@{}l@{}}
\begin{array}[t]{@{}l@{}}
Y_1;
\\ Y_2)
\end{array}
\end{array}$
\end{tabular}
\end{document}
Edit: Since Werner asked for a more realistic use case, here is an example. I would like the closing parenthesis to automatically appear after \mathsf{closeR}.
% arara: pdflatex
\documentclass{article}
\usepackage{xparse}
\usepackage{amsmath}
\usepackage{mathtools}
\ExplSyntaxOn
\DeclarePairedDelimiterXPP\caseL[1]{\mathsf{caseL}}\lparen\rparen{\end{array}}%
{
\begin{array}[t]{@{}l@{}}
\seq_set_split:Nnn \l_tmpa_seq { | } {#1}
\seq_clear:N \l_tmpb_seq
\seq_map_variable:NNn \l_tmpa_seq \l_tmpa_tl
{
\tl_replace_once:Nnn \l_tmpa_tl { => } { \Rightarrow }
\seq_put_right:NV \l_tmpb_seq \l_tmpa_tl
}
\seq_use:Nn \l_tmpb_seq { \mid }
}
\NewDocumentCommand \selectR { m m }
{
\begin{array}[t]{@{}l@{}}
\mathsf{selectR} \mskip\medmuskip #1 ;
#2
\end{array}
}
\NewDocumentCommand \waitL { m }
{
\begin{array}[t]{@{}l@{}}
\mathsf{waitL} ; #1
\end{array}
}
\NewDocumentCommand \closeR { } { \mathsf{closeR} }
\ExplSyntaxOff
\begin{document}
$q_1 = \caseL{a => \selectR{b}{\\ \selectR{a}{q_0}} \\\mkern-8.5mu
| b => q_1 \\\mkern-8.5mu
| c => \waitL{\\ \selectR{b}{\\ \selectR{c}{\closeR}}}}$
\end{document}


minimalclass, see Why should the minimal class be avoided? – egreg Oct 01 '16 at 06:39