Skip to content

Downgrade missing references from errors to warning #4035

Open

Description

@m-krastev

Description

Coming from LaTeX, you could compile a document even if a reference is not defined. This would trigger a warning and a "??" would be printed on the resulting file.

Currently, Typst just errs and exits the whole compiler process (e.g. if using typst watch).

Use Case

A similar functionality where the error is ignored and a warning is emitted instead would help creative flow while writing so that one does not have to immediately go back to a missing reference and try to address it.

Activity

  1. added
    feature request
    on Apr 29, 2024
  2. added
    diagnostics
    on Apr 29, 2024
  3. Enivex commented on Apr 29, 2024

    @Enivex
    Collaborator

    See #1276 and #1322

  4. m-krastev commented on Apr 30, 2024

    @m-krastev
    Author

    I would love for the functionality of #1276 to be included in the base compiler, as this should not be considered as a critical compiler failure.

  5. laurmaedje commented on Apr 30, 2024

    @laurmaedje
    Member

    If we can come up with a good design, I'm open to it.

  6. Coekjan commented on May 8, 2024

    @Coekjan
    Contributor

    Maybe we can add a cli argument (like --allow-missing-ref, or something else) to toggle the compile/watch behavior:

    1. normal (current) behavior: deny missing ref
    2. --allow-missing-ref behavior: warn on missing ref, and print ? (or something else, or something configurable by cli args) in the result
  7. LaurenzV commented on May 8, 2024

    @LaurenzV
    Collaborator

    I think instead of having a specific flags just for refs we should instead think about how to implement a more generalized system for enabling/disabling warnings, then this could be extended to this specific use case as well.

  8. jack-jjm commented on May 16, 2024

    @jack-jjm

    Yes! You want to be able to just put the references in as you're writing and add the actual reference targets at the end. An --ignore-refs flag or something would be ideal. The current behavior encourages putting in a bunch of dummy referands just to get the compiler off your back, which is worse since you might forget them.

    This at the beginning of the document makes a good workaround:

    #show ref: it => {
      it.target
    }
    

    However, this doesn't solve the problem because now all refs will be replaced by a placeholder, even ones that work, so you can't gradually fix broken refs and have them fill in. This will do both:

    #show ref: it => {
      if query(it.target).len() > 0 {
        it
      } else {
        it.target
      }
    }
    
  9. Eismandel commented on Jul 3, 2024

    @Eismandel

    Thank you for your solution. As I tend to overlook such messages, I added some additional code

    #let MissingRef(body, small_text: 5pt) = {
          let body = if body == [] {
            [Missing Ref: XXX]
          } else {
            body
          }
          set text(fill: white, size: small_text, weight: "bold")
          text()[~~]
          box(
            fill: rgb("#e046d3"),
            outset: 4pt,
            radius: 3pt,
            stroke: luma(1),
            [#body #place()[    
              #set text(size: 0pt)    
              #figure(kind: "MissingRef", supplement: "", caption: body, []),
            ]])
          text()[~~]
    }
    

    With the #show rule

    #show ref: it => {
      if query(it.target).len() > 0 {
        it
      } else {
        MissingRef[Ref Missing #str(it.target)]
    
      }
    }
    

    With this set, I can create a new outline only displayed when there are some missing refs

    #context {
      let elems = query(
        selector(figure.where(kind: "MissingRef")),
       )
       if elems.len() > 0 [
          #pagebreak()
          //#set text(fill: rgb("#D70F37"), size: 30pt, weight: "bold")
          #text(fill: rgb("#D70F37"), size: 30pt, weight: "bold")[Missing Refs]
          #linebreak()
          //#set text(fill: rgb("#D70F37"), size: 12pt)
          #text(fill: rgb("#D70F37"), size: 12pt)[
            #outline(
              title: [],
              target: figure.where(kind: "MissingRef")
              )
          ]
          #pagebreak()
     ] 
    }
    
    

    This is even cooler as compiler warnings, as I tend to ignore them and with this outline, I get informed within the document directly

  10. jack-jjm commented on Jul 6, 2024

    @jack-jjm

    To be honest, I'm wondering if a compiler flag would be the best solution. I think a standard (built in) package you could import that would do this for you might be better.

  11. laurmaedje commented on Jul 6, 2024

    @laurmaedje
    Member

    At this point, I think the best solution is to just downgrade it to a warning.

  12. hbierlee commented on Jul 9, 2024

    @hbierlee

    I would also be in favor of warnings for missing refs. Developing and debugging is easier when you can remove large parts of the document, and now everything is very strongly connected.

    #show ref: it => {
      if query(it.target).len() > 0 {
        it
      } else {
        it.target
      }
    }
    

    This is a great help, but unfortunately does not seem to work for citations which return () when queried. I've opened a separate issue. If someone has a workaround there, let me know.

  13. changed the title [-]Add support for missing references (w/ warnings)[/-] [+]Downgrade missing references from errors to warning[/+] on Jul 15, 2024
  14. added
    urgent
    on Jul 15, 2024
  15. Andrew15-5 commented on Jul 29, 2024

    @Andrew15-5
    Contributor

    At this point, I think the best solution is to just downgrade it to a warning.

    Is this the line?

    eco_format!("label `{}` does not exist in the document", label.repr())

    echo '@a' | typst c -f pdf - /dev/null
  16. 2 remaining items

  17. jack-jjm commented on Aug 4, 2024

    @jack-jjm

    I don't think I would mind as long as the compiler tells me how to switch it to a warning in the error message

  18. PgBiel commented on Aug 4, 2024

    @PgBiel
    Contributor

    The whole thing is that people want to just keep writing before filling in their references.

    I'd argue that the compiler is right to be loud about this by default: the main use case is when the references do, in fact, exist, to the point that we have autocomplete for existing references, and I'd certainly not want to accidentally share a document with missing references at some spots (can be easy to miss when the document is large) - warnings are good, but an error is even better and ensures you won't miss it. I feel like blocking compilation unless you're certain this is what you want is a good default, and you only have to change it once per module. Warning by default feels like a step backwards on reliability, imo.

    I don't think I would mind as long as the compiler tells me how to switch it to a warning in the error message

    Sounds like a good idea to me!

  19. Enivex commented on Aug 4, 2024

    @Enivex
    Collaborator

    I'd argue that warning by default is better for usability. Otherwise you'll have to add preamble to every single subfile (chapters e.g.) to compile them stand-alone.

  20. PgBiel commented on Aug 4, 2024

    @PgBiel
    Contributor

    Otherwise you'll have to add preamble to every single subfile (chapters e.g.) to compile them stand-alone.

    I'm fine with that tradeoff. Using subfiles standalone is already problematic for any kind of introspection, not just references, so I'm not sure this would bring enough of a gain compared to having a more general solution to provide more context to subfiles.

    Besides, we could add compiler flags that permit controlling warning levels externally regardless of the file being compiled, or even project-wide settings in a future typst.toml.

    Edit: This ties into what was being discussed previously in this issue regarding compiler flags for controlling warnings (regardless of their default levels), and it's worth emphasizing how warnings could be less effective as a default for the more abundantly common use case (expect all references to exist), given the following comment:

    As I tend to overlook such messages, (...)

  21. removed
    urgent
    on Sep 17, 2024
  22. PgBiel commented on Sep 17, 2024

    @PgBiel
    Contributor

    Re: #4974 (comment)
    Cc @Enivex

    I have the exact opposite impression. The majority would rather have references be a warning, without blocking compilation.

    I think arguing in terms of amount of users isn't productive in this discussion (and was a mistake in my part) because there is actually overlap between the groups "users who would like missing references to not block compilation" and "users who would like missing references to block compilation". Rather, the same user may want both at different moments.

    Let's consider the two "purposes" for triggering a Typst compilation below (which would influence what would block it or not), in a usual workflow for writing a document:

    1. Preview: when you just want to preview your document, missing references are usually OK, since you're just looking to have an idea of how it looks.
      • Although a missing reference might still change how the document looks due to show rules on #ref, so not all documents would produce accurate preview compilations if missing references are allowed, so it should still be toggleable somehow (see one potential proposal below).
    2. Export: when you want to share your document to others (e.g. turn in your thesis, present your slides and so on), you certainly do not want to allow missing references for obvious reasons. For example, you wouldn't want a reviewer to ask what is this red @typstlaur text. A warning would help in this case, but it is often the case that people export with warnings anyway because they're satisfied with how everything looks and don't want to spend more precious time satisfying the Typst compiler (and thus may miss this warning which is clearly different from something like redundant **, which can be safely ignored).

    Therefore, I'd argue that

    1. Being stricter by default is better, as I'd rather have the compiler, by default, reject otherwise valid preview compilations than accept one invalid export compilation. Typst is here to ensure quality in your documents, and detecting this kind of problem (at the right time) is part of what makes the Typst compiler so useful and helpful.
    2. But it should still be possible to make the compiler more flexible. One potential proposal here is to differentiate preview and export compilations somehow. This could be implemented by marking some errors as dismissible for preview compilations (/ "deny-by-default warnings"), and:
      • The web app and LSPs would compile in "preview mode" / downgrade those warnings by default when displaying the document preview, allowing the user to still preview their documents, whereas clicking the export button would either fail or at least prompt the user for confirmation, listing problems which should be given attention;
      • The Typst CLI is more often than not used for final exports, so it should fail compilation by default, but could simulate the same behavior through a --preview flag which downgrades dismissible errors.

    Hopefully this clarifies my position better; I think this isn't a matter of catering to a certain group users or another, but rather (since those groups do have an intersection) appealing to different needs they may have in their workflow with Typst.

  23. laurmaedje commented on Sep 17, 2024

    @laurmaedje
    Member

    Martin and I had thoughts in a similar direction. I don't like --allow-missing-refs at all, but a generic preview/draft compile that demotes certain errors to warnings and is enabled by default for previews sounds like a good idea.

  24. peekxc commented on Sep 30, 2024

    @peekxc

    Yes! You want to be able to just put the references in as you're writing and add the actual reference targets at the end. An --ignore-refs flag or something would be ideal. The current behavior encourages putting in a bunch of dummy referands just to get the compiler off your back, which is worse since you might forget them.

    This at the beginning of the document makes a good workaround:

    #show ref: it => {
      it.target
    }
    

    However, this doesn't solve the problem because now all refs will be replaced by a placeholder, even ones that work, so you can't gradually fix broken refs and have them fill in. This will do both:

    #show ref: it => {
      if query(it.target).len() > 0 {
        it
      } else {
        it.target
      }
    }
    

    This did not work for me. Still hitting compiler errors (typst 0.11.1)

    Edit: I encountered this in trying to convert a large Latex source not correctly translated from pandoc to typst, wherein I'm constantly commenting out large portions of the source and manually translate the transpiled-typst to manually written typst. Because I want instant preview while doing this, raising errors on missing label or redundant label is cumbersome.

    One workaround I found was as follows (not the best, but workable).

    1. Via regex, select all the labels in the doc source of the form eq:my_equation
    2. De-duplicate the labels via any way (e.g. some tool like this)
    3. Go to the end of the document, and put:

    $ 1 $ eq:my_equation

    on each line.

    1. All labels now exist and the document should now compile. As you proceed with uncommenting large portions of code, you can remove the labels at the end as you manually add them.
  25. lucascherzer commented on Jan 20, 2025

    @lucascherzer

    @PgBiel

    But it should still be possible to make the compiler more flexible

    As I independently came to a similar conclusion (see #5710), I'd like to interject here in this conversation as well.
    Differentiating preview and release is, at least in my opinion a powerful and useful feature.
    I'm using typst right now for a university project, and this feature would significantly improve my workflow.

    Regarding the implementation details, I think we can take inspiration from the rust compiler (specifically with cargo). Firstly, a --release flag or something similar is an easy and quick option that does 99% of what 90% of users want (I assume).
    To cater to the rest, a declarative config file (like a config.toml) could expose more options.

  26. laurmaedje commented on Jan 20, 2025

    @laurmaedje
    Member

    I would definitely prefer this to be opt-in instead opt out, i.e. --draft instead of --release

  27. lucascherzer commented on Feb 4, 2025

    @lucascherzer

    Another thing to consider is how this could be exposed to package authors.
    Consider for example the fletcher package. It has the option to display grid lines for debugging purposes. You would not want to keep this on for the final version.

    Having an option as a plugin author to mark certain features as "draft-only" would be great!

  28. ukoethe commented on Mar 2, 2025

    @ukoethe

    In a draft document, I'd also like the option to render missing references as placeholders. I tried the proposed solution

    #show ref: it => {
      if query(it.target).len() > 0 {
        it
      } else {
        underline(stroke: (paint: red, thickness: 2pt, dash: "densely-dotted"), [undefined: \@#str(it.target)])
      }
    }

    It works nicely on equation references, but seems to prevent citations from being rendered at all. Can the above code be improved for this use case?

    Edit: The above refers to citations in the form @einstein1905relativity, not to #cite(<einstein1905relativity>).

  29. azuline commented on Oct 29, 2025

    @azuline

    In my case I have a very large set of notes, essentially a large survey, which I've split into several volumes. The volumes cross-reference each other, but I also like to compile and open them separately because the entire group is rather large. I am now trying to migrate from LaTeX and I've hit this stumbling block =/

  30. rijuyuezhu commented on Nov 5, 2025

    @rijuyuezhu

    It seems that from a certain version (I think typst v0.14.0), the method metioned above (using query(it.target).len() > 0) does not work for bibliography entries. My alternative solution is

    #import "@preview/citegeist:0.2.0": load-bibliography
    
    #let all-bib-entries() = {
      let bib-file = {
        let all-bib = query(bibliography)
        if all-bib.len() > 0 {
          all-bib.at(0).sources.at(0)
        } else {
          none
        }
      }
      if bib-file == none {
        (:)
      } else {
        load-bibliography(read(bib-file))
      }
    }
    
    #let possible-missing-ref(it) = {
      if str(it.target) in all-bib-entries() or it.element != none {
        it
      } else {
        text(fill: red)[\<Target not found: #emph(str(it.target))\>]
      }
    }
    
    #show ref: possible-missing-ref
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

    diagnosticsfeature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions