I've declared a lot of math operators lately, e.g. \DeclareMathOperator{\Hom}{Hom}, \DeclareMathOperator{\End}{End} and so forth. This is getting a bit annoying and seems automatable: what I'd really like is to have this behavior for every capitalized word, e.g. if I type \Foo in a document I'd like for this to be interpreted as a math operator without having to specify it in advance. Is there an easy way to do this?
- 849
3 Answers
Example for such a loop: \DeclareMathOperators takes a comma separated list of math operator names without backslash and turns them to math operator commands. Spaces and empty entries in the list are removed.
\usepackage{amsmath}
\makeatletter
\newcommand*{\DeclareMathOperators}[1]{%
\@for\@tmp:=#1\do{%
% remove spaces
\edef\@tmp{%
\@firstofone{\expandafter\zap@space\@tmp} \@empty
}%
\ifx\@tmp\@empty
\else
% declare math operator
\expandafter\DeclareMathOperator
\csname\@tmp\expandafter\endcsname\expandafter{\@tmp}%
% \wlog prints into the .log file
% or \typeout can be used for console output
\wlog{* Math operator "\@backslashchar \@tmp" defined.}%
\fi
}%
}
\makeatother
\DeclareMathOperators{
End,
Foo,
Hom,
}
- 271,626
You mean something like this? You cannot get closer to what you want than defining all used terms in a cycle.
\documentclass{article}
\usepackage{amsmath}
\makeatletter
\@for \op:={Dom,Hom}\do{
\@ifundefined{\op}{
\edef\DMOtemp{\noexpand\DeclareMathOperator{\csname\op\endcsname}{\op}}
\DMOtemp
}{}
}
\makeatother
\begin{document}
\[ \Dom A \neq \Hom B \]
\end{document}
We use LaTeX's \@for since pgffor makes grouping which makes definitions local and then it doesn't work. For each element of the list, we prepare the definition as \DMOtemp->\DeclareMathOperator{\Dom}{Dom}, and then we execute it. The \@ifundefined is quite necessary since if we wanted to re-define something, it would have bad consequences (the thing being re-defined would get executed at the line with \edef and the whole thing would probably fail). On the other hand, \csname blabla\endcsname for \blabla being undefined leaves just \blabla there, which is quite correct.
- 51,322
Here's some example how to define a comma separated list of math operators:
\documentclass[12pt]{minimal}
\usepackage{amsmath,etoolbox}
\newcommand{\DeclareMathOp}[1]{
\csgdef{#1}{\operatorname{#1}}
}
\newcommand{\DeclareMathOps}[1]{
\forcsvlist{\DeclareMathOp}{#1}
}
\DeclareMathOp{HULL}
\DeclareMathOps{OPA,OPB,OPC}
\begin{document}
$\HULL\OPA\OPB$
\end{document}
- 649
\RequirePackageshould be reinterpreted as a math operator ;^) ? – Steven B. Segletes Feb 12 '14 at 19:07