summaryrefslogtreecommitdiff
path: root/src/library/mod.rs
blob: 433a4c73ff6f69fb1ab61b6c4d67bfaad4a42a4b (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
//! The _Typst_ standard library.

use crate::syntax::Scope;
use crate::func::prelude::*;

pub_use_mod!(font);
pub_use_mod!(layout);
pub_use_mod!(page);
pub_use_mod!(spacing);

/// Create a scope with all standard functions.
pub fn std() -> Scope {
    let mut std = Scope::new::<ValFunc>();

    // Basics
    std.add::<ValFunc>("val");

    // Font setup
    std.add::<FontFamilyFunc>("font.family");
    std.add::<FontStyleFunc>("font.style");
    std.add::<FontWeightFunc>("font.weight");
    std.add::<FontSizeFunc>("font.size");
    std.add_with_meta::<ContentSpacingFunc>("word.spacing", ContentKind::Word);

    // Layout
    std.add_with_meta::<ContentSpacingFunc>("line.spacing", ContentKind::Line);
    std.add_with_meta::<ContentSpacingFunc>("par.spacing", ContentKind::Paragraph);
    std.add::<AlignFunc>("align");
    std.add::<DirectionFunc>("direction");
    std.add::<BoxFunc>("box");

    // Spacing
    std.add::<LineBreakFunc>("n");
    std.add::<LineBreakFunc>("line.break");
    std.add::<ParBreakFunc>("par.break");
    std.add::<PageBreakFunc>("page.break");
    std.add_with_meta::<SpacingFunc>("spacing", None);
    std.add_with_meta::<SpacingFunc>("h", Some(Horizontal));
    std.add_with_meta::<SpacingFunc>("v", Some(Vertical));

    // Page setup
    std.add::<PageSizeFunc>("page.size");
    std.add::<PageMarginsFunc>("page.margins");

    std
}

function! {
    /// `val`: Layouts the body with no special effect.
    #[derive(Debug, Clone, PartialEq)]
    pub struct ValFunc {
        body: Option<SyntaxModel>,
    }

    parse(header, body, state, f) {
        header.args.pos.items.clear();
        header.args.key.pairs.clear();
        ValFunc { body: body!(opt: body, state, f) }
    }

    layout(self, ctx, f) {
        match &self.body {
            Some(model) => vec![LayoutSyntaxModel(model)],
            None => vec![],
        }
    }
}

/// Layout an optional body with a change of the text style.
fn styled<'a, T, F>(
    body: &'a Option<SyntaxModel>,
    ctx: LayoutContext<'_>,
    data: Option<T>,
    f: F,
) -> Commands<'a> where F: FnOnce(&mut TextStyle, T) {
    if let Some(data) = data {
        let mut style = ctx.style.text.clone();
        f(&mut style, data);

        match body {
            Some(model) => vec![
                SetTextStyle(style),
                LayoutSyntaxModel(model),
                SetTextStyle(ctx.style.text.clone()),
            ],
            None => vec![SetTextStyle(style)],
        }
    } else {
        vec![]
    }
}