Skip to content

Instantly share code, notes, and snippets.

@Dovias
Last active September 13, 2025 19:17
Show Gist options
  • Save Dovias/a10c455d3c18f1801e96a525622499c5 to your computer and use it in GitHub Desktop.
Save Dovias/a10c455d3c18f1801e96a525622499c5 to your computer and use it in GitHub Desktop.
Text clipping function in typst

Text clipping function in Typst

Since, I couldn't find any proper text clipping function for the typst documents on the internet, i've decided to make it myself. This function utilizes binary search to find the most optimal clipped text length, according to its rendered counterpart.

By default clipped text content is being suffixed by ... marker which you can change by setting marker function argument to anything else:

#let clip(text, content, length, marker: "...") = {
  context {
    let element = content(text)
    if (measure(element).width <= length) {
      return element
    }

    let low = 0
    let high = text.len()

    let clipped = ""
    while low <= high {
      let middle = low + calc.floor((high - low) / 2)

      let candidate = content(text.slice(0, middle) + marker)
      let candidate_width = measure(candidate).width
      if candidate_width == length {
        return candidate
      }

      if candidate_width > length {
        high = middle - 1
      } else {
        low = middle + 1
        
        clipped = candidate
      }
    }

    clipped
  }
}

Usage

Usage example of text clipping function
#par(
  clip(
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
    content => text(upper(content), size: 14pt),
    10cm
  ),
  leading: 1.166em,
  spacing: 1.166em
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment