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
//! Generate a table of contents from a Markdown document.
//!
//! # Examples
//!
//! ```
//! use pulldown_cmark_toc::TableOfContents;
//!
//! let text = "# Heading\n\n## Subheading\n\n## Subheading with `code`\n";
//!
//! let toc = TableOfContents::new(text);
//! assert_eq!(
//!     toc.to_cmark(),
//!     r#"- [Heading](#heading)
//!   - [Subheading](#subheading)
//!   - [Subheading with `code`](#subheading-with-code)
//! "#
//! );
//! ```

mod render;

use std::borrow::Borrow;
use std::collections::HashMap;
use std::slice::Iter;

use lazy_static::lazy_static;
use pulldown_cmark::{Event, Options as CmarkOptions, Parser, Tag};
use regex::Regex;

pub use render::{ItemSymbol, Options};

/////////////////////////////////////////////////////////////////////////
// Definitions
/////////////////////////////////////////////////////////////////////////

/// Represents a heading.
#[derive(Debug, Clone)]
pub struct Heading<'a> {
    /// The Markdown events between the heading tags.
    events: Vec<Event<'a>>,
    /// The heading level.
    level: u32,
}

/// Represents a Table of Contents.
#[derive(Debug)]
pub struct TableOfContents<'a> {
    headings: Vec<Heading<'a>>,
}

/////////////////////////////////////////////////////////////////////////
// Implementations
/////////////////////////////////////////////////////////////////////////

impl Heading<'_> {
    /// The raw events contained between the heading tags.
    pub fn events(&self) -> Iter<Event> {
        self.events.iter()
    }

    /// The heading level.
    pub fn level(&self) -> &u32 {
        &self.level
    }

    /// The heading text with all Markdown code stripped out.
    ///
    /// The output of this this function can be used to generate an anchor.
    pub fn text(&self) -> String {
        let mut buf = String::new();
        for event in self.events() {
            if let Event::Text(s) | Event::Code(s) = event {
                buf.push_str(&s);
            }
        }
        buf
    }

    /// Generate an anchor link for this heading.
    ///
    /// This is calculated in the same way that GitHub calculates it.
    pub fn anchor(&self) -> String {
        lazy_static! {
            static ref RE: Regex = Regex::new(r"[^\w\- ]").unwrap();
        }
        RE.replace_all(&self.text().to_ascii_lowercase().replace(" ", "-"), "")
            .into_owned()
    }
}

impl<'a> TableOfContents<'a> {
    /// Construct a new table of contents from Markdown text.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pulldown_cmark_toc::TableOfContents;
    /// let toc = TableOfContents::new("# Heading\n");
    /// ```
    pub fn new(text: &'a str) -> Self {
        let events = Parser::new_ext(text, CmarkOptions::all());
        Self::new_with_events(events)
    }

    /// Construct a new table of contents from parsed Markdown events.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pulldown_cmark_toc::TableOfContents;
    /// use pulldown_cmark::Parser;
    ///
    /// let parser = Parser::new("# Heading\n");
    /// let toc = TableOfContents::new_with_events(parser);;
    /// ```
    pub fn new_with_events<I, E>(events: I) -> Self
    where
        I: Iterator<Item = E>,
        E: Borrow<Event<'a>>,
    {
        let mut current: Option<Heading> = None;
        let mut headings = Vec::new();

        for event in events {
            let event = event.borrow();
            match &*event {
                Event::Start(Tag::Heading(level)) => {
                    current = Some(Heading {
                        events: Vec::new(),
                        level: *level,
                    });
                }
                Event::End(Tag::Heading(level)) => {
                    let heading = current.take().unwrap();
                    assert_eq!(heading.level, *level);
                    headings.push(heading);
                }
                event => {
                    if let Some(heading) = current.as_mut() {
                        heading.events.push(event.clone());
                    }
                }
            }
        }
        Self { headings }
    }

    /// Iterate over the headings in this table of contents.
    ///
    /// # Examples
    ///
    /// Simple iteration over each heading.
    /// ```
    /// # use pulldown_cmark_toc::TableOfContents;
    /// let toc = TableOfContents::new("# Heading\n");
    ///
    /// for heading in toc.headings() {
    ///     // use heading
    /// }
    /// ```
    ///
    /// Filtering out certain heading levels.
    /// ```
    /// # use pulldown_cmark_toc::TableOfContents;
    /// let toc = TableOfContents::new("# Heading\n## Subheading\n");
    ///
    /// for heading in toc.headings().filter(|h| (2..6).contains(h.level())) {
    ///     // use heading
    /// }
    /// ```
    pub fn headings(&self) -> Iter<Heading> {
        self.headings.iter()
    }

