vle 1.19.4

Very Little Editor - an exercise in minimalist text editing
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Copyright 2026 Brian Langenberger
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::buffer::Source;
use logos::{Lexer, Logos};
use ratatui::style::Color;

mod c;
mod cpp;
mod css;
mod csv;
mod cue;
mod fish;
mod flac;
mod git;
mod go;
mod html;
mod ini;
mod java;
mod js;
mod json;
mod makefile;
mod markdown;
mod patch;
mod perl;
mod php;
mod python;
mod regex;
mod ron;
mod rust;
mod sh;
mod sql;
mod swift;
mod test;
mod tex;
mod toml;
mod ts;
mod tutorial;
mod xml;
mod yaml;
mod zig;

// This editor is intended to be used on terminals with both
// light text on dark backgrounds as well as dark text on light backgrounds
// without having to modify any colors or probe for the terminal's color scheme.
// As such, predefined colors (red, green, yellow, blue, magenta, etc.)
// should be preferred instead of RGB colors (since users can redefine them)
// and black/white should be avoided altogether.
// Boldface is also difficult to detect in a dark color scheme
// and shouldn't be relied upon.

#[derive(Default)]
pub enum HighlightState {
    #[default]
    Normal,
    Commenting,
}

/// A multi-line comment start or end
pub enum MultiComment {
    Start,
    End,
}

pub enum MultiCommentType {
    Bidirectional(fn(&str) -> Option<MultiComment>),
    Unidirectional(fn(HighlightState, &str) -> HighlightState),
}

/// A subset of all of Ratatui's possible modifiers
#[derive(Copy, Clone, Default)]
pub enum Modifier {
    #[default]
    Plain,
    Bold,
    Italic,
    Underlined,
}

#[derive(Copy, Clone)]
pub struct Highlight {
    pub color: Option<Color>,
    pub modifier: Modifier,
}

impl From<Color> for Highlight {
    fn from(color: Color) -> Self {
        Self {
            color: Some(color),
            modifier: Modifier::default(),
        }
    }
}

impl From<Highlight> for ratatui::style::Style {
    fn from(highlight: Highlight) -> Self {
        let style = match highlight.modifier {
            Modifier::Plain => Self::default(),
            Modifier::Italic => Self::default().italic(),
            Modifier::Underlined => Self::default().underlined(),
            Modifier::Bold => Self::default().bold(),
        };
        match highlight.color {
            Some(color) => style.fg(color),
            None => style,
        }
    }
}

type Underliner = for<'s> fn(&'s str) -> Box<dyn Iterator<Item = std::ops::Range<usize>> + 's>;

/// Implemented for different syntax highlighters
pub trait Highlighter: std::fmt::Debug + std::fmt::Display {
    /// Yields portions of the string to highlight in a particular color
    /// range is in bytes
    fn highlight<'s>(
        &self,
        s: &'s str,
        state: &'s mut HighlightState,
    ) -> Box<dyn Iterator<Item = (Highlight, std::ops::Range<usize>)> + 's>;

    /// Yields portions of the string to underline
    /// range is in bytes
    fn underline(&self) -> Option<Underliner> {
        None
    }

    /// Returns true if the format requires actual tabs instead of spaces
    /// (pretty sure this only applies to Makefiles)
    fn tabs_required(&self) -> bool {
        false
    }

    /// If format supports multi-line comments,
    /// returns function which returns the first one that
    /// exists in a line, if any
    fn multicomment(&self) -> Option<MultiCommentType> {
        None
    }
}

impl Highlighter for Box<dyn Highlighter> {
    fn highlight<'s>(
        &self,
        s: &'s str,
        state: &'s mut HighlightState,
    ) -> Box<dyn Iterator<Item = (Highlight, std::ops::Range<usize>)> + 's> {
        Box::as_ref(self).highlight(s, state)
    }

    fn underline(
        &self,
    ) -> Option<for<'s> fn(&'s str) -> Box<dyn Iterator<Item = std::ops::Range<usize>> + 's>> {
        Box::as_ref(self).underline()
    }

    fn tabs_required(&self) -> bool {
        Box::as_ref(self).tabs_required()
    }

    fn multicomment(&self) -> Option<MultiCommentType> {
        Box::as_ref(self).multicomment()
    }
}

#[derive(Debug)]
pub struct DefaultHighlighter;

impl Highlighter for DefaultHighlighter {
    fn highlight<'s>(
        &self,
        _s: &'s str,
        _state: &'s mut HighlightState,
    ) -> Box<dyn Iterator<Item = (Highlight, std::ops::Range<usize>)> + 's> {
        Box::new(std::iter::empty())
    }
}

impl std::fmt::Display for DefaultHighlighter {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        "Plain".fmt(f)
    }
}

pub use regex::Regex;
pub use test::Test;
pub use tutorial::Tutorial;

pub trait Plain {
    fn is_comment_start(&self) -> bool;
}

pub trait Commenting {
    fn is_comment_end(&self) -> bool;
}

