Symbolics.jl and Latexify.jl: customize latex representations?

(Julia 1.6)
I deal with equations from publications and the variables there have lots of subscripts and superscripts. They cannot be represented as Julia variable names and I would prefer not to compromise. For example, I might want something like this:

using LaTeXStrings,Latexify, Symbolics
@variables x_plus  # this is a variable
 # this is what I would like the variable to be written as
repr_map = Dict(x_plus => L"x^{+}_{A,\alpha_{1}}")

Now I want to do something like

@latexify x_plus + x_plus^2 + factorial(x_plus)
 # and also give the macro my `repr_map`, tell it somehow that I want factorial written as !...

and get x^{+}_{A,\alpha_{1}} + {(x^{+}_{A,\alpha_{1}})}^2 + (x^{+}_{A,\alpha_{1}})!.

Is there a way to do this? One thing I tried was modifying Latexify.jl (this file: Latexify.jl/…/function2latex.jl) to add my own symbols. This doesn’t really work for everything and of course having to modify the library isn’t a good solution. Is there a way to add “custom rules” to Latexify?

If there is no way currently, would such an idea be consistent with what Latexify.jl is trying to do? If so, I would be willing to help implement it.

Perhaps something like this (does not work) would be a good API:

x_plus = L"x^{+}_{A,\alpha_{1}}"
@latexify $x_plus + $x_plus^2 + factorial($x_plus)

Something like this might be possible too

@variables var"x^{+}_{A,\alpha_{1}}"
x_plus =  var"x^{+}_{A,\alpha_{1}}"
# continue to use x_plus.

It partially works already. However, when using this, the latex representation crashes (doesn’t use enough parentheses or braces).

julia> latexify(x_plus + x_plus^2 + factorial(x_plus))
L"\begin{equation}
x^{+}_{{A,\alpha\_{1}}} + x^{+}_{{A,\alpha\_{1}}}^{2} + \mathrm{factorial}\left( x^{+}_{{A,\alpha\_{1}}} \right)
\end{equation}
"

(latex rendering error: “Double exponent: use braces to clarify”)

Also, this won’t help with the factorial to ! issue.

The problem with the “latex rendering error” in my last post can be partially solved by adding even more brackets to the variable name (symbol). Of course, this does not help with things like factorial.


@variables var"{x^{+}_{A,\alpha_{1}}}"

Note that in the output, the second-order-subscript “1” is not represented properly because Latexify escapes the underscore. I don’t think there is a way to mitigate this right now, short of editing Latexify.jl sources.