    /// Render the table of contents as Markdown.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pulldown_cmark_toc::TableOfContents;
    /// let toc = TableOfContents::new("# Heading\n## Subheading\n");
    /// assert_eq!(
    ///     toc.to_cmark(),
    ///     "- [Heading](#heading)\n  - [Subheading](#subheading)\n"
    /// );
    /// ```
    #[must_use]
    pub fn to_cmark(&self) -> String {
        self.to_cmark_with_options(Options::default())
    }

    /// Render the table of contents as Markdown with extra options.
    ///
    /// # Examples
    ///
    /// ```
    /// # use pulldown_cmark_toc::{ItemSymbol, Options, TableOfContents};
    /// let toc = TableOfContents::new("# Heading\n## Subheading\n");
    /// let options = Options::default()
    ///     .item_symbol(ItemSymbol::Asterisk)
    ///     .levels(2..=6)
    ///     .indent(4);
    /// assert_eq!(
    ///     toc.to_cmark_with_options(options),
    ///     "* [Subheading](#subheading)\n"
    /// );
    /// ```
    #[must_use]
    pub fn to_cmark_with_options(&self, options: Options) -> String {
        let Options {
            item_symbol,
            levels,
            indent,
        } = options;

        // this is to record duplicates
        let mut counts = HashMap::new();

        let mut buf = String::new();
        for heading in self.headings().filter(|h| levels.contains(h.level())) {
            let title = crate::render::to_cmark(heading.events());
            let anchor = heading.anchor();
            let indent = indent * (heading.level() - levels.start()) as usize;

            // make sure the anchor is unique
            let i = counts
                .entry(anchor.clone())
                .and_modify(|i| *i += 1)
                .or_insert(0);
            let anchor = match *i {
                0 => anchor,
                i => format!("{}-{}", anchor, i),
            };

            buf.push_str(&format!(
                "{:indent$}{} [{}](#{})\n",
                "",
                item_symbol,
                title,
                anchor,
                indent = indent,
            ));
        }
        buf
    }
}

/////////////////////////////////////////////////////////////////////////
// Unit tests
/////////////////////////////////////////////////////////////////////////

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

    use pulldown_cmark::CowStr::Borrowed;
    use pulldown_cmark::Event::{Code, Text};

    #[test]
    fn heading_text_with_code() {
        let heading = Heading {
            events: vec![Code(Borrowed("Another")), Text(Borrowed(" heading"))],
            level: 1,
        };
        assert_eq!(heading.text(), "Another heading");
    }

    #[test]
    fn heading_text_with_links() {
        let events = Parser::new("Here [TOML](https://toml.io)").collect();
        let heading = Heading { events, level: 1 };
        assert_eq!(heading.text(), "Here TOML");
    }

    #[test]
    fn heading_anchor_with_code() {
        let heading = Heading {
            events: vec![Code(Borrowed("Another")), Text(Borrowed(" heading"))],
            level: 1,
        };
        assert_eq!(heading.anchor(), "another-heading");
    }

    #[test]
    fn heading_anchor_with_links() {
        let events = Parser::new("Here [TOML](https://toml.io)").collect();
        let heading = Heading { events, level: 1 };
        assert_eq!(heading.anchor(), "here-toml");
    }

    #[test]
    fn toc_new() {
        let toc = TableOfContents::new("# Heading\n\n## `Another` heading\n");
        assert_eq!(toc.headings[0].events, [Text(Borrowed("Heading"))]);
        assert_eq!(toc.headings[0].level, 1);
        assert_eq!(
            toc.headings[1].events,
            [Code(Borrowed("Another")), Text(Borrowed(" heading"))]
        );
        assert_eq!(toc.headings[1].level, 2);
        assert_eq!(toc.headings.len(), 2);
    }

    #[test]
    fn toc_to_cmark_unique_anchors() {
        let toc = TableOfContents::new("# Heading\n\n# Heading\n\n# `Heading`");
        assert_eq!(
            toc.to_cmark(),
            "- [Heading](#heading)\n- [Heading](#heading-1)\n- [`Heading`](#heading-2)\n"
        )
    }
}