shrs_core/readline/
highlight.rs

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
//! Syntax highlighting
//!
//! Highlighters are handlers that modify the style of the line buffer,
//! which can be used to provide syntax highlighting.

use std::marker::PhantomData;

use anyhow::Result;
use crossterm::style::{Color, ContentStyle};
use shrs_lang::{Lexer, Token};
use shrs_utils::StyledBuf;

use super::super::prelude::Param;
use crate::prelude::{Shell, States};

/// Simple highlighter that colors the entire line one color
#[derive(Default)]
pub struct DefaultHighlighter {
    pub style: ContentStyle,
}

impl Highlighter for DefaultHighlighter {
    fn highlight(&self, _sh: &Shell, _ctx: &States, buf: &String) -> Result<StyledBuf> {
        let mut styled_buf = StyledBuf::empty();

        styled_buf.push(
            &buf,
            ContentStyle {
                foreground_color: Some(Color::Green),
                ..Default::default()
            },
        );

        Ok(styled_buf)
    }
}

/// Trait that modifies a [`StyledBuf`] inplace and applies a theme to highlight the text
///
/// Can be used standalone to apply a set of syntax rules
pub trait SyntaxTheme {
    fn apply(&self, buf: &mut StyledBuf);
}

/// A highlighter implementation that applies a list of [`SyntaxTheme`] to the line buffer
///
/// [`Syntax Theme`] are applied in order, so more general ones should be inserted first.
pub struct SyntaxHighlighter {
    auto: ContentStyle,
    pub syntax_themes: Vec<Box<dyn SyntaxTheme>>,
}
impl Default for SyntaxHighlighter {
    fn default() -> Self {
        Self {
            auto: ContentStyle::default(),
            syntax_themes: vec![Box::new(ShrsTheme::default())],
        }
    }
}

impl SyntaxHighlighter {
    ///pushes a `SyntaxTheme` to the end of the list
    pub fn push_rule(&mut self, syntax_theme: Box<dyn SyntaxTheme>) {
        self.syntax_themes.push(syntax_theme);
    }

    pub fn new(auto: ContentStyle, themes: Vec<Box<dyn SyntaxTheme>>) -> Self {
        SyntaxHighlighter {
            auto,
            syntax_themes: themes,
        }
    }
}
impl Highlighter for SyntaxHighlighter {
    fn highlight(&self, _sh: &Shell, _ctx: &States, buf: &String) -> Result<StyledBuf> {
        let mut styled_buf = StyledBuf::new(&buf).style(self.auto);

        for syntax_theme in self.syntax_themes.iter() {
            syntax_theme.apply(&mut styled_buf);
        }

        Ok(styled_buf)
    }
}

/// Implementation of a highlighter for the shrs language.
///
/// Utilizes the shrs parser to parse and highlight various tokens based on their type
pub struct ShrsTheme {
    cmd_style: ContentStyle,
    string_style: ContentStyle,
    reserved_style: ContentStyle,
}
impl Default for ShrsTheme {
    fn default() -> Self {
        ShrsTheme::new(
            ContentStyle {
                foreground_color: Some(Color::Blue),
                ..Default::default()
            },
            ContentStyle {
                foreground_color: Some(Color::Green),
                ..Default::default()
            },
            ContentStyle {
                foreground_color: Some(Color::Yellow),
                ..Default::default()
            },
        )
    }
}
impl ShrsTheme {
    pub fn new(
        cmd_style: ContentStyle,
        string_style: ContentStyle,
        reserved_style: ContentStyle,
    ) -> Self {
        ShrsTheme {
            cmd_style,
            string_style,
            reserved_style,
        }
    }
}
impl SyntaxTheme for ShrsTheme {
    fn apply(&self, buf: &mut StyledBuf) {
        let content = buf.content.clone();
        let lexer = Lexer::new(content.as_str());
        let mut is_cmd = true;
        for token in lexer.flatten() {
            match token.1.clone() {
                Token::WORD(_) => {
                    if is_cmd {
                        buf.apply_style_in_range(token.0..token.2, self.cmd_style);
                        is_cmd = false;
                    }
                },
                //Tokens that make next word command
                Token::IF
                | Token::THEN
                | Token::ELSE
                | Token::ELIF
                | Token::DO
                | Token::CASE
                | Token::AND_IF
                | Token::OR_IF
                | Token::SEMI
                | Token::DSEMI
                | Token::AMP
                | Token::PIPE => {
                    is_cmd = true;
                },
                _ => (),
            }
            match token.1 {
                Token::IF
                | Token::ELSE
                | Token::FI
                | Token::THEN
                | Token::ELIF
                | Token::DO
                | Token::DONE
                | Token::CASE
                | Token::ESAC
                | Token::WHILE
                | Token::UNTIL
                | Token::FOR
                | Token::IN => {
                    buf.apply_style_in_range(token.0..token.2, self.reserved_style);
                },
                _ => (),
            }
            if let Token::WORD(w) = token.1 {
                if w.starts_with('\'') || w.starts_with('\"') {
                    buf.apply_style_in_range(token.0..token.2, self.string_style);
                }
            }
        }
    }
}

