| 1 |
use comrak::{ |
| 2 |
Arena, Options, |
| 3 |
arena_tree::NodeEdge, |
| 4 |
nodes::{Node, NodeValue}, |
| 5 |
parse_document, |
| 6 |
}; |
| 7 |
|
| 8 |
// `node.traverse()`` creates an iterator that will traverse |
| 9 |
// the current node and all descendants in order. |
| 10 |
// The iterator yields `NodeEdges`. `NodeEdges` can have the |
| 11 |
// following values: |
| 12 |
// |
| 13 |
// `NodeEdge::Start(node)` Start of node. |
| 14 |
// `NodeEdge::End(node)` End of node. |
| 15 |
// `None` End of iterator at bottom of last branch. |
| 16 |
// |
| 17 |
// This example extracts plain text ignoring nested |
| 18 |
// markup. |
| 19 |
|
| 20 |
// Note: root can be any Node, not just document root. |
| 21 |
|
| 22 |
fn extract_text_traverse(root: Node<'_>) -> String { |
| 23 |
let mut output_text = String::new(); |
| 24 |
|
| 25 |
// Use `traverse` to get an iterator of `NodeEdge` and process each. |
| 26 |
for edge in root.traverse() { |
| 27 |
if let NodeEdge::Start(node) = edge { |
| 28 |
// Handle the Start edge to process the node's value. |
| 29 |
if let NodeValue::Text(ref text) = node.data().value { |
| 30 |
// If the node is a text node, append its text to `output_text`. |
| 31 |
output_text.push_str(text); |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
output_text |
| 37 |
} |
| 38 |
|
| 39 |
fn main() { |
| 40 |
let markdown_input = "Hello, *worl[d](https://example.com/)*"; |
| 41 |
// Nested inline markup. Equivalent html should look like this: |
| 42 |
//"<p>Hello, <em>worl<a href="https://example.com">d</a></em></p> |
| 43 |
|
| 44 |
println!("INPUT: {}", markdown_input); |
| 45 |
|
| 46 |
// setup parser |
| 47 |
let arena = Arena::new(); |
| 48 |
let options = Options::default(); |
| 49 |
|
| 50 |
// parse document and return root. |
| 51 |
let root = parse_document(&arena, markdown_input, &options); |
| 52 |
|
| 53 |
// extract text and print |
| 54 |
println!("OUTPUT: {}", extract_text_traverse(root).as_str()) |
| 55 |
} |
| 56 |
|
| 57 |
#[cfg(test)] |
| 58 |
mod tests { |
| 59 |
// Import everything from the outer module to make it available for tests |
| 60 |
use super::*; |
| 61 |
|
| 62 |
#[test] |
| 63 |
fn extract_text_traverse_test() { |
| 64 |
let markdown_input = "Hello, *worl[d](https://example.com/)*"; |
| 65 |
let arena = Arena::new(); |
| 66 |
let options = Options::default(); |
| 67 |
let root = parse_document(&arena, markdown_input, &options); |
| 68 |
assert_eq!("Hello, world", extract_text_traverse(root)); |
| 69 |
} |
| 70 |
} |