4

I am using a function for summing numbers like in paper and my input at arguments is like this: \showsum{123+456}

I need to replace the custom function with other from package xlop - \opadd. I want the same function name but there are 2 separated arguments in \opadd and I want to use {123+456} for \opadd arguments. How to make this delimiter?

\documentclass{article}
\usepackage{xlop}
\usepackage{amsmath}
 \usepackage{setspace}
\newcommand{\showsum}[2][c]{%
    $\edef\originalplusmathcode{\the\mathcode`+}%
    \begingroup\lccode`~=`+ \lowercase{\endgroup\def~}{\\\mathchar\originalplusmathcode&}%
    \edef\originalminusmathcode{\the\mathcode`-}%
    \begingroup\lccode`~=`- \lowercase{\endgroup\def~}{\\\mathchar\originalminusmathcode&}%
    \mathcode`+ "8000
    \mathcode`- "8000
    \begin{array}[#1]{@{}r@{\;}r@{}}
    & #2 \\
    \hline
    & \the\numexpr#2\relax
    \end{array}%
    $%
}

\begin{document}
 Original function(don't need anymore)\showsum{123+456}
 \\
 \\
 Replacement needed \opadd{123}{456}

\end{document}
Simeon Simeonov
  • 819
  • 5
  • 11

1 Answers1

7

You can use a macro with delimited arguments:

\documentclass{article}
\usepackage{xlop}

\newcommand{\showsum}[1]{\doshowsum#1\doshowsum}
\def\doshowsum#1+#2\doshowsum{\opadd{#1}{#2}}

\begin{document}

\showsum{123+456} \qquad \opadd{123}{456}

\end{document}

enter image description here

You can also support subtraction:

\documentclass{article}
\usepackage{xparse}
\usepackage{xlop}

\ExplSyntaxOn
\NewDocumentCommand{\showsum}{m}
 {
  \regex_match:nnTF { \+ } { #1 }
   {
    \simeon_showsum:nnn { #1 } { \+ } { opadd }
   }
   {
    \simeon_showsum:nnn { #1 } { \- } { opsub }
   }
 }
\cs_new_protected:Nn \simeon_showsum:nnn
 {
  \tl_set:Nn \l_tmpa_tl { #1 }
  % remove all spaces
  \regex_replace_all:nnN { \s } { } \l_tmpa_tl
  % replace <number>+<number> with \opadd{<number>}{<number>} or
  % replace <number>-<number> with \opsub{<number>}{<number>}
  \regex_replace_once:nnN
   { \A ([^#2]*) #2 (.*) \Z }
   { \c{#3}\cB\{\1\cE\}\cB\{\2\cE\} }
   \l_tmpa_tl
  % deliver the result
  \tl_use:N \l_tmpa_tl
 }
\ExplSyntaxOff

\begin{document}

\showsum{123+456} \qquad \showsum{456-123}

\end{document}

enter image description here

egreg
  • 1,121,712