| 1 |
use comrak::nodes::NodeValue; |
| 2 |
use comrak::{Arena, Options, format_html, parse_document}; |
| 3 |
|
| 4 |
fn replace_text(document: &str, orig_string: &str, replacement: &str) -> String { |
| 5 |
// The returned nodes are created in the supplied Arena, and are bound by its lifetime. |
| 6 |
let arena = Arena::new(); |
| 7 |
|
| 8 |
// Parse the document into a root `Node` |
| 9 |
let root = parse_document(&arena, document, &Options::default()); |
| 10 |
|
| 11 |
// Iterate over all the descendants of root. |
| 12 |
for node in root.descendants() { |
| 13 |
if let NodeValue::Text(ref mut text) = node.data_mut().value { |
| 14 |
// If the node is a text node, replace `orig_string` with `replacement`. |
| 15 |
*text = text.to_mut().replace(orig_string, replacement).into() |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
let mut html = String::new(); |
| 20 |
format_html(root, &Options::default(), &mut html).unwrap(); |
| 21 |
|
| 22 |
html |
| 23 |
} |
| 24 |
|
| 25 |
fn main() { |
| 26 |
let doc = |
| 27 |
"Hello, pretty world!\n\n1. Do you like [pretty](#) paintings?\n2. Or *pretty* music?\n"; |
| 28 |
let orig = "pretty"; |
| 29 |
let repl = "beautiful"; |
| 30 |
let html = replace_text(doc, orig, repl); |
| 31 |
|
| 32 |
println!("{}", html); |
| 33 |
} |
| 34 |
|
| 35 |
#[cfg(test)] |
| 36 |
mod tests { |
| 37 |
use super::*; |
| 38 |
use ntest::{assert_false, assert_true}; |
| 39 |
|
| 40 |
#[test] |
| 41 |
fn sample_replace() { |
| 42 |
let doc = "Replace deeply nested *[foo](https://example.com)* with bar.\n\nReplace shallow foo with bar."; |
| 43 |
let orig = "foo"; |
| 44 |
let repl = "bar"; |
| 45 |
let html = replace_text(&doc, &orig, &repl); |
| 46 |
println!("{:?}", html); |
| 47 |
assert_false!(html.contains("foo")); |
| 48 |
assert_true!(html.contains("bar")); |
| 49 |
assert_true!(html.contains("<a")); |
| 50 |
assert_true!(html.contains("<p")); |
| 51 |
} |
| 52 |
} |