Skip to content

Commit 7e2a00d

Browse files
authored
Merge pull request #3920 from rust-lang/listings-without-file-name
infra: support `Listing`s without `file-name`
2 parents 444932b + ad673cf commit 7e2a00d

File tree

1 file changed

+49
-14
lines changed
  • packages/mdbook-trpl-listing/src

1 file changed

+49
-14
lines changed

packages/mdbook-trpl-listing/src/lib.rs

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -260,17 +260,19 @@ fn rewrite_listing(src: &str, mode: Mode) -> Result<String, String> {
260260
struct Listing {
261261
number: String,
262262
caption: String,
263-
file_name: String,
263+
file_name: Option<String>,
264264
}
265265

266266
impl Listing {
267267
fn opening_html(&self) -> String {
268-
format!(
269-
r#"<figure class="listing">
270-
<span class="file-name">Filename: {file_name}</span>
271-
"#,
272-
file_name = self.file_name
273-
)
268+
let figure = String::from("<figure class=\"listing\">\n");
269+
270+
match self.file_name.as_ref() {
271+
Some(file_name) => format!(
272+
"{figure}<span class=\"file-name\">Filename: {file_name}</span>\n",
273+
),
274+
None => figure,
275+
}
274276
}
275277

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

285287
fn opening_text(&self) -> String {
286-
format!("\nFilename: {file_name}\n", file_name = self.file_name)
288+
self.file_name
289+
.as_ref()
290+
.map(|file_name| format!("\nFilename: {file_name}\n"))
291+
.unwrap_or_default()
287292
}
288293

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

349-
let file_name = self
350-
.file_name
351-
.ok_or_else(|| String::from("Missing file-name"))?
352-
.to_owned();
353-
354354
Ok(Listing {
355355
number,
356356
caption,
357-
file_name,
357+
file_name: self.file_name.map(String::from),
358358
})
359359
}
360360
}
@@ -459,6 +459,41 @@ Save the file and go back to your terminal window"#
459459
);
460460
}
461461

462+
#[test]
463+
fn no_filename() {
464+
let result = rewrite_listing(
465+
r#"This is the opening.
466+
467+
<Listing number="1-1" caption="This is the caption">
468+
469+
```rust
470+
fn main() {}
471+
```
472+
473+
</Listing>
474+
475+
This is the closing."#,
476+
Mode::Default,
477+
);
478+
479+
assert!(result.is_ok());
480+
assert_eq!(
481+
result.unwrap(),
482+
r#"This is the opening.
483+
484+
<figure class="listing">
485+
486+
````rust
487+
fn main() {}
488+
````
489+
490+
<figcaption>Listing 1-1: This is the caption</figcaption>
491+
</figure>
492+
493+
This is the closing."#
494+
);
495+
}
496+
462497
/// Check that the config options are correctly handled.
463498
///
464499
/// Note: none of these tests particularly exercise the *wiring*. They just

0 commit comments

Comments
 (0)