highlight: Honor textmate regex anchors

c456f70eff0e996e35882b429a9d54b762914584
Track first-line and begin-position anchor state while tokenizing so \A
and \G behave like TextMate. Appending a synthetic line terminator also
lets grammars match end-of-line constructs without exposing that byte in
emitted spans.
Alexis Sellier committed ago 1 parent 355417ff
crates/highlight/src/grammar.rs +49 -1
56 56
    /// Interned scope id.
57 57
    pub scope: ScopeId,
58 58
}
59 59
60 60
/// Per-line parser state.
61 -
#[derive(Clone, Debug, Default, Eq, PartialEq)]
61 +
#[derive(Clone, Debug, Eq, PartialEq)]
62 62
pub struct LineState {
63 63
    /// Open begin/end rules carried across line boundaries.
64 64
    stack: Vec<OpenRule>,
65 +
    /// Whether the next line tokenized from this state is the first line.
66 +
    first_line: bool,
65 67
}
66 68
67 69
impl LineState {
68 70
    /// Returns true when there are no open multi-line rules.
69 71
    pub fn is_empty(&self) -> bool {
74 76
    pub fn depth(&self) -> usize {
75 77
        self.stack.len()
76 78
    }
77 79
}
78 80
81 +
impl Default for LineState {
82 +
    /// Creates parser state for the first line of a document.
83 +
    fn default() -> Self {
84 +
        Self {
85 +
            stack: Vec::new(),
86 +
            first_line: true,
87 +
        }
88 +
    }
89 +
}
90 +
91 +
/// Regex anchor availability for one tokenizer step.
92 +
#[derive(Clone, Copy, Debug)]
93 +
pub(super) struct AnchorState {
94 +
    /// Whether `\A` should be allowed for this line.
95 +
    first_line: bool,
96 +
    /// Byte position where `\G` should be allowed.
97 +
    begin_position: Option<usize>,
98 +
}
99 +
100 +
impl AnchorState {
101 +
    /// Creates anchor state for a new line.
102 +
    pub(super) fn new(first_line: bool) -> Self {
103 +
        Self {
104 +
            first_line,
105 +
            begin_position: None,
106 +
        }
107 +
    }
108 +
109 +
    /// Allows `\G` at `position`.
110 +
    pub(super) fn set_begin_position(&mut self, position: usize) {
111 +
        self.begin_position = Some(position);
112 +
    }
113 +
114 +
    /// Returns Oniguruma search options for a search starting at `position`.
115 +
    pub(super) fn search_options(self, position: usize) -> SearchOptions {
116 +
        let mut options = SearchOptions::SEARCH_OPTION_NONE;
117 +
        if !self.first_line {
118 +
            options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_STRING;
119 +
        }
120 +
        if self.begin_position != Some(position) {
121 +
            options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_POSITION;
122 +
        }
123 +
        options
124 +
    }
125 +
}
126 +
79 127
/// Immutable compiled grammar data.
80 128
#[derive(Debug)]
81 129
pub struct Grammar {
82 130
    /// Human-readable grammar name.
83 131
    pub name: String,
crates/highlight/src/grammar/pattern.rs +66 -89
183 183
    next_rule: usize,
184 184
    /// Scope-name interner.
185 185
    interner: ScopeInterner,
186 186
}
187 187
188 -
/// End match found before any nested match on the current line.
189 -
struct EndOnLine {
190 -
    /// The regex match that closed the rule.
191 -
    matched: RegexMatch,
192 -
    /// Spans emitted by nested patterns scanned while looking for the end.
193 -
    spans: Vec<ScopeSpan>,
194 -
}
195 -
196 188
impl Scope {
197 189
    /// Builds a scope from an optional raw TextMate name.
198 190
    fn from_raw(name: Option<&str>, interner: &mut ScopeInterner) -> Self {
199 191
        let Some(name) = name else { return Self::None };
200 192
        let path = name
286 278
        self,
287 279
        sets: &[PatternSet],
288 280
        line: &str,
289 281
        pos: usize,
290 282
        cache: &mut EndRegexCache,
283 +
        anchors: AnchorState,
291 284
    ) -> Option<Match> {
292 285
        let mut active = Vec::new();
293 -
        self.find_next_inner(sets, line, pos, cache, &mut active)
286 +
        self.find_next_inner(sets, line, pos, cache, anchors, &mut active)
294 287
    }
295 288
296 289
    /// Finds the next pattern match while carrying the active include stack.
297 290
    fn find_next_inner(
298 291
        self,
299 292
        sets: &[PatternSet],
300 293
        line: &str,
301 294
        pos: usize,
302 295
        cache: &mut EndRegexCache,
296 +
        anchors: AnchorState,
303 297
        active: &mut Vec<PatternSetId>,
304 298
    ) -> Option<Match> {
305 299
        if active.contains(&self) || active.len() > MAX_INCLUDE_DEPTH {
306 300
            return None;
307 301
        }
308 302
        active.push(self);
309 303
        let found = sets
310 304
            .get(self.index())
311 -
            .and_then(|set| set.find_next_inner(sets, line, pos, cache, active));
305 +
            .and_then(|set| set.find_next_inner(sets, line, pos, cache, anchors, active));
312 306
        active.pop();
313 307
        found
314 308
    }
315 309
}
316 310
343 337
        &self,
344 338
        sets: &[PatternSet],
345 339
        line: &str,
346 340
        pos: usize,
347 341
        cache: &mut EndRegexCache,
342 +
        anchors: AnchorState,
348 343
        active: &mut Vec<PatternSetId>,
349 344
    ) -> Option<Match> {
350 345
        if pos > line.len() || !line.is_char_boundary(pos) {
351 346
            return None;
352 347
        }
353 -
        let mut found = self.find_next_local(sets, line, pos, cache);
348 +
        let mut found = self.find_next_local(line, pos, cache, anchors);
354 349
        for include in &self.includes {
355 -
            let Some(candidate) = include.find_next_inner(sets, line, pos, cache, active) else {
350 +
            let Some(candidate) = include.find_next_inner(sets, line, pos, cache, anchors, active)
351 +
            else {
356 352
                continue;
357 353
            };
358 354
            found = match found {
359 355
                Some(current) if current.start <= candidate.start => Some(current),
360 356
                _ => Some(candidate),
364 360
    }
365 361
366 362
    /// Finds the next local pattern match at or after `pos`.
367 363
    fn find_next_local(
368 364
        &self,
369 -
        sets: &[PatternSet],
370 365
        line: &str,
371 366
        pos: usize,
372 367
        cache: &mut EndRegexCache,
368 +
        anchors: AnchorState,
373 369
    ) -> Option<Match> {
374 370
        let regexes = self.regexes.as_ref()?;
375 371
        let (entry, captures) = regexes.captures_with_options(
376 372
            line,
377 373
            pos,
378 374
            line.len(),
379 375
            RegSetLead::Position,
380 -
            SearchOptions::SEARCH_OPTION_NONE,
376 +
            anchors.search_options(pos),
381 377
        )?;
382 378
        let pattern = self.patterns.get(entry)?;
383 379
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
384 380
385 -
        pattern.match_result(regex_match, sets, line, cache)
381 +
        pattern.match_result(regex_match, line, cache)
386 382
    }
387 383
}
388 384
389 385
impl PatternCompiler<'_> {
390 386
    /// Creates a compiler for a raw grammar.
613 609
        };
614 610
        end.resume(dynamic_end, cache)
615 611
    }