pub enum EitherLexer<'s, P: Logos<'s>, C: Logos<'s>> {
    Plain(Lexer<'s, P>),
    Commenting(Lexer<'s, C>),
}

impl<'s, P, C> EitherLexer<'s, P, C>
where
    P: Logos<'s, Extras: Default>,
    C: Logos<'s, Source = P::Source, Extras = P::Extras>,
{
    pub fn new(state: &HighlightState, source: &'s <P as Logos<'s>>::Source) -> Self {
        match state {
            HighlightState::Normal => Self::Plain(Lexer::new(source)),
            HighlightState::Commenting => Self::Commenting(Lexer::new(source)),
        }
    }
}

impl<'s, P, C> Iterator for EitherLexer<'s, P, C>
where
    P: Logos<'s, Source = str, Extras: Default> + Plain,
    C: Logos<'s, Source = P::Source, Extras = P::Extras, Error = P::Error> + Commenting + Into<P>,
{
    type Item = (Result<P, P::Error>, std::ops::Range<usize>);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Plain(lexer) => {
                let token = lexer.next()?;
                let pair = (token, lexer.span());
                if let (Ok(token), _) = &pair
                    && token.is_comment_start()
                {
                    *self =
                        EitherLexer::Commenting(std::mem::replace(lexer, Lexer::new("")).morph());
                }
                Some(pair)
            }
            Self::Commenting(lexer) => {
                let token = lexer.next()?;
                let span = lexer.span();
                match token {
                    Ok(token) => {
                        if token.is_comment_end() {
                            *self = EitherLexer::Plain(
                                std::mem::replace(lexer, Lexer::new("")).morph(),
                            );
                        }
                        Some((Ok(token.into()), span))
                    }
                    Err(err) => Some((Err(err), span)),
                }
            }
        }
    }
}

pub fn syntax(source: &Source) -> Box<dyn Highlighter> {
    use std::collections::HashMap;
    use std::sync::LazyLock;

    static EXT_MAP: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
        std::env::var("VLE_EXT_MAP")
            .ok()
            .map(|whole| {
                whole
                    .split(',')
                    .filter_map(|s| {
                        s.split_once('=')
                            .map(|(from, to)| (from.trim().to_string(), to.trim().to_string()))
                            .filter(|(from, to)| !from.is_empty() && !to.is_empty())
                    })
                    .collect()
            })
            .unwrap_or_default()
    });

    if matches!(source, Source::Test) {
        return Box::new(Test);
    }

    match source
        .extension()
        .map(|ext| EXT_MAP.get(ext).map(|s| s.as_str()).unwrap_or(ext))
    {
        None => match source.file_name() {
            Some(file_name) => match file_name.as_ref() {
                "Makefile" | "makefile" => Box::new(makefile::Makefile),
                "COMMIT_EDITMSG" => Box::new(git::Git),
                _ => Box::new(DefaultHighlighter),
            },
            None => Box::new(DefaultHighlighter),
        },
        Some("rs") => Box::new(rust::Rust),
        Some("c" | "h" | "C" | "H") => Box::new(c::C),
        Some("cpp" | "cc" | "cxx" | "c++" | "hh" | "hpp" | "hxx" | "h++") => Box::new(cpp::Cpp),
        Some("py") => Box::new(python::Python),
        Some("json") => Box::new(json::Json),
        Some("ron") => Box::new(ron::Ron),
        Some("md" | "markdown") => Box::new(markdown::Markdown),
        Some("html" | "htm") => Box::new(html::Html),
        Some("xml" | "svg") => Box::new(xml::Xml),
        Some("sql") => Box::new(sql::Sql),
        Some("css") => Box::new(css::Css),
        Some("js") => Box::new(js::JavaScript),
        Some("ts") => Box::new(ts::TypeScript),
        Some("php") => Box::new(php::Php),
        Some("yaml") => Box::new(yaml::Yaml),
        Some("java") => Box::new(java::Java),
        Some("go") => Box::new(go::Go),
        Some("patch" | "diff") => Box::new(patch::Patch),
        Some("csv") => Box::new(csv::Csv),
        Some("toml") => Box::new(toml::Toml),
        Some("ini") => Box::new(ini::Ini),
        Some("fish") => Box::new(fish::Fish),
        Some("sh") => Box::new(sh::Shell),
        Some("zig") => Box::new(zig::Zig),
        Some("swift") => Box::new(swift::Swift),
        Some("pl" | "pm") => Box::new(perl::Perl),
        Some("tex") => Box::new(tex::Tex),
        Some("ana") => Box::new(flac::Analysis),
        Some("cue" | "CUE") => Box::new(cue::Cuesheet),
        _ => Box::new(DefaultHighlighter),
    }
}

