gmi 0.2.1

A rust library to use the gemini protocol with an aim to be lightweight
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
//! A gemtext parser
//!
//! This library will parse gemtext into various [Nodes](GemtextNode)

#[derive(Debug, Eq, PartialEq, Clone)]
/// A singular gemtext node.
pub enum GemtextNode {
    /// A pure text block. The string contained within is the entire line of text
    Text(String),
    /// A link.
    ///
    /// A link is found by a line starting with the characters "=>" followed by a space
    ///
    /// The first string contained is the link itself and the second string is an optional
    /// descriptor
    Link(String, Option<String>),
    /// A heading
    /// A heading starts with a singular # with a space following.
    /// The string contained is the text that follows the heading marker
    Heading(String),
    /// A subheading
    ///
    /// A subheading starts with the characters "##" with a space following.
    /// The string contained is the text that folllows the subheading marker.
    SubHeading(String),
    /// A subsubheading
    ///
    /// A subsubheading starts with the characters "###" with a space following.
    /// The string contained is the text that follows the subheading marker
    SubSubHeading(String),
    /// A list item
    ///
    /// A list item starts with the character "*".
    /// Unlike markdown, '-' is not allowed to start a list item
    ///
    /// The string contained is the text that follows the list item marker.
    ListItem(String),
    /// A block quote
    ///
    /// A blockquote starts with the character ">".
    ///
    /// The string contained is the text that follows the blockquote marker
    Blockquote(String),
    /// A block of preformatted text.
    ///
    /// A preformatted text block starts with the characters "\`\`\`"
    ///
    /// The first string contained is the text within the preformatted text (newlines and all). The second string is an optional formatting tag for the preformatted text a la Markdown. It's worth noting that this is more clearly listed as an "alt text" as opposed to a formatting tag.
    Preformatted(String, Option<String>),
    /// A singular empty line
    EmptyLine,
}

impl core::fmt::Display for GemtextNode {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            GemtextNode::EmptyLine => write!(f, ""),
            GemtextNode::Text(s) => write!(f, "{}", s),
            GemtextNode::Link(s, None) => {
                write!(f, "=> {}", s)
            },
            GemtextNode::Link(s, Some(d)) => {
                write!(f, "=> {} {}", s, d)
            },
            GemtextNode::Heading(s) => write!(f, "# {}", s),
            GemtextNode::SubHeading(s) => write!(f, "## {}", s),
            GemtextNode::SubSubHeading(s) => write!(f, "### {}", s),
            GemtextNode::ListItem(s) => write!(f, "* {}", s),
            GemtextNode::Blockquote(s) => write!(f, "> {}", s),
            GemtextNode::Preformatted(s, None) => {
                write!(f, "```\n{}\n```", s)
            }
            GemtextNode::Preformatted(s, Some(d)) => {
                write!(f, "```{}\n{}\n```", d, s)
            }
        }
    }
}

#[derive(Debug)]
enum ParseState {
    Searching,
    Text,
    FirstLinkChar,
    SecondLinkChar,
    LinkLink,
    LinkDesc,
    ListWaitForSpace,
    ListItem,
    FirstTick,
    SecondTick,
    PreformattedTextType,
    HeadingStart,
    Heading,
    SubHeadingStart,
    SubHeading,
    SubSubHeadingStart,
    SubSubHeading,
    BlockquoteStart,
    Blockquote,
}