616 612
617 613
    /// Returns true when this begin/while rule continues on `line`.
618 -
    pub(super) fn continues_while(&self, line: &str) -> bool {
614 +
    pub(super) fn continues_while(&self, line: &str, anchors: AnchorState) -> bool {
619 615
        match &self.body {
620 616
            PatternBody::BeginWhile { while_regex, .. } => {
621 -
                RegexMatch::find(while_regex, line, 0, false)
617 +
                RegexMatch::find(while_regex, line, 0, false, anchors)
622 618
                    .is_some_and(|matched| matched.start == 0)
623 619
            }
624 620
            PatternBody::Match { .. } | PatternBody::BeginEnd { .. } => true,
625 621
        }
626 622
    }
627 623
624 +
    /// Finds this rule's end match at or after `pos`.
625 +
    pub(super) fn find_end_match(
626 +
        &self,
627 +
        end: &EndRegex<'_>,
628 +
        line: &str,
629 +
        mut pos: usize,
630 +
        anchors: AnchorState,
631 +
    ) -> Option<RegexMatch> {
632 +
        loop {
633 +
            let matched = RegexMatch::find_end(
634 +
                end.regex(),
635 +
                line,
636 +
                pos,
637 +
                !self.captures.end.is_empty(),
638 +
                anchors,
639 +
            )?;
640 +
            if matches!(end.source(), "\"" | "'") && is_escaped_at(line, matched.start) {
641 +
                pos = matched.next_pos(line);
642 +
                continue;
643 +
            }
644 +
            return Some(matched);
645 +
        }
646 +
    }
647 +
628 648
    /// Adds capture-group spans plus the pattern's own scope span for one regex match.
629 649
    pub(super) fn append_match_spans(
630 650
        &self,
631 651
        matched: &RegexMatch,
632 652
        captures: &Captures,
667 687
668 688
    /// Builds a [`Match`] for one regex hit, dispatching by body kind.
669 689
    fn match_result(
670 690
        &self,
671 691
        regex_match: RegexMatch,
672 -
        sets: &[PatternSet],
673 692
        line: &str,
674 693
        cache: &mut EndRegexCache,
675 694
    ) -> Option<Match> {
676 695
        match &self.body {
677 696
            PatternBody::Match { .. } => Some(self.simple_match(regex_match)),
678 -
            PatternBody::BeginEnd { end, .. } => {
679 -
                self.begin_match(end, regex_match, sets, line, cache)
680 -
            }
697 +
            PatternBody::BeginEnd { end, .. } => self.begin_match(end, regex_match, line, cache),
681 698
            PatternBody::BeginWhile { .. } => Some(self.begin_while_match(regex_match, line)),
682 699
        }
683 700
    }
684 701
685 702
    /// Builds a match for a single-line match rule.
697 714
    /// Builds a match for a begin/end rule, eagerly closing on the same line if possible.
698 715
    fn begin_match(
699 716
        &self,
700 717
        end_pattern: &EndPattern,
701 718
        begin: RegexMatch,
702 -
        sets: &[PatternSet],
703 719
        line: &str,
704 720
        cache: &mut EndRegexCache,
705 721
    ) -> Option<Match> {
706 722
        let end_regex = end_pattern.resolve_for_begin(&begin, line, cache)?;
707 723
        let dynamic_end = end_regex.dynamic_source();
708 -
        let same_line_end = self.find_same_line_end(&end_regex, sets, line, begin.end, cache);
709 -
710 724
        let mut spans = Vec::new();
711 725
        self.append_match_spans(&begin, &self.captures.begin, &mut spans);
712 726
713 -
        let (end_byte, open_rule) = if let Some(close) = &same_line_end {
714 -
            Scope::push_content_visible(
715 -
                &self.scope,
716 -
                &self.content_scope,
717 -
                &mut spans,
718 -
                begin.end,
719 -
                close.matched.start,
720 -
            );
721 -
            spans.extend(close.spans.iter().copied());
722 -
            self.append_match_spans(&close.matched, &self.captures.end, &mut spans);
723 -
            (close.matched.end, None)
724 -
        } else {
725 -
            // The begin region is already covered by `append_match_spans` above;
726 -
            // the rest of the line is emitted by the tokenizer once this rule
727 -
            // is pushed and the next event is handled inside it.
728 -
            (
729 -
                begin.end,
730 -
                Some(OpenRule {
731 -
                    rule_id: self.id,
732 -
                    dynamic_end,
733 -
                }),
734 -
            )
735 -
        };
736 -
737 727
        Some(Match {
738 728
            start: begin.start,
739 -
            end: end_byte,
729 +
            end: begin.end,
740 730
            spans,
741 -
            open_rule,
731 +
            open_rule: Some(OpenRule {
732 +
                rule_id: self.id,
733 +
                dynamic_end,
734 +
            }),
742 735
        })
743 736
    }
744 737
745 738
    /// Builds a match for a begin/while rule.
746 739
    fn begin_while_match(&self, begin: RegexMatch, line: &str) -> Match {
759 752
                dynamic_end: None,
760 753
            }),
761 754
        }
