Skip to main content

gitpoulpi_hosting/
xrefs.rs

1//! Cross references in issue and pull-request text (plan `conversations`, 4c).
2//!
3//! What a token means depends on the host the text came from: `#7` is an
4//! issue on GitHub, a work item on Azure DevOps, a revision-less number on
5//! Redmine, nothing on Jira. [`scan`] finds every token the host's grammar
6//! gives a meaning to and says where it points. Pure; the TUI paints the
7//! spans, the CLI prints them.
8//!
9//! The repository's own linked sources are matched first, through
10//! [`refs::scan_message`], so a Jira key resolves inside a GitHub PR comment
11//! and opens in the app. Whatever the host grammar adds on top points at the
12//! web page.
13//!
14//! Never matched: anything in code spans or fenced blocks, inside Markdown
15//! link constructs (they already have a target), e-mail addresses, `C#1`,
16//! `UTF-8` / `SHA-256` / `ISO-8601`, URL fragments, words that merely look
17//! like a hash (`decade`, `1234567`).
18//!
19//! Offsets are char offsets into the scanned text, `[start, end)`.
20
21use gitpoulpi_config::ApiFamily;
22
23use crate::refs::{self, RefContext, RefKind};
24use crate::spec::spec_for;
25
26/// Where the text came from and what the repository links to.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28pub struct XrefContext {
29    /// The host (flavor) of the text; `None` = only the repository's links
30    /// and plain URLs resolve.
31    pub family: Option<ApiFamily>,
32    /// `https://host` of that host (instance root; never the API root).
33    pub web_base: String,
34    /// The project path on that host (`owner/repo`, `group/proj`).
35    pub project: String,
36    /// The repository's linked ISSUES and PULLS sources.
37    pub repo_links: RefContext,
38    /// Local notes: names of the Markdown notes (for `[[wikilinks]]`).
39    pub local_notes: Vec<String>,
40}
41
42/// An item the app can open itself.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct ItemTarget {
45    pub family: ApiFamily,
46    pub web_base: String,
47    pub project: String,
48    pub kind: RefKind,
49    /// 0 when the item has no number (a note, a Trello card by id).
50    pub number: u64,
51    /// The canonical key: `#7`, `!4`, `ABC-12`, the note name.
52    pub key: String,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ChipKind {
57    Label,
58    Milestone,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum XrefTarget {
63    /// An item of the repository's linked sources, or a local note.
64    InApp(ItemTarget),
65    /// A page on the host: open in the browser (after the link confirm).
66    Web(String),
67    /// `@login`; the profile address when the host has one.
68    Mention { login: String, url: Option<String> },
69    /// A commit id; whether it exists in the repository is the caller's call.
70    Commit { sha: String, url: Option<String> },
71    /// A label or milestone shown as a chip, not a link.
72    Chip { kind: ChipKind, name: String },
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Xref {
77    pub start: usize,
78    pub end: usize,
79    /// The text as written.
80    pub text: String,
81    pub target: XrefTarget,
82}
83
84const MAX_DIGITS: usize = 9;
85
86fn is_word(c: char) -> bool {
87    c.is_alphanumeric() || c == '_'
88}
89
90fn is_hex(c: char) -> bool {
91    c.is_ascii_hexdigit()
92}
93
94/// Every reference in `text`, in order, without overlaps.
95pub fn scan(text: &str, ctx: &XrefContext) -> Vec<Xref> {
96    let chars: Vec<char> = text.chars().collect();
97    let mut s = Scanner::new(&chars, ctx);
98    s.run();
99    s.finish()
100}
101
102struct Scanner<'a> {
103    chars: &'a [char],
104    /// `chars` with everything no token may match in blanked out.
105    masked: Vec<char>,
106    ctx: &'a XrefContext,
107    taken: Vec<bool>,
108    found: Vec<Xref>,
109}
110
111impl<'a> Scanner<'a> {
112    fn new(chars: &'a [char], ctx: &'a XrefContext) -> Self {
113        Self {
114            chars,
115            masked: chars.to_vec(),
116            ctx,
117            taken: vec![false; chars.len()],
118            found: Vec::new(),
119        }
120    }
121
122    fn mask(&mut self, a: usize, b: usize) {
123        for c in &mut self.masked[a..b.min(self.chars.len())] {
124            if *c != '\n' {
125                *c = ' ';
126            }
127        }
128    }
129
130    fn add(&mut self, start: usize, end: usize, target: XrefTarget) -> bool {
131        if start >= end || self.taken[start..end].iter().any(|t| *t) {
132            return false;
133        }
134        for t in &mut self.taken[start..end] {
135            *t = true;
136        }
137        self.found.push(Xref {
138            start,
139            end,
140            text: self.chars[start..end].iter().collect(),
141            target,
142        });
143        true
144    }
145
146    fn finish(mut self) -> Vec<Xref> {
147        self.found.sort_by_key(|x| x.start);
148        self.found
149    }
150
151    fn run(&mut self) {
152        for (a, b) in code_ranges(self.chars) {
153            self.mask(a, b);
154        }
155        if self.ctx.family == Some(ApiFamily::LocalMarkdown) || !self.ctx.local_notes.is_empty() {
156            self.notes();
157        }
158        for (a, b) in link_ranges(&self.masked) {
159            self.mask(a, b);
160        }
161        self.urls();
162        self.repo_links();
163        self.host_tokens();
164    }
165
166    // -- local notes -------------------------------------------------------
167
168    fn note_known(&self, name: &str) -> Option<String> {
169        if self.ctx.local_notes.is_empty() {
170            return Some(name.to_string());
171        }
172        let want = name.to_lowercase();
173        self.ctx
174            .local_notes
175            .iter()
176            .find(|n| {
177                let n = n.to_lowercase();
178                n == want || n.rsplit('/').next() == Some(want.as_str())
179            })
180            .cloned()
181    }
182
183    fn note_target(&self, name: String) -> XrefTarget {
184        XrefTarget::InApp(ItemTarget {
185            family: ApiFamily::LocalMarkdown,
186            web_base: String::new(),
187            project: self.ctx.project.clone(),
188            kind: RefKind::Issue,
189            number: 0,
190            key: name,
191        })
192    }
193
194    fn notes(&mut self) {
195        let c = self.masked.clone();
196        let n = c.len();
197        let mut i = 0;
198        while i < n {
199            // [[note]] and [[note|alias]]
200            if c[i] == '[' && c.get(i + 1) == Some(&'[') {
201                if let Some(close) = find_pair(&c, i + 2, "]]") {
202                    let inner: String = c[i + 2..close].iter().collect();
203                    if !inner.contains(['[', ']', '\n']) {
204                        let name = inner.split('|').next().unwrap_or("");
205                        let name = name.split(['#', '^']).next().unwrap_or("").trim();
206                        if !name.is_empty() {
207                            if let Some(known) = self.note_known(name) {
208                                let target = self.note_target(known);
209                                if self.add(i, close + 2, target) {
210                                    self.mask(i, close + 2);
211                                }
212                            }
213                        }
214                        i = close + 2;
215                        continue;
216                    }
217                }
218            }
219            // [text](relative/path.md#frag)
220            if c[i] == '[' && c.get(i + 1) != Some(&'[') {
221                if let Some((end, dest)) = md_link_at(&c, i) {
222                    let path = dest.split(['#', '?']).next().unwrap_or("");
223                    let relative = !path.contains("://")
224                        && !path.starts_with(['/', '#'])
225                        && !path.contains(':');
226                    if relative && path.to_lowercase().ends_with(".md") {
227                        let name = path.trim_start_matches("./").trim_end_matches(".md");
228                        let name = name.trim_end_matches(".MD");
229                        let target = self.note_target(name.to_string());
230                        if self.add(i, end, target) {
231                            self.mask(i, end);
232                        }
233                    }
234                    i = end;
235                    continue;
236                }
237            }
238            i += 1;
239        }
240    }
241
242    // -- URLs --------------------------------------------------------------
243
244    fn bases(&self) -> Vec<String> {
245        let mut v = vec![self.ctx.web_base.clone()];
246        if let Some(i) = &self.ctx.repo_links.issues {
247            v.push(i.web_base.clone());
248        }
249        if let Some(p) = &self.ctx.repo_links.pulls {
250            v.push(p.web_base.clone());
251        }
252        v.retain(|b| !b.is_empty());
253        v.iter_mut()
254            .for_each(|b| *b = b.trim_end_matches('/').to_lowercase());
255        v
256    }
257
258    fn urls(&mut self) {
259        let c = self.masked.clone();
260        let n = c.len();
261        let bases = self.bases();
262        let mut i = 0;
263        while i < n {
264            if (c[i] == 'h' || c[i] == 'H') && boundary_loose(&c, i) {
265                let rest: String = c[i..n.min(i + 8)].iter().collect::<String>().to_lowercase();
266                if rest.starts_with("http://") || rest.starts_with("https://") {
267                    let mut j = i;
268                    while j < n
269                        && !c[j].is_whitespace()
270                        && !matches!(c[j], '<' | '>' | '"' | '\'' | '`')
271                    {
272                        j += 1;
273                    }
274                    let end = i + trim_url_end(&c[i..j]);
275                    let url: String = c[i..end].iter().collect();
276                    if let Some(target) = self.classify_url(&url, &bases) {
277                        self.add(i, end, target);
278                    }
279                    // Whatever it is, nothing inside a URL is a token.
280                    self.mask(i, j);
281                    i = j;
282                    continue;
283                }
284            }
285            i += 1;
286        }
287    }
288
289    fn classify_url(&self, url: &str, bases: &[String]) -> Option<XrefTarget> {
290        // A Trello card (or any URL the linked sources already know).
291        let found = refs::scan_message(url, &self.ctx.repo_links);
292        if let [f] = found.as_slice() {
293            if f.start == 0 && f.end == url.chars().count() {
294                return Some(self.in_app(f));
295            }
296        }
297        let lower = url.to_lowercase();
298        if !bases.iter().any(|b| lower.starts_with(b.as_str())) {
299            return None;
300        }
301        let no_frag = url.split(['#', '?']).next().unwrap_or(url);
302        let segs: Vec<&str> = no_frag
303            .split('/')
304            .skip(3)
305            .filter(|s| !s.is_empty())
306            .collect();
307        let (kind, number, key) = item_in_path(&segs)?;
308        match kind {
309            UrlItem::Commit => Some(XrefTarget::Commit {
310                sha: key,
311                url: Some(url.to_string()),
312            }),
313            UrlItem::Issue | UrlItem::Pull => {
314                if let (Some(n), UrlItem::Pull, Some(p)) =
315                    (number, kind, self.ctx.repo_links.pulls.as_ref())
316                {
317                    // Compare with the linked source's own address of the PR
318                    // (its sigil may also be an issue's, so `refs` can't tell).
319                    let own = (spec_for(p.family).pr_web_url)(&p.web_base, &p.project, n);
320                    if own.as_deref().is_some_and(|u| same_url(u, url)) {
321                        return Some(XrefTarget::InApp(ItemTarget {
322                            family: p.family,
323                            web_base: p.web_base.clone(),
324                            project: p.project.clone(),
325                            kind: RefKind::PullRequest,
326                            number: n,
327                            key: format!("{}{n}", spec_for(p.family).pr_sigil),
328                        }));
329                    }
330                }
331                let (sigil, reference) = match (&number, kind) {
332                    (Some(n), UrlItem::Issue) => ('#', n.to_string()),
333                    (Some(n), UrlItem::Pull) => (self.pull_sigil(), n.to_string()),
334                    _ => ('\0', key.clone()),
335                };
336                let token = if sigil == '\0' {
337                    reference
338                } else {
339                    format!("{sigil}{reference}")
340                };
341                for f in refs::scan_message(&token, &self.ctx.repo_links) {
342                    if f.start == 0
343                        && f.end == token.chars().count()
344                        && f.url.as_deref().is_some_and(|u| same_url(u, url))
345                    {
346                        return Some(self.in_app(&f));
347                    }
348                }
349                Some(XrefTarget::Web(url.to_string()))
350            }
351        }
352    }
353
354    fn pull_sigil(&self) -> char {
355        self.ctx
356            .repo_links
357            .pulls
358            .as_ref()
359            .map(|p| spec_for(p.family).pr_sigil)
360            .or_else(|| self.ctx.family.map(|f| spec_for(f).pr_sigil))
361            .unwrap_or('#')
362    }
363
364    // -- the repository's own links ----------------------------------------
365
366    fn in_app(&self, f: &refs::FoundRef) -> XrefTarget {
367        let (family, web_base, project) = match f.kind {
368            RefKind::Issue => self
369                .ctx
370                .repo_links
371                .issues
372                .as_ref()
373                .map(|l| (l.family, l.web_base.clone(), l.project.clone())),
374            RefKind::PullRequest => self
375                .ctx
376                .repo_links
377                .pulls
378                .as_ref()
379                .map(|l| (l.family, l.web_base.clone(), l.project.clone())),
380        }
381        .unwrap_or((
382            self.ctx.family.unwrap_or(ApiFamily::Github),
383            self.ctx.web_base.clone(),
384            self.ctx.project.clone(),
385        ));
386        let digits: String = f
387            .text
388            .chars()
389            .rev()
390            .take_while(char::is_ascii_digit)
391            .collect::<Vec<_>>()
392            .into_iter()
393            .rev()
394            .collect();
395        XrefTarget::InApp(ItemTarget {
396            family,
397            web_base,
398            project,
399            kind: f.kind,
400            number: if f.text.starts_with("http") {
401                0
402            } else {
403                digits.parse().unwrap_or(0)
404            },
405            key: f.reference.clone(),
406        })
407    }
408
409    fn repo_links(&mut self) {
410        let masked: String = self.masked.iter().collect();
411        for f in refs::scan_message(&masked, &self.ctx.repo_links) {
412            let target = self.in_app(&f);
413            self.add(f.start, f.end, target);
414        }
415    }
416
417    /// `#N` / `!N` through the linked sources first, else the host's page.
418    fn number_target(&self, sigil: char, n: u64) -> Option<XrefTarget> {
419        let token = format!("{sigil}{n}");
420        for f in refs::scan_message(&token, &self.ctx.repo_links) {
421            if f.start == 0 && f.end == token.chars().count() {
422                return Some(self.in_app(&f));
423            }
424        }
425        self.web_number(&self.ctx.project, sigil, n)
426    }
427
428    fn web_number(&self, project: &str, sigil: char, n: u64) -> Option<XrefTarget> {
429        let family = self.ctx.family?;
430        let base = self.ctx.web_base.as_str();
431        if base.is_empty() || (project.is_empty() && family != ApiFamily::Redmine) {
432            return None;
433        }
434        let spec = spec_for(family);
435        let url = if sigil == '!' {
436            (spec.pr_web_url)(base, project, n)
437        } else {
438            (spec.issue_web_url)(base, project, &n.to_string())
439        };
440        url.map(XrefTarget::Web)
441    }
442
443    // -- host grammar --------------------------------------------------------
444
445    fn host_tokens(&mut self) {
446        let c = self.masked.clone();
447        let n = c.len();
448        let mut i = 0;
449        while i < n {
450            if self.taken[i] {
451                i += 1;
452                continue;
453            }
454            let hit = self.token_at(&c, i);
455            match hit {
456                Some((end, target)) => {
457                    if self.add(i, end, target) {
458                        i = end;
459                    } else {
460                        i += 1;
461                    }
462                }
463                None => i += 1,
464            }
465        }
466    }
467
468    fn family(&self) -> Option<ApiFamily> {
469        self.ctx.family
470    }
471
472    fn token_at(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
473        let fam = self.family();
474        match c[i] {
475            '@' => self.mention(c, i),
476            '#' | '!' => self.number(c, i),
477            '~' | '%' if fam == Some(ApiFamily::Gitlab) => chip(c, i),
478            '{' if fam == Some(ApiFamily::Bitbucket) => {
479                let end = uuid_braced(c, i)?;
480                let login: String = c[i..end].iter().collect();
481                Some((end, XrefTarget::Mention { login, url: None }))
482            }
483            _ => {
484                if !boundary_strict(c, i) {
485                    return None;
486                }
487                self.slug_ref(c, i)
488                    .or_else(|| self.gh_key(c, i))
489                    .or_else(|| self.redmine(c, i))
490                    .or_else(|| self.gerrit_change_id(c, i))
491                    .or_else(|| self.sha(c, i))
492            }
493        }
494    }
495
496    fn commit_url(&self, project: &str, sha: &str) -> Option<String> {
497        let family = self.family()?;
498        if self.ctx.web_base.is_empty() || project.is_empty() {
499            return None;
500        }
501        (spec_for(family).commit_url)(&self.ctx.web_base, project, sha)
502    }
503
504    fn sha(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
505        let end = sha_end(c, i)?;
506        let sha: String = c[i..end].iter().collect();
507        let url = self.commit_url(&self.ctx.project, &sha);
508        Some((end, XrefTarget::Commit { sha, url }))
509    }
510
511    fn number(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
512        let sigil = c[i];
513        if i > 0 && (is_word(c[i - 1]) || matches!(c[i - 1], '&' | '/' | '\\' | '#' | '!')) {
514            return None;
515        }
516        let (end, n) = digits_at(c, i + 1)?;
517        if c.get(end).is_some_and(|x| is_word(*x)) {
518            return None;
519        }
520        let fam = self.family()?;
521        let allowed = match sigil {
522            '#' => matches!(
523                fam,
524                ApiFamily::Github
525                    | ApiFamily::Gitlab
526                    | ApiFamily::Gitea
527                    | ApiFamily::Redmine
528                    | ApiFamily::AzureDevops
529            ),
530            _ => matches!(
531                fam,
532                ApiFamily::Gitlab | ApiFamily::Gitea | ApiFamily::AzureDevops
533            ),
534        };
535        if !allowed {
536            return None;
537        }
538        Some((end, self.number_target(sigil, n)?))
539    }
540
541    fn gh_key(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
542        if self.family() != Some(ApiFamily::Github)
543            || c[i] != 'G'
544            || c.get(i + 1) != Some(&'H')
545            || c.get(i + 2) != Some(&'-')
546        {
547            return None;
548        }
549        let (end, n) = digits_at(c, i + 3)?;
550        if c.get(end).is_some_and(|x| is_word(*x)) {
551            return None;
552        }
553        Some((end, self.number_target('#', n)?))
554    }
555
556    fn redmine(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
557        if self.family() != Some(ApiFamily::Redmine) {
558            return None;
559        }
560        let word: String = c[i..c.len().min(i + 7)].iter().collect();
561        if word == "commit:" {
562            let end = sha_end(c, i + 7)?;
563            let sha: String = c[i + 7..end].iter().collect();
564            return Some((end, XrefTarget::Commit { sha, url: None }));
565        }
566        if c[i] == 'r' && !self.ctx.web_base.is_empty() {
567            let (end, n) = digits_at(c, i + 1)?;
568            if c.get(end).is_some_and(|x| is_word(*x)) {
569                return None;
570            }
571            let base = self.ctx.web_base.trim_end_matches('/');
572            let url = if self.ctx.project.is_empty() {
573                format!("{base}/repository/revisions/{n}")
574            } else {
575                format!(
576                    "{base}/projects/{}/repository/revisions/{n}",
577                    self.ctx.project
578                )
579            };
580            return Some((end, XrefTarget::Web(url)));
581        }
582        None
583    }
584
585    fn gerrit_change_id(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
586        if self.family() != Some(ApiFamily::Gerrit) || c[i] != 'I' || self.ctx.web_base.is_empty() {
587            return None;
588        }
589        let end = i + 41;
590        if end > c.len() || !c[i + 1..end].iter().all(|x| is_hex(*x)) {
591            return None;
592        }
593        if c.get(end).is_some_and(|x| is_word(*x)) {
594            return None;
595        }
596        let id: String = c[i..end].iter().collect();
597        let base = self.ctx.web_base.trim_end_matches('/');
598        Some((end, XrefTarget::Web(format!("{base}/q/{id}"))))
599    }
600
601    /// `owner/repo#N`, `group/proj!N`, `proj#N`, `owner/repo@sha`.
602    fn slug_ref(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
603        let fam = self.family()?;
604        if !matches!(
605            fam,
606            ApiFamily::Github | ApiFamily::Gitea | ApiFamily::Gitlab
607        ) {
608            return None;
609        }
610        let mut j = i;
611        let mut segs = 0;
612        loop {
613            let start = j;
614            while j < c.len() && (c[j].is_ascii_alphanumeric() || matches!(c[j], '_' | '.' | '-')) {
615                j += 1;
616            }
617            if j == start {
618                return None;
619            }
620            segs += 1;
621            if c.get(j) == Some(&'/') && c.get(j + 1).is_some_and(|x| x.is_ascii_alphanumeric()) {
622                j += 1;
623            } else {
624                break;
625            }
626        }
627        let slug_end = j;
628        let sigil = *c.get(j)?;
629        let slug: String = c[i..slug_end].iter().collect();
630        if slug.ends_with(['.', '-']) {
631            return None;
632        }
633        let fits = match fam {
634            ApiFamily::Gitlab => {
635                segs >= 2 || (slug.len() >= 2 && slug.starts_with(|x: char| x.is_ascii_lowercase()))
636            }
637            _ => segs == 2,
638        };
639        if !fits {
640            return None;
641        }
642        let project = if segs == 1 {
643            // `proj#N`: a sibling project in the same group.
644            match self.ctx.project.rsplit_once('/') {
645                Some((group, _)) => format!("{group}/{slug}"),
646                None => slug.clone(),
647            }
648        } else {
649            slug.clone()
650        };
651        match sigil {
652            '#' | '!' if sigil == '#' || fam == ApiFamily::Gitlab => {
653                let (end, n) = digits_at(c, slug_end + 1)?;
654                if c.get(end).is_some_and(|x| is_word(*x)) {
655                    return None;
656                }
657                if project == self.ctx.project {
658                    return Some((end, self.number_target(sigil, n)?));
659                }
660                Some((end, self.web_number(&project, sigil, n)?))
661            }
662            '@' if segs >= 2 => {
663                let end = sha_end(c, slug_end + 1)?;
664                let sha: String = c[slug_end + 1..end].iter().collect();
665                let url = self.commit_url(&project, &sha);
666                Some((end, XrefTarget::Commit { sha, url }))
667            }
668            _ => None,
669        }
670    }
671
672    fn mention(&self, c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
673        let fam = self.family()?;
674        if i > 0
675            && (is_word(c[i - 1])
676                || matches!(
677                    c[i - 1],
678                    '@' | '.' | '/' | '\\' | '&' | '-' | '_' | '+' | '=' | '%'
679                ))
680        {
681            return None;
682        }
683        if fam == ApiFamily::AzureDevops {
684            if c.get(i + 1) != Some(&'<') {
685                return None;
686            }
687            let end = uuid_plain(c, i + 2)?;
688            if c.get(end) != Some(&'>') {
689                return None;
690            }
691            return Some((
692                end + 1,
693                XrefTarget::Mention {
694                    login: "user".to_string(),
695                    url: None,
696                },
697            ));
698        }
699        if !matches!(
700            fam,
701            ApiFamily::Github
702                | ApiFamily::Gitlab
703                | ApiFamily::Gitea
704                | ApiFamily::Bitbucket
705                | ApiFamily::Jira
706                | ApiFamily::Linear
707                | ApiFamily::YouTrack
708                | ApiFamily::Redmine
709                | ApiFamily::Trello
710        ) {
711            return None;
712        }
713        if fam == ApiFamily::Bitbucket && c.get(i + 1) == Some(&'{') {
714            let end = uuid_braced(c, i + 1)?;
715            let login: String = c[i + 1..end].iter().collect();
716            return Some((end, XrefTarget::Mention { login, url: None }));
717        }
718        let mut j = i + 1;
719        if !c.get(j).is_some_and(|x| x.is_ascii_alphanumeric()) {
720            return None;
721        }
722        while j < c.len() && (c[j].is_ascii_alphanumeric() || matches!(c[j], '_' | '.' | '-')) {
723            j += 1;
724        }
725        while matches!(c[j - 1], '.' | '-' | '_') {
726            j -= 1;
727        }
728        let mut login: String = c[i + 1..j].iter().collect();
729        let base = self.ctx.web_base.trim_end_matches('/');
730        let mut url = match fam {
731            ApiFamily::Github | ApiFamily::Gitlab | ApiFamily::Gitea | ApiFamily::Trello
732                if !base.is_empty() =>
733            {
734                Some(format!("{base}/{login}"))
735            }
736            ApiFamily::Bitbucket if !base.is_empty() => Some(format!("{base}/{login}/")),
737            _ => None,
738        };
739        if fam == ApiFamily::Github && c.get(j) == Some(&'/') {
740            // `@org/team`
741            let mut k = j + 1;
742            while k < c.len() && (c[k].is_ascii_alphanumeric() || matches!(c[k], '_' | '-')) {
743                k += 1;
744            }
745            if k > j + 1 {
746                let team: String = c[j + 1..k].iter().collect();
747                url = (!base.is_empty()).then(|| format!("{base}/orgs/{login}/teams/{team}"));
748                login = format!("{login}/{team}");
749                j = k;
750            }
751        }
752        if c.get(j).is_some_and(|x| is_word(*x)) {
753            return None;
754        }
755        Some((j, XrefTarget::Mention { login, url }))
756    }
757}
758
759// ---------------------------------------------------------------------------
760// helpers
761
762/// Not glued to a word, an entity or a path.
763fn boundary_loose(c: &[char], i: usize) -> bool {
764    i == 0 || (!is_word(c[i - 1]) && !matches!(c[i - 1], '&' | '/' | '\\'))
765}
766
767/// `boundary_loose` and not part of a dotted, dashed or tagged run.
768fn boundary_strict(c: &[char], i: usize) -> bool {
769    boundary_loose(c, i)
770        && (i == 0 || !matches!(c[i - 1], '.' | '-' | '@' | '#' | '%' | '~' | '+' | '='))
771}
772
773fn digits_at(c: &[char], from: usize) -> Option<(usize, u64)> {
774    let mut j = from;
775    while j < c.len() && c[j].is_ascii_digit() {
776        j += 1;
777    }
778    if j == from || j - from > MAX_DIGITS {
779        return None;
780    }
781    let n = c[from..j].iter().collect::<String>().parse().ok()?;
782    Some((j, n))
783}
784
785/// End of a 7 to 40 digit commit id at `i`: it needs a digit and a letter
786/// (so `decade` and `1234567` are not ids) and may not run into a word.
787fn sha_end(c: &[char], i: usize) -> Option<usize> {
788    let mut j = i;
789    while j < c.len() && is_hex(c[j]) {
790        j += 1;
791    }
792    let len = j - i;
793    if !(7..=40).contains(&len) {
794        return None;
795    }
796    let run = &c[i..j];
797    if !run.iter().any(char::is_ascii_digit) || !run.iter().any(char::is_ascii_alphabetic) {
798        return None;
799    }
800    match c.get(j) {
801        Some(n) if is_word(*n) || *n == '-' => return None,
802        Some('.') if c.get(j + 1).is_some_and(|x| x.is_alphanumeric()) => return None,
803        _ => {}
804    }
805    Some(j)
806}
807
808fn uuid_plain(c: &[char], i: usize) -> Option<usize> {
809    let end = i + 36;
810    let s = c.get(i..end)?;
811    let ok = s.iter().enumerate().all(|(k, ch)| {
812        if matches!(k, 8 | 13 | 18 | 23) {
813            *ch == '-'
814        } else {
815            is_hex(*ch)
816        }
817    });
818    ok.then_some(end)
819}
820
821fn uuid_braced(c: &[char], i: usize) -> Option<usize> {
822    if c.get(i) != Some(&'{') {
823        return None;
824    }
825    let end = uuid_plain(c, i + 1)?;
826    (c.get(end) == Some(&'}')).then_some(end + 1)
827}
828
829/// GitLab `~label`, `~"a b"`, `%milestone`.
830fn chip(c: &[char], i: usize) -> Option<(usize, XrefTarget)> {
831    let sigil = c[i];
832    if i > 0 && (is_word(c[i - 1]) || matches!(c[i - 1], '~' | '%' | '/' | '\\')) {
833        return None;
834    }
835    let first = *c.get(i + 1)?;
836    let kind = if sigil == '~' {
837        if first == '~' {
838            return None;
839        }
840        ChipKind::Label
841    } else {
842        let numeric = first.is_ascii_digit()
843            || (first == 'v' && c.get(i + 2).is_some_and(char::is_ascii_digit));
844        if !(numeric || first == '"') {
845            return None;
846        }
847        ChipKind::Milestone
848    };
849    if first == '"' {
850        let close = (i + 2..c.len().min(i + 62)).find(|&k| c[k] == '"' || c[k] == '\n')?;
851        if c[close] != '"' || close == i + 2 {
852            return None;
853        }
854        let name: String = c[i + 2..close].iter().collect();
855        return Some((close + 1, XrefTarget::Chip { kind, name }));
856    }
857    if !first.is_ascii_alphanumeric() {
858        return None;
859    }
860    let mut j = i + 1;
861    while j < c.len() && (c[j].is_ascii_alphanumeric() || matches!(c[j], '_' | '.' | '-' | ':')) {
862        j += 1;
863    }
864    while matches!(c[j - 1], '.' | '-' | ':') {
865        j -= 1;
866    }
867    if j - (i + 1) < 2 && kind == ChipKind::Label {
868        return None;
869    }
870    let name: String = c[i + 1..j].iter().collect();
871    Some((j, XrefTarget::Chip { kind, name }))
872}
873
874// -- URLs ---------------------------------------------------------------------
875
876#[derive(Clone, Copy, PartialEq, Eq)]
877enum UrlItem {
878    Issue,
879    Pull,
880    Commit,
881}
882
883/// What an address path names: `(kind, number, key)`; the key is the
884/// `KEY-N` of a tracker or the commit id.
885fn item_in_path(segs: &[&str]) -> Option<(UrlItem, Option<u64>, String)> {
886    let num = |s: Option<&&str>| s.and_then(|s| s.parse::<u64>().ok());
887    for (k, seg) in segs.iter().enumerate() {
888        let next = segs.get(k + 1);
889        match *seg {
890            "issues" if num(next).is_some() => {
891                return Some((UrlItem::Issue, num(next), String::new()))
892            }
893            "pull" | "pulls" | "merge_requests" | "pull-requests" | "pullrequest"
894                if num(next).is_some() =>
895            {
896                return Some((UrlItem::Pull, num(next), String::new()));
897            }
898            "edit" if k > 0 && segs[k - 1] == "_workitems" && num(next).is_some() => {
899                return Some((UrlItem::Issue, num(next), String::new()));
900            }
901            "+" if num(next).is_some() => return Some((UrlItem::Pull, num(next), String::new())),
902            "browse" | "issue" => {
903                if let Some(key) = next.filter(|n| is_issue_key(n)) {
904                    return Some((UrlItem::Issue, None, (*key).to_string()));
905                }
906            }
907            "commit" | "commits" => {
908                if let Some(sha) = next.filter(|n| {
909                    n.len() >= 7 && n.len() <= 40 && n.chars().all(|c| c.is_ascii_hexdigit())
910                }) {
911                    return Some((UrlItem::Commit, None, (*sha).to_string()));
912                }
913            }
914            _ => {}
915        }
916    }
917    None
918}
919
920fn is_issue_key(s: &str) -> bool {
921    let Some((key, n)) = s.rsplit_once('-') else {
922        return false;
923    };
924    !key.is_empty()
925        && key
926            .chars()
927            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
928        && !n.is_empty()
929        && n.chars().all(|c| c.is_ascii_digit())
930}
931
932fn same_url(a: &str, b: &str) -> bool {
933    let norm = |u: &str| {
934        u.split(['#', '?'])
935            .next()
936            .unwrap_or("")
937            .trim_end_matches('/')
938            .to_lowercase()
939    };
940    norm(a) == norm(b)
941}
942
943/// Length of the URL in `run` once sentence punctuation is cut off.
944fn trim_url_end(run: &[char]) -> usize {
945    let mut end = run.len();
946    while end > 0 {
947        let last = run[end - 1];
948        let drop = match last {
949            '.' | ',' | ';' | ':' | '!' | '?' | '*' => true,
950            ')' | ']' | '}' => {
951                let (open, close) = match last {
952                    ')' => ('(', ')'),
953                    ']' => ('[', ']'),
954                    _ => ('{', '}'),
955                };
956                let o = run[..end].iter().filter(|c| **c == open).count();
957                let cl = run[..end].iter().filter(|c| **c == close).count();
958                cl > o
959            }
960            _ => false,
961        };
962        if drop {
963            end -= 1;
964        } else {
965            break;
966        }
967    }
968    end
969}
970
971// -- Markdown structure ----------------------------------------------------------
972
973/// Ranges of fenced blocks and inline code spans.
974fn code_ranges(c: &[char]) -> Vec<(usize, usize)> {
975    let mut out = Vec::new();
976    let mut fence: Option<(char, usize, usize)> = None; // (char, len, start)
977    let mut line_start = 0;
978    while line_start < c.len() {
979        let mut line_end = line_start;
980        while line_end < c.len() && c[line_end] != '\n' {
981            line_end += 1;
982        }
983        let next_start = (line_end + 1).min(c.len());
984        let line = &c[line_start..line_end];
985        let indent = line.iter().take_while(|x| **x == ' ').count();
986        let body = &line[indent.min(line.len())..];
987        let run = |ch: char| body.iter().take_while(|x| **x == ch).count();
988        if let Some((fc, flen, start)) = fence {
989            if indent <= 3 && run(fc) >= flen && body[run(fc)..].iter().all(|x| x.is_whitespace()) {
990                out.push((start, next_start));
991                fence = None;
992            }
993        } else if indent <= 3 && (run('`') >= 3 || run('~') >= 3) {
994            let ch = if run('`') >= 3 { '`' } else { '~' };
995            // A backtick fence's info string may not hold backticks.
996            if ch == '~' || !body[run('`')..].contains(&'`') {
997                fence = Some((ch, run(ch), line_start));
998            }
999        } else {
1000            inline_code(c, line_start, line_end, &mut out);
1001        }
1002        line_start = next_start;
1003        if next_start == line_end {
1004            break;
1005        }
1006    }
1007    if let Some((_, _, start)) = fence {
1008        out.push((start, c.len()));
1009    }
1010    out
1011}
1012
1013fn inline_code(c: &[char], from: usize, to: usize, out: &mut Vec<(usize, usize)>) {
1014    let mut i = from;
1015    while i < to {
1016        if c[i] != '`' {
1017            i += 1;
1018            continue;
1019        }
1020        let mut n = 0;
1021        while i + n < to && c[i + n] == '`' {
1022            n += 1;
1023        }
1024        let mut j = i + n;
1025        let mut closed = None;
1026        while j < to {
1027            if c[j] == '`' {
1028                let mut m = 0;
1029                while j + m < to && c[j + m] == '`' {
1030                    m += 1;
1031                }
1032                if m == n {
1033                    closed = Some(j + m);
1034                    break;
1035                }
1036                j += m;
1037            } else {
1038                j += 1;
1039            }
1040        }
1041        match closed {
1042            Some(end) => {
1043                out.push((i, end));
1044                i = end;
1045            }
1046            None => i += n,
1047        }
1048    }
1049}
1050
1051/// The index of `pat` at or after `from`, on the same line.
1052fn find_pair(c: &[char], from: usize, pat: &str) -> Option<usize> {
1053    let p: Vec<char> = pat.chars().collect();
1054    let mut i = from;
1055    while i + p.len() <= c.len() {
1056        if c[i] == '\n' {
1057            return None;
1058        }
1059        if c[i..i + p.len()] == p[..] {
1060            return Some(i);
1061        }
1062        i += 1;
1063    }
1064    None
1065}
1066
1067/// A `[text](dest)` starting at `[` at `i`: `(end, dest)`.
1068fn md_link_at(c: &[char], i: usize) -> Option<(usize, String)> {
1069    let mut depth = 0;
1070    let mut j = i;
1071    while j < c.len() {
1072        match c[j] {
1073            '\n' => return None,
1074            '[' => depth += 1,
1075            ']' => {
1076                depth -= 1;
1077                if depth == 0 {
1078                    break;
1079                }
1080            }
1081            _ => {}
1082        }
1083        j += 1;
1084    }
1085    if j >= c.len() || c.get(j + 1) != Some(&'(') {
1086        return None;
1087    }
1088    let mut k = j + 2;
1089    let mut paren = 1;
1090    while k < c.len() {
1091        match c[k] {
1092            '\n' => return None,
1093            '(' => paren += 1,
1094            ')' => {
1095                paren -= 1;
1096                if paren == 0 {
1097                    let inner: String = c[j + 2..k].iter().collect();
1098                    let dest = inner
1099                        .split_whitespace()
1100                        .next()
1101                        .unwrap_or("")
1102                        .trim_matches(['<', '>']);
1103                    return Some((k + 1, dest.to_string()));
1104                }
1105            }
1106            _ => {}
1107        }
1108        k += 1;
1109    }
1110    None
1111}
1112
1113/// Ranges of `[text](dest)` and `![alt](src)`.
1114fn link_ranges(c: &[char]) -> Vec<(usize, usize)> {
1115    let mut out = Vec::new();
1116    let mut i = 0;
1117    while i < c.len() {
1118        if c[i] == '[' {
1119            if let Some((end, _)) = md_link_at(c, i) {
1120                let start = if i > 0 && c[i - 1] == '!' { i - 1 } else { i };
1121                out.push((start, end));
1122                i = end;
1123                continue;
1124            }
1125        }
1126        i += 1;
1127    }
1128    out
1129}
1130
1131#[cfg(test)]
1132mod tests;