markdown_toc/
lib.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
extern crate percent_encoding;

use percent_encoding::{percent_encode, CONTROLS};
use std::path::PathBuf;
use std::str::FromStr;

fn slugify(text: &str) -> String {
    percent_encode(
        text.replace(" ", "-").to_lowercase().as_bytes(),
        CONTROLS,
    )
    .to_string()
}

pub struct Heading {
    pub depth: usize,
    pub title: String,
}

impl FromStr for Heading {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim_end();
        if trimmed.starts_with("#") {
            let mut depth = 0usize;
            let title = trimmed
                .chars()
                .skip_while(|c| {
                    if *c == '#' {
                        depth += 1;
                        true
                    } else {
                        false
                    }
                })
                .collect::<String>()
                .trim_start()
                .to_owned();
            Ok(Heading {
                depth: depth - 1,
                title,
            })
        } else {
            Err(())
        }
    }
}

impl Heading {
    pub fn format(&self, config: &Config) -> Option<String> {
        if self.depth >= config.min_depth
            && config.max_depth.map(|d| self.depth <= d).unwrap_or(true)
        {
            Some(format!(
                "{}{} {}",
                " ".repeat(config.indent)
                    .repeat(self.depth - config.min_depth),
                &config.bullet,
                if config.no_link {
                    self.title.clone()
                } else {
                    format!("[{}](#{})", &self.title, slugify(&self.title))
                }
            ))
        } else {
            None
        }
    }
}

pub enum InputFile {
    Path(PathBuf),
    StdIn,
}

// enum Inline {
//     None,
//     Inline,
//     InlineAndReplace,
// }

pub struct Config {
    pub input_file: InputFile,
    pub bullet: String,
    pub indent: usize,
    pub max_depth: Option<usize>,
    pub min_depth: usize,
    pub header: Option<String>,
    pub no_link: bool,
    // inline: Inline,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            input_file: InputFile::StdIn,
            bullet: String::from("1."),
            indent: 4,
            max_depth: None,
            min_depth: 0,
            no_link: false,
            header: Some(String::from("## Table of Contents")),
            // inline: Inline::None,
        }
    }
}