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
use std::fs::File;
use std::io::prelude::*;

const COMMENT_BEGIN: &str = "<!-- BEGIN mktoc -->";
const COMMENT_END: &str = "<!-- END mktoc -->";

/// reads a file into a mutable string
fn read_file(file_path: String) -> Result<String, ::std::io::Error> {
    let mut file = File::open(file_path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    Ok(contents)
}

fn text_to_url(text: &str) -> String {
    text.trim()
        .replace(" ", "-")
        .replace("(", "")
        .replace(")", "")
        .replace("`", "")
        .replace("´", "")
        .replace("'", "")
        .replace("\"", "")
        .replace("[", "")
        .replace("]", "")
        .replace("{", "")
        .replace("}", "")
        .replace("?", "")
        .replace("¿", "")
        .replace("!", "")
        .replace("¡", "")
        .replace(".", "")
        .replace(",", "")
        .replace("\\", "")
        .replace("/", "")
        .replace(":", "")
        .replace(";", "")
        .replace("§", "")
        .replace("$", "")
        .replace("%", "")
        .replace("&", "")
        .replace("=", "")
        .replace("^", "")
        .replace("°", "")
        .replace("#", "")
        .replace("+", "")
        .replace("*", "")
        .replace("<", "")
        .replace(">", "")
        .to_ascii_lowercase()
}

/// parses a string and extracts all headlines to build a table of contents
///
/// Uses a basic regex "((#{1,6}\s))((.*))" to parse headings out of the
pub fn generate_toc(original_content: String, min_depth: i32, max_depth: i32) -> String {
    let mut already_found_code_open = false;
    let mut code_block_found = false;
    let mut new_toc = String::from(COMMENT_BEGIN);
    let re = regex::Regex::new(r"((#{1,6}\s))((.*))").unwrap();
    for line in original_content.lines() {
        let line_s: String = line.chars().take(3).collect();
        if line_s == "```".to_owned() {
            code_block_found = true;
        }

        if !code_block_found && !already_found_code_open {
            if line.starts_with("#") {
                // Check if the regex matches, if it doesn't continue skip (continue) the loop.
                let caps = match re.captures(line) {
                    Some(matched) => matched,
                    None => { continue; }
                };
                
                let level: i32 = (caps.get(2).unwrap().as_str().chars().count() - 1) as i32;
                
                if level < min_depth {
                    continue;
                }

                if level > max_depth {
                    continue;
                }

                let text = caps.get(3).unwrap().as_str();
                let link = text_to_url(text);
                let spaces = match level {
                    3 => String::from("  "),
                    4 => String::from("    "),
                    5 => String::from("      "),
                    6 => String::from("        "),
                    _ => String::from(""),
                };

                new_toc = format!(
                    "{old}\n{spaces}- [{text}](#{link})",
                    old = new_toc.as_str(),
                    spaces = spaces,
                    text = text,
                    link = link
                );
            }
        }

        if code_block_found && already_found_code_open {
            code_block_found = false;
            already_found_code_open = false;
        }

        if line.starts_with("```") {
            already_found_code_open = true;
        }
    }

    new_toc = format!("{}\n{}", new_toc, COMMENT_END);

    new_toc
}

/// takes a file path as `String` and returns a table of contents for the file
pub fn make_toc(
    file_path_in: String,
    min_depth: i32,
    max_depth: i32,
) -> Result<String, ::std::io::Error> {
    let content = read_file(file_path_in)?;
    let new_toc = generate_toc(content.to_owned(), min_depth, max_depth);
    let re_toc =
        regex::Regex::new(r"(?ms)^(<!-- BEGIN mktoc -->)(.*?)(<!-- END mktoc -->)").unwrap();
    let res: String = re_toc
        .replacen(content.as_str(), 1, new_toc.as_str())
        .into_owned();

    Ok(res)
}