How to properly justify text in a figure caption?

It’s better to avoid using square bracket blocks in most cases. See Create a dedicated section on dangers of using square brackets carelessly (multi-line) · Issue #6844 · typst/typst · GitHub. Also, the whitespace should be replaced with non-break whitespace. Additionally, depending on use cases, a correct re-implementation would be something like this:

#show figure.caption: set text(0.85em)
#show figure.caption: set par(justify: true)
#show figure.caption: it => context {
  show: block.with(width: 45%)
  if it.numbering != none and it.supplement != none {
    let sequence = [].func()
    let supplement = it.supplement
    let numbers = if it.numbering != none {
      it.counter.display(it.numbering)
    }
    let is-empty-supplement = {
      it.supplement.func() == sequence and it.supplement.children.len() == 0
    }
    if not is-empty-supplement { supplement += [~] }
    strong[#supplement#numbers]
    it.separator
  }
  it.body
}

// #set figure(supplement: none)
// #figure(caption: "hey", numbering: none, rect())
#set figure.caption(separator: [ --- ])
#figure(caption: "hey", numbering: "I", rect())

The less you need to (potentially) tweak, the shorter you can make the show rule.

A very short yet hacky solution would be text (regex) show rule:

#show figure.caption: set text(0.85em)
#show figure.caption: set par(justify: true)
#show figure.caption: set block(width: 45%)
#show figure.caption: it => {
  show regex("Figure" + sym.space.nobreak + "\\d+:"): strong
  it
}

#figure(caption: lorem(7), rect())

But you also should stay away from text (string/regex) show rules. From @laurmaedje:

here:

Regex show rules have, in my view, primarily proven useful as a very flexible last resort tool for situations that have no really good solutions.

and here:

you could hack something together with a regex show rule that selects words and creates boxed skews, but both typography and performance will be very bad if this is used for more than a few words

If you profile your document compilation and this does not meaningfully increase compilation time, or you don’t care about it, then you can happily use it. But it’s a bad habit that you might accidentally share with others that don’t have all this context. Which is even worse.

1 Like