How do function definitions and arguments work in math?

I am a bit confused about how exactly function definitions and the syntax for arguments. I have looked at the relevant “Function Type” page on the wiki already.
The desired function should take in some text, and then return the text with an accent overtop. Essentially just a simple shortcut/macro.
My code:

// Definition
#let op(opText) = [
  $accent(opText, hat)$
]

// Below works
#op[testHere]
// Below works
$#op[testTwo]$
// Below works
$op(A)$
// Below errors
$op(Atest)$

I don’t understand why sometimes in math mode the # symbol is not needed. I would appreciate some clarification about why the specific examples work/don’t work.
Thank you!

Maybe you have missed Function calls in the Math doc?

// Below errors
$op(Atest)$
// Below works
$op("Atest")$

Hi. The link @Y.D.X provided should help with the function part, the problem with the last example is answered in the Variables section.

$op("Atest")$

The compiler actually already gives you the solution:

unknown variable: Atest

Hint: if you meant to display multiple letters as is, try adding spaces between each letter: `A t e s t`

Hint: or if you meant to display this as text, try placing it in quotes: `"Atest"`

As to the “macro”, you can use the built-in hat function available in math mode. The list of exported functions.

1 Like

You can use language identifier for appropriate syntax highlighting.

1 Like

Useful trivia: If you want to call other builtins in equations - for any reason - that’s also possible, for example this way to call the normal stack:

$std.stack(dir: #ttb, spacing: #1em, pi = 1, pi = 2, pi = 3)$

The benefit of calling regular functions without #: You are still in math mode in the arguments.

I’m not sure if the docs mention which functions are in scope in equations and which are not. (We could guess it’s everything in math.* and nothing else, but off hand I’m not sure.)

One more thing you need to know: single letter functions and variables always need a #:

#let h = 1
#let hi = 2
$h,#h,hi$

image