| 1 |
// Extract the document title by srching for a level-one header at the root level. |
| 2 |
|
| 3 |
use comrak::{Arena, Options, nodes::NodeValue, parse_document}; |
| 4 |
|
| 5 |
fn main() { |
| 6 |
println!("{:?}", get_document_title("# Hello\n")); |
| 7 |
println!("{:?}", get_document_title("## Hello\n")); |
| 8 |
println!("{:?}", get_document_title("# `hi` **there**\n")); |
| 9 |
} |
| 10 |
|
| 11 |
fn get_document_title(document: &str) -> String { |
| 12 |
let arena = Arena::new(); |
| 13 |
let root = parse_document(&arena, document, &Options::default()); |
| 14 |
|
| 15 |
for node in root.children() { |
| 16 |
let header = match node.data().value { |
| 17 |
NodeValue::Heading(c) => c, |
| 18 |
_ => continue, |
| 19 |
}; |
| 20 |
|
| 21 |
if header.level != 1 { |
| 22 |
continue; |
| 23 |
} |
| 24 |
|
| 25 |
return node.collect_text(); |
| 26 |
} |
| 27 |
|
| 28 |
"Untitled Document".to_string() |
| 29 |
} |