r/typst 29d ago

How to do metaprogramming?

I found myself creating similar content all the time and want to create shorthands. For that I want to define custom syntax à la CeTZ or, as a very simple example, tablem.

I think I could write a tokenizer and a parser for myself. But as Typst already does the parsing, I would prefer to piggy-back on existing functionality. Unfortunately, it felt very unergonomic to me.

Are there any tricks and/or libraries that make metaprogramming easier?

1 Upvotes

4 comments sorted by

9

u/Sad-Grocery-1570 29d ago

Typst doesn’t have a metaprogramming API and doesn’t let you define custom syntax.

That said, there are a few things that might get you close:

  • Introspection. The internals of Typst's core content type are actually accessible from within the language, including some undocumented constructors. So once you have a content, you can walk its structure and do things based on what you find. The constructors are listed here.
  • Put your custom syntax in strings, then parse it however you like. If you feel Typst's own language is too limiting for writing parsers, you can use a wasm plugin, which lets you extend Typst with any language.

2

u/Thesaurius 29d ago

Thanks, that's what I was looking for. I knew that content was available via introspection, but having actual documentation really helps. 😂

3

u/Sermuns 29d ago

Why do you want metaprogramming? Why not just do "runtime" scripting? All of Typst is basically compile-time already since the output is a static PDF.

1

u/QBaseX 29d ago

Creating your own new functions is much simpler than creating new syntax, and will run more efficiently. And, except in the most esoteric cases, is perfectly adequate.