762 755
    }
763 756
764 -
    /// Finds the first end match on the line, scanning past nested matches that occur before it.
765 -
    fn find_same_line_end(
766 -
        &self,
767 -
        end: &EndRegex<'_>,
768 -
        sets: &[PatternSet],
769 -
        line: &str,
770 -
        mut pos: usize,
771 -
        cache: &mut EndRegexCache,
772 -
    ) -> Option<EndOnLine> {
773 -
        let end_regex = end.regex();
774 -
        let end_source = end.source();
775 -
        let capture_end = !self.captures.end.is_empty();
776 -
        let mut spans = Vec::new();
777 -
        loop {
778 -
            let matched = RegexMatch::find_end(end_regex, line, pos, capture_end)?;
779 -
            // Skip escaped quote-character ends -- only `"` and `'` are handled.
780 -
            // Other end-pattern shapes are matched literally without escape awareness.
781 -
            if matches!(end_source, "\"" | "'") && is_escaped_at(line, matched.start) {
782 -
                pos = matched.next_pos(line);
783 -
                continue;
784 -
            }
785 -
            let nested_match = self.nested.find_next(sets, line, pos, cache);
786 -
            let Some(nested_match) = nested_match else {
787 -
                return Some(EndOnLine { matched, spans });
788 -
            };
789 -
            if nested_match.start >= matched.start {
790 -
                return Some(EndOnLine { matched, spans });
791 -
            }
792 -
            pos = nested_match.next_pos(line);
793 -
            spans.extend(nested_match.spans);
794 -
        }
795 -
    }
