Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current page margins in typst

Tags:

margins

typst

In typst I want to write code that does something if the current location is at (or close to) the left-hand margin.

How can I get the value of the current page margins as numbers?

For example, the code below does what I want with the default 25mm margins, but I want it to work with arbitrary page margins. So I want to change the hard-coded 25 to a function which returns the current left margin value, in mm, as a number.

#let lr() = locate(l=>if l.position().x.mm()<=25 [*left* ] else  [_right_ ])

#let n = 0
#while n < 100 {
  n = n+1
  [#lr()]
}

output

like image 386
user108903 Avatar asked Nov 29 '25 18:11

user108903


1 Answers

With Typst 0.11 and context you can access the values set by set rules. Hence, you could use this snippet:

#set page(margin: (left: 10%))
#context {
  // In Typst 0.11, `auto` is not yet resolved in context blocks so we
  // need to check for it and apply the default
  let left = if page.margin == auto or page.margin.left == auto {
    // https://typst.app/docs/reference/layout/page/#parameters-margin
    // The margins are set automatically to 2.5/21 times the smaller dimension of the page
    calc.min(page.width, page.height)*2.5/21
  } else {
    // l.position returns a length but page.margin.left returns a relative
    // length. We resolve it here manually.
    page.margin.left.length + page.margin.left.ratio * page.width
  }

  let lr() = locate(l=> if l.position().x <= left [*left* ] else  [_right_ ])

  let n = 0
  while n < 100 {
    n = n+1
    [#lr()]
  }
}

As you see above, there are still some peculiarities with regards to the resolution of auto and relative lengths, but we expect to fix that in the future.

like image 65
Martin Avatar answered Dec 01 '25 23:12

Martin