/// Implement this trait to define your own highlighter command
pub trait Highlighter {
    fn highlight(&self, sh: &Shell, states: &States, buf: &String) -> Result<StyledBuf>;
}

pub trait IntoHighlighter<Input> {
    type Highlighter: Highlighter;
    fn into_highlighter(self) -> Self::Highlighter;
}

pub struct FunctionHighlighter<Input, F> {
    f: F,
    marker: PhantomData<fn() -> Input>,
}

impl<F> Highlighter for FunctionHighlighter<(Shell, String), F>
where
    for<'a, 'b> &'a F: Fn(&Shell, &String) -> Result<StyledBuf>,
{
    fn highlight(&self, sh: &Shell, _ctx: &States, buf: &String) -> Result<StyledBuf> {
        fn call_inner(
            f: impl Fn(&Shell, &String) -> Result<StyledBuf>,
            sh: &Shell,
            buf: &String,
        ) -> Result<StyledBuf> {
            f(&sh, &buf)
        }

        call_inner(&self.f, sh, &buf)
    }
}

macro_rules! impl_highlighter {
    (
        $($params:ident),*
    ) => {
        #[allow(non_snake_case)]
        #[allow(unused)]
        impl<F, $($params: Param),+> Highlighter for FunctionHighlighter<($($params,)+), F>
            where
                for<'a, 'b> &'a F:
                    Fn( $($params),+,&Shell,&String)->Result<StyledBuf> +
                    Fn( $(<$params as Param>::Item<'b>),+,&Shell,&String )->Result<StyledBuf>
        {
            fn highlight(&self, sh: &Shell,states: &States, buf: &String)->Result<StyledBuf> {
                fn call_inner<$($params),+>(
                    f: impl Fn($($params),+,&Shell,&String)->Result<StyledBuf>,
                    $($params: $params),*
                    ,sh:&Shell,buf:&String
                ) -> Result<StyledBuf>{
                    f($($params),*,sh,buf)
                }

                $(
                    let $params = $params::retrieve(sh,states).unwrap();
                )+

                call_inner(&self.f, $($params),+,sh,&buf)
            }
        }
    }
}

impl<F> IntoHighlighter<()> for F
where
    for<'a, 'b> &'a F: Fn(&Shell, &String) -> Result<StyledBuf>,
{
    type Highlighter = FunctionHighlighter<(Shell, String), Self>;

    fn into_highlighter(self) -> Self::Highlighter {
        FunctionHighlighter {
            f: self,
            marker: Default::default(),
        }
    }
}

impl<H: Highlighter> IntoHighlighter<H> for H {
    type Highlighter = H;

    fn into_highlighter(self) -> Self::Highlighter {
        self
    }
}

macro_rules! impl_into_highlighter {
    (
        $($params:ident),+
    ) => {
        impl<F, $($params: Param),+> IntoHighlighter<($($params,)*)> for F
            where
                for<'a, 'b> &'a F:
                    Fn( $($params),+,&Shell,&String ) ->Result<StyledBuf>+
                    Fn( $(<$params as Param>::Item<'b>),+,&Shell,&String )->Result<StyledBuf>
        {
            type Highlighter = FunctionHighlighter<($($params,)+), Self>;

            fn into_highlighter(self) -> Self::Highlighter {
                FunctionHighlighter {
                    f: self,
                    marker: Default::default(),
                }
            }
        }
    }
}
all_the_tuples!(impl_highlighter, impl_into_highlighter);