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
pub(crate) trait TrimAsciiWhitespace {
    fn trim_ascii_whitespace(&self) -> &str;

    fn trim_start_ascii_whitespace(&self) -> &str;

    fn trim_end_ascii_whitespace(&self) -> &str;
}

impl<S> TrimAsciiWhitespace for S
where
    S: AsRef<str>,
{
    #[inline]
    fn trim_ascii_whitespace(&self) -> &str {
        self.as_ref()
            .trim_matches(|ch: char| ch.is_ascii_whitespace())
    }

    #[inline]
    fn trim_start_ascii_whitespace(&self) -> &str {
        self.as_ref()
            .trim_start_matches(|ch: char| ch.is_ascii_whitespace())
    }

    #[inline]
    fn trim_end_ascii_whitespace(&self) -> &str {
        self.as_ref()
            .trim_end_matches(|ch: char| ch.is_ascii_whitespace())
    }
}

pub(crate) trait StripWhitespace {
    /// Strip leading whitespace.
    ///
    /// A tuple of (striped_text, Option<leading_whitespace>) will be returned.
    fn strip_leading_whitespace(&self) -> (&str, Option<&str>);

    /// Strip trailing whitespace.
    ///
    /// A tuple of (striped_text, Option<trailing_whitespace>) will be returned.
    fn strip_trailing_whitespace(&self) -> (&str, Option<&str>);
}

impl<S> StripWhitespace for S
where
    S: AsRef<str>,
{
    fn strip_leading_whitespace(&self) -> (&str, Option<&str>) {
        let text = self.as_ref();
        let mut start = 0;
        for (idx, ch) in text.char_indices() {
            if ch.is_whitespace() {
                start = idx + ch.len_utf8();
            } else {
                break;
            }
        }
        if start != 0 {
            (&text[start..], Some(&text[..start]))
        } else {
            (text, None)
        }
    }

    fn strip_trailing_whitespace(&self) -> (&str, Option<&str>) {
        let text = self.as_ref();
        let mut end: Option<usize> = None;
        for (idx, ch) in text.char_indices().rev() {
            if ch.is_whitespace() {
                end = Some(idx);
            } else {
                break;
            }
        }
        if let Some(end) = end {
            (&text[..end], Some(&text[end..]))
        } else {
            (text, None)
        }
    }
}

pub(crate) fn compress_whitespace(input: &str) -> String {
    let mut result = String::new();
    if input.len() == 0 {
        return result;
    }
    let mut in_whitespace = false;

    for c in input.chars() {
        if c.is_ascii_whitespace() {
            if !in_whitespace {
                result.push(' ');
                in_whitespace = true;
            }
        } else {
            result.push(c);
            in_whitespace = false;
        }
    }

    result
}

pub(crate) fn indent_text_except_first_line(
    text: &str,
    indent: usize,
    trim_line_end: bool,
) -> String {
    if indent == 0 {
        return text.to_string();
    }
    let mut result_lines: Vec<String> = Vec::new();
    let indent_text = " ".repeat(indent);
    for (idx, line) in text.lines().enumerate() {
        let line = if trim_line_end { line.trim_end() } else { line };
        if idx == 0 {
            result_lines.push(line.to_string());
        } else {
            result_lines.push(format!("{}{}", indent_text, line));
        }
    }
    result_lines.join("\n")
}

pub(crate) fn is_markdown_atx_heading(text: &str) -> bool {
    let mut is_prev_ch_hash = false;
    for ch in text.chars() {
        if ch == '#' {
            is_prev_ch_hash = true;
        } else if ch == ' ' {
            return is_prev_ch_hash;
        } else {
            return false;
        }
    }
    false
}

pub(crate) fn index_of_markdown_ordered_item_dot(text: &str) -> Option<usize> {
    let mut is_prev_ch_numeric = false;
    let mut is_prev_ch_dot = false;
    for (index, ch) in text.chars().enumerate() {
        if ch.is_numeric() {
            is_prev_ch_numeric = true;
        } else if ch == '.' {
            if !is_prev_ch_numeric {
                return None;
            }
            is_prev_ch_dot = true;
        } else if ch == ' ' {
            if is_prev_ch_dot {
                return Some(index - 1);
            } else {
                return None;
            }
        } else {
            return None;
        }
    }
    None
}