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](https://i.stack.imgur.com/wTwBl.png)
% !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}
Defining a command within another command requires to use the \csname #1 \endcsname
approach for the \NewDocumentCommand
(or \newcommand
as well) (assuming #1 is the name of the new command, as argument of the outer command), preceeded by \expandafter
If a command is defined within another one, all parameter arguments characters #
have to be doubled, it i.e. ##1
, ##2
, etc.
\documentclass{article}
\usepackage{xparse}
\newcommand{\added}[1]{%
\Large%
\textbf{Arg was #1}%
}
\newcommand{\definerevision}[1]{%
\expandafter\NewDocumentCommand\csname #1\endcsname{gg}{\added[id=#1,remark={##1}]{##2}}%
}
\definerevision{MOE}
\definerevision{LARRY}
\definerevision{CURLY}
\begin{document}
\MOE{Added}{only this}
\LARRY{Added}{other more important stuff}
\CURLY{Screwed}{up the whole thing}
\end{document}
Best Answer
Use
expl3
:What's the advantage? You can easily generalize your command using the same idea.