Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

fix(harper-tex): mask horizontal whitespace before % comments (#3108)

Juraj Klaricfe7e36695f0f
diff --git a/harper-tex/src/masker.rs b/harper-tex/src/masker.rs
index 38118da74..aa60860b3 100644
--- a/harper-tex/src/masker.rs
+++ b/harper-tex/src/masker.rs
@@ -20,7 +20,9 @@ impl harper_core::Masker for Masker {
let c = source[cursor];
- if matches!(c, '%') {
+ if let Some(ws) = whitespace_before_comment_at_cursor(cursor, source) {
+ actions.push_back(CursorAction::PushMaskAndIncBy(ws));
+ } else if matches!(c, '%') {
actions.push_back(CursorAction::PushMaskAndIncBy(1));
} else if let Some(ws) = newline_whitespace_at_cursor(cursor, source) {
actions.push_back(CursorAction::PushMaskAndIncBy(ws));
@@ -57,6 +59,24 @@ impl harper_core::Masker for Masker {
}
}
+/// If the cursor is at horizontal whitespace immediately followed by `%` on the same line,
+/// return the length of the whitespace run so it can be masked along with the comment.
+fn whitespace_before_comment_at_cursor(cursor: usize, source: &[char]) -> Option<usize> {
+ let c = *source.get(cursor)?;
+ if c == '\n' || !c.is_whitespace() {
+ return None;
+ }
+ let ws_len = source[cursor..]
+ .iter()
+ .take_while(|&&ch| ch.is_whitespace() && ch != '\n')
+ .count();
+ if source.get(cursor + ws_len) == Some(&'%') {
+ Some(ws_len)
+ } else {
+ None
+ }
+}
+
/// If the cursor is at a newline, mask the newline and any following whitespace (indentation).
/// This prevents indentation at the start of lines from being grammar-checked.
fn newline_whitespace_at_cursor(cursor: usize, source: &[char]) -> Option<usize> {
@@ -291,6 +311,22 @@ mod tests {
assert_eq!(allowed, "word word");
}
+ #[test]
+ fn masks_whitespace_before_comment() {
+ let source: Vec<_> = "some text % aligned comment".chars().collect();
+ let mask = Masker::default().create_mask(&source);
+ let allowed: Vec<String> = mask
+ .iter_allowed(&source)
+ .map(|(_, chars)| chars.iter().collect::<String>())
+ .collect();
+ for span in &allowed {
+ assert!(
+ !span.ends_with(' '),
+ "Trailing space before comment leaked through: {span:?}"
+ );
+ }
+ }
+
#[test]
fn ignores_many_comment_signs() {
let source: Vec<_> = "%%%".chars().collect();