/// Parse gemtext into a vector of [GemtextNode]s
///
/// This will take a [`&str`] and return a vector of [GemtextNode]s. Because of the nature of the way
/// gemtext works, this parsing step cannot fail. It can only return garbage.
///
/// # Example:
/// ```
/// # use gmi::gemtext;
/// # fn main() {
/// let text = r#"# A test page!
/// Hello! This is a test page!"#;
/// let gemtext_nodes = gemtext::parse_gemtext(text);
/// if let gemtext::GemtextNode::Heading(s) = &gemtext_nodes[0] {
///     assert_eq!(s, "A test page!");
/// } else {
///     panic!("Incorrect type!");
/// }
/// # }
///
pub fn parse_gemtext(text: &str) -> Vec<GemtextNode> {
    // Let's define our parsing flags
    let mut is_in_preformatted = false;
    let mut preformatted_text_has_type = false;

    let mut nodes: Vec<GemtextNode> = Vec::new();
    let mut preformatted_text: String = String::new();
    let mut preformatted_text_type: String = String::new();

    for line in text.lines() {
        if is_in_preformatted {
            if line.starts_with("```") {
                if preformatted_text_has_type {
                    nodes.push(GemtextNode::Preformatted(
                        preformatted_text.clone(),
                        Some(preformatted_text_type.clone()),
                    ));
                } else {
                    nodes.push(GemtextNode::Preformatted(preformatted_text.clone(), None));
                }
                is_in_preformatted = false;
                preformatted_text.clear();
            } else {
                preformatted_text.push_str(line);
                preformatted_text.push('\n');
            }
            continue;
        }
        let trimmed_line = line.trim();
        if trimmed_line.is_empty() {
            nodes.push(GemtextNode::EmptyLine);
            continue;
        }
        // A simple enum to keep our parsing state
        let mut current_parse_state: ParseState = ParseState::Searching;
        let mut temp1 = String::new();
        let mut temp2 = String::new();
        // Go character by character and set our state accordingly
        for c in line.chars() {
            match current_parse_state {
                ParseState::Searching => match c {
                    '=' => current_parse_state = ParseState::FirstLinkChar,
                    '*' => current_parse_state = ParseState::ListWaitForSpace,
                    '`' => current_parse_state = ParseState::FirstTick,
                    '#' => current_parse_state = ParseState::HeadingStart,
                    '>' => current_parse_state = ParseState::BlockquoteStart,
                    _ => {
                        current_parse_state = ParseState::Text;
                    }
                },
                //=====
                //Text parsing
                //=====
                ParseState::Text => break,
                //=====
                //Link parsing
                //=====
                ParseState::FirstLinkChar => match c {
                    '>' => current_parse_state = ParseState::SecondLinkChar,
                    _ => {
                        current_parse_state = ParseState::Text;
                    }
                },
                ParseState::SecondLinkChar => {
                    if !c.is_whitespace() {
                        current_parse_state = ParseState::LinkLink;
                        temp1.push(c);
                    }
                }
                ParseState::LinkLink => {
                    if c.is_whitespace() {
                        current_parse_state = ParseState::LinkDesc;
                    } else {
                        temp1.push(c);
                    }
                }
                ParseState::LinkDesc => temp2.push(c),
                //=====
                //List parsing
                //=====
                ParseState::ListWaitForSpace => {
                    if !c.is_whitespace() {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::ListItem;
                    }
                }
                ParseState::ListItem => temp1.push(c),
                //======
                //Preformatted text
                //======
                ParseState::FirstTick => {
                    if c != '`' {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::SecondTick;
                    }
                }
                ParseState::SecondTick => {
                    if c != '`' {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::PreformattedTextType;
                        preformatted_text_type.clear();
                    }
                }
                ParseState::PreformattedTextType => preformatted_text_type.push(c),
                //=====
                //Headings
                //=====
                ParseState::HeadingStart => {
                    if c == '#' {
                        current_parse_state = ParseState::SubHeadingStart;
                    } else if !c.is_whitespace() {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::Heading;
                    }
                }
                ParseState::Heading => temp1.push(c),
                ParseState::SubHeadingStart => {
                    if c == '#' {
                        current_parse_state = ParseState::SubSubHeadingStart;
                    } else if !c.is_whitespace() {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::SubHeading;
                    }
                }
                ParseState::SubHeading => temp1.push(c),
                ParseState::SubSubHeadingStart => {
                    if c == '#' {
                        current_parse_state = ParseState::SubSubHeading;
                    } else if !c.is_whitespace() {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::SubSubHeading;
                    }
                }
                ParseState::SubSubHeading => temp1.push(c),
                ParseState::BlockquoteStart => {
                    if !c.is_whitespace() {
                        current_parse_state = ParseState::Text;
                    } else {
                        current_parse_state = ParseState::Blockquote;
                    }
                }
                ParseState::Blockquote => temp1.push(c),
            }
        }
        // Clean up any parse state we are in
        match current_parse_state {
            ParseState::Text => nodes.push(GemtextNode::Text(line.to_string())),

            ParseState::SecondLinkChar => nodes.push(GemtextNode::Text("=".to_string())),
            ParseState::LinkLink => nodes.push(GemtextNode::Link(temp1, None)),
            ParseState::LinkDesc => {
                if temp2.is_empty() {
                    nodes.push(GemtextNode::Link(temp1, None));
                } else {
                    nodes.push(GemtextNode::Link(temp1, Some(temp2)));
                }
            }

            ParseState::ListItem => nodes.push(GemtextNode::ListItem(temp1)),

            ParseState::FirstTick => nodes.push(GemtextNode::Text("`".to_string())),
            ParseState::SecondTick => nodes.push(GemtextNode::Text("``".to_string())),
            ParseState::PreformattedTextType => {
                is_in_preformatted = true;
                if preformatted_text_type.is_empty() {
                    preformatted_text_has_type = false;
                } else {
                    preformatted_text_has_type = true;
                }
            }
            ParseState::Heading => nodes.push(GemtextNode::Heading(temp1)),
            ParseState::HeadingStart => nodes.push(GemtextNode::Text("#".to_string())),
            ParseState::SubHeading => nodes.push(GemtextNode::SubHeading(temp1)),
            ParseState::SubHeadingStart => nodes.push(GemtextNode::Text("##".to_string())),
            ParseState::SubSubHeading => nodes.push(GemtextNode::SubSubHeading(temp1)),
            ParseState::SubSubHeadingStart => nodes.push(GemtextNode::Text("###".to_string())),
            ParseState::Blockquote => nodes.push(GemtextNode::Blockquote(temp1)),
            s => panic!("Invalid state: {:?}", s),
        }
    }
    nodes
}

