aboutsummaryrefslogtreecommitdiff
path: root/rprt-engine/src/selection_functions/result_transformation.rs
blob: 89a071a67c5145856dd92a6e4993ca859ec50aa6 (plain)
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
use crate::buffer::BufferID;
use crate::selection::{Interval, Selection};
use crate::selection_functions::types::{SFArguments, SFError, SFResult};
use crate::state::EditorState;

pub fn complement_transform(es: &EditorState, result: Selection, _: &SFArguments) -> SFResult {
    fn complement_rank0(
        es: &EditorState,
        buffer_id: BufferID,
        pos: usize,
    ) -> Result<Selection, SFError> {
        if let Some(buf) = es.get_buffer(buffer_id) {
            let mut ranges = Vec::new();
            if pos > 0 {
                ranges.push(Interval::new(0, pos));
            }
            let max_pos = buf.max_pos();
            if pos + 1 < max_pos {
                ranges.push(Interval::new(pos + 1, max_pos));
            }
            Ok(Selection::Ranges { buffer_id, ranges })
        } else {
            Err(SFError::BufferNotFound(buffer_id))
        }
    }

    fn complement_rank1(
        es: &EditorState,
        buffer_id: BufferID,
        interval: &Interval,
    ) -> Result<Selection, SFError> {
        if let Some(buf) = es.get_buffer(buffer_id) {
            let max_pos = buf.max_pos();
            if interval.start == 0 && interval.end >= max_pos {
                return Ok(Selection::empty());
            }

            let mut ranges = Vec::new();
            if interval.start == 0 {
                if interval.end < max_pos {
                    ranges.push(Interval::new(interval.end, max_pos));
                }
            } else if interval.end == max_pos {
                ranges.push(Interval::new(0, interval.start));
            } else {
                ranges.push(Interval::new(0, interval.start));
                ranges.push(Interval::new(interval.end, max_pos));
            }
            Ok(Selection::Ranges { buffer_id, ranges })
        } else {
            Err(SFError::BufferNotFound(buffer_id))
        }
    }

    result.vectorise(es, complement_rank0, complement_rank1)
}

pub fn conditional_transform(
    _: &EditorState,
    mut result: Selection,
    arg: &SFArguments,
) -> SFResult {
    if !result.is_empty() {
        Ok(match arg {
            // TODO: think about this niladic case?
            SFArguments::Niladic { .. } => Selection::empty(),
            SFArguments::Monadic { es: _, left } => left.clone(),
            SFArguments::Dyadic {
                es: _,
                left,
                right: _,
            } => left.clone(),
        })
    } else {
        Ok(result)
    }
}