broken_link_callbacks/
broken-link-callbacks.rs

1use pulldown_cmark::{html, BrokenLink, Options, Parser};
2
3fn main() {
4    let input: &str = "Hello world, check out [my website][].";
5    println!("Parsing the following markdown string:\n{}", input);
6
7    // Setup callback that sets the URL and title when it encounters
8    // a reference to our home page.
9    let callback = |broken_link: BrokenLink| {
10        if broken_link.reference.as_ref() == "my website" {
11            println!(
12                "Replacing the markdown `{}` of type {:?} with a working link",
13                &input[broken_link.span], broken_link.link_type,
14            );
15            Some(("http://example.com".into(), "my example website".into()))
16        } else {
17            None
18        }
19    };
20
21    // Create a parser with our callback function for broken links.
22    let parser = Parser::new_with_broken_link_callback(input, Options::empty(), Some(callback));
23
24    // Write to String buffer.
25    let mut html_output: String = String::with_capacity(input.len() * 3 / 2);
26    html::push_html(&mut html_output, parser);
27
28    // Check that the output is what we expected.
29    let expected_html: &str =
30        "<p>Hello world, check out <a href=\"http://example.com\" title=\"my example website\">my website</a>.</p>\n";
31    assert_eq!(expected_html, &html_output);
32
33    // Write result to stdout.
34    println!("\nHTML output:\n{}", &html_output);
35}