3

This question already has an answer here:

I'm looking for a way to replace \DeclareMathOperator{\Operator}{Operator} by something which would resemble \MathOperator{Operator}. I tried to define a new command \newcommand\MathOperator[1]{\DeclareMathOperator{\#1}{#1}} and then call it \MathOperator{MyOperator} but this doesn't seem to work, I got the following error: "Undefined control sequence." when calling $\MyOperator$. Any idea what I should do?

Thanks a lot.

marked as duplicate by Andrew, egreg, yo', user13907, Malipivo Sep 9 '14 at 13:28

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Please show a full but minimal example of this. Your question is a bit difficult to understand. You never define \MyOperator above. That's for sure. – LaRiFaRi Sep 9 '14 at 12:46
  • I suspect that \#1 is understand by TeX as 2 tokens, not as 1. I'm no expert though. – Pece Sep 9 '14 at 12:47
  • 2
    You should use \csname #1\endcsname instead of \#1. See What exactly do \csname and \endcsname do? – Werner Sep 9 '14 at 12:53
  • @Andrew, thanks for this thread, I missed it I guess. I'm still a bit concerned though: when I copy paste the code from the accepted answer, I get the following error message "! Argument of \DeclareMyOperator has an extra }." when calling \DeclareMathOperators{Rep,Tet,Maps,Diff}, any idea why? – G Viaud Sep 9 '14 at 13:15
  • Are you sure that you copied the code properly as it works for me. – Andrew Sep 9 '14 at 13:19
8

I do not think it is a good idea to redefine \DeclareMathOperator but rather make your own macro to create operatornames. One method would be to use etoolbox and use

\newcommand\myDeclareMathOperator[1]{\csdef{#1}{\operatorname{#1}}}

Note that some names are just not good names for macros, for example you will burn your self on this one: \myDeclareMathOperator{span}

This one is a little safer

\newcommand\myDeclareMathOperator[1]{
  \ifcsundef{#1}{
    \csdef{#1}{\operatorname{#1}}
  }{
   \PackageError{MyMacros}{#1 is already used as a macro name}{}
  }
}

and if we in addition use xparse we can support the * notation:

\NewDocumentCommand\myDeclareMathOperator{ s m }{
  \ifcsundef{#2}{
    \csdef{#2}{
      \IfBooleanTF{#1}{\operatorname*}{\operatorname}{#2}
    }
  }{
   \PackageError{MyMacros}{#2 is already used as a macro name}{}
  }
}
  • @GViaud, I've added a few additions – daleif Sep 9 '14 at 13:22

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