typst

Typst add non-breaking whitespace in code


I have a custom function that formats a URL with an icon. I want the space between the label and the icon to be non-breaking. For this I would use the ~ character, but this does not work in code.

For example

== Unsuccessful attempt

#let mylink(label, dest) = {
  link(dest)[#emph(underline(label + "~" + box("URL!")))]
}


#mylink("hello", "https://wikipedia.org") // FAILS as ~ is used as a character


== Without code

hello~#box("URL!") // works

#link("https://wikipedia.org")[hello~URL!] // works

#link("https://wikipedia.org")[#underline("hello~URL!")] // FAILS as ~ is used as a character

enter image description here


Solution

  • In code, you have access to the sym.space.nobreak symbol:

    #link("https://wikipedia.org")[#underline("hello" + sym.space.nobreak + "URL!")]
    

    enter image description here

    If you find yourself needing nonbreaking spaces in code often, you can define your own shorthand function with a show rule:

    #let escape-nobreak(body) = {
      // Or use whatever other shorthand you want
      show " ": sym.space.nobreak
      body
    }
    
    #escape-nobreak[
      Some other text...
    
      
      // Will have the same appearance as the screenshot above
      #link("https://wikipedia.org")[#underline("hello URL!")]
    ]