Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

infra: support Listings without file-name #3920

Merged
merged 1 commit into from
May 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 49 additions & 14 deletions packages/mdbook-trpl-listing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,17 +260,19 @@ fn rewrite_listing(src: &str, mode: Mode) -> Result<String, String> {
struct Listing {
number: String,
caption: String,
file_name: String,
file_name: Option<String>,
}

impl Listing {
fn opening_html(&self) -> String {
format!(
r#"<figure class="listing">
<span class="file-name">Filename: {file_name}</span>
"#,
file_name = self.file_name
)
let figure = String::from("<figure class=\"listing\">\n");

match self.file_name.as_ref() {
Some(file_name) => format!(
"{figure}<span class=\"file-name\">Filename: {file_name}</span>\n",
),
None => figure,
}
}

fn closing_html(&self, trailing: &str) -> String {
Expand All @@ -283,7 +285,10 @@ impl Listing {
}

fn opening_text(&self) -> String {
format!("\nFilename: {file_name}\n", file_name = self.file_name)
self.file_name
.as_ref()
.map(|file_name| format!("\nFilename: {file_name}\n"))
.unwrap_or_default()
}

fn closing_text(&self, trailing: &str) -> String {
Expand Down Expand Up @@ -346,15 +351,10 @@ impl<'a> ListingBuilder<'a> {
.ok_or_else(|| String::from("Missing caption"))?
.to_owned();

let file_name = self
.file_name
.ok_or_else(|| String::from("Missing file-name"))?
.to_owned();

Ok(Listing {
number,
caption,
file_name,
file_name: self.file_name.map(String::from),
})
}
}
Expand Down Expand Up @@ -459,6 +459,41 @@ Save the file and go back to your terminal window"#
);
}

#[test]
fn no_filename() {
let result = rewrite_listing(
r#"This is the opening.

<Listing number="1-1" caption="This is the caption">

```rust
fn main() {}
```

</Listing>

This is the closing."#,
Mode::Default,
);

assert!(result.is_ok());
assert_eq!(
result.unwrap(),
r#"This is the opening.

<figure class="listing">

````rust
fn main() {}
````

<figcaption>Listing 1-1: This is the caption</figcaption>
</figure>

This is the closing."#
);
}

/// Check that the config options are correctly handled.
///
/// Note: none of these tests particularly exercise the *wiring*. They just
Expand Down