summaryrefslogtreecommitdiff
path: root/src/library/align.rs
blob: 4b2ee8c3e48f42716e9e6bd69db4cd06b11a3737 (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
//! Alignment function.

use super::prelude::*;
use crate::layout::Alignment;


/// Allows to align content in different ways.
#[derive(Debug, PartialEq)]
pub struct AlignFunc {
    alignment: Alignment,
    body: Option<SyntaxTree>,
}

impl Function for AlignFunc {
    fn parse(header: &FuncHeader, body: Option<&str>, ctx: ParseContext)
        -> ParseResult<Self> where Self: Sized {

        if header.args.len() != 1 || !header.kwargs.is_empty() {
            return err("expected exactly one positional argument specifying the alignment");
        }

        let alignment = if let Expression::Ident(ident) = &header.args[0] {
            match ident.as_str() {
                "left" => Alignment::Left,
                "right" => Alignment::Right,
                s => return err(format!("invalid alignment specifier: '{}'", s)),
            }
        } else {
            return err(format!("expected alignment specifier, found: '{}'", header.args[0]));
        };

        let body = if let Some(body) = body {
            Some(parse(body, ctx)?)
        } else {
            None
        };

        Ok(AlignFunc { alignment, body })
    }

    fn layout(&self, mut ctx: LayoutContext) -> LayoutResult<Option<Layout>> {
        if let Some(body) = &self.body {
            // Override the previous alignment and do the layouting.
            ctx.space.alignment = self.alignment;
            layout(body, ctx)
                .map(|l| Some(Layout::Boxed(l)))
        } else {
            unimplemented!("context-modifying align func")
        }
    }
}