I want to create a custom function in Typst that allows me to color content inside of the math mode, for example s^+
in a color specified in a parameter (the content should of course be a parameter as well).
So my attempt is based on this reddit post, but the parameter for the color is missing in the answer.
My best solution is #let colMath(x, color) = text(fill: color)[$#x$]
, but then I have to call it using something like #colMath($s_2^-$, red)
, even if the function call is in math mode already. When I remove the # I can also remove the $s_2^-$
, but then it says "the variable red is not defined".
I guess part of the problem is that I don't really understand when to use the # and when not.
Thank you for any help or advice :)
Your error occurs because variables like red
are only defined in the typst code mode, not math mode. You can get around this by defining red
as a variable in your outer scope, i.e. with #let red = red
. Since inner scopes (the math mode) can access all variables at outer levels, this no longer relies on builtin names being accessible and instead treats it like any other variable/function/etc.
Another way is to simply enter markup mode using #red
in the function call.
In sum: your understanding of #
is correct -- it enters code mode, which exposes red
and similar builtins. When math mode is active, you have to declare those variables explicitly in your outer scope or enter markup mode to use the builtin definition.
#let colMath(x, color) = text(fill: color)[$#x$]
// Define your own variable
#let red = red
$a x^2 + b x + c colMath(s_2^-, red)$
// Or simply enter markup mode inside the function call:
$a x^2 + b x + c colMath(s_2^-, #red)$