Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

GREP styles: empty matches don't count toward the per-paragraph cap

Brandon Thomas637c32506a51
diff --git a/crates/compose/src/grep.rs b/crates/compose/src/grep.rs
index 09c6459e0..6f9e8f9e3 100644
--- a/crates/compose/src/grep.rs
+++ b/crates/compose/src/grep.rs
@@ -385,6 +385,17 @@ impl Grep {
self.re.find_iter(text).take(limit).map(|m| m.map(|m| m.range()).map_err(run_err)).collect()
}
+ /// Non-empty matches in `text`, at most `limit` of them: an empty match styles nothing, so it
+ /// doesn't count toward a GREP style's cap.
+ pub fn find_nonempty(&self, text: &str, limit: usize) -> Result<Vec<Range<usize>>, GrepError> {
+ self.re
+ .find_iter(text)
+ .filter(|m| !m.as_ref().is_ok_and(|m| m.range().is_empty()))
+ .take(limit)
+ .map(|m| m.map(|m| m.range()).map_err(run_err))
+ .collect()
+ }
+
/// Matches in `text` and their replacements, `template` expanded per match (`$1`…; see
/// [`translate_replacement`]). Stops after the first match when `first_only`.
pub fn replacements(&self, text: &str, template: &str, first_only: bool) -> Result<Vec<(Range<usize>, String)>, GrepError> {
diff --git a/crates/compose/src/overlay.rs b/crates/compose/src/overlay.rs
index 5c95b0ec8..b09ef908e 100644
--- a/crates/compose/src/overlay.rs
+++ b/crates/compose/src/overlay.rs
@@ -106,7 +106,7 @@ pub(crate) fn overlays(text: &str, range: Range<usize>, nested: &[NestedStyle],
}
with_pattern(&g.pattern, |slot| {
let Some(re) = slot else { return };
- match re.find_all(text.get(range.start..end).unwrap_or(""), crate::grep::MAX_MATCHES_PER_PARAGRAPH) {
+ match re.find_nonempty(text.get(range.start..end).unwrap_or(""), crate::grep::MAX_MATCHES_PER_PARAGRAPH) {
Ok(ms) => {
if ms.len() == crate::grep::MAX_MATCHES_PER_PARAGRAPH {
log::warn!("GREP style {:?} matched more than {} times in one paragraph; the rest are not styled", g.pattern, ms.len());
@@ -127,6 +127,15 @@ pub(crate) fn overlays(text: &str, range: Range<usize>, nested: &[NestedStyle],
mod tests {
use super::*;
+ /// A pattern that can match nothing still styles a paragraph longer than the cap: empty
+ /// matches don't count toward it.
+ #[test]
+ fn empty_matches_do_not_use_up_the_grep_cap() {
+ let text = format!("{}a", "b".repeat(crate::grep::MAX_MATCHES_PER_PARAGRAPH + 100));
+ let o = overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "A".into(), pattern: "a*".into() }], 0);
+ assert_eq!(o.len(), 1, "the one non-empty match at the end is styled");
+ }
+
/// A GREP style's scan is bounded two ways (#1598): the matches one paragraph can take, and
/// the patterns kept compiled at once.
#[test]