#[macro_export]
macro_rules! highlighter {
    ($syntax:ty, $token:ty) => {
        highlighter!($syntax, $token, None);
    };
    ($syntax:ty, $token:ty, $underliner:expr) => {
        impl $crate::syntax::Highlighter for $syntax {
            fn highlight<'s>(
                &self,
                s: &'s str,
                _state: &'s mut $crate::syntax::HighlightState,
            ) -> Box<dyn Iterator<Item = (Highlight, std::ops::Range<usize>)> + 's> {
                Box::new(<$token>::lexer(s).spanned().filter_map(|(t, r)| {
                    t.ok()
                        .and_then(|t| Highlight::try_from(t).ok())
                        .map(|c| (c, r))
                }))
            }

            fn underline(
                &self,
            ) -> Option<for<'s> fn(&'s str) -> Box<dyn Iterator<Item = std::ops::Range<usize>> + 's>> {
                $underliner
            }
        }
    };
    ($syntax:ty, $token:ty, $comment_start:ident, $comment_end:ident, $start:literal, $end:literal, $comment_color:expr) => {
        highlighter!($syntax, $token, $comment_start, $comment_end, $start, $end, $comment_color, None);
    };
    ($syntax:ty, $token:ty, $comment_start:ident, $comment_end:ident, $start:literal, $end:literal, $comment_color:expr, $underliner:expr) => {
        impl Plain for $token {
            fn is_comment_start(&self) -> bool {
                matches!(self, Self::$comment_start)
            }
        }

        impl Commenting for $token {
            fn is_comment_end(&self) -> bool {
                matches!(self, Self::$comment_end)
            }
        }

        #[derive(Logos, Debug)]
        #[logos(skip r"[ \t\n]+")]
        enum CommentEnd {
            #[token($end)]
            EndComment,
        }

        impl From<CommentEnd> for $token {
            fn from(c: CommentEnd) -> Self {
                match c {
                    CommentEnd::EndComment => Self::$comment_end,
                }
            }
        }

        impl Commenting for CommentEnd {
            fn is_comment_end(&self) -> bool {
                true
            }
        }

        impl $crate::syntax::Highlighter for $syntax {
            fn highlight<'s>(
                &self,
                s: &'s str,
                state: &'s mut $crate::syntax::HighlightState,
            ) -> Box<dyn Iterator<Item = (Highlight, std::ops::Range<usize>)> + 's> {
                use $crate::syntax::{EitherLexer, HighlightState};

                let lexer: EitherLexer<$token, CommentEnd> = EitherLexer::new(&state, s);

                Box::new(lexer.filter_map(move |(t, r)| {
                    match state {
                        HighlightState::Normal => t
                            .ok()
                            .inspect(|t| {
                                if t.is_comment_start() {
                                    *state = HighlightState::Commenting;
                                }
                            })
                            .and_then(|t| Highlight::try_from(t).ok())
                            .map(|c| (c, r)),
                        HighlightState::Commenting => Some(match t {
                            Ok(end) if end.is_comment_end() => {
                                *state = HighlightState::default();
                                (Highlight::try_from(end).ok()?, r)
                            }
                            _ => ($comment_color, r),
                        }),
                    }
                }))
            }

            fn underline(
                &self,
            ) -> Option<for<'s> fn(&'s str) -> Box<dyn Iterator<Item = std::ops::Range<usize>> + 's>> {
                $underliner
            }

            fn multicomment(&self) -> Option<$crate::syntax::MultiCommentType> {
                use $crate::syntax::{MultiComment, MultiCommentType};

                #[derive(Logos, Debug)]
                #[logos(skip r"[ \t\n]+")]
                enum Comment {
                    #[token($start)]
                    Start,
                    #[token($end)]
                    End,
                }

                impl From<Comment> for MultiComment {
                    fn from(c: Comment) -> MultiComment {
                        match c {
                            Comment::Start => MultiComment::Start,
                            Comment::End => MultiComment::End,
                        }
                    }
                }

                Some(MultiCommentType::Bidirectional(|s: &str| {
                    Comment::lexer(s).find_map(|token| token.ok().map(|t| t.into()))
                }))
            }
        }
    };
}

#[macro_export]
macro_rules! underliner {
    ($s:ident, $class:ty) => {
        Some(|$s| {
            Box::new(
                <$class>::lexer($s)
                    .spanned()
                    .filter_map(|(t, r)| t.ok().map(|_| r)),
            )
        })
    };
}

pub mod color {
    use crate::syntax::{Highlight, Modifier};
    use ratatui::style::Color;

    // A unified color scheme across common syntax items

    pub const KEYWORD: Highlight = Highlight {
        color: Some(Color::Blue),
        modifier: Modifier::Plain,
    };
    pub const FLOW: Highlight = Highlight {
        color: Some(Color::Blue),
        modifier: Modifier::Plain,
    };
    pub const CONSTANT: Highlight = Highlight {
        color: Some(Color::Red),
        modifier: Modifier::Plain,
    };
    pub const TYPE: Highlight = Highlight {
        color: Some(Color::Magenta),
        modifier: Modifier::Plain,
    };
    pub const COMMENT: Highlight = Highlight {
        color: Some(Color::DarkGray),
        modifier: Modifier::Italic,
    };
    pub const STRING: Highlight = Highlight {
        color: Some(Color::Green),
        modifier: Modifier::Plain,
    };
    pub const NUMBER: Highlight = Highlight {
        color: Some(Color::Cyan),
        modifier: Modifier::Plain,
    };
}