#[cfg(test)]
mod tests {
    macro_rules! test_prelude {
        ($n:ident, $c:tt) => {
            #[test]
            fn $n() {
            use $crate::gemtext::*;
            $c
        }}
    }
    //
    //====
    //
    test_prelude!(display_test, {
        // Text
        assert_eq!(GemtextNode::Text(String::from("This is a test")).to_string(), "This is a test");
        // Link
        assert_eq!(GemtextNode::Link(String::from("gemini://link_test"), None).to_string(), "=> gemini://link_test");
        assert_eq!(GemtextNode::Link(String::from("gemini://link_test"), Some(String::from("A test lol"))).to_string(), "=> gemini://link_test A test lol");
        // Heading
        assert_eq!(GemtextNode::Heading(String::from("A test heading")).to_string(), "# A test heading");
        // Subheading
        assert_eq!(GemtextNode::SubHeading(String::from("A test subheading")).to_string(), "## A test subheading");
        // Subsubheading
        assert_eq!(GemtextNode::SubSubHeading(String::from("A test subsubheading")).to_string(), "### A test subsubheading");
        // List Item
        assert_eq!(GemtextNode::ListItem(String::from("A list item")).to_string(), "* A list item");
        // Blockquote
        assert_eq!(GemtextNode::Blockquote(String::from("A blockquote test")).to_string(), "> A blockquote test");
        // Preformatted
        assert_eq!(GemtextNode::Preformatted(String::from("A preformatted block"), None).to_string(), "```\nA preformatted block\n```");
        assert_eq!(GemtextNode::Preformatted(String::from("A preformatted block"), Some(String::from("with alt text"))).to_string(), "```with alt text\nA preformatted block\n```");
        // Empty line
        assert_eq!(GemtextNode::EmptyLine.to_string(), "");
    });
    //
    //===
    //
    test_prelude!(parse_gemtext, {
        let test_article = r#"# Hello!
This is a test article for using to test the parsing of the gemtext stuff! For example, the next thing is a link!
=> gemini://a_test_link
And next is a link with some alt text
=> gemini://a_test_link some alt text
And now we'll get a subheading in here. And why not? We'll throw an empty line before it!

## A subheading
We'll also do a subsubheading
### A subsubheading
Then we'll do some list items
* list item 1
* list item 2
* list item 3
And a blockquote
> Just do it!
And we'll do some preformatted text with no alt text
```
fn main() {
    println!("Hello world!");
}
```
And some preformatted text with alt text
```rust
fn main() {
    println!("Goodbye world!");
}
```"#;
        let test_article_parsed = vec![GemtextNode::Heading(String::from("Hello!")),
        GemtextNode::Text(String::from("This is a test article for using to test the parsing of the gemtext stuff! For example, the next thing is a link!")),
        GemtextNode::Link(String::from("gemini://a_test_link"), None),
        GemtextNode::Text(String::from("And next is a link with some alt text")),
        GemtextNode::Link(String::from("gemini://a_test_link"), Some(String::from("some alt text"))),
        GemtextNode::Text(String::from("And now we'll get a subheading in here. And why not? We'll throw an empty line before it!")),
        GemtextNode::EmptyLine,
        GemtextNode::SubHeading(String::from("A subheading")),
        GemtextNode::Text(String::from("We'll also do a subsubheading")),
        GemtextNode::SubSubHeading(String::from("A subsubheading")),
        GemtextNode::Text(String::from("Then we'll do some list items")),
        GemtextNode::ListItem(String::from("list item 1")),
        GemtextNode::ListItem(String::from("list item 2")),
        GemtextNode::ListItem(String::from("list item 3")),
        GemtextNode::Text(String::from("And a blockquote")),
        GemtextNode::Blockquote(String::from("Just do it!")),
        GemtextNode::Text(String::from("And we'll do some preformatted text with no alt text")),
        GemtextNode::Preformatted(String::from(r#"fn main() {
    println!("Hello world!");
}
"#), None),
        GemtextNode::Text(String::from("And some preformatted text with alt text")),
        GemtextNode::Preformatted(String::from(r#"fn main() {
    println!("Goodbye world!");
}
"#), Some(String::from("rust")))
        ];
        // Parse the article
        let actual_parsed_article = parse_gemtext(test_article);
        for (actual_article_node, test_article_node) in actual_parsed_article.iter().zip(test_article_parsed.iter()) {
            assert_eq!(actual_article_node, test_article_node);
        }
    });
}