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.