diff --git a/packages/mdbook-trpl-listing/src/lib.rs b/packages/mdbook-trpl-listing/src/lib.rs index eeb3db008f..99b62cc0a6 100644 --- a/packages/mdbook-trpl-listing/src/lib.rs +++ b/packages/mdbook-trpl-listing/src/lib.rs @@ -260,17 +260,19 @@ fn rewrite_listing(src: &str, mode: Mode) -> Result { struct Listing { number: String, caption: String, - file_name: String, + file_name: Option, } impl Listing { fn opening_html(&self) -> String { - format!( - r#"
-Filename: {file_name} -"#, - file_name = self.file_name - ) + let figure = String::from("
\n"); + + match self.file_name.as_ref() { + Some(file_name) => format!( + "{figure}Filename: {file_name}\n", + ), + None => figure, + } } fn closing_html(&self, trailing: &str) -> String { @@ -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 { @@ -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), }) } } @@ -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. + ++ +```rust +fn main() {} +``` + + + +This is the closing."#, + Mode::Default, + ); + + assert!(result.is_ok()); + assert_eq!( + result.unwrap(), + r#"This is the opening. + +
+ +````rust +fn main() {} +```` + +
Listing 1-1: This is the caption
+
+ +This is the closing."# + ); + } + /// Check that the config options are correctly handled. /// /// Note: none of these tests particularly exercise the *wiring*. They just