[Tex/LaTex] Macro: Replace all occurrences of a word

macros

I repeatedly use certain keywords such as var in my document which I highlight using \src{var}. This is cumbersome to type and gets annoying after a while. Repeatedly search-and-replacing var to \src{var} and then \src{\src{var}} to \src{var} also seems needlessly complicated. I want to tell LaTeX to replace all occurrences of var with \src{var}. I found \def that reduces the typing to \var{}, which is not much better. Something similar to the C preprocessor maybe: #define var \src{var}.
I found the "Replacing all the dots"-example but failed to modify it to "Replacing all the vars". Thanks for the help.

Best Answer

Here's a LuaTeX-based solution. It (i) defines a Lua function that changes all instances of "var" (note the spaces before and after "var") to "\src{var}" and (ii) registers this function with the process_input_buffer callback. This callback operates on the entire input stream before TeX processes it. Separately, I define a TeX macro called \src so that TeX knows what to do when it encounters the instruction \src{var}.

With this setup, words such as "aardvark", "bivariate", and "covariance" are left alone. In the second input line below, the first and last instances of "var" are also left unchanged since they're not preceded and followed by a space. Finally, should there already be instances of \src{var} in your input file, they won't be operated on by the Lua function either -- they'll just get executed by TeX as one would expect.

Observe that nothing is written back to the .tex input file, i.e., your input file won't get littered with lots of \src statements.

By the way, I assume that the real string that's supposed to be operated on by \src in your file is a bit more unique than var. If so, you can probably dispense with the requirement that the string be both preceded and followed by a space.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{fontspec,xcolor}
\usepackage{luacode,luatexbase} 

\begin{luacode}
local function vartosrcvar ( line )
  return string.gsub(line, " var " , " \\src{var} ") 
end
luatexbase.add_to_callback( "process_input_buffer",  vartosrcvar, "var_to_srcvar")
\end{luacode}

\newcommand\src[1]{\textcolor{red}{#1}} % define "\src" to suit your needs

\begin{document}
aardvark bivariate covariance varnish

var uno var due var tre var
\end{document}