2

I am trying to shorten down on writing math with variables, and therefore one of the steps needed is to split the equation string at the first = sign and put a & sign in front of it for alignment. This works great except for when I put the actual ampersand in before the second part of the string. It works with the ampersand if I manually add the second string. See my example, with the commented-out code. How do I make sense of this?

\documentclass[11pt]{article}
\usepackage{xstring,amsmath}

\newcommand{\splitEquals}[1]{%
\StrCut{#1}{=}{\macroA}{\macroB}%
%enable only one at a time:
%\macroA&=3+4       %works
%\macroA&=\macroB   %doesn't work
\macroA=\macroB     %works
}
\begin{document}
%\splitEquals{d=3+4}
\begin{align*}
    \splitEquals{d=3+4}
\end{align*}
\end{document}

Edit: The result of splitEquals should be: d&=3+4, which would align it nicely. I do not require any lineending.

2
  • Please clarify what you mean by "split". Do you simply want an & inserted before the & character, or do you also require a line break, or something else altogether?
    – Mico
    Dec 18, 2015 at 18:45
  • I'd like and &before the =sign, but it doesn't work when I add the \macroBafter it
    – Runar
    Dec 18, 2015 at 19:05

1 Answer 1

6

The problem here is that the macros \macroA and \macroB is created within the "first cell" of the align environment, but then used in a construction that spans "multiple cells". In the left (first) cell is \macroA and to the right is = \macroB. The macro creation doesn't survive beyond the current cell, as the definition is local (or within that group).

You can correct for this by making it global. Here's a very quick way using \xdef, although other means are also possible:

\documentclass{article}
\usepackage{xstring,amsmath}

\newcommand{\splitEquals}[1]{%
  \StrCut{#1}{=}{\macroA}{\macroB}%
  \xdef\macroB{\macroB}% Make \macroB global
  \macroA &= \macroB
}

\begin{document}

\begin{align*}
  \splitEquals{d=3+4}
\end{align*}

\end{document}

An xstring-free choice might be

\makeatletter
\newcommand{\splitEquals}[1]{\expandafter\splitEqu@ls#1}
\def\splitEqu@ls#1=#2{#1 &= #2}
\makeatother

where you use argument delimiters to break at the = sign.

1
  • This works great, and shows me a better way to do it, great! Splitting the string seemed to have some problems when I added sin60or similar to the string, so clearly it is not the best way to achieve it.
    – Runar
    Dec 18, 2015 at 19:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .