fml 0.6.10

Friendly Markup Language
Documentation
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
#![allow(unused)]

mod delimiteds;
mod headings;
mod nestables;
mod scripts;

use std::ops::Not;

use super::{
    Stream,
    macros::{not, slice_till},
};
use crate::{
    ast::{FmlColor, FmlList, FmlValue, FmlValues, ListItem},
    parser::{
        ESCAPABLE_TOKENS, State,
        functions::{
            macros::*,
            styles::{
                delimiteds::delimiteds,
                headings::headings,
                nestables::nestables,
                scripts::{line_scripts, scripts},
            },
        },
    },
};

use winnow::{
    Result,
    ascii::*,
    combinator::{repeat, *},
    error::{ContextError, ParserError, StrContext},
    prelude::*,
    token::*,
};

// = begin reused code =
// Source - https://stackoverflow.com/a/47541878
// Posted by trent, modified by community. See post 'Timeline' for change history
// Retrieved 2026-08-15, License - CC BY-SA 3.0
#[cfg(not(windows))]
const LINE_ENDING: &'static str = "\n";
#[cfg(windows)]
const LINE_ENDING: &'static str = "\r\n";
// = end reused code =

/// Helper for parsing already found scopes
fn inner_fml(scope: &str, state: State) -> Result<FmlValues> {
    let mut stream = Stream {
        input: scope,
        state,
    };
    fml_values(stream)
}
/// Helper for optionally wrapping an FmlValue in colored values
fn wrap_in_colors(mut fml: FmlValue, fg: Option<String>, bg: Option<String>) -> FmlValue {
    if let Some(color) = fg {
        fml = FmlValue::ColorFg(FmlColor {
            color,
            body: vec![fml].into(),
        })
    }
    if let Some(color) = bg {
        fml = FmlValue::ColorBg(FmlColor {
            color,
            body: vec![fml].into(),
        })
    }
    fml
}

fn line_spanning<'i>(input: &mut Stream<'i>) -> Result<FmlValue> {
    let is_in_heading = input.state.is_in_heading;
    let is_in_script = input.state.is_in_script;

    alt((
        nestables,
        cond(!is_in_heading, headings).verify_map(|x| x),
        cond(!is_in_script, line_scripts).verify_map(|x| x),
    ))
    .parse_next(input)
}

// The lone Code Block
// also used in section detection, hence it's public
pub fn code_block<'i>(input: &mut Stream<'i>) -> Result<FmlValue> {
    let block_end = || preceded(multispace0, "```");

    // not(end) prevents one-word-codeblocks being interpreted as none-codeblocks cuz of a
    // misguided language detection
    let lang = terminated(
        slice_till!(
            1..,
            not!(alt((multispace1, (opt("\\"), "```").value("```"))))
        ),
        not(block_end()),
    )
    .map(ToString::to_string);

    let body_inner = alt((
        r"\```".value("```"),
        slice_till!(1.., not!(alt((r"\```", block_end())))),
    ));

    // Repetition of "at least once" along with terminating multispace0 prevents blank codeblocks
    let body = repeat_till(1.., body_inner, peek(block_end())).map(|(acc, _term)| acc);
    (
        delimited(
            "```",
            opt(terminated(lang, multispace1)),
            // remove blank lines between start/lang and first non-blank line
            repeat(0.., (space0, line_ending)).map(|()| ()),
        ),
        terminated(body, block_end()),
    )
        // TODO: test for necessity of this verify
        // this verify should be redundant
        .verify(|(_, body): &(Option<String>, String)| !body.trim().is_empty())
        .map(|(lang, body)| FmlValue::CodeBlock { lang, body })
        .parse_next(input)
}

// And once all the styles have been defined