796 757
}
797 758
798 759
/// Whether the byte at `pos` is preceded by an odd number of backslashes.
799 760
fn is_escaped_at(line: &str, pos: usize) -> bool {
800 761
    if pos > line.len() || !line.is_char_boundary(pos) {
826 787
827 788
    /// Returns the open rule pushed onto the parser stack by this match, if any.
828 789
    pub(super) fn open_rule(&self) -> Option<OpenRule> {
829 790
        self.open_rule.clone()
830 791
    }
792 +
793 +
    /// Returns the byte position where this match ended.
794 +
    pub(super) fn end(&self) -> usize {
795 +
        self.end
796 +
    }
831 797
}
832 798
833 799
impl RegexMatch {
834 800
    /// Finds one regex match starting at `pos`.
835 -
    pub(super) fn find(regex: &Regex, line: &str, pos: usize, keep_captures: bool) -> Option<Self> {
801 +
    pub(super) fn find(
802 +
        regex: &Regex,
803 +
        line: &str,
804 +
        pos: usize,
805 +
        keep_captures: bool,
806 +
        anchors: AnchorState,
807 +
    ) -> Option<Self> {
836 808
        if pos > line.len() || !line.is_char_boundary(pos) {
837 809
            return None;
838 810
        }
839 811
        let mut region = Region::new();
840 812
        let _ = regex.search_with_options(
841 813
            line,
842 814
            pos,
843 815
            line.len(),
844 -
            SearchOptions::SEARCH_OPTION_NONE,
816 +
            anchors.search_options(pos),
845 817
            Some(&mut region),
846 818
        )?;
847 819
        let (start, end) = region.pos(0)?;
848 820
        if start > end || end > line.len() {
849 821
            return None;
870 842
    pub(super) fn find_end(
871 843
        regex: &Regex,
872 844
        line: &str,
873 845
        pos: usize,
874 846
        keep_captures: bool,
847 +
        anchors: AnchorState,
875 848
    ) -> Option<Self> {
876 -
        if let Some(matched) = Self::find(regex, line, pos, keep_captures) {
849 +
        if let Some(matched) = Self::find(regex, line, pos, keep_captures, anchors) {
877 850
            return Some(matched);
878 851
        }
879 852
        let search = pos.checked_sub(1)?;
880 -
        let matched = Self::find(regex, line, search, keep_captures)?;
853 +
        let matched = Self::find(regex, line, search, keep_captures, anchors)?;
881 854
882 855
        (matched.start >= pos).then_some(matched)
883 856
    }
884 857
885 858
    /// Builds a match record from Oniguruma captures.
970 943
    use super::*;
971 944
972 945
    #[test]
973 946
    fn invalid_regex_offsets_are_ignored() {
974 947
        let regex = Regex::new("\"").unwrap();
948 +
        let anchors = AnchorState::new(true);
975 949
976 -
        assert!(RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true).is_none());
977 -
        assert!(RegexMatch::find(&regex, "รฉ", 1, true).is_none());
950 +
        assert!(
951 +
            RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true, anchors)
952 +
                .is_none()
953 +
        );
954 +
        assert!(RegexMatch::find(&regex, "รฉ", 1, true, anchors).is_none());
978 955
    }
979 956
980 957
    #[test]
981 958
    fn regex_match_offsets_are_absolute_after_full_line_search() {
982 959
        let regex = Regex::new("(bar)").unwrap();
983 -
        let matched = RegexMatch::find(&regex, "foobar", 3, true).unwrap();
960 +
        let matched = RegexMatch::find(&regex, "foobar", 3, true, AnchorState::new(true)).unwrap();
984 961
985 962
        assert_eq!(matched.start, 3);
986 963
        assert_eq!(matched.end, 6);
987 964
        assert_eq!(matched.captures[1], Some((3, 6)));
988 965
    }
crates/highlight/src/grammar/tokenize.rs +60 -23
53 53
54 54
        if matches!(self.grammar.kind, GrammarKind::Json) {
55 55
            json::tokenize_line_into(line, spans);
56 56
            return;
57 57
        }
58 -
        let line = trim_line_end(line);
58 +
        let visible = trim_line_end(line);
59 +
        let visible_len = visible.len();
60 +
        let mut line = String::with_capacity(visible_len + 1);
61 +
        line.push_str(visible);
62 +
        line.push('\n');
59 63
        let mut pos = 0;
64 +
        let mut anchors = AnchorState::new(state.first_line);
60 65
61 66
        while pos < line.len() {
62 -
            pos = self.advance(state, line, pos, spans);
67 +
            pos = self.advance(state, &line, pos, spans, &mut anchors);
63 68
        }
64 -
        self.close_empty_rules_at_end(state, line, spans);
69 +
        self.close_empty_rules_at_end(state, &line, spans, &mut anchors);
70 +
        clamp_spans(spans, visible_len);
71 +
        state.first_line = false;
65 72
    }
66 73
67 74
    /// Performs one tokenization step and returns the next byte position.
68 75
    fn advance(
69 76
        &mut self,
70 77
        state: &mut LineState,
71 78
        line: &str,
72 79
        pos: usize,
73 80
        spans: &mut Vec<ScopeSpan>,
81 +
        anchors: &mut AnchorState,
74 82
    ) -> usize {
75 83
        if let Some(open) = state.stack.last().cloned() {
76 -
            self.advance_inside_open_rule(state, line, pos, spans, open)
84 +
            self.advance_inside_open_rule(state, line, pos, spans, open, anchors)
77 85
        } else {
78 -
            self.advance_at_root(state, line, pos, spans)
86 +
            self.advance_at_root(state, line, pos, spans, anchors)
79 87
        }
80 88
    }
81 89
82 90
    /// Advances past one root-level pattern match, or to end of line if there is none.
83 91
    fn advance_at_root(
84 92
        &mut self,
85 93
        state: &mut LineState,
86 94
        line: &str,
87 95
        pos: usize,
88 96
        spans: &mut Vec<ScopeSpan>,
97 +
        anchors: &mut AnchorState,
89 98
    ) -> usize {
90 -
        let Some(found) =
91 -
            self.grammar
92 -
                .patterns
93 -
                .find_next(&self.grammar.pattern_sets, line, pos, &mut self.cache)
99 +
        let Some(found) = self.grammar.patterns.find_next(
100 +
            &self.grammar.pattern_sets,
101 +
            line,
102 +
            pos,
103 +
            &mut self.cache,
104 +
            *anchors,
105 +
        )
94 106
        else {
95 107
            return line.len();
96 108
        };
97 109
        let next_pos = found.next_pos_after_open(line);
98 110
        let opened = found.open_rule();
111 +
        let anchor = found.end();
99 112
        spans.extend(found.spans);
100 113
101 114
        if let Some(opened) = opened {
102 115
            state.stack.push(opened);
116 +
            anchors.set_begin_position(anchor);
103 117
        }
104 118
        next_pos
105 119
    }
106 120
107 121
    /// Advances past one event inside the currently open begin/end rule.
110 124
        state: &mut LineState,
111 125
        line: &str,
112 126
        pos: usize,
113 127
        spans: &mut Vec<ScopeSpan>,
114 128
        open: OpenRule,
129 +
        anchors: &mut AnchorState,
115 130
    ) -> usize {
116 131
        let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) else {
117 132
            state.stack.pop();
118 133
            return pos;
119 134
        };
120 -
        if pos == 0 && !pattern.continues_while(line) {
135 +
        if pos == 0 && !pattern.continues_while(line, *anchors) {
121 136
            state.stack.pop();
122 137
            return pos;
123 138
        }
124 139
        let Some(end) = pattern.resume_end(open.dynamic_end.as_deref(), &mut self.cache) else {
125 -
            return self.advance_inside_while_rule(state, line, pos, spans, pattern);
140 +
            return self.advance_inside_while_rule(state, line, pos, spans, pattern, anchors);
126 141
        };
127 -
        self.next_event_inside(pattern, &end, line, pos)
128 -
            .apply(state, line, pos, spans, pattern)
142 +
        self.next_event_inside(pattern, &end, line, pos, *anchors)
143 +
            .apply(state, line, pos, spans, pattern, anchors)
129 144
    }
130 145
131 146
    /// Advances past one nested event inside an open begin/while rule.
132 147
    fn advance_inside_while_rule(
133 148
        &mut self,
134 149
        state: &mut LineState,
135 150
        line: &str,
136 151
        pos: usize,
137 152
        spans: &mut Vec<ScopeSpan>,
138 153
        pattern: &Pattern,
154 +
        anchors: &mut AnchorState,
139 155
    ) -> usize {
140 -
        let nested =
141 -
            pattern
142 -
                .nested
143 -
                .find_next(&self.grammar.pattern_sets, line, pos, &mut self.cache);
156 +
        let nested = pattern.nested.find_next(
157 +
            &self.grammar.pattern_sets,
158 +
            line,
159 +
            pos,
160 +
            &mut self.cache,
161 +
            *anchors,
162 +
        );
144 163
        let Some(nested) = nested else {
145 164
            Scope::push_content_visible(
146 165
                &pattern.scope,
147 166
                &pattern.content_scope,
148 167
                spans,
151 170
            );
152 171
            return line.len();
153 172
        };
154 173
        let next_pos = nested.next_pos_after_open(line);
155 174
        let opened = nested.open_rule();
175 +
        let anchor = nested.end();
156 176
157 177
        Scope::push_content_visible(
158 178
            &pattern.scope,
159 179
            &pattern.content_scope,
160 180
            spans,
163 183
        );
164 184
        spans.extend(nested.spans);
165 185
166 186
        if let Some(opened) = opened {
167 187
            state.stack.push(opened);
188 +
            anchors.set_begin_position(anchor);
168 189
        }
169 190
        next_pos
170 191
    }
171 192
172 193
    /// Closes zero-width end rules that match at the end of a line.
173 194
    fn close_empty_rules_at_end(
174 195
        &mut self,
175 196
        state: &mut LineState,
176 197
        line: &str,
177 198
        spans: &mut Vec<ScopeSpan>,
199 +
        anchors: &mut AnchorState,
178 200
    ) {
179 201
        while !state.is_empty() {
180 202
            let depth = state.depth();
181 -
            let pos = self.advance(state, line, line.len(), spans);
203 +
            let pos = self.advance(state, line, line.len(), spans, anchors);
182 204
            if pos != line.len() || state.depth() >= depth {
183 205
                break;
184 206
            }
185 207
        }
186 208
    }
190 212
        &mut self,
191 213
        pattern: &Pattern,
192 214
        end: &EndRegex<'_>,
193 215
        line: &str,
194 216
        pos: usize,
217 +
        anchors: AnchorState,
195 218
    ) -> InsideEvent {
196 -
        let nested =
197 -
            pattern
198 -
                .nested
199 -
                .find_next(&self.grammar.pattern_sets, line, pos, &mut self.cache);
200 -
        let close = RegexMatch::find_end(end.regex(), line, pos, !pattern.captures.end.is_empty());
219 +
        let nested = pattern.nested.find_next(
220 +
            &self.grammar.pattern_sets,
221 +
            line,
222 +
            pos,
223 +
            &mut self.cache,
224 +
            anchors,
225 +
        );
226 +
        let close = pattern.find_end_match(end, line, pos, anchors);
201 227
202 228
        match (nested, close) {
203 229
            (Some(nested), Some(close)) if nested.start < close.start => {
204 230
                InsideEvent::Nested(nested)
205 231
            }
214 240
    pub(super) fn end_regex_cache_len(&self) -> usize {
215 241
        self.cache.len()
216 242
    }
217 243
}
218 244
245 +
/// Trims token spans back to the caller-visible line range.
246 +
fn clamp_spans(spans: &mut Vec<ScopeSpan>, visible_len: usize) {
247 +
    for span in spans.iter_mut() {
248 +
        span.end = span.end.min(visible_len);
249 +
    }
250 +
    spans.retain(|span| span.start < span.end);
251 +
}
252 +
219 253
/// One event found inside an open begin/end rule.
220 254
enum InsideEvent {
221 255
    /// Nested pattern matched before the end pattern.
222 256
    Nested(Match),
223 257
    /// End pattern closed the open rule.
233 267
        state: &mut LineState,
234 268
        line: &str,
235 269
        pos: usize,
236 270
        spans: &mut Vec<ScopeSpan>,
237 271
        pattern: &Pattern,
272 +
        anchors: &mut AnchorState,
238 273
    ) -> usize {
239 274
        match self {
240 275
            Self::Close(close) => {
241 276
                Scope::push_content_visible(
242 277
                    &pattern.scope,
249 284
                state.stack.pop();
250 285
                close.next_pos(line)
251 286
            }
252 287
            Self::Nested(nested) => {
253 288
                let next_pos = nested.next_pos_after_open(line);
289 +
                let anchor = nested.end();
254 290
255 291
                Scope::push_content_visible(
256 292
                    &pattern.scope,
257 293
                    &pattern.content_scope,
258 294
                    spans,
263 299
264 300
                spans.extend(nested.spans);
265 301
266 302
                if let Some(opened) = opened {
267 303
                    state.stack.push(opened);
304 +
                    anchors.set_begin_position(anchor);
268 305
                }
269 306
                next_pos
270 307
            }
271 308
            Self::None => {
272 309
                Scope::push_content_visible(
crates/highlight/src/tests.rs +70 -0
332 332
333 333
    assert!(scopes.contains(&"meta.embedded.block.test"));
334 334
    assert!(scopes.contains(&"source.embedded.test"));
335 335
}
336 336
337 +
#[test]
338 +
fn begin_string_anchor_only_matches_first_line() {
339 +
    let grammar = Grammar::from_str(
340 +
        r#"{
341 +
            "name":"Test",
342 +
            "scopeName":"source.test",
343 +
            "patterns":[
344 +
                {"match":"\\Afoo","name":"keyword.first-line.test"}
345 +
            ],
346 +
            "repository":{}
347 +
        }"#,
348 +
    )
349 +
    .unwrap();
350 +
    let mut state = LineState::default();
351 +
352 +
    let first = grammar.tokenize_line(&mut state, "foo");
353 +
    let second = grammar.tokenize_line(&mut state, "foo");
354 +
355 +
    assert!(scope_names(&grammar, &first).contains(&"keyword.first-line.test"));
356 +
    assert!(!scope_names(&grammar, &second).contains(&"keyword.first-line.test"));
357 +
}
358 +
359 +
#[test]
360 +
fn begin_position_anchor_only_matches_rule_continuation() {
361 +
    let grammar = Grammar::from_str(
362 +
        r#"{
363 +
            "name":"Test",
364 +
            "scopeName":"source.test",
365 +
            "patterns":[
366 +
                {
367 +
                    "begin":"a",
368 +
                    "end":"z",
369 +
                    "name":"meta.anchor.test",
370 +
                    "patterns":[{"match":"\\Gb","name":"keyword.anchor.test"}]
371 +
                }
372 +
            ],
373 +
            "repository":{}
374 +
        }"#,
375 +
    )
376 +
    .unwrap();
377 +
378 +
    let adjacent = grammar.tokenize_line(&mut LineState::default(), "abz");
379 +
    let separated = grammar.tokenize_line(&mut LineState::default(), "acbz");
380 +
381 +
    assert!(scope_names(&grammar, &adjacent).contains(&"keyword.anchor.test"));
382 +
    assert!(!scope_names(&grammar, &separated).contains(&"keyword.anchor.test"));
383 +
}
384 +
385 +
#[test]
386 +
fn tokenizer_exposes_textmate_line_terminator_to_patterns() {
387 +
    let grammar = Grammar::from_str(
388 +
        r#"{
389 +
            "name":"Test",
390 +
            "scopeName":"source.test",
391 +
            "patterns":[
392 +
                {"begin":"x","end":"\\n","name":"meta.line.test"}
393 +
            ],
394 +
            "repository":{}
395 +
        }"#,
396 +
    )
397 +
    .unwrap();
398 +
    let mut state = LineState::default();
399 +
400 +
    let spans = grammar.tokenize_line(&mut state, "x");
401 +
402 +
    assert!(state.is_empty());
403 +
    assert!(scope_names(&grammar, &spans).contains(&"meta.line.test"));
404 +
    assert!(spans.iter().all(|span| span.end <= 1));
405 +
}
406 +
337 407
#[test]
338 408
fn capture_scope_paths_emit_each_scope() {
339 409
    let grammar = Grammar::from_str(
340 410
        r#"{
341 411
            "name":"Test",