Here is a solution with luatex
. The idea is to use the process_input_buffer
callback so that luatex will check every input line of text for the word to be emphasized. If it is found and if it is the first time, then it adds a macro around the word to emphasize it.
I use pattern matching to detect if the word is not a 'subword' of an other and to detect punctuation.
Note that I'm not a guru with pattern matching using the string
library (I should have done it with lpeg
...). So it breaks for the detection of bar
(feel free to correct my code).
First the lua
file (save it as first-occurence.lua
).
local gsub = string.gsub
local find = string.find
first_occurence = first_occurence or {}
first_occurence.table = first_occurence.table or {}
function first_occurence.add (s)
first_occurence.table[#first_occurence.table + 1] =
{ [1] = s, [2] = true}
end
function first_occurence.start ()
luatexbase.add_to_callback(
'process_input_buffer',
function (s)
for i = 1, #first_occurence.table do
if first_occurence.table[i][2] then
local j = find(s,
'[^%a]-' ..
first_occurence.table[i][1] ..
'[\n\t ,.:;!?]+')
if j then
-- The final 1 is to limit substitutions made to one.
s = gsub(s, '[^%a]-' .. first_occurence.table[i][1] .. '[\n\t ,.:;!?]+','\\emph{%1}',1)
first_occurence.table[i][2] = false
end
end
end
return s
end,
'replace_first_occurence')
end
function first_occurence.stop ()
luatexbase.remove_from_callback(
'process_input_buffer', 'replace_first_occurence')
end
return first_occurence
Then the tex
file.
\documentclass{standalone}
\usepackage{luatexbase}
\directlua{dofile('first-occurence.lua')}
\def\startreplacefirstoccurence{%
\directlua{first_occurence.start()}}
\def\stopreplacefirstoccurence{%
\directlua{first_occurence.stop()}}
\def\addtoreplacefirstoccurence#1{%
\directlua{first_occurence.add('\luatexluaescapestring{#1}')}}
\addtoreplacefirstoccurence{Test}
\addtoreplacefirstoccurence{foo}
\addtoreplacefirstoccurence{bar}
\begin{document}
Test
\startreplacefirstoccurence
Test Test Test foobar foo bar
\end{document}
acronym
can be used for this, however, I have no personal experience to provide you a full answer. – yo' Apr 3 '12 at 9:50