pub fn fml_values<'i>(input: Stream<'i>) -> Result<FmlValues> {
    // Options are used to filter out some newlines that i had no cleaner way to omit
    let opt_vals: Vec<_> = repeat(
        1..,
        alt((
            styled_text.map(|x| Some(x)),
            nl_peek_linespan.map(|()| None),
            plain_text.map(|x| Some(x)),
        )),
    )
    .parse(input)
    .map_err(|e| e.into_inner())?;
    Ok(opt_vals
        .into_iter()
        .filter_map(|x| x)
        .collect::<Vec<_>>()
        .into())
}

fn styled_text<'i>(input: &mut Stream<'i>) -> Result<FmlValue> {
    let is_sol = input.state.is_sol;
    let is_in_script = input.state.is_in_script;

    alt((
        // this delimit is only done here not to fuck up the sections
        delimited(
            multispace0,
            code_block,
            repeat(0.., (space0, line_ending).void()).map(|()| ()),
        ),
        delimiteds,
        cond(is_sol, line_spanning).verify_map(|x| x),
        cond(!is_in_script, scripts).verify_map(|x| x),
    ))
    .parse_next(input)
}

fn nl_stateful<'i>(input: &mut Stream<'i>) -> Result<&'i str> {
    let res = line_ending.parse_next(input)?;
    input.state.is_sol = true;
    Ok(res)
}

fn nl_peek_linespan<'i>(input: &mut Stream<'i>) -> Result<()> {
    let res =
        preceded(nl_stateful, peek(alt((code_block, line_spanning))).void()).parse_next(input);
    if res.is_ok() {
        input.state.is_sol = true;
    }
    res
}

fn plain_text<'i>(input: &mut Stream<'i>) -> Result<FmlValue> {
    fn normal_char<'i>(input: &mut Stream<'i>) -> Result<&'i str> {
        let res = not!(
            esc_identity!(one_of(ESCAPABLE_TOKENS)),
            line_ending,
            styled_text
        )
        .parse_next(input);
        let is_sol = &mut input.state.is_sol;
        if res.is_ok() && *is_sol {
            *is_sol = false;
        }
        res
    }

    // let state: &mut State = &mut input.state;

    let pt = preceded(
        not(nl_peek_linespan),
        alt((
            normal_char,
            esc_identity!(one_of(ESCAPABLE_TOKENS)),
            nl_stateful,
        )),
    );

    (
        // since plaintext gets called once everything else has failed,
        // we can be sure the first char aint a style
        any,
        repeat(0.., pt).fold(String::new, |mut acc, new| {
            acc.push_str(new);
            acc
        }),
    )
        .map(|(ch, mut s): (char, String)| {
            s.insert(0, ch);
            FmlValue::Text(s)
        })
        .parse_next(input)
}

#[cfg(test)]
mod tests {
    use crate::ast::{Content, FmlValue::Superscript, Section};

    use super::*;

