How can I extract source code examples from a typ file?

Hi all,

I’m curious about the best method to extract source code examples from a Typst intermediate file, where the variables have already been processed.
Previously, I achieved this by using Asciidoctor to generate an HTML file, then running a script to extract each tagged source block into a separate file.

Any advice would be appreciated.
Thanks in advance!

I don’t have time for a longer answer right now but you might look into using Typst’s support for command line queries, see here in the documentation.

Okay, with a bit more time: You can label each piece of source code that you want to export with a common label, like <export-code>:

```python
def test():
    print("Hello World!")
``` <export-code>

Then, you can use the command typst query main.typ "<export-code>" (with Typst installed locally on your computer, the web app cannot do this) to get a JSON with all those source elements, like this:

[{"func":"raw","text":"def test():\n    print(\"#output\")","block":true,"lang":"python","align":"start","syntaxes":[],"theme":"auto","tab-size":2,"lines":[{"func":"line","number":1,"count":2,"text":"def test():","body":{"func":"sequence","children":[{"func":"styled","child":{"func":"text","text":"def"},"styles":".."},{"func":"styled","child":{"func":"text","text":" "},"styles":".."},{"func":"styled","child":{"func":"text","text":"test"},"styles":".."},{"func":"styled","child":{"func":"text","text":"("},"styles":".."},{"func":"styled","child":{"func":"text","text":")"},"styles":".."},{"func":"styled","child":{"func":"text","text":":"},"styles":".."}]}},{"func":"line","number":2,"count":2,"text":"    print(\"#output\")","body":{"func":"sequence","children":[{"func":"text","text":"    "},{"func":"styled","child":{"func":"text","text":"print"},"styles":".."},{"func":"styled","child":{"func":"text","text":"("},"styles":".."},{"func":"styled","child":{"func":"text","text":"\""},"styles":".."},{"func":"styled","child":{"func":"text","text":"#output"},"styles":".."},{"func":"styled","child":{"func":"text","text":"\""},"styles":".."},{"func":"styled","child":{"func":"text","text":")"},"styles":".."}]}}],"label":"<export-code>"}]

or you can say typst query main.typ "<export-code>" --field text to just get the source snippets, i.e.

["def test():\n    print(\"Hello World!\")"]

If you construct your code examples using Typst variables, query will reflect the final result. (But writing parametric code like this is not super nice as the raw blocks disable variable interpolation. You can do it by constructing raw elements by hand, though.)

There is currently no way of getting all raw elements without labeling them, as they are not “locatable”. The documention promises that this restriction will be lifted in the future.

1 Like

Thank you @eike !
I don’t know why I thought that Typst produced some kind of intermediate file that could be read.
Your comments helped me further.