The best way to do it manually would be to transform test"a $i"
into string("a ", i)
(which is what regular interpolation does). (The key thing to remember is that macros only know how things are “spelled”, not what their values are. By transforming the expression into string("a ", i)
or similar, you defer the evaluation of i
until the code actually executes and the value is known.)
An example of how to do this can be found in the implementation of the L"..."
macro from the LaTeXStrings.jl package. In that macro, $
is treated as the beginning of a LaTeX equation, so it is left as is, but the string %$
is used for interpolation instead.
The steps are to (1) parse your string to find (unescaped) $
, (2) call Meta.parseatom
(or Meta.parse
with greedy=false
) to parse the next complete Julia expression after the $
, and (3) emit the desired expression from the macro, e.g. a call to string
(or the latexstring
constructor in the case above).