    fn str2stream<'i>(input: &'i str) -> Stream<'i> {
        Stream {
            input,
            state: State::default(),
        }
    }

    #[test]
    fn no_empty_text() {
        use FmlValue::*;
        let mut inp = r"a 1^{1}
- a";
        let exp = Content(
            Section(
                vec![
                    Text("a 1".into()),
                    Superscript(Text("1".into()).into()),
                    List(vec![ListItem(Text("a".into()).into())].into()),
                ]
                .into(),
            )
            .into(),
        );
        assert_eq!(crate::parse(inp).unwrap(), exp);
    }

    #[cfg(test)]
    mod delimited {
        use super::*;

        #[test]
        fn normal() {
            let mut inp = r"*styled text*";
            let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
            let exp = "styled text".to_string();
            assert_eq!(res.unwrap(), exp);
        }

        #[test]
        fn escaped() {
            let mut inp = r"*styled \* line \of t\\ext*";
            let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
            let exp = r"styled * line \of t\ext".to_string();
            assert_eq!(res.unwrap(), exp);
        }

        #[test]
        fn unescaped() {
            let mut inp = r"*styled text\\*";
            let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
            let exp = r"styled text\".to_string();
            assert_eq!(res.unwrap(), exp);
        }

        #[cfg(test)]
        mod fails {
            use super::*;

            #[test]
            fn empty() {
                let mut inp = r"**";
                let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
                assert!(res.is_err());
            }

            #[test]
            fn blank() {
                let mut inp = r"* 	*";
                let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
                assert!(res.is_err());
            }

            #[test]
            fn blank_multiline() {
                let mut inp = r"* 	
					*";
                let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
                assert!(res.is_err());
            }

            #[test]
            fn escape_start() {
                let mut inp = r"\*styled text*";
                let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
                assert!(res.is_err());
            }

            #[test]
            fn escape_end() {
                let mut inp = r"*styled text\*";
                let res: Result<String> = delimited_esc!("*").parse_next(&mut inp);
                assert!(res.is_err());
            }
        }
    }

    #[cfg(test)]
    mod code_block {
        use super::*;

        #[test]
        fn one_line() {
            let inp = r"```javax.util.AbstractShortestJavaClassPath.MandatoryGlobalState.doSomething()```";
            let res = code_block.parse(str2stream(inp));
            let exp = FmlValue::CodeBlock {
                lang: None,
                body:
                    r"javax.util.AbstractShortestJavaClassPath.MandatoryGlobalState.doSomething()"
                        .to_string(),
            };
            assert_eq!(res.unwrap(), exp);
        }

        #[test]
        fn one_line_lang() {
            let inp = r"```java javax.util.AbstractShortestJavaClassPath.MandatoryGlobalState.doSomething()```";
            let res = code_block.parse(str2stream(inp));
            let exp = FmlValue::CodeBlock {
                lang: Some("java".to_string()),
                body:
                    r"javax.util.AbstractShortestJavaClassPath.MandatoryGlobalState.doSomething()"
                        .to_string(),
            };
            assert_eq!(res.unwrap(), exp);
        }

        #[test]
        fn multiline() {
            let inp = r#"```
fn main() {
    println!("Hello, world!");
}
```"#;
            let res = code_block.parse(str2stream(inp));
            let exp = FmlValue::CodeBlock {
                lang: None,
                body: r#"fn main() {
    println!("Hello, world!");
}"#
                .to_string(),
            };
            assert_eq!(res.unwrap(), exp);
        }

        #[test]
        fn multiline_lang() {
            let inp = r#"```rust
fn main() {
    println!("Hello, world!");
}
```"#;
            let res = code_block.parse(str2stream(inp));
            let exp = FmlValue::CodeBlock {
                lang: Some("rust".to_string()),
                body: r#"fn main() {
    println!("Hello, world!");
}"#
                .to_string(),
            };
            assert_eq!(res.unwrap(), exp);
        }

        mod fails {
            use super::*;

            #[test]
            fn empty() {
                let inp = "``````";
                let res = code_block.parse(str2stream(inp));
                assert!(res.is_err());
            }

            #[test]
            fn blank() {
                let inp = "```	  	 ```";
                let res = code_block.parse(str2stream(inp));
                eprintln!("{res:#?}");
                assert!(res.is_err());
            }

            #[test]
            fn blank_multiline() {
                let inp = r"```

					```";
                let res = code_block.parse(str2stream(inp));
                eprintln!("{res:#?}");
                assert!(res.is_err());
            }
        }

        // KUUUUUUUUURRWAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        // note to self: repeat_till applies middle parser BEFORE checking with the third
        // #[test]
        // fn fuck() {
        // 	use winnow::combinator::repeat_till;

        // 	fn parser<'i>(s: &mut &'i str) -> Result<String> {
        // 		repeat_till(1.., any, "e").map(|(s, _)| s).parse_next(s)
        // 	}

        //	assert!(parser.parse_peek("e").is_err());
        //  assert!(parser.parse_peek("ae").is_ok());
        // 	assert!(parser.parse("ee").is_err()); // FAILS!!!
        // }
    }
}