Repository navigation
Description
This issue proposes a design which would allow users to emit multiple files from a single Typst project. The main goal of this work is to enable emitting web sites with multiple pages, but the design enables further use cases. The feature would initially be guarded behind a feature flag, similarly to HTML export.
Design
Currently, Typst supports four export formats spread across two targets: The formats PDF, PNG, and SVG are backed by the paged target and the HTML format has its own target.
This design introduces a new format and target called bundle. When this target is selected (from the CLI via -f bundle), multiple output files can be created from a single Typst file/project, all emitted to one output directory.
The design centers around the document function. Currently, this function can only be used in set rules. The function is extended to be directly callable. A single call to the document function results in one output file within the output directory.
The document function gains six new parameters:
-
path: string | path(required): This parameter designates the path in the output directory of the document. It may contain interior slashes, which result in nested directories. The extension of the path is used to infer the format. -
body: content(required): The content that is processed to produce the file. -
format: "pdf" | "png" | "svg" | "html" | auto(optional): The export format. Ifautoor omitted, inferred from the path. -
ppi: int | auto(optional): Defines the default PPI (pixels per inch) used when rastering things. Initially, this would be used for raster export. In the future, it may also be used to define the PPI for raster effects in PDF export or for image recoding in PDF export. -
pages: array | auto(optional): The pages to output for paged documents. The array may contain integers indicating single pages and pairs (arrays of length two) of integers defining ranges. -
pdf: dictionary(optional): PDF-specific options, which includesstandard: string | auto, andtagged: bool | auto. This property supports folding. We might want to split upstandardintoversionandstandards. This was discussed before, but not decided. If we do so, it should be split up in the CLI as well.
These configuration parameters mirror the document options exposed in the CLI (--ppi, --pages, --pdf-standard, --no-pdf-tags), with format-specific options in a dictionary, and options that may apply to multiple formats top-level. This extends the existing mapping between document.date and --creation-timestamp. Notably, we only expose export options, not environment parameters such as --root or --font-path.
In addition to the document function, a new asset function is introduced. This function can be used to emit a file whose contents are a raw string or bytes, in no particular format.
The existing experimental target function (guarded behind the html feature) returns "bundle" when the bundle target is selected. When within a document, it returns the appropriate target for that document.
Use Cases
-
Building a multi-page web site:
#document("index.html")[ #title[Home] - #link(<blog>)[Go to blog] ] #document("blog/index.html", title: "Laurenz's Blog")[ #title[Blog] My blog!!! ] <blog>
-
Producing a secondary file alongside the main file:
#document( "slides.pdf", pdf: (standard: "a-2b"), [...], ) #context asset( "speaker-notes.json", json.encode(query(<note>).map(it => it.value)), )
-
Producing multiple files from the same content. In principle, this feature can be very powerful for producing varied versions of the same content, with differeng style or state configuration, e.g. a paper + slides, or two versions of a document with terms in different languages. In practice, many such use cases would initially be obstructed by how introspection would behave in multi-file export. See the "Limitations" sections for more details.
-
Setting defaults for export options for single-file export:
#set document(pdf: (standard: "ua-1")) ...
Details
-
Different documents can observe each other's contents through introspection. For introspection purposes, the whole bundle is one large output that is iterated on, rather than each document iterating separately. This enables various cross-document introspection use cases. In particular, documents could be labelled and linked to as far as this is supported by the specific export targets. The same holds for cross-document links.
-
A document inherits styles from where it is placed:
#set text(red) #document("main.pdf", [This is red])
-
Top-level content is not allowed in the bundle target, i.e. this is an error when exporting a bundle:
Top-level content! #document("main.pdf")[...]
An exception to this would be spaces, parbreaks, and content that vanishes during realization (e.g. metadata, which shows as empty content regardless of the target) as these may naturally arise from formatting.
-
Nested documents or assets are not allowed, i.e. this is an error:
#document("main.pdf", document("other.pdf", [...]))
In theory, this could be useful (particularly assets in documents, e.g. when emitting an image or data file used by a document in HTML export), but it's not clear whether this is semantically appropriate. Moreover, care would need to be taken to iteratively discover all nested document/assets elements. If this is considered desirable, it could be added later.
-
Duplicate documents/assets with the same path are an error.
-
PNG/SVG documents which result in more than one file require a pattern in the path name (as in the CLI).
-
In the CLI, bundle output must be explicitly enabled with
-f bundleand emits a directory of files. The directory output overwrites existing colliding files on disk, but does not delete unrelated files in the output directory.typst watchserves multi-file output with the live reloading server known from HTML export. Files are served from memory, so unrelated files in the output directory on disk are not served.
Limitations
As mentioned above, I would like to support cross-document introspection, as it unlocks many useful features like cross-linking, cross-HTML-page navs and outlines, etc. However, for some use cases such as reusing the same content across multiple deliverables, this might be undesirable:
#show: it => {
document("paper.pdf", it)
state("slides").update(true)
// Heading numbering is not reset here ...
document("slides.pdf", it)
}
...That said, similar things can already happen within a document (see e.g. #1841). Forbidding cross-document introspection generally seems like an unsuitable solution. It would severely limit the usefulness of the feature. Rather, I believe a more general mechanism that can be used both within and across documents is necessary. However, this is considered out of scope of the work on multi-file export.
Unresolved questions
Should CLI options or document parameters take precedence? Is a difference being made between parameters configured via set rule in single file export versus parameters configured via direct arguments in bundle export?
Currently, a non-auto document.date takes precedence over the CLI's creation timestamp. However, I think it would be more useful if the document could specify a default export setting (a "preferred rendition" in XMP terms), with the CLI still having the option to override it. We might want to change the behavior here.
In particular, something like set document(format: "png") could be nice, but should imo be overridable.
Alternatives
I have considered one primary alternative: Instead of producing any kind of document with the document function, we could have per-format elements, pdf, png, svg, and html. The pdf, and html elements would take on the role of the existing modules and absorb their definitions. This would be a minor breaking changes as the module -> element change would be observable, but normal usage such as html.elem or pdf.attach would continue to work as usual.
Upsides of this alternative:
- Format-specific export options could be cleanly exposed as properties on these types instead of all of them having to be fitted into dictionaries passed to per-format arguments on the
documentfunction. - Only one place where each format exists: As a top-level binding that both creates such a document and exposes format-specific definitions. With the document design, we have both the top-level
pdfmodule and thedocument.pdffield for PDF-specific document settings.
Downsides of this alternative:
- Pollution of the global scope, and potential for collisions, in particular if we might gain additional export formats such as plain text or Pandoc AST; how would the plain text document element be called? That said, formats that require custom definitions would need a module either way.
- Larger API surface with duplicated arguments for path and cross-format options. More annoying to set a default for such options, e.g.
#set document(pages: ((1, 5), 3))would need to become three separate set rules forpdf,png, andsvg. - Conceptually an output file and a
documenthave a 1-1 relationship, so using the same element has a certain elegance to it. Things likeset pdf(standard: "ua-1")would need to behave similarly toset document(..). - The
svgelement could be mistaken for a function that embeds an SVG. To an extent, the same holds for the existingpdfmodule, but a bit less so as it's a module rather than an element. - To me, the document-centered design seems more coherent with the rest of Typst. Elements like
imageorbibliographyalso abstract over multiple internal formats, rather than each format having its own element. Thedocumentelement would follow this pattern. - No natural way to set the default export format (unlike
set document(format: "png")).
Another option would be to keep multi-file export as an HTML-specific thing (html.document/html.page + html.asset) if it's not considered useful enough for other targets. This was the initial idea when starting work on HTML, but upon discovering the potential for a generalization I very much started to like the idea of supporting this as a general mechanism.
Activity
MDLC01 commentedon Jan 22, 2026
A concern I have with this is that the label will be far from the document declaration "header" (the path and title) if the document content is long. Also, is there a way to get the path of a document? For example, if I want to add a
<link>HTML tag that links to a document produced in the bundle.Do you have an example of a situation where this is desirable? One problem I see with it is if I remove a
documentit will never be removed from the output directory unless I do it manually.Intuitively, I view
documentparameters as having higher precedence because they are specified closer to the content itself (the same way element function arguments take precedence over set rules). But as you wrote it seems more useful the other way around so I would say CLI options should have higher precedence even though it is counterintuitive at first.Somewhat relatedly, I wonder whether the following should work. It doesn't do what I expect as of 0.14.2 with
page(page({set page(flipped: true)})creates a vertical page before the horizontal page).laurmaedje commentedon Jan 22, 2026
In practice, you'd typically rather create a new file for a document and start it with
If you want to label it you could then do
This is a tad ugly, but if you write a blog likely you'll have a wrapper function anyways to set up your page and add some extra metadata.
And in a future where labels can be used in code mode (which I could imagine), perhaps this:
Depends on what you mean by "get". Often, you'll just know the path because you defined it. Otherwise, you'll need to know something else about the document to identify it. It's a normal element, so you could query it and access its fields. If you're within the document,
document.pathwill not work as it's not a settable property but if #6721 materializes, it might become possible in the future.I am concerned with the user accidentally deleting a folder with important data in it just because it happens to have the same name as the basename of the compiled file. I think I'd rather err on the side of caution. Deleting & regenerating the output directory is easy after all. But I'm not 100% sure on this one.
I don't think it would or should, in the same way that the set rule in
#rect[#set rect(..); ..]does not affect the outer rectangle.YDX-2147483647 commentedon Jan 22, 2026
Keeping unrelated files is necessary for combining typst with other build tools.
Example: typst + vite
I use vite to generate
*.{css,js}from*.ts, and use typst to generate*.html.*.{css,js}has hash suffixes, somain.typhas to parse.vite/manifest.json(e.g.,vite.typin clreq-gap for typst) to determine the filenames forhtml.{style,script}.Therefore,
typst compilehas to be executed aftervite build, and it should keep the files generated byvite build.flowchart LR main.ts -->|vite| main-D7UwJRdw.js main.ts -->|vite| main-CNOFRLvp.css main.ts -->|vite| .vite/manifest.json -->|"#read(…)"| main.typ -->|typst| index.html main.typ -->|typst| about.html subgraph src main.ts main.typ end subgraph dist main-D7UwJRdw.js main-CNOFRLvp.css index.html about.html endYou may argue that I should manage
*.{css,js}in typst with#asset("…", read(…)), but that introduces additional copies.Moreover, when running
vite dev+typst watch, those files live inhttp://localhost:5173. I don't think typst should allow things like#read("http://…").Related issues
Batch compilation #2738 can be achieved by creating a
main.typthat generatesdocuments in a for loop.Simultaneous query & compile #3015 becomes possible if
document.pathsupportsstdout.MDLC01 commentedon Jan 22, 2026
I see. Then I think at least
typst watchshould delete documents when they are removed from the source.YDX-2147483647 commentedon Jan 27, 2026
Does the current design cover file-level dependency management?
Will the following work reliably? What if the order of two
#documents is reversed?Edit: After laurmaedje replied, I realize that I over-simplified the example. There's a show rule in my original code.
show image: externalize
laurmaedje commentedon Jan 27, 2026
The order of documents does not matter, but this would generally not be supported, as
document("a.png", ..)is part of the output root andimage("a.png")reads from the project or package root. For HTML, you could usehtml.img(src: "a.png")though as that will be emitted as-is.I think that's overall sensible: If you use
image, you provide raw image data from a path or file and let Typst take care of emitting it into the HTML or bundle. If you want to create the image file on your own viadocument, you can drop one level down to the raw HTML API to reference it. This also makes sense in so far as for PDF, there isn't a way to reference an external image. There, you might as well put the content inline instead of in an image. So, this seems fairly HTML-specific.dayala1 commentedon Jan 29, 2026
Lovely feature. Generating batches of documents could be very useful tl automate applying a template tk each element in some data. E.g. creating a form document for each person in a csv.
laurmaedje commentedon Feb 16, 2026
I want to share a couple thoughts on the matter of introspection. I originally just stated that "this is considered out of scope of the work on multi-file export". I've sinced thought more about the topic.
It would be lovely if the result of this thinking would be a simple feature that "solves" the issues at the intersection of multi-file export and introspection, though unfortunately I can't quite deliver that. But before we get into the details, let me restate what the issue is.
Generally speaking, a bundle consisting of a couple of documents falls into two broad categories:
The documents together form a larger work that should be considered a single whole. This could, for instance, be the case for a book that can either be exported as a PDF or a bundle of HTML pages, one per chapter. In this use case, all the documents should be seamlessly cross-introspectible, with referencing, table of contents, etc. all global for the bundle.
The documents are individual works whose production is merely orchestrated by a single Typst file. This could be a bunch of letters produced from some XML data, different translations of the same document, or a document and a presentation produced from some shared content. For these use cases, documents should be more isolated, with something like a table of contents being local to the document. That said, even in this case, it's not out of the question to want to perform some cross-document introspection like referencing a section in another document.
To express both use cases, some user input is needed. Regardless of the chosen default, something needs to decide whether an
#outline()I put into one of mydocuments observes headings in another one. The most direct way to approach this issue is thus to expose this bit of information as a toggle. This could take the form of something like adocument(isolated: true, ..)or it could be some function that creates an introspection scope of sorts by wrapping around multiple documents. Such a design would raise some additional questions (how is convergence defined? does it isolate in both directions?), but it would not be excessively hard to implement.Unfortunately, even though it would cover some use cases, I believe the design would in practice prove limiting. It's perfectly possible to want to cross-link across HTML pages, having an outline and heading counters per HTML page, but a bibliography global to a web site. Isolation is not always a global or per document property, it's something that needs control on a fine-grained basis.
Thus, I am fairly convinced that the real solution is not some scoped isolation mechanism, but rather to make use of and extend the existing selection mechanism. The
outlinefunction already has atargetmechanism. Similarly, for the bibliography, we're in the process of adding a selector-based interface to support multiple bibliographies (see #7277 1). Queries and metadata naturally already support arbitrary selectors.Missing ingredients to make this comfortable to use for document isolation are a
within/ descendant selector (which is planned; I also have a prototype branch) and some convenient way to select the current document. A per-document outline could look something like this:context outline(target: selector(heading).within(here().document())). Now, this is a bit of a mouthful, but if we were to add syntax for a within selector which would also be useful for show rules, it might be something likecontext outline(target: here().document() > heading). Of course, the selector for the current document could also look differently.States are in a less comfortable spot since they are string-keyed. Though I gotta admit, I do find myself agreeing with a take on the Typst Forum that states are often not the right tool. The difficulty in scoping them down to a document is mirrored in the difficulty of producing unique state keys within a document (e.g. for a single figure that contains some items that need to coordinate statefully). Query + metadata-based designs typically have the upper hand in such cases for precisely the same reason due to which they are easier to handle in the bundle target.
Counters, though very parallel in design to states, are a somewhat different story, since they do literally have a selector key in their API. However, like with states, the wish to scope them to a document is mirrored in a wish to scope them within the document, e.g. to a section (see #2652).
The counting system is probably due for an overhaul at some point (I expect @jbirnick will be happy to hear me admitting to this) and perhaps state is not the best abstraction one way or another and best supplanted by custom types (the better version of metadata) + queries. I do not have any concrete answers on these design issues at the moment, but I do think that the bundle export merely surfaces existing issues with states and counters, and those are best solved at their core and not through some document isolation mechanism.
With this, I've already covered most of the introspection API. Across the board, my impression is that solving isolation in a fine-grained manner in the individual APIs will result in a much more flexible system than the blunt tool that is per-document isolation, with benefits even beyond the bundle export target.
Unfortunately, expanding (and also rethinking some of) these APIs is a broad task that will take a longer while. In the meantime, the "many small works" bundle use case will be less well supported than the "one big work" use case for bundle export. However, I do consider the latter more pressing as the former is more readily served by separate compilations. In particular, the "big work" one is useful for the in-progress Typst documentation built in Typst, which is the current main motivation for the work on bundle export. It's also worth reiterating that, like HTML export, the bundle export will remain experimental for the time being.
Finally, the implementation I plan to proceed with is future compatible with both options, should we come to different conclusions in the future. But I think I do make a sufficiently strong case for excluding something like
document.isolatedfrom the initial work in optimism for a better solution down the road.Footnotes
It may look stuck, but it's still on our radar. The design is sound, it's just a matter of getting the implementation into a mergeable state. ↩