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

Strip leading trailing empty lines in doc code blocks #103376

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
69 changes: 67 additions & 2 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,71 @@ impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
}
}

/// This iterator strips all the leading and trailing empty lines in the code block. For example:
///
/// ```
///
/// let x = 12;
///
/// // hello
///
/// ```
///
/// It'll only keep:
///
/// ```
/// let x = 12;
///
/// // hello
/// ```
struct CodeblockTextIter<'a, T: Iterator<Item = Cow<'a, str>>> {
iter: T,
found_first_non_empty: bool,
pending_content: VecDeque<Cow<'a, str>>,
}

impl<'a, T: Iterator<Item = Cow<'a, str>>> CodeblockTextIter<'a, T> {
fn new(iter: T) -> Self {
Self { iter, found_first_non_empty: false, pending_content: VecDeque::new() }
}
}

impl<'a, T: Iterator<Item = Cow<'a, str>>> Iterator for CodeblockTextIter<'a, T> {
type Item = Cow<'a, str>;

fn next(&mut self) -> Option<Self::Item> {
// If there are still stored content because there were empty lines before a non-empty one,
// we need to provide all of them too.
if let Some(next) = self.pending_content.pop_front() {
return Some(next);
}
while let Some(next) = self.iter.next() {
// As long as we don't encounter the first non-empty lines, we skip all of them.
if !self.found_first_non_empty {
if !next.trim().is_empty() {
self.found_first_non_empty = true;
return Some(next);
}
} else if !next.trim().is_empty() {
// We need to check the buffer since it could have been filled in the meantime
// if empty lines were encountered.
if let Some(front) = self.pending_content.pop_front() {
self.pending_content.push_back(next);
return Some(front);
}
return Some(next);
} else {
// We encountered an empty line but it's maybe not the last line so we need to
// store it just in case.
self.pending_content.push_back(next);
}
}
// We clear the content in case `next` is called afterwards.
self.pending_content.clear();
None
}
}

impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
type Item = Event<'a>;

Expand All @@ -246,8 +311,8 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
_ => {}
}
}
let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
let text = lines.intersperse("\n".into()).collect::<String>();
let lines = CodeblockTextIter::new(origtext.lines().filter_map(|l| map_line(l).for_html()));
let text = lines.intersperse(Cow::Borrowed("\n")).collect::<String>();

let parse_result = match kind {
CodeBlockKind::Fenced(ref lang) => {
Expand Down
63 changes: 63 additions & 0 deletions src/librustdoc/html/markdown/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::{find_testable_code, plain_text_summary, short_markdown_summary};
use super::{ErrorCodes, HeadingOffset, IdMap, Ignore, LangString, Markdown, MarkdownItemInfo};
use rustc_span::create_default_session_globals_then;
use rustc_span::edition::{Edition, DEFAULT_EDITION};

#[test]
Expand Down Expand Up @@ -309,3 +310,65 @@ fn test_find_testable_code_line() {
t("```rust\n```\n```rust\n```", &[1, 3]);
t("```rust\n```\n ```rust\n```", &[1, 3]);
}

#[test]
fn test_handling_of_starting_and_trailing_empty_lines() {
fn t(input: &str, expect: &str) {
let mut map = IdMap::new();
let output = Markdown {
content: input,
links: &[],
ids: &mut map,
error_codes: ErrorCodes::Yes,
edition: DEFAULT_EDITION,
playground: &None,
heading_offset: HeadingOffset::H2,
}
.into_string();
assert_eq!(output, expect, "original: {}", input);
}

create_default_session_globals_then(|| {
t(
"\
```
// hello


f();

// bye
```",
r#"
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="comment">// hello


</span>f();

<span class="comment">// bye</span></code></pre></div>
"#,
);
t(
"\
```


// hello

f();

// bye



```",
r#"
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="comment">// hello

</span>f();

<span class="comment">// bye</span></code></pre></div>
"#,
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test case with boring lines at the start and end, since these are the use cases that actually motivate this feature.

        t(
            "\
```
# hello


f();


# goodbye
```",
            r#"
<div class="example-wrap"><pre class="rust rust-example-rendered"><code>f();</code></pre></div>
"#,
        );

});
}