summaryrefslogtreecommitdiff
path: root/library/src/meta/reference.rs
blob: 328e6098a189ee67e058cb687e723413ca2a58b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use super::{BibliographyElem, CiteElem, Counter, Figurable, Numbering};
use crate::prelude::*;
use crate::text::TextElem;

/// A reference to a label or bibliography.
///
/// The reference function produces a textual reference to a label. For example,
/// a reference to a heading will yield an appropriate string such as "Section
/// 1" for a reference to the first heading. The references are also links to
/// the respective element. Reference syntax can also be used to
/// [cite]($func/cite) from a bibliography.
///
/// Referenceable elements include [headings]($func/heading),
/// [figures]($func/figure), and [equations]($func/math.equation). To create a
/// custom referenceable element like a theorem, you can create a figure of a
/// custom [`kind`]($func/figure.kind) and write a show rule for it. In the
/// future, there might be a more direct way to define a custom referenceable
/// element.
///
/// If you just want to link to a labelled element and not get an automatic
/// textual reference, consider using the [`link`]($func/link) function instead.
///
/// ## Example { #example }
/// ```example
/// #set heading(numbering: "1.")
/// #set math.equation(numbering: "(1)")
///
/// = Introduction <intro>
/// Recent developments in
/// typesetting software have
/// rekindled hope in previously
/// frustrated researchers. @distress
/// As shown in @results, we ...
///
/// = Results <results>
/// We discuss our approach in
/// comparison with others.
///
/// == Performance <perf>
/// @slow demonstrates what slow
/// software looks like.
/// $ O(n) = 2^n $ <slow>
///
/// #bibliography("works.bib")
/// ```
///
/// ## Syntax { #syntax }
/// This function also has dedicated syntax: A reference to a label can be
/// created by typing an `@` followed by the name of the label (e.g.
/// `[= Introduction <intro>]` can be referenced by typing `[@intro]`).
///
/// To customize the supplement, add content in square brackets after the
/// reference: `[@intro[Chapter]]`.
///
/// ## Customization { #customization }
/// If you write a show rule for references, you can access the referenced
/// element through the `element` field of the reference. The `element` may
/// be `{none}` even if it exists if Typst hasn't discovered it yet, so you
/// always need to handle that case in your code.
///
/// ```example
/// #set heading(numbering: "1.")
/// #set math.equation(numbering: "(1)")
///
/// #show ref: it => {
///   let eq = math.equation
///   let el = it.element
///   if el != none and el.func() == eq {
///     // Override equation references.
///     numbering(
///       el.numbering,
///       ..counter(eq).at(el.location())
///     )
///   } else {
///     // Other references as usual.
///     it
///   }
/// }
///
/// = Beginnings <beginning>
/// In @beginning we prove @pythagoras.
/// $ a^2 + b^2 = c^2 $ <pythagoras>
/// ```
///
/// Display: Reference
/// Category: meta
#[element(Synthesize, Locatable, Show)]
pub struct RefElem {
    /// The target label that should be referenced.
    #[required]
    pub target: Label,

    /// A supplement for the reference.
    ///
    /// For references to headings or figures, this is added before the
    /// referenced number. For citations, this can be used to add a page number.
    ///
    /// ```example
    /// #set heading(numbering: "1.")
    /// #set ref(supplement: it => {
    ///   if it.func() == heading {
    ///     "Chapter"
    ///   } else {
    ///     "Thing"
    ///   }
    /// })
    ///
    /// = Introduction <intro>
    /// In @intro, we see how to turn
    /// Sections into Chapters. And
    /// in @intro[Part], it is done
    /// manually.
    /// ```
    pub supplement: Smart<Option<Supplement>>,

    /// A synthesized citation.
    #[synthesized]
    pub citation: Option<CiteElem>,

    /// The referenced element.
    #[synthesized]
    pub element: Option<Content>,
}

impl Synthesize for RefElem {
    fn synthesize(&mut self, vt: &mut Vt, styles: StyleChain) -> SourceResult<()> {
        let citation = self.to_citation(vt, styles)?;
        self.push_citation(Some(citation));
        self.push_element(None);

        let target = self.target();
        if vt.introspector.init() && !BibliographyElem::has(vt, &target.0) {
            if let Ok(elem) = vt.introspector.query_label(&target) {
                self.push_element(Some(elem.into_inner()));
                return Ok(());
            }
        }

        Ok(())
    }
}

