Skip to content

Convenient string formatting #2267

Open

Description

@szdytom

Description

Add a way to format strings, it can be like printf in C, std::format in C++ or format! in Rust, for example

#str.printf("[%s]: %.3f", "hello", 10 / 3) // yields [hello]: 3.333

Use Case

I wanted output the value of a variable in 2 digits, I found it seems that I must do something like:

#(str(calc.floor(x)) + "." + str(calc.rem(calc.floor(x * 10), 10)) + str(calc.rem(calc.round(x * 100), 10)))

If we have something like printf, it can be replaced by:

#str.printf("%.2f", x)

Activity

  1. added
    feature request
    on Sep 30, 2023
  2. PgBiel commented on Sep 30, 2023

    @PgBiel
    Contributor
  3. added
    scripting
    on Oct 2, 2023
  4. changed the title [-]support "formatted print" like printf[/-] [+]Convenient string formatting[/+] on Jul 16, 2024
  5. tingerrr commented on Apr 14, 2025

    @tingerrr
    Contributor

    This just came up on the discord, and I figured I'd give some context on what has been discussed there before.

    This is something Laurenz wants to support, but it's not a high priority because of the aforementioned package and other things that are more important.
    It would look similar to embedding things in content for consistency. So one would have "#foo #bar" where foo and bar are variables in scope. There was no further discussion about formatting modifiers, but this can be proposed/discussed here.

  6. Andrew15-5 commented on Apr 14, 2025

    @Andrew15-5
    Contributor

    I will add a message to hopefully make this issue easier to find: f-string, string interpolation.

    From https://forum.typst.app/t/tiny-date-formatter/3622, it would be nice if you can either pass content as arguments, or to allow evaluating code expressions written as string.

  7. goyalyashpal commented on Jun 19, 2025

    @goyalyashpal

    Description

    A lightweight (text-only) counterpart to content [ ... ] for easy string concatenation

    • This will ease the string manipulation hugely compared to doing gymnastics with + and quotes in typst code (typc) language.

    • Example:

      // Current
      X + " " + X + "\n" + X

      vs.

      // Envisioned
      [
        #X #X
        #X
      ]
    • In other words, a typ (typst marking) construct, but with just plain strings, so that it can be used anywhere a sting is needed,

    • so that rather than the function failing out on error: expected string, found content, this construct itself will fail out when some non-string thing is used in here.

    • in python language analogy, it would be comparison of new f-strings templating vs. old + explicit string concatenation.

    Use Case

    • this feature makes ad-hoc manipulation of text-content very easy.
    • there are lots and lots of places (functions) in typst where plain text is required as input.
    • this feature will make all those functions very flexible to extend to suit particular use.

    the situation / use-case which triggered this need today is as follows:

    • while listing code from source files using typst inbuilt raw(), ...
      (as neither zebraw.zebraw nor sourcerer.code works with v0.13.1)
    • ... prepend a line mentioning the file name (commented) to the read(file) programmatically
    • ... to act as context for the code-listing without requiring any fancy setup

    here's how i attempted it:

    • concerned part along with context (click me to expand)

      // Excerpt from the function body, hence the variables & conditionals
      let filecontents = if prependName == true {
      
          if type(comment) == str {
            // Single line (aka line terminated) comment
            comment + " " + filename + "\n" + read(file)
      
          } else if type(comment) == array [
            // Syntax terminated comment: 
            // Like in Web Dev: HTML/CSS/Jinja: <!-- ... -->   /* ... */  {# ... #}
            #comment.at(0) #filename #comment.at(1)
            #read(file)
      
          ]  // <~~~ error: expected string, found content
        } else {
          read(file)
        }

    • focusing on just the concerned part:

      [
        #comment.at(0) #filename #comment.at(1)
        #read(file)
      ]  // <~~~ error: expected string, found content
    • versus current way to fight with typc (typst code):

      {
        comment.at(0) + " " + filename + " " + comment.at(1) + "\n" + read(file)
        // Linebreaks aren't allowed here, Can't improve readability that way either
      }

    I have stumbled on this issue before too at various other uses, but can't recall atm. i will add those here if & when found to provide more hands-on example of use cases.

    Meta

    I have searched both the github issues & discussions, and didn't find any existing report on this topic.

    other tangents:

  8. goyalyashpal commented on Jun 20, 2025

    @goyalyashpal

    [to] output the value in 2 digits, I found it seems that I must do something like:

    #(str(calc.floor(x)) + "." + str(calc.rem(calc.floor(x * 10), 10)) + str(calc.rem(calc.round(x * 100), 10)))

    - @ szdytom at #2267 (comment)

    for the give particular example, that is rather bad approach. why not just multiply by 10^2 , truncate (drop decimals), then divide by 10^2 ? here, 2 is the precision you want.

  9. goyalyashpal commented on Aug 2, 2025

    @goyalyashpal

    Collection of use-case examples for this text-only-templating construct, along with their currently working counterpart (mostly using array.join)

    2. For raw.text: Prepend commented filename to listing file contents

    • ref: (neither zebraw.zebraw v0.5.5 nor sourcerer.code v0.2.1 worked with v0.13.1)

    • Isolated envisioned sample:

      [
        #comment.at(0) #filename #comment.at(1)
        #read(file)
      ]
      
    • Envisioned sample with context:

      // Excerpt from the function body, hence the variables & conditionals
      let filecontents = if prependName == true {
      
          if type(comment) == str {
            // Single line (aka line terminated) comment
            comment + " " + filename + "\n" + read(file)
      
          } else if type(comment) == array [
            // Syntax terminated comment: 
            // Like in Web Dev: HTML/CSS/Jinja: <!-- ... -->   /* ... */  {# ... #}
            #comment.at(0) #filename #comment.at(1)
            #read(file)
      
          ]  // <~~~ error: expected string, found content
        } else {
          read(file)
        }
      

    • Working example in current typst:

      (
        comment.at(0), filename, comment.at(1), 
        read(file),
      ).join(" ", last: "\n")
      
      // Older naive method
      // Linebreaks aren't allowed here, Can't improve readability that way either
      /*
      {
        comment.at(0) + " " + filename + " " + comment.at(1) + "\n" + read(file)
      }
       */

    3. Create panic or assert.message with sys.version

    • ref: set typst version in document #6567 and submodule repo's archive? yunanwg/brilliant-CV#102

    • Isolated envisioned sample:

      #let versionError = [
        Currently using typst v#sys.version; \
        please use v#typVersion to compile this document.
      ]
      
    • Envisioned sample with context:

      #let typVersion = version(0, 11, 1)
      
      #let versionError = [
        Currently using typst v#sys.version; \
        please use v#typVersion to compile this document.
      ]  // <~~~ Here
      
      #assert.eq(
        sys.version,
        typVersion,
        message: versionError  // <~~~ Here
      )
      

    • Working example in current typst:

      // Currently using typst v0.12.0; please use v0.11.1 to compile this document.
      
      #let versionError = {
        "Currently using typst v"
        str(sys.version)
        "; please use v"
        str(typVersion)
        " to compile this document."
      }
      
      
      // The .join(" ") doesn't work well here due to "v0.123..."
      /*
      #let versionError = (
        "Currently using typst v",
        str(sys.version),
        "; please use v",
        str(typVersion),
        "to compile this document.",
      ).join(" ")
      */
      

  10. Andrew15-5 commented on Aug 2, 2025

    @Andrew15-5
    Contributor

    currently required something like follows using array.join:

    As was mentioned before, use oxifmt package if you don't like a more verbose native approach. You don't have to use str or join with it. It doesn't have markup-based templating, only string-based. For markup, you can try t4t's get.text(), usually it converts to str pretty well.

  11. goyalyashpal commented on Aug 2, 2025

    @goyalyashpal

    As was mentioned before, use oxifmt package

    - @ Andrew15-5 at #2267 (comment)

    what is the scope of this issue?

  12. Andrew15-5 commented on Aug 2, 2025

    @Andrew15-5
    Contributor

    I don't get the purpose of the question if the title and OP explain it.

  13. goyalyashpal commented on Aug 2, 2025

    @goyalyashpal

    i dont get the purpose of "as mentioned before ... oxifmt" ?

  14. tingerrr commented on Aug 2, 2025

    @tingerrr
    Contributor

    I agree that "as mentioned before ... oxifmt" does not add anything to the discussion when they simply added a motivating use case for string formatting.

  15. Andrew15-5 commented on Aug 2, 2025

    @Andrew15-5
    Contributor

    The use of str and join are not required if you don't want to write them. Use a package that does more or less what this issue is about. A mention of a use case of version type in error strings is enough. The rest doesn't add anything new, really.

  16. tingerrr commented on Aug 2, 2025

    @tingerrr
    Contributor

    This issue is about adding string formatting to Typst, telling someone who adds an example of why this is a good idea to use a package just derails the discussion.

  17. goyalyashpal commented on Aug 2, 2025

    @goyalyashpal
  18. H2CO3 commented on Oct 14, 2025

    @H2CO3

    [to] output the value in 2 digits, I found it seems that I must do something like:
    #(str(calc.floor(x)) + "." + str(calc.rem(calc.floor(x * 10), 10)) + str(calc.rem(calc.round(x * 100), 10)))

    for the give particular example, that is rather bad approach. why not just multiply by 10^2 , truncate (drop decimals), then divide by 10^2 ? here, 2 is the precision you want.

    Because it will end up with no decimals as a string if the rounded end result happens to be an integer. In the case of a single decimal place, the issue is even worse as it comes up way higher (around 10% of all numbers on average), which makes these numbers look inconsistent when placed e.g. in a table.

  19. tingerrr commented on Dec 22, 2025

    @tingerrr
    Contributor

    After some discussion in the community forge, Laurenz and a few others came to the conclusion that, if supported, the interpolation syntax should be consistent with content mode: "foo #<expr> bar" embeds <expr> between "foo " and " bar", converting it into a string if necessary just like the same source code in content mode would turn it into content.

    It's unlikely that Typst will gain format specifiers for things like decimal precision and zero padding, these things should be controlled through some other mechanism. I personally think this makes sense because the unification of types and elements should make it easier to control formatting of numbers in a consistent and efficient manner, for example. 1

    Laurenz noted that he'll write up his thoughts next year regarding edition-like migrations for breaking changes to syntax and semantics of Typst, which should come in handy for this feature too.

    Here are a few problems I encountered while implementing an MVP that prompted the discussion on the forge:

    • Color constructors allow an optional # at the start of RGB(A) hex codes, these would benefit the most from the aforementioned migration mechanism. Introducing this syntax would otherwise break all usages of hexcodes in color constructors.
    • To stay consistent with content mode, #foo;-bar would evaluate to str(foo) + "-bar" (note the missing ;). I mentioned that this never felt right to me because it is surprising for most people. Laurenz is open to revisiting the semicolon termination across both string interpolation and content mode for consistency. This would also benefit from the aforementioned migration mechanism because it is particularly hard to spot.
    • Like string escapes, incomplete interpolations will simply be included in the string as is, e.g. "foo #" literally evaluates to "foo #". This behavior for escapes is explicitly mentioned on the regex docs. Though, if interpolation is implemented more like described above (similar to ECMAScript template literals), then this is no longer possible and inconsistent. Though, perhaps this is fine, I prefer the explicit parsing failure to be quite honest.

    cc: @laurmaedje I didn't explicitly quote you, but if I got something wrong, feel free to correct me here.

    Footnotes

    1. With user defined types and the element-type-unification, types could simply have a str method which controls the to-string conversion. This would not be settable, as string interpolation happens during evaluation. With this, a type like float could have one or multiple formatting methods that takes a few parameters like padding and decimal precision and return an object which implements str and respects these parameters. ↩

  20. Andrew15-5 commented on Dec 25, 2025

    @Andrew15-5
  21. YPares commented on Oct 10, 2026

    @YPares

    Until this is addressed, I've implemented https://github.com/YPares/typstware/tree/master#minijinja which provides the minijinja string-templating engine. It's not as direct as string interpolation (you need to explictly pass the values to splice in as a dictionary), but it's still much more convenient than manual string conversions and concatenation.

  22. tingerrr commented on Oct 10, 2026

    @tingerrr
    Contributor

    Hmm, I wonder why my PR is not linked here yet, I guess I never connected the two other than by commit message. See #7620.

  23. goyalyashpal commented on Oct 10, 2026

    @goyalyashpal
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 requestscripting

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions