3

I would like to remove the math mode in a text that is not defined directly, but in a macro. Here is my code:

\documentclass{book}

\begingroup
  \lccode`\~=`$
  \lowercase{\endgroup
    \def~#1~{\ignorespaces}%
  }
\def\removemath{%
  \begingroup
  \catcode`$=\active
  \removemathX
}
\def\removemathX#1{%
  #1
  \endgroup
}

\edef\nomath#1{
\removemath{#1}
}

\begin{document}

\chapter{XXXXXX}
\newcommand\aaaa{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}
\removemath{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}
\removemath{\aaaa}
\nomath{\aaaa}

\end{document}

In this example, the first removemath works, but the second removemath and nomath does not work. I am not sure why. Is it an expansion problem? Maybe something else? Can someone suggest a solution?

  • 1
    removemath is using catcode changes so will only work at the top level, the characters in \aaaa have already been tokenised so catcode changes have no effect. However it isn't clear why you are using catcode changes, you copuld use a delimited argument on a normal catcode $. – David Carlisle Jan 25 at 22:15
3

You can remove one formula at a time:

\documentclass{book}

\makeatletter
\newcommand{\removemath}[1]{%
  \expandafter\removemath@#1$$\@nil
}
\def\removemath@#1$#2$#3\@nil{%
  #1%
  \if\relax\detokenize{#3}\relax
    \expandafter\@gobble
  \else
    \expandafter\@firstofone
  \fi
  {\removemath@#3\@nil}%
}
\makeatother


\begin{document}

\newcommand\aaaa{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}

--\removemath{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}--

--\removemath{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD}--

--\removemath{AAA$^{1}$, BBB, CCC$^{3}$, DDD}--

--\removemath{\aaaa}--

\end{document}

enter image description here

The same with a regular expression approach:

\documentclass{book}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\removemath}{m}
 {
  \peter_removemath:o { #1 }
 }

\cs_new_protected:Nn \peter_removemath:n
 {
  \tl_set:Nn \l__peter_removemath_tl { #1 }
  \regex_replace_all:nnN { \$ [^$]* \$ } {} \l__peter_removemath_tl
  \l__peter_removemath_tl
 }
\cs_generate_variant:Nn \peter_removemath:n { o }
\tl_new:N \l__peter_removemath_tl
\ExplSyntaxOff

\begin{document}

\newcommand\aaaa{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}

--\removemath{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD$^{4}$}--

--\removemath{AAA$^{1}$, BBB$^{2}$, CCC$^{3}$, DDD}--

--\removemath{AAA$^{1}$, BBB, CCC$^{3}$, DDD}--

--\removemath{\aaaa}--

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.