Snippet: LaTeX \cancelto for Typst

(Second equation had cancelto(extra-pad: #false, ...).)

For those who wants to be a little extra fancy with their simplifications. This works in block equations by default. Inline math might need cancelto(block: #false, ...) if you have fractions or limits or sums, etc..

#let cancelto(
  to,
  body,
  fill: black,
  stroke: 0.04em,
  head-size: 0.35em,
  label-offset: (0.25em, -0.25em),
  label-gap: 0.1em,
  label-scale: 0.7,
  block: true,
  extra-pad: true,
) = context {
  let body-eq = math.equation(block: block, numbering: none, body)
  let body-size = measure(body-eq)

  // Label
  let label = text(size: label-scale * 1em, to)
  let label-size = measure(label)

  // Label center relative to body's center + horizon
  let ox = label-offset.at(0).to-absolute()
  let oy = label-offset.at(1).to-absolute()
  let lx = body-size.width / 2 + ox + label-size.width / 2
  let ly = -body-size.height / 2 + oy - label-size.height / 2

  // Direction from body center to label center
  let dist-pt = calc.sqrt(lx.pt() * lx.pt() + ly.pt() * ly.pt())
  let dist = dist-pt * 1pt
  let ux = if dist-pt > 1e-6 { lx.pt() / dist-pt } else { 1.0 }
  let uy = if dist-pt > 1e-6 { ly.pt() / dist-pt } else { 0.0 }
  let angle = calc.atan2(lx.pt(), ly.pt())

  // Leave some space between arrow and label
  let gap-abs = label-gap.to-absolute()
  let bx = label-size.width / 2 + gap-abs
  let by = label-size.height / 2 + gap-abs
  let tx = if calc.abs(ux) > 1e-6 { bx / calc.abs(ux) } else { 1e9 * 1pt }
  let ty = if calc.abs(uy) > 1e-6 { by / calc.abs(uy) } else { 1e9 * 1pt }
  let t-edge = calc.min(tx, ty)

  let r-tip = calc.max(0pt, dist - t-edge)
  let len = 2 * r-tip

  // Arrowhead sizes
  let hl = head-size.to-absolute()
  let hw = hl * 0.35

  let arrow = rotate(
    angle,
    box(width: len, height: 2 * hw, {
      place(left + horizon, line(
        length: calc.max(0pt, len - hl * 0.5),
        stroke: stroke,
      ))
      place(right + horizon, polygon(
        fill: fill,
        (0em, 0em),
        (0em, 2 * hw),
        (hl, hw),
      ))
    }),
  )

  let pad = if extra-pad {
    (
      top: calc.max(0pt, (ly - label-size.height / 2) - body-size.height / 2),
      right: calc.max(0pt, (lx + label-size.width / 2) - body-size.width / 2),
    )
  } else {
    0pt
  }

  box(inset: pad, {
    body-eq
    place(center + horizon, arrow)
    place(center + horizon, dx: lx, dy: ly, label)
  })
}

Is there an equivalent to Latex's \cancelto in Typst? was my source of inspiration.

1 Like