Skip to content

Load fonts / font families from files or bytes #2469

Open

Description

@Caellian

Description

It would be nice if fonts could be loaded from typ files for use in templates and icon packages.

Use Case

I want to use a icon font, and instead of having it installed locally (which isn't ideal for packages), I'd like to include it with a relative path.

Activity

  1. added
    feature request
    on Oct 22, 2023
  2. laurmaedje commented on Oct 22, 2023

    @laurmaedje
    Member
  3. added
    text
    on Oct 22, 2023
  4. Caellian commented on Feb 6, 2024

    @Caellian
    Author

    As a workaround, --font-path=<path> can be used.

    Providing a build script that specifies a local font directory should work for public projects so that people don't forget to include/install fonts.

  5. MatejKafka commented on Sep 4, 2024

    @MatejKafka

    +1. Using --font-path works, but when I'm building a template using a custom font, it's an extra step to instruct the user to always pass the parameter when invoking Typst. I can place an image inside a template directory and read it using a relative path, I don't see why I should not be able to do the same with a font file shipped with the template.

  6. pixup1 commented on Sep 23, 2024

    @pixup1

    I don't really understand why the --font-path=<path> argument was implemented instead of this in the first place. Fonts are assets, just like images, they should be loaded in the same way.

  7. laurmaedje commented on Sep 23, 2024

    @laurmaedje
    Member

    Because originally fonts came fully from the external environment (the system) and font-path was an extension to that. I agree that font-path isn't great, but can't everything right first try.

  8. laurmaedje commented on Sep 23, 2024

    @laurmaedje
    Member

    Also: This is not trivial to design and implement nicely.

  9. Caellian commented on Sep 23, 2024

    @Caellian
    Author

    This is not trivial to design and implement nicely.

    I concur, @pixup1 it might seem like they're the same thing, but there's a lot more work required to make typ files just handle an additional command than it is to read an argument. Making fonts loadable from scripts using relative paths requires a lot of difficult decisions:

    • should there be a #loadfont(path, name) command that's required before font name can be used?
    • should #text(font:(path, name, path, ...)) check for every string whether it exists on FS which is incredibly slow (there's no "is this a path" function because any utf-8 string is a path)?
      • should a new path type be introduced for this purpose, #image doesn't require one because the string argument can only be a path?
    • multiple paths can lead to the same file, even more complicated if you handle symlinks. This makes caching non-trivial to implement (and makes #text(font:(path, name, path, ...)) even slower).
    • actually writing support for this takes time, on top of loading system fonts which is time consuming to do well in a cross-platform way on its own.

    I suggested #loadfont(path, name) route as it seems that supporting #text(font:(path)) would slow down compilation of most existing documents.

    If I were writing typst from scratch I'd probably do the exact same thing and leave this for later (ok I wouldn't, but I'd allow myself to get stuck on font handling for a month; a principled programmer would).

    There's a "workaround" that works great for now and I'd prefer devs focus on issues which don't have (as simple) workarounds. IMO this is a low priority issue.

    I believe this issue has enough details to explain what the requirements for its fulfillment are, there's a workaround, and besides completion I see no potential for further development. It'd be good etiquette not to bump it with comments that are negative and don't contribute to it being done, leave a thumbs up if you want it instead or make a PR.

  10. doggobit0 commented on Mar 6, 2025

    @doggobit0

    +1, and specifically I would want to second the potential for this to be used with packages.

    For example, the package I am currently working on makes use of several Open Font License fonts, that I could package alongside the typ files, and have them imported without the user ever having to do anything manually.

    So something like:

    #loadfont(path, name)

    for local directory fonts, and maybe something like

    #loadfont(path, name, package: "foobar")

    if the path should be interpreted relative to the package root

  11. doggobit0 commented on Mar 6, 2025

    @doggobit0

    If needed, I'd be happy to spearhead an RFC proposal (or the equialent typst process) for this to document some possibilities for the syntax itself and then even help with the implementation.

    I'd just need a bit of light guidance and pointers from someone who has successfully contributed to the project before, to make sure I'm not barking up the wrong tree :)

  12. doggobit0 commented on Mar 6, 2025

    @doggobit0

    Okay so I had a look over the codebase, and while I'm 100% sure I missed some things, maybe @laurmaedje could share from his experience here...

    It seems that we have a World trait that is implemented by SystemWorld, that then starts the document compilation. Fonts are currently loaded when setting up the world, and not updated over time. So I can see a few challenges:

    1. The fonts are accessed by index, that's probably not great for our case, as the indices might change. We could work around this by only allowing the addition of fonts, but that might be more of a hack than a strategic impl.
    2. The world is Sync + Send, so we need to make sure we handle concurrency in the registering. Now, that would probably not be necessary (I don't imagine multiple threads parse the document) but it is required by the bound. However, it's not impossible, just something to keep in mind.
    3. Specifically, the slots field on it seems to be serving a similar purpose, and it's already a Mutex<HashMap<...>>, so we might be able to follow similar practices.

    The fonts are held in these FontSlot objects that hold the paths and also caches the font data in memory if it was accessed. Now, this might cause some issues if the compiler is watching for changes and the font files get changed, but Laurenz can probably advise here. I would also argue that handling live font file changes can be postponed by panicking and marking as a known limitation for a while. One open question here would be whether we want to extend the FontSearcher functionality that populates these FontSlot to also handle path-based imports, or whether we want to keep a completely different Font registry for these. There's probably pros and cons for each method.

    Anyway, to get the ball rolling on this, here's my proposal to cut this into manageable bites:

    1. Move from an index-based registry to a HashMap (or name, UUID, we can figure out the specifics) so that we make room for modifying the underlying collection at runtime
    2. Implement functionality to load new fonts at runtime, without actually exposing it to the CLI, merely having it populate into the store. (Now this could either be a self-standing commit or part of the next, but just so we can limit the blast radius)
    3. Implement a way to load fonts via runtime scripting, for example:
      • sys.with-font
      • load-font
      • text(font: (path: ...))
        Personally I am for now in favour of the first, as it would hide this implementation from all but tech-savvy users while we gain confidence in the implementation.
  13. laurmaedje commented on Mar 7, 2025

    @laurmaedje
    Member

    The loadfont design is rather problematic because this function would have a side effect, which is not allowed in Typst. My thinking was more in the direction of having a font or font family type that can be loaded from a path (#3488 is related), that can then be passed to text.font instead of a string. This way, everything stays pure. However, there are many open design questions, e.g. how family grouping works (so that bold via ** continues to work). There was some discussion about this in the Fonts forge thread on Discord recently. Unfortunately, I haven't been able to give much input to the discussion there yet as I'm rather stretched for time.

    Note that fonts that are set like this wouldn't (and couldn't) be added to the World. The World is read-only and just a way to provide external things to Typst. If the font is loaded via path or bytes, it's already loaded via World::file. Past the font loading stage, Typst does not refer to fonts via the index, the index is only there to make the association between World::font and the data in World::book.

  14. changed the title [-]Load fonts from relative paths[/-] [+]Load fonts / font families from files or bytes[/+] on Mar 7, 2025
  15. Caellian commented on Mar 13, 2025

    @Caellian
    Author

    loadfont design is rather problematic because this function would have a side effect

    The way I thought about it was that it gets treated declaratively and affects the whole documents - like CSS @font-face does. But returning a handle is also good and probably more intuitive for end-users.

    how family grouping works

    Suggestion made by Terefang74 is the way to go because of HTML/CSS export I think - the end result will always have to specify all that data and it can't be inferred from files. Typst could use metadata from font files to fill in weight, variable axes, etc.

    Probably a less known/used feature are non-standard variable axes in fonts, which the Discord example overlooks. I'd like the final API to support arbitrary axes in form of a dictionary because they can truly be anything (besides wght, ital, slnt, opsz) - e.g. GRAD, serif size, etc.

    In the end, the final font family type is actually a union of different font variants and axis permutations. Variants could be inferred from the name, axes can't be computed correctly across the board because correctness depends on how the font was made.

    To reiterate on the API design:

    Details
    #let variant-a = font.variant(
      name: "Sans Serif",
      source: read("/usr/share/fonts/myfont-sansserif.otf", "bytes"), // or path?
      weights: (
        wght: (default: 400, min: 1, max: 999), // produce warnings and clamp out of range
        ital: (), // default is optional (defined in font file), as well as min & max.
      ), // or inferred from font file
    )
    
    #let variant-b = font.variant(
      name: "Serif",
      source: read("/usr/share/fonts/myfont-serif.otf", "bytes"),
      weights: (
        wght: (default: 500, min: 1, max: 999),
        ital: (default: 0, min: 0, max: 1),
        srif: (), // a custom axis
      ), // or inferred from font file
    )
    
    #let my-font = font.family(
      name: "My Font",
      authors: ("My Font Forge",),
      license: "OFL",
      variants: (variant-a, variant-b, ...),
      default-variant: variant-a, // or implicitly the first one
    )
    
    #text(font: my-font, font-variant: "Serif", font-variation-settings: (
      ital: 1,
      srif: 10
    ))[Hello Font World]

    As for **, I suggest adding hints to variants which specify axis values, and then picking the variant with hints that are closest to expected ones:

    #let variant-c = font.variant(
      name: "Bold",
      hints: (
        wght: 700,
      ), // see next paragraph
      source: read("/usr/share/fonts/myfont-bold.otf", "bytes"),
    )
    #let variant-d = font.variant(
      name: "Black",
      hints: (
        wght: 900,
      ), // see next paragraph
      source: read("/usr/share/fonts/myfont-black.otf", "bytes"),
    )
    #let variant-e = font.variant(
      name: "Black Italic",
      hints: (
        wght: 900,
        ital: 1,
      ), // see next paragraph
      source: read("/usr/share/fonts/myfont-black-italic.otf", "bytes"),
    )

    For a highly specialized text element like the example above, ** should try to append wght: 700 to query, but I feel ** should have higher priority than font-variation-settings and font-variant specified on text - in case of fonts that don't cover all possible variations. Otherwise people will not understand why ** isn't working.

  16. terefang commented on Jun 11, 2025

    @terefang

    In the end, the final font family type is actually a union of different font variants and axis permutations. Variants could be inferred from the name, axes can't be computed correctly across the board because correctness depends on how the font was made.

    also see my comment here

  17. marked Relative Font Imports #7012 as a duplicate of this issue on Oct 3, 2025
  18. dayala1 commented on Dec 19, 2025

    @dayala1
    Contributor

    This would be a quite important feature for me since in order to spread the use of typst it would be ideal to be able to share a project and tell colleagues to just load it in vscode and press preview. The moment CLI arguments are needed, this breaks. I would like to have some way in the typ file to configure some of the existing cli arguments (e.g. some kind of optional file header), though having the option to load beyond that would also be useful.

  19. DerZade commented on Jan 14, 2026

    @DerZade

    This would be a quite important feature for me since in order to spread the use of typst it would be ideal to be able to share a project and tell colleagues to just load it in vscode and press preview. The moment CLI arguments are needed, this breaks. I would like to have some way in the typ file to configure some of the existing cli arguments (e.g. some kind of optional file header), though having the option to load beyond that would also be useful.

    @dayala1 Not really a fix for this, but as a side note:

    For VSCode you can simply add the font paths in the .vscode/settings.json, which should work for preview:

    {
        "tinymist.fontPaths": [
            "${workspaceFolder}/fonts",
        ]
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requesttext

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions