rustdoc_to_markdown: Support bold and italics (#12501)

This PR extends `rustdoc_to_markdown` with support for bold and italic
text.

Release Notes:

- N/A
This commit is contained in:
Marshall Bowers
2024-05-30 16:06:21 -04:00
committed by GitHub
parent 279c5ab81f
commit 6fe665ab94
2 changed files with 30 additions and 3 deletions
@@ -132,8 +132,12 @@ impl MarkdownWriter {
fn start_tag(&mut self, tag: &HtmlElement) -> StartTagOutcome {
if tag.is_inline() && self.is_inside("p") {
if !self.markdown.ends_with(' ') {
self.push_str(" ");
if let Some(parent) = self.current_element_stack.iter().last() {
if !parent.is_inline() {
if !self.markdown.ends_with(' ') {
self.push_str(" ");
}
}
}
}
@@ -146,6 +150,8 @@ impl MarkdownWriter {
"h5" => self.push_str("\n\n##### "),
"h6" => self.push_str("\n\n###### "),
"p" => self.push_blank_line(),
"strong" => self.push_str("**"),
"em" => self.push_str("_"),
"code" => {
if !self.is_inside("pre") {
self.push_str("`");
@@ -219,6 +225,8 @@ impl MarkdownWriter {
fn end_tag(&mut self, tag: &HtmlElement) {
match tag.tag.as_str() {
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => self.push_str("\n\n"),
"strong" => self.push_str("**"),
"em" => self.push_str("_"),
"code" => {
if !self.is_inside("pre") {
self.push_str("`");
@@ -114,7 +114,7 @@ mod tests {
let expected = indoc! {"
## Serde
Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.
Serde is a framework for _**ser**_ializing and _**de**_serializing Rust data structures efficiently and generically.
The Serde ecosystem consists of data structures that know how to serialize and deserialize themselves along with data formats that know how to serialize and deserialize other things. Serde provides the layer by which these two groups interact with each other, allowing any supported data structure to be serialized and deserialized using any supported data format.
@@ -132,6 +132,25 @@ mod tests {
)
}
#[test]
fn test_styled_text() {
let html = indoc! {r#"
<p>This text is <strong>bolded</strong>.</p>
<p>This text is <em>italicized</em>.</p>
"#};
let expected = indoc! {"
This text is **bolded**.
This text is _italicized_.
"}
.trim();
assert_eq!(
convert_rustdoc_to_markdown(html.as_bytes()).unwrap(),
expected
)
}
#[test]
fn test_rust_code_block() {
let html = indoc! {r#"