impl Show for RefElem {
    #[tracing::instrument(name = "RefElem::show", skip_all)]
    fn show(&self, vt: &mut Vt, styles: StyleChain) -> SourceResult<Content> {
        if !vt.introspector.init() {
            return Ok(Content::empty());
        }

        let target = self.target();
        let elem = vt.introspector.query_label(&self.target());

        if BibliographyElem::has(vt, &target.0) {
            if elem.is_ok() {
                bail!(self.span(), "label occurs in the document and its bibliography");
            }

            return Ok(self.to_citation(vt, styles)?.pack().spanned(self.span()));
        }

        let elem = elem.at(self.span())?;
        if !elem.can::<dyn Refable>() {
            if elem.can::<dyn Figurable>() {
                bail!(
                    self.span(),
                    "cannot reference {} directly, try putting it into a figure",
                    elem.func().name()
                );
            } else {
                bail!(self.span(), "cannot reference {}", elem.func().name());
            }
        }

        let supplement = match self.supplement(styles) {
            Smart::Auto | Smart::Custom(None) => None,
            Smart::Custom(Some(supplement)) => {
                Some(supplement.resolve(vt, [(*elem).clone().into()])?)
            }
        };

        let lang = TextElem::lang_in(styles);
        let region = TextElem::region_in(styles);
        let reference = elem
            .with::<dyn Refable>()
            .expect("element should be refable")
            .reference(vt, supplement, lang, region)?;

        Ok(reference.linked(Destination::Location(elem.location().unwrap())))
    }
}

impl RefElem {
    /// Turn the reference into a citation.
    pub fn to_citation(&self, vt: &mut Vt, styles: StyleChain) -> SourceResult<CiteElem> {
        let mut elem = CiteElem::new(vec![self.target().0]);
        elem.0.set_location(self.0.location().unwrap());
        elem.synthesize(vt, styles)?;
        elem.push_supplement(match self.supplement(styles) {
            Smart::Custom(Some(Supplement::Content(content))) => Some(content),
            _ => None,
        });

        Ok(elem)
    }
}

/// Additional content for a reference.
pub enum Supplement {
    Content(Content),
    Func(Func),
}

impl Supplement {
    /// Tries to resolve the supplement into its content.
    pub fn resolve(
        &self,
        vt: &mut Vt,
        args: impl IntoIterator<Item = Value>,
    ) -> SourceResult<Content> {
        match self {
            Supplement::Content(content) => Ok(content.clone()),
            Supplement::Func(func) => func.call_vt(vt, args).map(|v| v.display()),
        }
    }

    /// Tries to get the content of the supplement.
    /// Returns `None` if the supplement is a function.
    pub fn as_content(self) -> Option<Content> {
        match self {
            Supplement::Content(content) => Some(content),
            _ => None,
        }
    }
}

cast_from_value! {
    Supplement,
    v: Content => Self::Content(v),
    v: Func => Self::Func(v),
}

cast_to_value! {
    v: Supplement => match v {
        Supplement::Content(v) => v.into(),
        Supplement::Func(v) => v.into(),
    }
}

/// Marks an element as being able to be referenced. This is used to implement
/// the `@ref` element. It is expected to build the [`Content`] that gets linked
/// by the [`RefElem`].
pub trait Refable {
    /// Tries to build a reference content for this element.
    ///
    /// # Arguments
    /// - `vt` - The virtual typesetter.
    /// - `supplement` - The supplement of the reference.
    /// - `lang`: The language of the reference.
    /// - `region`: The region of the reference.
    fn reference(
        &self,
        vt: &mut Vt,
        supplement: Option<Content>,
        lang: Lang,
        region: Option<Region>,
    ) -> SourceResult<Content>;

    /// Tries to build an outline element for this element.
    /// If this returns `None`, the outline will not include this element.
    /// By default this just calls [`Refable::reference`].
    fn outline(
        &self,
        vt: &mut Vt,
        lang: Lang,
        region: Option<Region>,
    ) -> SourceResult<Option<Content>> {
        self.reference(vt, None, lang, region).map(Some)
    }

    /// Returns the level of this element.
    /// This is used to determine the level of the outline.
    /// By default this returns `0`.
    fn level(&self) -> usize {
        0
    }

    /// Returns the numbering of this element.
    fn numbering(&self) -> Option<Numbering>;

    /// Returns the counter of this element.
    fn counter(&self) -> Counter;
}