| 1 |
// Example provided by https://github.com/slonkazoid --- thank you! |
| 2 |
// (https://github.com/kivikakk/comrak/issues/557) |
| 3 |
// |
| 4 |
// Defaults image title text to alt text, if provided. |
| 5 |
|
| 6 |
use comrak::nodes::{Node, NodeLink, NodeValue}; |
| 7 |
use comrak::{Arena, parse_document}; |
| 8 |
|
| 9 |
fn autotitle_images( |
| 10 |
nl: &mut NodeLink, |
| 11 |
_context: &mut comrak::html::Context, |
| 12 |
node: Node<'_>, |
| 13 |
entering: bool, |
| 14 |
) { |
| 15 |
if !entering || !nl.title.is_empty() { |
| 16 |
return; |
| 17 |
} |
| 18 |
|
| 19 |
let mut s = String::new(); |
| 20 |
|
| 21 |
for child in node.children() { |
| 22 |
if let Some(text) = child.data().value.text() { |
| 23 |
s += text; |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
nl.title = s; |
| 28 |
} |
| 29 |
|
| 30 |
fn formatter<'a>( |
| 31 |
context: &mut comrak::html::Context, |
| 32 |
node: &'a comrak::nodes::AstNode<'a>, |
| 33 |
entering: bool, |
| 34 |
) -> Result<comrak::html::ChildRendering, std::fmt::Error> { |
| 35 |
if let NodeValue::Image(ref mut nl) = node.data_mut().value { |
| 36 |
autotitle_images(nl, context, node, entering); |
| 37 |
} |
| 38 |
comrak::html::format_node_default(context, node, entering) |
| 39 |
} |
| 40 |
|
| 41 |
fn main() { |
| 42 |
let arena = Arena::new(); |
| 43 |
let parsed = parse_document(&arena, "", &Default::default()); |
| 44 |
|
| 45 |
let mut out = String::new(); |
| 46 |
comrak::html::format_document_with_formatter( |
| 47 |
parsed, |
| 48 |
&Default::default(), |
| 49 |
&mut out, |
| 50 |
&Default::default(), |
| 51 |
formatter, |
| 52 |
(), |
| 53 |
) |
| 54 |
.unwrap_or_else(|_| unreachable!("writing to String cannot fail")); |
| 55 |
|
| 56 |
println!("{out}"); |
| 57 |
} |