[Tex/LaTex] Automatic species names in latex / command that does something differently the second time it is run

text manipulation

In academic publications it is a rule of thumb that the first time you give a species name, you write the genus and species in full…and the second time you can abbreviate the genus.

First time:

Escherichia coli

second time:

E. coli

I wanted a latex way to do this automatically. After some searching, I eventually came up with this, and I thought I'd share it..

%% Meta-Command for defining new species macros
\newcommand{\species}[4]{\newcommand{#1}{\ifdefined
    #2{\itshape #4}\xspace \else\newcommand{#2}{}{\itshape
    #3}\xspace \fi}
}

%% Defining new species
% The first argument is the name of the macro you will call in the document.
% The second argument is the name of a flag that is used to keep track of if this is the first time the macro is being called.
% The third argument is what is written the first time the macro is called
% The fourth argument is what is written every subsequent time the macro is called.

\species{\ecoli}{\ecolihbd}{Escherichia coli}{E.\;coli}
\species{\rsphaeroides}{\rspaheroideshbd}{Rhodobacter
  sphaeroides}{R.\;sphaeroides}
\species{\abrasilense}{\abrasilensehbd}{Azospirillum
  brasilense}{A.\;brasilense}
\species{\celegans}{\celeganshbd}{Caenorhabditis elegans}{C\;elegans}
\species{\pseudomonads}{\pseudomonadshbd}{Pseudomonads}{Pseudomonads}

%%

%%% Then later on, in the document:
\ecoli is an example of a model species.  People study \ecoli because
people have studied \ecoli.

Output:

Escherichia coli is an example of a model species. People study E. coli because people have studied E. coli.

Best Answer

You don't need the flag: just define the macro to print the complete name and then globally redefining itself to print the abbreviated name. The global definition is needed because the first appearance might be in a group (an environment, for instance).

\documentclass{article}
\usepackage{xspace}

%% Meta-Command for defining new species macros
\newcommand{\species}[3]{%
  \newcommand{#1}{\gdef#1{\textit{#3}\xspace}\textit{#2}\xspace}}

%% Defining new species
% The first argument is the name of the macro you will call in the document.
% The second argument is what is written the first time the macro is called
% The third argument is what is written every subsequent time the macro is called.

\species{\ecoli}{Escherichia coli}{E.~coli}
\species{\rsphaeroides}{Rhodobacter sphaeroides}{R.~sphaeroides}
\species{\abrasilense}{Azospirillum brasilense}{A.~brasilense}
\species{\celegans}{Caenorhabditis elegans}{C.~elegans}
\species{\pseudomonads}{Pseudomonads}{Pseudomonads}

%%

\begin{document}
\ecoli is an example of a model species.  People study \ecoli because
people have studied \ecoli.

\end{document}
Related Question