Skip to content

Commit

Permalink
fix(#73) do not disturb code block detection when preventing escape
Browse files Browse the repository at this point in the history
  • Loading branch information
SichangHe committed Jun 10, 2024
1 parent 1978c0c commit 7376d42
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/source_range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,27 @@ where
for (event, range) in event_and_ranges {
let update_event_end_index = !matches!(*event.borrow(), Event::Start(_));
let prevent_escape_leading_special_characters = match (&range, event.borrow()) {
// IMPORTANT: Any changes that allow anything other than `Text`
// breaks the assumption below.
(Some(range), Event::Text(_)) => {
range.start <= state.last_event_end_index ||
// Some source characters are not captured,
// so check the previous character.
source.as_bytes().get(range.start.saturating_sub(1)) != Some(&b'\\')
}
_ => false,
};
let was_in_code_block = state.is_in_code_block;
} && !state.is_in_code_block;
if prevent_escape_leading_special_characters {
// Hack to not escape leading special characters.
state.is_in_code_block = true;
}
cmark_resume_one_event(event, &mut formatter, &mut state, &options)?;
state.is_in_code_block = was_in_code_block;
if prevent_escape_leading_special_characters {
// Assumption: this case only happens when `event` is `Text`,
// so `state.is_in_code_block` should not be changed to `true`.
// Also, `state.is_in_code_block` was `false`.
state.is_in_code_block = false;
}

if let (true, Some(range)) = (update_event_end_index, range) {
state.last_event_end_index = range.end
Expand Down
28 changes: 28 additions & 0 deletions tests/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,34 @@ mod inline_elements {
)
}

#[test]
fn no_escaping_special_character_in_code() {
// https://github.com/Byron/pulldown-cmark-to-cmark/issues/73
let input = r#"
```rust
# fn main() {
println!("Hello, world!");
# }
```
"#;
let iter = pulldown_cmark::Parser::new(input);
let mut actual = String::new();
pulldown_cmark_to_cmark::cmark_with_source_range_and_options(
iter.map(|e| (e, None)),
input,
&mut actual,
Default::default(),
)
.unwrap();
let expected = r#"
````rust
# fn main() {
println!("Hello, world!");
# }
````"#;
assert_eq!(actual, expected);
}

#[test]
fn rustdoc_link() {
// Brackets are not escaped if not escaped in the source.
Expand Down

0 comments on commit 7376d42

Please sign in to comment.