highlight: Fix Markdown reference links

100003712416c91dc62f39576ec6a6bc9363e03d
Compile TextMate regexes with numbered captures even when grammars use
named groups, and keep zero-width begin/while matches from consuming
the first inline byte.

This lets Markdown reference links such as `[Title][link]` reach the
existing link-ref rule and emit title and reference scopes.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 565b66fa
crates/highlight/src/grammar.rs +10 -2
7 7
8 8
use std::collections::{BTreeMap, HashSet};
9 9
use std::path::Path;
10 10
use std::str::FromStr;
11 11
12 -
use onig::{RegSet, RegSetLead, Regex, Region, SearchOptions};
12 +
use onig::{RegSet, RegSetLead, Regex, RegexOptions, Region, SearchOptions, Syntax};
13 13
14 14
use crate::json;
15 15
use crate::raw::{RawCapture, RawGrammar, RawPattern, head_patterns};
16 16
use crate::util::{key, next_char_boundary, path_keys, trim_line_end};
17 17
use crate::{Error, MAX_INCLUDE_DEPTH};
26 26
use pattern::{Injection, OpenRule, PatternCompiler, PatternSet, PatternSetId, RuleLocation};
27 27
28 28
/// Display name for the built-in plain-text fallback grammar.
29 29
pub(crate) const PLAIN_TEXT_NAME: &str = "Plain Text";
30 30
31 +
/// Regex options used for TextMate pattern compilation.
32 +
pub(super) const TEXTMATE_REGEX_OPTIONS: RegexOptions = RegexOptions::REGEX_OPTION_CAPTURE_GROUP;
33 +
34 +
/// Compiles a TextMate regex with capture semantics expected by grammar captures.
35 +
pub(super) fn regex(pattern: &str) -> Result<Regex, onig::Error> {
36 +
    Regex::with_options(pattern, TEXTMATE_REGEX_OPTIONS, Syntax::default())
37 +
}
38 +
31 39
/// Interned scope identifier.
32 40
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33 41
pub struct ScopeId(
34 42
    /// Index into a grammar's interned scope-name table.
35 43
    usize,
178 186
    /// Compiles a raw grammar with raw cross-grammar include dependencies.
179 187
    pub fn compile_with(raw: &RawGrammar, dependencies: &[RawGrammar]) -> Result<Self, Error> {
180 188
        let compiled = PatternCompiler::new(raw, dependencies).compile()?;
181 189
        let head_match = head_patterns(raw.first_line_match.as_ref())
182 190
            .iter()
183 -
            .map(|pattern| Regex::new(pattern).map_err(|_| Error::InvalidRegex(pattern.clone())))
191 +
            .map(|pattern| regex(pattern).map_err(|_| Error::InvalidRegex(pattern.clone())))
184 192
            .collect::<Result<Vec<_>, _>>()?;
185 193
186 194
        Ok(Self {
187 195
            name: raw.display_name.clone().unwrap_or_else(|| raw.name.clone()),
188 196
            scope_name: raw.scope_name.clone(),
crates/highlight/src/grammar/end.rs +3 -2
9 9
use std::sync::Arc;
10 10
11 11
use onig::Regex;
12 12
13 13
use super::pattern::RegexMatch;
14 +
use super::regex;
14 15
15 16
/// Cache of regexes for resolved dynamic end patterns.
16 17
pub(super) type EndRegexCache = BTreeMap<String, Arc<Regex>>;
17 18
18 19
/// End-pattern definition stored on a compiled begin/end rule.
61 62
        if has_numeric_backrefs(source) {
62 63
            return Some(Self::Dynamic {
63 64
                source: source.to_owned(),
64 65
            });
65 66
        }
66 -
        let regex = Regex::new(source).ok()?;
67 +
        let regex = regex(source).ok()?;
67 68
68 69
        Some(Self::Static {
69 70
            source: source.to_owned(),
70 71
            regex,
71 72
        })
147 148
/// Returns the cached regex for `source`, compiling and inserting it on first use.
148 149
fn lookup_or_compile(cache: &mut EndRegexCache, source: &str) -> Option<Arc<Regex>> {
149 150
    if let Some(regex) = cache.get(source) {
150 151
        return Some(Arc::clone(regex));
151 152
    }
152 -
    let regex = Arc::new(Regex::new(source).ok()?);
153 +
    let regex = Arc::new(regex(source).ok()?);
153 154
    cache.insert(source.to_owned(), Arc::clone(&regex));
154 155
    Some(regex)
155 156
}
156 157
157 158
/// Returns true when `source` contains an unescaped numeric backreference.
crates/highlight/src/grammar/pattern.rs +6 -7
504 504
505 505
    /// Builds a pattern set and its combined regex search set.
506 506
    fn new(patterns: Vec<Pattern>, includes: Vec<PatternSetId>) -> Self {
507 507
        let sources: Vec<&str> = patterns.iter().map(Pattern::search_source).collect();
508 508
        let regexes = (!sources.is_empty())
509 -
            .then(|| RegSet::new(&sources).ok())
509 +
            .then(|| RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS).ok())
510 510
            .flatten();
511 511
512 512
        Self {
513 513
            patterns,
514 514
            includes,
651 651
            &pattern.begin,
652 652
            &pattern.end,
653 653
            &pattern.while_rule,
654 654
        ) {
655 655
            (Some(source), _, _, _) => {
656 -
                if Regex::new(source).is_err() {
656 +
                if regex(source).is_err() {
657 657
                    return Ok(());
658 658
                }
659 659
                PatternBody::Match {
660 660
                    source: source.clone(),
661 661
                }
662 662
            }
663 663
            (None, Some(begin), Some(end), _) => {
664 -
                if Regex::new(begin).is_err() {
664 +
                if regex(begin).is_err() {
665 665
                    return Ok(());
666 666
                }
667 667
                let Some(end) = EndPattern::compile(end) else {
668 668
                    return Ok(());
669 669
                };
672 672
                    end,
673 673
                    apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()),
674 674
                }
675 675
            }
676 676
            (None, Some(begin), None, Some(while_rule)) => {
677 -
                if Regex::new(begin).is_err() {
677 +
                if regex(begin).is_err() {
678 678
                    return Ok(());
679 679
                }
680 680
                let Some(while_rule) = EndPattern::compile(while_rule) else {
681 681
                    return Ok(());
682 682
                };
1136 1136
            return self.simple_match(begin, search);
1137 1137
        };
1138 1138
        let while_regex = while_rule.resolve_for_begin(&begin, search.line, search.cache);
1139 1139
        let dynamic_rule = while_regex.and_then(|while_regex| while_regex.dynamic_source());
1140 1140
        let mut spans = Vec::new();
1141 -
        let end = begin.next_pos(search.line);
1142 1141
1143 1142
        let mut context = search.span_context();
1144 1143
        self.append_match_spans(&begin, &self.captures.begin, &mut spans, &mut context);
1145 -
        self.scope.push_visible(&mut spans, begin.start, end);
1144 +
        self.scope.push_visible(&mut spans, begin.start, begin.end);
1146 1145
1147 1146
        Match {
1148 1147
            start: begin.start,
1149 -
            end,
1148 +
            end: begin.end,
1150 1149
            spans,
1151 1150
            open_rule: Some(OpenRule {
1152 1151
                rule_id: self.id,
1153 1152
                dynamic_rule,
1154 1153
                anchor_position: search.anchors.begin_position(),
crates/highlight/tests/syntaxes.rs +19 -0
159 159
    assert!(key_scopes.contains(&"punctuation.separator.key-value.mapping.yaml"));
160 160
    assert!(scalar_scopes.contains(&"string.quoted.double.yaml"));
161 161
    assert!(comment_scopes.contains(&"comment.line.number-sign.yaml"));
162 162
}
163 163
164 +
#[test]
165 +
fn markdown_highlights_reference_links() {
166 +
    let grammar = Grammar::from_str(syntaxes::MARKDOWN).unwrap();
167 +
    let scopes = tokenize_scopes(&grammar, "[Earlier this week][post]");
168 +
169 +
    assert!(
170 +
        scopes.contains(&"meta.link.reference.markdown"),
171 +
        "{scopes:?}"
172 +
    );
173 +
    assert!(
174 +
        scopes.contains(&"string.other.link.title.markdown"),
175 +
        "{scopes:?}"
176 +
    );
177 +
    assert!(
178 +
        scopes.contains(&"constant.other.reference.link.markdown"),
179 +
        "{scopes:?}"
180 +
    );
181 +
}
182 +
164 183
/// Tokenizes `line` and returns its scope names.
165 184
fn tokenize_scopes<'a>(grammar: &'a Grammar, line: &str) -> Vec<&'a str> {
166 185
    let mut state = LineState::default();
167 186
    let mut tokenizer = LineTokenizer::new(grammar);
168 187
    let spans = tokenizer.tokenize_line(&mut state, line);