From b3896908a39a4a91d8f6b3c9d78ceb7ea9abbf6a Mon Sep 17 00:00:00 2001 From: Noah Hellman Date: Sun, 15 Jan 2023 21:40:15 +0100 Subject: [PATCH] inline: trim verbatim whitespace --- src/inline.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ src/span.rs | 4 ++++ 2 files changed, 46 insertions(+) diff --git a/src/inline.rs b/src/inline.rs index 283c3e6..13d9e11 100644 --- a/src/inline.rs +++ b/src/inline.rs @@ -159,6 +159,9 @@ impl + Clone> Parser { let mut span_inner = Span::empty_at(self.span.end()); let mut span_outer = None; + let mut non_whitespace_first = None; + let mut non_whitespace_last = None; + while let Some(t) = self.eat() { if matches!(t.kind, lex::Kind::Seq(lex::Sequence::Backtick)) && t.len == opener_len { @@ -193,10 +196,23 @@ impl + Clone> Parser { } break; } + if !matches!(t.kind, lex::Kind::Whitespace) { + if non_whitespace_first.is_none() { + non_whitespace_first = Some((t.kind, span_inner.end())); + } + non_whitespace_last = Some((t.kind, span_inner.end() + t.len)); + } span_inner = span_inner.extend(t.len); self.reset_span(); } + if let Some((lex::Kind::Seq(lex::Sequence::Backtick), pos)) = non_whitespace_first { + span_inner = span_inner.with_start(pos); + } + if let Some((lex::Kind::Seq(lex::Sequence::Backtick), pos)) = non_whitespace_last { + span_inner = span_inner.with_end(pos); + } + self.events.push_back(Event { kind: EventKind::Str, span: span_inner, @@ -572,6 +588,32 @@ mod test { ); } + #[test] + fn verbatim_whitespace() { + test_parse!( + "` `", + (Enter(Verbatim), "`"), + (Str, " "), + (Exit(Verbatim), "`"), + ); + test_parse!( + "` abc `", + (Enter(Verbatim), "`"), + (Str, " abc "), + (Exit(Verbatim), "`"), + ); + } + + #[test] + fn verbatim_trim() { + test_parse!( + "` ``abc`` `", + (Enter(Verbatim), "`"), + (Str, "``abc``"), + (Exit(Verbatim), "`"), + ); + } + #[test] fn math() { test_parse!( diff --git a/src/span.rs b/src/span.rs index 54c5a2f..5da9670 100644 --- a/src/span.rs +++ b/src/span.rs @@ -26,6 +26,10 @@ impl Span { Self::new(start, self.end()) } + pub fn with_end(self, end: usize) -> Self { + Self::new(self.start(), end) + } + pub fn with_len(self, len: usize) -> Self { Self::by_len(self.start(), len) }