[Tex/LaTex] Highlight First Occurrence of a Particular Word

highlighting

I'm writing a scientific paper, and in this paper, I present a series of new terms. The first time a new term is presented, I would like LaTeX to automatically highlight this – e.g. by using italics or small caps.

Does such a package exist? Or if not, do any of you know an alternative way to accomplish the same?

Best Answer

You can't do this in a fully automated way. It's not possible to give a list of words and get TeX recognize the first occurrence.

What you can do is to mark the terms in the .tex file, after giving the list and something like the following code:

\documentclass{article}

%%% Code to set up special term treatment
\makeatletter
\newcommand{\specialterms}[1]{%
  \@for\next:=#1\do
    {\@namedef{specialterm@\detokenize\expandafter{\next}}{}}%
}
\newcommand\term[1]{%
  \@ifundefined{specialterm@\detokenize{#1}}
    {#1}{\emph{#1}\global\expandafter\let\csname specialterm@\detokenize{#1}\endcsname\relax}%
}
\makeatother

%%% Here we define the special terms we want
\specialterms{foo,bar,baz}

\begin{document}

First occurrence of \term{foo} and second occurrence of \term{foo}.

First occurrence of \term{baz}. Now \term{bar} and
again \term{bar} and \term{baz} and \term{foo}.

\end{document}

enter image description here

What does the code do? The \@for is just an easier way to avoid saying something like

\specialterm{foo}\specialterm{bar}\specialterm{baz}

With \specialterms{foo,bar,baz} we execute the same code for each term: for example, the command \specialterm@foo is defined essentially to do nothing. Indeed we'll examine only its "existence": when LaTeX finds \term{foo} it looks whether \specialterm@foo is defined: if it is it prints \emph{foo} and undefines \specialterm@foo (making it equivalent to \relax, which, for \@ifundefined is exactly being undefined); otherwise it prints foo.

The \detokenize bit is just to avoid problems if the term contains accented characters.

Related Question