# How to redefine macro \\ within environment bmatrix?

I want to redefine macro \\ within an instance of environment bmatrix from package amsmath. But bmatrix does not respect redefinition of \\ outside or within bmatrix:

\newcommand{\im}[1]{{
\renewcommand{\\}{;&}
\begin{bmatrix}#1\end{bmatrix}
}}

\newcommand{\im}[1]{
\begin{bmatrix}\renewcommand{\\}{;&}#1\end{bmatrix}
}


Instead of trying to redefine \\, I use a token cycle that pre-scans the tokens of the argument to \im, and substitutes the tokens ;& for every instance found of \\. All other tokens are echoed as they originally appear.

\documentclass{article}
\usepackage{amsmath,tokcycle}
\newcommand{\im}[1]{{\resettokcycle
\tokencyclexpress\begin{bmatrix}#1\end{bmatrix}\endtokencyclexpress
}}
\begin{document}
$\begin{bmatrix}a\\b\end{bmatrix}$
versus
$\im{a\\b}$
\end{document}


You rather want to process your input. With expl3 it's essentially a one-liner.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\im}{m}
{
\begin{bmatrix}
\seq_set_split:Nnn \l_tmpa_seq { \\ } { #1 }
\seq_use:Nn \l_tmpa_seq { ; & }
\end{bmatrix}
}

\ExplSyntaxOff

\begin{document}

$\im{a\\b}$

\end{document}


The spacing seems a bit weird, though. You can consider not using bmatrix.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\im}{m}
{
\left[
\seq_set_split:Nnn \l_tmpa_seq { \\ } { #1 }
\seq_use:Nn \l_tmpa_seq { {;} \mspace{\thickmuskip} }
\right]
}

\ExplSyntaxOff

\begin{document}

$\im{a\\b}$

\end{document}


• I’d say a two-liner. Jul 9 at 9:38