typst_library/introspection/
locate.rs

1use comemo::Tracked;
2
3use crate::diag::HintedStrResult;
4use crate::engine::Engine;
5use crate::foundations::{Context, LocatableSelector, func};
6use crate::introspection::Location;
7
8/// Determines the location of an element in the document.
9///
10/// Takes a selector that must match exactly one element and returns that
11/// element's [`location`]. This location can, in particular, be used to
12/// retrieve the physical [`page`]($location.page) number and
13/// [`position`]($location.position) (page, x, y) for that element.
14///
15/// # Examples
16/// Locating a specific element:
17/// ```example
18/// #context [
19///   Introduction is at: \
20///   #locate(<intro>).position()
21/// ]
22///
23/// = Introduction <intro>
24/// ```
25#[func(contextual)]
26pub fn locate(
27    engine: &mut Engine,
28    context: Tracked<Context>,
29    /// A selector that should match exactly one element. This element will be
30    /// located.
31    ///
32    /// Especially useful in combination with
33    /// - [`here`] to locate the current context,
34    /// - a [`location`] retrieved from some queried element via the
35    ///   [`location()`]($content.location) method on content.
36    selector: LocatableSelector,
37) -> HintedStrResult<Location> {
38    selector.resolve_unique(engine.introspector, context)
39}