terminal_hyperlinks.rs

   1use alacritty_terminal::{
   2    Term,
   3    event::EventListener,
   4    grid::Dimensions,
   5    index::{Boundary, Column, Direction as AlacDirection, Point as AlacPoint},
   6    term::{
   7        cell::Flags,
   8        search::{Match, RegexIter, RegexSearch},
   9    },
  10};
  11use log::{info, warn};
  12use regex::Regex;
  13use std::{
  14    ops::{Index, Range},
  15    time::{Duration, Instant},
  16};
  17
  18const URL_REGEX: &str = r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^โŸจโŸฉ`']+"#;
  19const WIDE_CHAR_SPACERS: Flags =
  20    Flags::from_bits(Flags::LEADING_WIDE_CHAR_SPACER.bits() | Flags::WIDE_CHAR_SPACER.bits())
  21        .unwrap();
  22
  23pub(super) struct RegexSearches {
  24    url_regex: RegexSearch,
  25    path_hyperlink_regexes: Vec<Regex>,
  26    path_hyperlink_timeout: Duration,
  27}
  28
  29impl Default for RegexSearches {
  30    fn default() -> Self {
  31        Self {
  32            url_regex: RegexSearch::new(URL_REGEX).unwrap(),
  33            path_hyperlink_regexes: Vec::default(),
  34            path_hyperlink_timeout: Duration::default(),
  35        }
  36    }
  37}
  38impl RegexSearches {
  39    pub(super) fn new(
  40        path_hyperlink_regexes: impl IntoIterator<Item: AsRef<str>>,
  41        path_hyperlink_timeout_ms: u64,
  42    ) -> Self {
  43        Self {
  44            url_regex: RegexSearch::new(URL_REGEX).unwrap(),
  45            path_hyperlink_regexes: path_hyperlink_regexes
  46                .into_iter()
  47                .filter_map(|regex| {
  48                    Regex::new(regex.as_ref())
  49                        .inspect_err(|error| {
  50                            warn!(
  51                                concat!(
  52                                    "Ignoring path hyperlink regex specified in ",
  53                                    "`terminal.path_hyperlink_regexes`:\n\n\t{}\n\nError: {}",
  54                                ),
  55                                regex.as_ref(),
  56                                error
  57                            );
  58                        })
  59                        .ok()
  60                })
  61                .collect(),
  62            path_hyperlink_timeout: Duration::from_millis(path_hyperlink_timeout_ms),
  63        }
  64    }
  65}
  66
  67pub(super) fn find_from_grid_point<T: EventListener>(
  68    term: &Term<T>,
  69    point: AlacPoint,
  70    regex_searches: &mut RegexSearches,
  71) -> Option<(String, bool, Match)> {
  72    let grid = term.grid();
  73    let link = grid.index(point).hyperlink();
  74    let found_word = if let Some(ref url) = link {
  75        let mut min_index = point;
  76        loop {
  77            let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
  78            if new_min_index == min_index || grid.index(new_min_index).hyperlink() != link {
  79                break;
  80            } else {
  81                min_index = new_min_index
  82            }
  83        }
  84
  85        let mut max_index = point;
  86        loop {
  87            let new_max_index = max_index.add(term, Boundary::Cursor, 1);
  88            if new_max_index == max_index || grid.index(new_max_index).hyperlink() != link {
  89                break;
  90            } else {
  91                max_index = new_max_index
  92            }
  93        }
  94
  95        let url = url.uri().to_owned();
  96        let url_match = min_index..=max_index;
  97
  98        Some((url, true, url_match))
  99    } else {
 100        let (line_start, line_end) = (term.line_search_left(point), term.line_search_right(point));
 101        if let Some((url, url_match)) = RegexIter::new(
 102            line_start,
 103            line_end,
 104            AlacDirection::Right,
 105            term,
 106            &mut regex_searches.url_regex,
 107        )
 108        .find(|rm| rm.contains(&point))
 109        .map(|url_match| {
 110            let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 111            sanitize_url_punctuation(url, url_match, term)
 112        }) {
 113            Some((url, true, url_match))
 114        } else {
 115            path_match(
 116                &term,
 117                line_start,
 118                line_end,
 119                point,
 120                &mut regex_searches.path_hyperlink_regexes,
 121                regex_searches.path_hyperlink_timeout,
 122            )
 123            .map(|(path, path_match)| (path, false, path_match))
 124        }
 125    };
 126
 127    found_word.map(|(maybe_url_or_path, is_url, word_match)| {
 128        if is_url {
 129            // Treat "file://" IRIs like file paths to ensure
 130            // that line numbers at the end of the path are
 131            // handled correctly
 132            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
 133                (path.to_string(), false, word_match)
 134            } else {
 135                (maybe_url_or_path, true, word_match)
 136            }
 137        } else {
 138            (maybe_url_or_path, false, word_match)
 139        }
 140    })
 141}
 142
 143fn sanitize_url_punctuation<T: EventListener>(
 144    url: String,
 145    url_match: Match,
 146    term: &Term<T>,
 147) -> (String, Match) {
 148    let mut sanitized_url = url;
 149    let mut chars_trimmed = 0;
 150
 151    // First, handle parentheses balancing using single traversal
 152    let (open_parens, close_parens) =
 153        sanitized_url
 154            .chars()
 155            .fold((0, 0), |(opens, closes), c| match c {
 156                '(' => (opens + 1, closes),
 157                ')' => (opens, closes + 1),
 158                _ => (opens, closes),
 159            });
 160
 161    // Trim unbalanced closing parentheses
 162    if close_parens > open_parens {
 163        let mut remaining_close = close_parens;
 164        while sanitized_url.ends_with(')') && remaining_close > open_parens {
 165            sanitized_url.pop();
 166            chars_trimmed += 1;
 167            remaining_close -= 1;
 168        }
 169    }
 170
 171    // Handle trailing periods
 172    if sanitized_url.ends_with('.') {
 173        let trailing_periods = sanitized_url
 174            .chars()
 175            .rev()
 176            .take_while(|&c| c == '.')
 177            .count();
 178
 179        if trailing_periods > 1 {
 180            sanitized_url.truncate(sanitized_url.len() - trailing_periods);
 181            chars_trimmed += trailing_periods;
 182        } else if trailing_periods == 1
 183            && let Some(second_last_char) = sanitized_url.chars().rev().nth(1)
 184            && (second_last_char.is_alphanumeric() || second_last_char == '/')
 185        {
 186            sanitized_url.pop();
 187            chars_trimmed += 1;
 188        }
 189    }
 190
 191    if chars_trimmed > 0 {
 192        let new_end = url_match.end().sub(term, Boundary::Grid, chars_trimmed);
 193        let sanitized_match = Match::new(*url_match.start(), new_end);
 194        (sanitized_url, sanitized_match)
 195    } else {
 196        (sanitized_url, url_match)
 197    }
 198}
 199
 200fn path_match<T>(
 201    term: &Term<T>,
 202    line_start: AlacPoint,
 203    line_end: AlacPoint,
 204    hovered: AlacPoint,
 205    path_hyperlink_regexes: &mut Vec<Regex>,
 206    path_hyperlink_timeout: Duration,
 207) -> Option<(String, Match)> {
 208    if path_hyperlink_regexes.is_empty() || path_hyperlink_timeout.as_millis() == 0 {
 209        return None;
 210    }
 211    debug_assert!(line_start <= hovered);
 212    debug_assert!(line_end >= hovered);
 213    let search_start_time = Instant::now();
 214
 215    let timed_out = || {
 216        let elapsed_time = Instant::now().saturating_duration_since(search_start_time);
 217        (elapsed_time > path_hyperlink_timeout)
 218            .then_some((elapsed_time.as_millis(), path_hyperlink_timeout.as_millis()))
 219    };
 220
 221    // This used to be: `let line = term.bounds_to_string(line_start, line_end)`, however, that
 222    // api compresses tab characters into a single space, whereas we require a cell accurate
 223    // string representation of the line. The below algorithm does this, but seems a bit odd.
 224    // Maybe there is a clean api for doing this, but I couldn't find it.
 225    let mut line = String::with_capacity(
 226        (line_end.line.0 - line_start.line.0 + 1) as usize * term.grid().columns(),
 227    );
 228    let first_cell = &term.grid()[line_start];
 229    line.push(first_cell.c);
 230    let mut start_offset = 0;
 231    let mut hovered_point_byte_offset = None;
 232
 233    if !first_cell.flags.intersects(WIDE_CHAR_SPACERS) {
 234        start_offset += first_cell.c.len_utf8();
 235        if line_start == hovered {
 236            hovered_point_byte_offset = Some(0);
 237        }
 238    }
 239
 240    for cell in term.grid().iter_from(line_start) {
 241        if cell.point > line_end {
 242            break;
 243        }
 244        let is_spacer = cell.flags.intersects(WIDE_CHAR_SPACERS);
 245        if cell.point == hovered {
 246            debug_assert!(hovered_point_byte_offset.is_none());
 247            if start_offset > 0 && cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
 248                // If we hovered on a trailing spacer, back up to the end of the previous char's bytes.
 249                start_offset -= 1;
 250            }
 251            hovered_point_byte_offset = Some(start_offset);
 252        } else if cell.point < hovered && !is_spacer {
 253            start_offset += cell.c.len_utf8();
 254        }
 255
 256        if !is_spacer {
 257            line.push(match cell.c {
 258                '\t' => ' ',
 259                c @ _ => c,
 260            });
 261        }
 262    }
 263    let line = line.trim_ascii_end();
 264    let hovered_point_byte_offset = hovered_point_byte_offset?;
 265    let found_from_range = |path_range: Range<usize>,
 266                            link_range: Range<usize>,
 267                            position: Option<(u32, Option<u32>)>| {
 268        let advance_point_by_str = |mut point: AlacPoint, s: &str| {
 269            for _ in s.chars() {
 270                point = term
 271                    .expand_wide(point, AlacDirection::Right)
 272                    .add(term, Boundary::Grid, 1);
 273            }
 274
 275            // There does not appear to be an alacritty api that is
 276            // "move to start of current wide char", so we have to do it ourselves.
 277            let flags = term.grid().index(point).flags;
 278            if flags.contains(Flags::LEADING_WIDE_CHAR_SPACER) {
 279                AlacPoint::new(point.line + 1, Column(0))
 280            } else if flags.contains(Flags::WIDE_CHAR_SPACER) {
 281                AlacPoint::new(point.line, point.column - 1)
 282            } else {
 283                point
 284            }
 285        };
 286
 287        let link_start = advance_point_by_str(line_start, &line[..link_range.start]);
 288        let link_end = advance_point_by_str(link_start, &line[link_range]);
 289        let link_match = link_start
 290            ..=term
 291                .expand_wide(link_end, AlacDirection::Left)
 292                .sub(term, Boundary::Grid, 1);
 293
 294        (
 295            {
 296                let mut path = line[path_range].to_string();
 297                position.inspect(|(line, column)| {
 298                    path += &format!(":{line}");
 299                    column.inspect(|column| path += &format!(":{column}"));
 300                });
 301                path
 302            },
 303            link_match,
 304        )
 305    };
 306
 307    for regex in path_hyperlink_regexes {
 308        let mut path_found = false;
 309
 310        for captures in regex.captures_iter(&line) {
 311            path_found = true;
 312            let match_range = captures.get(0).unwrap().range();
 313            let (path_range, line_column) = if let Some(path) = captures.name("path") {
 314                let parse = |name: &str| {
 315                    captures
 316                        .name(name)
 317                        .and_then(|capture| capture.as_str().parse().ok())
 318                };
 319
 320                (
 321                    path.range(),
 322                    parse("line").map(|line| (line, parse("column"))),
 323                )
 324            } else {
 325                (match_range.clone(), None)
 326            };
 327            let link_range = captures
 328                .name("link")
 329                .map_or_else(|| match_range.clone(), |link| link.range());
 330
 331            if !link_range.contains(&hovered_point_byte_offset) {
 332                // No match, just skip.
 333                continue;
 334            }
 335            let found = found_from_range(path_range, link_range, line_column);
 336
 337            if found.1.contains(&hovered) {
 338                return Some(found);
 339            }
 340        }
 341
 342        if path_found {
 343            return None;
 344        }
 345
 346        if let Some((timed_out_ms, timeout_ms)) = timed_out() {
 347            warn!("Timed out processing path hyperlink regexes after {timed_out_ms}ms");
 348            info!("{timeout_ms}ms time out specified in `terminal.path_hyperlink_timeout_ms`");
 349            return None;
 350        }
 351    }
 352
 353    None
 354}
 355
 356#[cfg(test)]
 357mod tests {
 358    use crate::terminal_settings::TerminalSettings;
 359
 360    use super::*;
 361    use alacritty_terminal::{
 362        event::VoidListener,
 363        grid::Dimensions,
 364        index::{Boundary, Column, Line, Point as AlacPoint},
 365        term::{Config, cell::Flags, test::TermSize},
 366        vte::ansi::Handler,
 367    };
 368    use regex::Regex;
 369    use settings::{self, Settings, SettingsContent};
 370    use std::{cell::RefCell, ops::RangeInclusive, path::PathBuf, rc::Rc};
 371    use url::Url;
 372    use util::paths::PathWithPosition;
 373
 374    fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
 375        let results: Vec<_> = Regex::new(re)
 376            .unwrap()
 377            .find_iter(hay)
 378            .map(|m| m.as_str())
 379            .collect();
 380        assert_eq!(results, expected);
 381    }
 382
 383    #[test]
 384    fn test_url_regex() {
 385        re_test(
 386            URL_REGEX,
 387            "test http://example.com test 'https://website1.com' test mailto:bob@example.com train",
 388            vec![
 389                "http://example.com",
 390                "https://website1.com",
 391                "mailto:bob@example.com",
 392            ],
 393        );
 394    }
 395
 396    #[test]
 397    fn test_url_parentheses_sanitization() {
 398        // Test our sanitize_url_parentheses function directly
 399        let test_cases = vec![
 400            // Cases that should be sanitized (unbalanced parentheses)
 401            ("https://www.google.com/)", "https://www.google.com/"),
 402            ("https://example.com/path)", "https://example.com/path"),
 403            ("https://test.com/))", "https://test.com/"),
 404            // Cases that should NOT be sanitized (balanced parentheses)
 405            (
 406                "https://en.wikipedia.org/wiki/Example_(disambiguation)",
 407                "https://en.wikipedia.org/wiki/Example_(disambiguation)",
 408            ),
 409            ("https://test.com/(hello)", "https://test.com/(hello)"),
 410            (
 411                "https://example.com/path(1)(2)",
 412                "https://example.com/path(1)(2)",
 413            ),
 414            // Edge cases
 415            ("https://test.com/", "https://test.com/"),
 416            ("https://example.com", "https://example.com"),
 417        ];
 418
 419        for (input, expected) in test_cases {
 420            // Create a minimal terminal for testing
 421            let term = Term::new(Config::default(), &TermSize::new(80, 24), VoidListener);
 422
 423            // Create a dummy match that spans the entire input
 424            let start_point = AlacPoint::new(Line(0), Column(0));
 425            let end_point = AlacPoint::new(Line(0), Column(input.len()));
 426            let dummy_match = Match::new(start_point, end_point);
 427
 428            let (result, _) = sanitize_url_punctuation(input.to_string(), dummy_match, &term);
 429            assert_eq!(result, expected, "Failed for input: {}", input);
 430        }
 431    }
 432
 433    #[test]
 434    fn test_url_periods_sanitization() {
 435        // Test URLs with trailing periods (sentence punctuation)
 436        let test_cases = vec![
 437            // Cases that should be sanitized (trailing periods likely punctuation)
 438            ("https://example.com.", "https://example.com"),
 439            (
 440                "https://github.com/zed-industries/zed.",
 441                "https://github.com/zed-industries/zed",
 442            ),
 443            (
 444                "https://example.com/path/file.html.",
 445                "https://example.com/path/file.html",
 446            ),
 447            (
 448                "https://example.com/file.pdf.",
 449                "https://example.com/file.pdf",
 450            ),
 451            ("https://example.com:8080.", "https://example.com:8080"),
 452            ("https://example.com..", "https://example.com"),
 453            (
 454                "https://en.wikipedia.org/wiki/C.E.O.",
 455                "https://en.wikipedia.org/wiki/C.E.O",
 456            ),
 457            // Cases that should NOT be sanitized (periods are part of URL structure)
 458            (
 459                "https://example.com/v1.0/api",
 460                "https://example.com/v1.0/api",
 461            ),
 462            ("https://192.168.1.1", "https://192.168.1.1"),
 463            ("https://sub.domain.com", "https://sub.domain.com"),
 464        ];
 465
 466        for (input, expected) in test_cases {
 467            // Create a minimal terminal for testing
 468            let term = Term::new(Config::default(), &TermSize::new(80, 24), VoidListener);
 469
 470            // Create a dummy match that spans the entire input
 471            let start_point = AlacPoint::new(Line(0), Column(0));
 472            let end_point = AlacPoint::new(Line(0), Column(input.len()));
 473            let dummy_match = Match::new(start_point, end_point);
 474
 475            // This test should initially fail since we haven't implemented period sanitization yet
 476            let (result, _) = sanitize_url_punctuation(input.to_string(), dummy_match, &term);
 477            assert_eq!(result, expected, "Failed for input: {}", input);
 478        }
 479    }
 480
 481    macro_rules! test_hyperlink {
 482        ($($lines:expr),+; $hyperlink_kind:ident) => { {
 483            use crate::terminal_hyperlinks::tests::line_cells_count;
 484            use std::cmp;
 485
 486            let test_lines = vec![$($lines),+];
 487            let (total_cells, longest_line_cells) =
 488                test_lines.iter().copied()
 489                    .map(line_cells_count)
 490                    .fold((0, 0), |state, cells| (state.0 + cells, cmp::max(state.1, cells)));
 491            let contains_tab_char = test_lines.iter().copied()
 492                .map(str::chars).flatten().find(|&c| c == '\t');
 493            let columns = if contains_tab_char.is_some() {
 494                // This avoids tabs at end of lines causing whitespace-eating line wraps...
 495                vec![longest_line_cells + 1]
 496            } else {
 497                // Alacritty has issues with 2 columns, use 3 as the minimum for now.
 498                vec![3, longest_line_cells / 2, longest_line_cells + 1]
 499            };
 500            test_hyperlink!(
 501                columns;
 502                total_cells;
 503                test_lines.iter().copied();
 504                $hyperlink_kind
 505            )
 506        } };
 507
 508        ($columns:expr; $total_cells:expr; $lines:expr; $hyperlink_kind:ident) => { {
 509            use crate::terminal_hyperlinks::tests::{ test_hyperlink, HyperlinkKind };
 510
 511            let source_location = format!("{}:{}", std::file!(), std::line!());
 512            for columns in $columns {
 513                test_hyperlink(columns, $total_cells, $lines, HyperlinkKind::$hyperlink_kind,
 514                    &source_location);
 515            }
 516        } };
 517    }
 518
 519    mod path {
 520        /// ๐Ÿ‘‰ := **hovered** on following char
 521        ///
 522        /// ๐Ÿ‘ˆ := **hovered** on wide char spacer of previous full width char
 523        ///
 524        /// **`โ€นโ€บ`** := expected **hyperlink** match
 525        ///
 526        /// **`ยซยป`** := expected **path**, **row**, and **column** capture groups
 527        ///
 528        /// [**`cโ‚€, cโ‚, โ€ฆ, cโ‚™;`**]โ‚’โ‚šโ‚œ := use specified terminal widths of `cโ‚€, cโ‚, โ€ฆ, cโ‚™` **columns**
 529        /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
 530        ///
 531        macro_rules! test_path {
 532            ($($lines:literal),+) => { test_hyperlink!($($lines),+; Path) };
 533        }
 534
 535        #[test]
 536        fn simple() {
 537            // Rust paths
 538            // Just the path
 539            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยปโ€บ");
 540            test_path!("โ€นยซ/test/cool๐Ÿ‘‰.rsยปโ€บ");
 541
 542            // path and line
 543            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:ยซ4ยปโ€บ");
 544            test_path!("โ€นยซ/test/cool.rsยป๐Ÿ‘‰:ยซ4ยปโ€บ");
 545            test_path!("โ€นยซ/test/cool.rsยป:ยซ๐Ÿ‘‰4ยปโ€บ");
 546            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป)โ€บ");
 547            test_path!("โ€นยซ/test/cool.rsยป๐Ÿ‘‰(ยซ4ยป)โ€บ");
 548            test_path!("โ€นยซ/test/cool.rsยป(ยซ๐Ÿ‘‰4ยป)โ€บ");
 549            test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป๐Ÿ‘‰)โ€บ");
 550
 551            // path, line, and column
 552            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:ยซ4ยป:ยซ2ยปโ€บ");
 553            test_path!("โ€นยซ/test/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ");
 554            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป,ยซ2ยป)โ€บ");
 555            test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป๐Ÿ‘‰,ยซ2ยป)โ€บ");
 556
 557            // path, line, column, and ':' suffix
 558            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:ยซ4ยป:ยซ2ยปโ€บ:");
 559            test_path!("โ€นยซ/test/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ:");
 560            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป,ยซ2ยป)โ€บ:");
 561            test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป,ยซ2ยป๐Ÿ‘‰)โ€บ:");
 562            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:(ยซ4ยป,ยซ2ยป)โ€บ:");
 563            test_path!("โ€นยซ/test/cool.rsยป:(ยซ4ยป,ยซ2ยป๐Ÿ‘‰)โ€บ:");
 564            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:(ยซ4ยป:ยซ2ยป)โ€บ:");
 565            test_path!("โ€นยซ/test/cool.rsยป:(ยซ4ยป:ยซ2ยป๐Ÿ‘‰)โ€บ:");
 566            test_path!("/test/cool.rs:4:2๐Ÿ‘‰:", "What is this?");
 567            test_path!("/test/cool.rs(4,2)๐Ÿ‘‰:", "What is this?");
 568
 569            // path, line, column, and description
 570            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ:Error!");
 571            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ:Error!");
 572
 573            // Cargo output
 574            test_path!("    Compiling Cool ๐Ÿ‘‰(/test/Cool)");
 575            test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰test/Coolยปโ€บ)");
 576            test_path!("    Compiling Cool (/test/Cool๐Ÿ‘‰)");
 577
 578            // Python
 579            test_path!("โ€นยซawe๐Ÿ‘‰some.pyยปโ€บ");
 580            test_path!("โ€นยซ๐Ÿ‘‰aยปโ€บ ");
 581
 582            test_path!("    โ€นF๐Ÿ‘‰ile \"ยซ/awesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 583            test_path!("    โ€นFile \"ยซ/awe๐Ÿ‘‰some.pyยป\", line ยซ42ยปโ€บ");
 584            test_path!("    โ€นFile \"ยซ/awesome.pyยป๐Ÿ‘‰\", line ยซ42ยปโ€บ: Wat?");
 585            test_path!("    โ€นFile \"ยซ/awesome.pyยป\", line ยซ4๐Ÿ‘‰2ยปโ€บ");
 586        }
 587
 588        #[test]
 589        fn simple_with_descriptions() {
 590            // path, line, column and description
 591            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:ยซ4ยป:ยซ2ยปโ€บ:ไพ‹Descไพ‹ไพ‹ไพ‹");
 592            test_path!("โ€นยซ/test/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ:ไพ‹Descไพ‹ไพ‹ไพ‹");
 593            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป,ยซ2ยป)โ€บ:ไพ‹Descไพ‹ไพ‹ไพ‹");
 594            test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป๐Ÿ‘‰,ยซ2ยป)โ€บ:ไพ‹Descไพ‹ไพ‹ไพ‹");
 595
 596            // path, line, column and description w/extra colons
 597            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป:ยซ4ยป:ยซ2ยปโ€บ::ไพ‹Descไพ‹ไพ‹ไพ‹");
 598            test_path!("โ€นยซ/test/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ::ไพ‹Descไพ‹ไพ‹ไพ‹");
 599            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป,ยซ2ยป)โ€บ::ไพ‹Descไพ‹ไพ‹ไพ‹");
 600            test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป,ยซ2ยป๐Ÿ‘‰)โ€บ::ไพ‹Descไพ‹ไพ‹ไพ‹");
 601        }
 602
 603        #[test]
 604        fn multiple_same_line() {
 605            test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยปโ€บ /test/cool.rs");
 606            test_path!("/test/cool.rs โ€นยซ/๐Ÿ‘‰test/cool.rsยปโ€บ");
 607
 608            test_path!(
 609                "โ€นยซ๐Ÿฆ€ multiple_๐Ÿ‘‰same_line ๐Ÿฆ€ยป ๐Ÿšฃยซ4ยป ๐Ÿ›๏ธยซ2ยปโ€บ: ๐Ÿฆ€ multiple_same_line ๐Ÿฆ€ ๐Ÿšฃ4 ๐Ÿ›๏ธ2:"
 610            );
 611            test_path!(
 612                "๐Ÿฆ€ multiple_same_line ๐Ÿฆ€ ๐Ÿšฃ4 ๐Ÿ›๏ธ2 โ€นยซ๐Ÿฆ€ multiple_๐Ÿ‘‰same_line ๐Ÿฆ€ยป ๐Ÿšฃยซ4ยป ๐Ÿ›๏ธยซ2ยปโ€บ:"
 613            );
 614
 615            // ls output (tab separated)
 616            test_path!(
 617                "โ€นยซCarg๐Ÿ‘‰o.tomlยปโ€บ\t\texperiments\t\tnotebooks\t\trust-toolchain.toml\ttooling"
 618            );
 619            test_path!(
 620                "Cargo.toml\t\tโ€นยซexper๐Ÿ‘‰imentsยปโ€บ\t\tnotebooks\t\trust-toolchain.toml\ttooling"
 621            );
 622            test_path!(
 623                "Cargo.toml\t\texperiments\t\tโ€นยซnote๐Ÿ‘‰booksยปโ€บ\t\trust-toolchain.toml\ttooling"
 624            );
 625            test_path!(
 626                "Cargo.toml\t\texperiments\t\tnotebooks\t\tโ€นยซrust-t๐Ÿ‘‰oolchain.tomlยปโ€บ\ttooling"
 627            );
 628            test_path!(
 629                "Cargo.toml\t\texperiments\t\tnotebooks\t\trust-toolchain.toml\tโ€นยซtoo๐Ÿ‘‰lingยปโ€บ"
 630            );
 631        }
 632
 633        #[test]
 634        fn colons_galore() {
 635            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ");
 636            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ:");
 637            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ");
 638            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ:");
 639            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ1ยป)โ€บ");
 640            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ1ยป)โ€บ:");
 641            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ1ยป,ยซ618ยป)โ€บ");
 642            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ1ยป,ยซ618ยป)โ€บ:");
 643            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป::ยซ42ยปโ€บ");
 644            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป::ยซ42ยปโ€บ:");
 645            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ1ยป,ยซ618ยป)โ€บ::");
 646        }
 647
 648        #[test]
 649        fn quotes_and_brackets() {
 650            test_path!("\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ\"");
 651            test_path!("'โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ'");
 652            test_path!("`โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ`");
 653
 654            test_path!("[โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ]");
 655            test_path!("(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ)");
 656            test_path!("{โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ}");
 657            test_path!("<โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ>");
 658
 659            test_path!("[\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ\"]");
 660            test_path!("'(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ)'");
 661
 662            test_path!("\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ\"");
 663            test_path!("'โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ'");
 664            test_path!("`โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ`");
 665
 666            test_path!("[โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ]");
 667            test_path!("(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ)");
 668            test_path!("{โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ}");
 669            test_path!("<โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ>");
 670
 671            test_path!("[\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยป:ยซ2ยปโ€บ\"]");
 672
 673            test_path!("\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ\"");
 674            test_path!("'โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ'");
 675            test_path!("`โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ`");
 676
 677            test_path!("[โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ]");
 678            test_path!("(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ)");
 679            test_path!("{โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ}");
 680            test_path!("<โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ>");
 681
 682            test_path!("[\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป)โ€บ\"]");
 683
 684            test_path!("\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ\"");
 685            test_path!("'โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ'");
 686            test_path!("`โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ`");
 687
 688            test_path!("[โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ]");
 689            test_path!("(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ)");
 690            test_path!("{โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ}");
 691            test_path!("<โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ>");
 692
 693            test_path!("[\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป(ยซ4ยป,ยซ2ยป)โ€บ\"]");
 694
 695            // Imbalanced
 696            test_path!("([โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ] was here...)");
 697            test_path!("[Here's <โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ>]");
 698            test_path!("('โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ' was here...)");
 699            test_path!("[Here's `โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ`]");
 700        }
 701
 702        #[test]
 703        fn trailing_punctuation() {
 704            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยปโ€บ:,..");
 705            test_path!("/test/cool.rs:,๐Ÿ‘‰..");
 706            test_path!("โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ:,");
 707            test_path!("/test/cool.rs:4:๐Ÿ‘‰,");
 708            test_path!("[\"โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ\"]:,");
 709            test_path!("'(โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ),,'...");
 710            test_path!("('โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ'::: was here...)");
 711            test_path!("[Here's <โ€นยซ/test/co๐Ÿ‘‰ol.rsยป:ยซ4ยปโ€บ>]::: ");
 712        }
 713
 714        #[test]
 715        fn word_wide_chars() {
 716            // Rust paths
 717            test_path!("โ€นยซ/๐Ÿ‘‰ไพ‹/cool.rsยปโ€บ");
 718            test_path!("โ€นยซ/ไพ‹๐Ÿ‘ˆ/cool.rsยปโ€บ");
 719            test_path!("โ€นยซ/ไพ‹/cool.rsยป:ยซ๐Ÿ‘‰4ยปโ€บ");
 720            test_path!("โ€นยซ/ไพ‹/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ");
 721
 722            // Cargo output
 723            test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰ไพ‹/Coolยปโ€บ)");
 724            test_path!("    Compiling Cool (โ€นยซ/ไพ‹๐Ÿ‘ˆ/Coolยปโ€บ)");
 725
 726            test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยปโ€บ)");
 727            test_path!("    Compiling Cool (โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยปโ€บ)");
 728            test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยป:ยซ4ยป:ยซ2ยปโ€บ)");
 729            test_path!("    Compiling Cool (โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยป(ยซ4ยป,ยซ2ยป)โ€บ)");
 730
 731            test_path!("    --> โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยปโ€บ");
 732            test_path!("    ::: โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยปโ€บ");
 733            test_path!("    --> โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยป:ยซ4ยป:ยซ2ยปโ€บ");
 734            test_path!("    ::: โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยป(ยซ4ยป,ยซ2ยป)โ€บ");
 735            test_path!("    panicked at โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยป:ยซ4ยป:ยซ2ยปโ€บ:");
 736            test_path!("    panicked at โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยป(ยซ4ยป,ยซ2ยป)โ€บ:");
 737            test_path!("    at โ€นยซ/๐Ÿ‘‰ไพ‹/Cool Spacesยป:ยซ4ยป:ยซ2ยปโ€บ");
 738            test_path!("    at โ€นยซ/ไพ‹๐Ÿ‘ˆ/Cool Spacesยป(ยซ4ยป,ยซ2ยป)โ€บ");
 739
 740            // Python
 741            test_path!("โ€นยซ๐Ÿ‘‰ไพ‹wesome.pyยปโ€บ");
 742            test_path!("โ€นยซไพ‹๐Ÿ‘ˆwesome.pyยปโ€บ");
 743            test_path!("    โ€นFile \"ยซ/๐Ÿ‘‰ไพ‹wesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 744            test_path!("    โ€นFile \"ยซ/ไพ‹๐Ÿ‘ˆwesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 745        }
 746
 747        #[test]
 748        fn non_word_wide_chars() {
 749            // Mojo diagnostic message
 750            test_path!("    โ€นFile \"ยซ/awe๐Ÿ‘‰some.๐Ÿ”ฅยป\", line ยซ42ยปโ€บ: Wat?");
 751            test_path!("    โ€นFile \"ยซ/awesome๐Ÿ‘‰.๐Ÿ”ฅยป\", line ยซ42ยปโ€บ: Wat?");
 752            test_path!("    โ€นFile \"ยซ/awesome.๐Ÿ‘‰๐Ÿ”ฅยป\", line ยซ42ยปโ€บ: Wat?");
 753            test_path!("    โ€นFile \"ยซ/awesome.๐Ÿ”ฅ๐Ÿ‘ˆยป\", line ยซ42ยปโ€บ: Wat?");
 754        }
 755
 756        /// These likely rise to the level of being worth fixing.
 757        mod issues {
 758            #[test]
 759            // <https://github.com/alacritty/alacritty/issues/8586>
 760            fn issue_alacritty_8586() {
 761                // Rust paths
 762                test_path!("โ€นยซ/๐Ÿ‘‰ไพ‹/cool.rsยปโ€บ");
 763                test_path!("โ€นยซ/ไพ‹๐Ÿ‘ˆ/cool.rsยปโ€บ");
 764                test_path!("โ€นยซ/ไพ‹/cool.rsยป:ยซ๐Ÿ‘‰4ยปโ€บ");
 765                test_path!("โ€นยซ/ไพ‹/cool.rsยป:ยซ4ยป:ยซ๐Ÿ‘‰2ยปโ€บ");
 766
 767                // Cargo output
 768                test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰ไพ‹/Coolยปโ€บ)");
 769                test_path!("    Compiling Cool (โ€นยซ/ไพ‹๐Ÿ‘ˆ/Coolยปโ€บ)");
 770
 771                // Python
 772                test_path!("โ€นยซ๐Ÿ‘‰ไพ‹wesome.pyยปโ€บ");
 773                test_path!("โ€นยซไพ‹๐Ÿ‘ˆwesome.pyยปโ€บ");
 774                test_path!("    โ€นFile \"ยซ/๐Ÿ‘‰ไพ‹wesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 775                test_path!("    โ€นFile \"ยซ/ไพ‹๐Ÿ‘ˆwesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 776            }
 777
 778            #[test]
 779            // <https://github.com/zed-industries/zed/issues/12338>
 780            fn issue_12338_regex() {
 781                // Issue #12338
 782                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซ'test file ๐Ÿ‘‰1.txt'ยปโ€บ");
 783                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซ๐Ÿ‘‰'test file 1.txt'ยปโ€บ");
 784            }
 785
 786            #[test]
 787            // <https://github.com/zed-industries/zed/issues/12338>
 788            fn issue_12338() {
 789                // Issue #12338
 790                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซtest๐Ÿ‘‰ใ€2.txtยปโ€บ");
 791                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซtestใ€๐Ÿ‘ˆ2.txtยปโ€บ");
 792                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซtest๐Ÿ‘‰ใ€‚3.txtยปโ€บ");
 793                test_path!(".rw-r--r--     0     staff 05-27 14:03 โ€นยซtestใ€‚๐Ÿ‘ˆ3.txtยปโ€บ");
 794
 795                // Rust paths
 796                test_path!("โ€นยซ/๐Ÿ‘‰๐Ÿƒ/๐Ÿฆ€.rsยปโ€บ");
 797                test_path!("โ€นยซ/๐Ÿƒ๐Ÿ‘ˆ/๐Ÿฆ€.rsยปโ€บ");
 798                test_path!("โ€นยซ/๐Ÿƒ/๐Ÿ‘‰๐Ÿฆ€.rsยป:ยซ4ยปโ€บ");
 799                test_path!("โ€นยซ/๐Ÿƒ/๐Ÿฆ€๐Ÿ‘ˆ.rsยป:ยซ4ยป:ยซ2ยปโ€บ");
 800
 801                // Cargo output
 802                test_path!("    Compiling Cool (โ€นยซ/๐Ÿ‘‰๐Ÿƒ/Coolยปโ€บ)");
 803                test_path!("    Compiling Cool (โ€นยซ/๐Ÿƒ๐Ÿ‘ˆ/Coolยปโ€บ)");
 804
 805                // Python
 806                test_path!("โ€นยซ๐Ÿ‘‰๐Ÿƒwesome.pyยปโ€บ");
 807                test_path!("โ€นยซ๐Ÿƒ๐Ÿ‘ˆwesome.pyยปโ€บ");
 808                test_path!("    โ€นFile \"ยซ/๐Ÿ‘‰๐Ÿƒwesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 809                test_path!("    โ€นFile \"ยซ/๐Ÿƒ๐Ÿ‘ˆwesome.pyยป\", line ยซ42ยปโ€บ: Wat?");
 810
 811                // Mojo
 812                test_path!("โ€นยซ/awe๐Ÿ‘‰some.๐Ÿ”ฅยปโ€บ is some good Mojo!");
 813                test_path!("โ€นยซ/awesome๐Ÿ‘‰.๐Ÿ”ฅยปโ€บ is some good Mojo!");
 814                test_path!("โ€นยซ/awesome.๐Ÿ‘‰๐Ÿ”ฅยปโ€บ is some good Mojo!");
 815                test_path!("โ€นยซ/awesome.๐Ÿ”ฅ๐Ÿ‘ˆยปโ€บ is some good Mojo!");
 816                test_path!("    โ€นFile \"ยซ/๐Ÿ‘‰๐Ÿƒwesome.๐Ÿ”ฅยป\", line ยซ42ยปโ€บ: Wat?");
 817                test_path!("    โ€นFile \"ยซ/๐Ÿƒ๐Ÿ‘ˆwesome.๐Ÿ”ฅยป\", line ยซ42ยปโ€บ: Wat?");
 818            }
 819
 820            #[test]
 821            // <https://github.com/zed-industries/zed/issues/40202>
 822            fn issue_40202() {
 823                // Elixir
 824                test_path!("[โ€นยซlib/blitz_apex_๐Ÿ‘‰server/stats/aggregate_rank_stats.exยป:ยซ35ยปโ€บ: BlitzApexServer.Stats.AggregateRankStats.update/2]
 825                1 #=> 1");
 826            }
 827
 828            #[test]
 829            // <https://github.com/zed-industries/zed/issues/28194>
 830            fn issue_28194() {
 831                test_path!(
 832                    "โ€นยซtest/c๐Ÿ‘‰ontrollers/template_items_controller_test.rbยป:ยซ20ยปโ€บ:in 'block (2 levels) in <class:TemplateItemsControllerTest>'"
 833                );
 834            }
 835
 836            #[test]
 837            #[cfg_attr(
 838                not(target_os = "windows"),
 839                should_panic(
 840                    expected = "Path = ยซ/test/cool.rs:4:NotDescยป, at grid cells (0, 1)..=(7, 2)"
 841                )
 842            )]
 843            #[cfg_attr(
 844                target_os = "windows",
 845                should_panic(
 846                    expected = r#"Path = ยซC:\\test\\cool.rs:4:NotDescยป, at grid cells (0, 1)..=(8, 1)"#
 847                )
 848            )]
 849            // PathWithPosition::parse_str considers "/test/co๐Ÿ‘‰ol.rs:4:NotDesc" invalid input, but
 850            // still succeeds and truncates the part after the position. Ideally this would be
 851            // parsed as the path "/test/co๐Ÿ‘‰ol.rs:4:NotDesc" with no position.
 852            fn path_with_position_parse_str() {
 853                test_path!("`โ€นยซ/test/co๐Ÿ‘‰ol.rs:4:NotDescยปโ€บ`");
 854                test_path!("<โ€นยซ/test/co๐Ÿ‘‰ol.rs:4:NotDescยปโ€บ>");
 855
 856                test_path!("'โ€นยซ(/test/co๐Ÿ‘‰ol.rs:4:2)ยปโ€บ'");
 857                test_path!("'โ€นยซ(/test/co๐Ÿ‘‰ol.rs(4))ยปโ€บ'");
 858                test_path!("'โ€นยซ(/test/co๐Ÿ‘‰ol.rs(4,2))ยปโ€บ'");
 859            }
 860        }
 861
 862        /// Minor issues arguably not important enough to fix/workaround...
 863        mod nits {
 864            #[test]
 865            fn alacritty_bugs_with_two_columns() {
 866                test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rsยป(ยซ4ยป)โ€บ");
 867                test_path!("โ€นยซ/test/cool.rsยป(ยซ๐Ÿ‘‰4ยป)โ€บ");
 868                test_path!("โ€นยซ/test/cool.rsยป(ยซ4ยป,ยซ๐Ÿ‘‰2ยป)โ€บ");
 869
 870                // Python
 871                test_path!("โ€นยซawe๐Ÿ‘‰some.pyยปโ€บ");
 872            }
 873
 874            #[test]
 875            #[cfg_attr(
 876                not(target_os = "windows"),
 877                should_panic(
 878                    expected = "Path = ยซ/test/cool.rsยป, line = 1, at grid cells (0, 0)..=(9, 0)"
 879                )
 880            )]
 881            #[cfg_attr(
 882                target_os = "windows",
 883                should_panic(
 884                    expected = r#"Path = ยซC:\\test\\cool.rsยป, line = 1, at grid cells (0, 0)..=(9, 2)"#
 885                )
 886            )]
 887            fn invalid_row_column_should_be_part_of_path() {
 888                test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rs:1:618033988749ยปโ€บ");
 889                test_path!("โ€นยซ/๐Ÿ‘‰test/cool.rs(1,618033988749)ยปโ€บ");
 890            }
 891
 892            #[test]
 893            #[cfg_attr(
 894                not(target_os = "windows"),
 895                should_panic(expected = "Path = ยซ/te:st/co:ol.r:s:4:2::::::ยป")
 896            )]
 897            #[cfg_attr(
 898                target_os = "windows",
 899                should_panic(expected = r#"Path = ยซC:\\te:st\\co:ol.r:s:4:2::::::ยป"#)
 900            )]
 901            fn many_trailing_colons_should_be_parsed_as_part_of_the_path() {
 902                test_path!("โ€นยซ/te:st/๐Ÿ‘‰co:ol.r:s:4:2::::::ยปโ€บ");
 903                test_path!("/test/cool.rs:::๐Ÿ‘‰:");
 904            }
 905        }
 906
 907        mod windows {
 908            // Lots of fun to be had with long file paths (verbatim) and UNC paths on Windows.
 909            // See <https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation>
 910            // See <https://users.rust-lang.org/t/understanding-windows-paths/58583>
 911            // See <https://github.com/rust-lang/cargo/issues/13919>
 912
 913            #[test]
 914            fn default_prompts() {
 915                // Windows command prompt
 916                test_path!(r#"โ€นยซC:\Users\someone\๐Ÿ‘‰testยปโ€บ>"#);
 917                test_path!(r#"C:\Users\someone\test๐Ÿ‘‰>"#);
 918
 919                // Windows PowerShell
 920                test_path!(r#"PS โ€นยซC:\Users\someone\๐Ÿ‘‰test\cool.rsยปโ€บ>"#);
 921                test_path!(r#"PS C:\Users\someone\test\cool.rs๐Ÿ‘‰>"#);
 922            }
 923
 924            #[test]
 925            fn unc() {
 926                test_path!(r#"โ€นยซ\\server\share\๐Ÿ‘‰test\cool.rsยปโ€บ"#);
 927                test_path!(r#"โ€นยซ\\server\share\test\cool๐Ÿ‘‰.rsยปโ€บ"#);
 928            }
 929
 930            mod issues {
 931                #[test]
 932                fn issue_verbatim() {
 933                    test_path!(r#"โ€นยซ\\?\C:\๐Ÿ‘‰test\cool.rsยปโ€บ"#);
 934                    test_path!(r#"โ€นยซ\\?\C:\test\cool๐Ÿ‘‰.rsยปโ€บ"#);
 935                }
 936
 937                #[test]
 938                fn issue_verbatim_unc() {
 939                    test_path!(r#"โ€นยซ\\?\UNC\server\share\๐Ÿ‘‰test\cool.rsยปโ€บ"#);
 940                    test_path!(r#"โ€นยซ\\?\UNC\server\share\test\cool๐Ÿ‘‰.rsยปโ€บ"#);
 941                }
 942            }
 943        }
 944
 945        mod perf {
 946            use super::super::*;
 947            use crate::TerminalSettings;
 948            use alacritty_terminal::{
 949                event::VoidListener,
 950                grid::Dimensions,
 951                index::{Column, Point as AlacPoint},
 952                term::test::mock_term,
 953                term::{Term, search::Match},
 954            };
 955            use settings::{self, Settings, SettingsContent};
 956            use std::{cell::RefCell, rc::Rc};
 957            use util_macros::perf;
 958
 959            fn build_test_term(line: &str) -> (Term<VoidListener>, AlacPoint) {
 960                let content = line.repeat(500);
 961                let term = mock_term(&content);
 962                let point = AlacPoint::new(
 963                    term.grid().bottommost_line() - 1,
 964                    Column(term.grid().last_column().0 / 2),
 965                );
 966
 967                (term, point)
 968            }
 969
 970            #[perf]
 971            pub fn cargo_hyperlink_benchmark() {
 972                const LINE: &str = "    Compiling terminal v0.1.0 (/Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal)\r\n";
 973                thread_local! {
 974                    static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
 975                        build_test_term(LINE);
 976                }
 977                TEST_TERM_AND_POINT.with(|(term, point)| {
 978                    assert!(
 979                        find_from_grid_point_bench(term, *point).is_some(),
 980                        "Hyperlink should have been found"
 981                    );
 982                });
 983            }
 984
 985            #[perf]
 986            pub fn rust_hyperlink_benchmark() {
 987                const LINE: &str = "    --> /Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal/terminal.rs:1000:42\r\n";
 988                thread_local! {
 989                    static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
 990                        build_test_term(LINE);
 991                }
 992                TEST_TERM_AND_POINT.with(|(term, point)| {
 993                    assert!(
 994                        find_from_grid_point_bench(term, *point).is_some(),
 995                        "Hyperlink should have been found"
 996                    );
 997                });
 998            }
 999
1000            #[perf]
1001            pub fn ls_hyperlink_benchmark() {
1002                const LINE: &str = "Cargo.toml        experiments        notebooks        rust-toolchain.toml    tooling\r\n";
1003                thread_local! {
1004                    static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
1005                        build_test_term(LINE);
1006                }
1007                TEST_TERM_AND_POINT.with(|(term, point)| {
1008                    assert!(
1009                        find_from_grid_point_bench(term, *point).is_some(),
1010                        "Hyperlink should have been found"
1011                    );
1012                });
1013            }
1014
1015            pub fn find_from_grid_point_bench(
1016                term: &Term<VoidListener>,
1017                point: AlacPoint,
1018            ) -> Option<(String, bool, Match)> {
1019                const PATH_HYPERLINK_TIMEOUT_MS: u64 = 1000;
1020
1021                thread_local! {
1022                    static TEST_REGEX_SEARCHES: RefCell<RegexSearches> =
1023                        RefCell::new({
1024                            let default_settings_content: Rc<SettingsContent> =
1025                                settings::parse_json_with_comments(&settings::default_settings())
1026                                    .unwrap();
1027                            let default_terminal_settings =
1028                                TerminalSettings::from_settings(&default_settings_content);
1029
1030                            RegexSearches::new(
1031                                &default_terminal_settings.path_hyperlink_regexes,
1032                                PATH_HYPERLINK_TIMEOUT_MS
1033                            )
1034                        });
1035                }
1036
1037                TEST_REGEX_SEARCHES.with(|regex_searches| {
1038                    find_from_grid_point(&term, point, &mut regex_searches.borrow_mut())
1039                })
1040            }
1041        }
1042    }
1043
1044    mod file_iri {
1045        // File IRIs have a ton of use cases, most of which we currently do not support. A few of
1046        // those cases are documented here as tests which are expected to fail.
1047        // See https://en.wikipedia.org/wiki/File_URI_scheme
1048
1049        /// [**`cโ‚€, cโ‚, โ€ฆ, cโ‚™;`**]โ‚’โ‚šโ‚œ := use specified terminal widths of `cโ‚€, cโ‚, โ€ฆ, cโ‚™` **columns**
1050        /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
1051        ///
1052        macro_rules! test_file_iri {
1053            ($file_iri:literal) => { { test_hyperlink!(concat!("โ€นยซ๐Ÿ‘‰", $file_iri, "ยปโ€บ"); FileIri) } };
1054        }
1055
1056        #[cfg(not(target_os = "windows"))]
1057        #[test]
1058        fn absolute_file_iri() {
1059            test_file_iri!("file:///test/cool/index.rs");
1060            test_file_iri!("file:///test/cool/");
1061        }
1062
1063        mod issues {
1064            #[cfg(not(target_os = "windows"))]
1065            #[test]
1066            #[should_panic(expected = "Path = ยซ/test/แฟฌฯŒฮดฮฟฯ‚/ยป, at grid cells (0, 0)..=(15, 1)")]
1067            fn issue_file_iri_with_percent_encoded_characters() {
1068                // Non-space characters
1069                // file:///test/แฟฌฯŒฮดฮฟฯ‚/
1070                test_file_iri!("file:///test/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82/"); // URI
1071
1072                // Spaces
1073                test_file_iri!("file:///te%20st/co%20ol/index.rs");
1074                test_file_iri!("file:///te%20st/co%20ol/");
1075            }
1076        }
1077
1078        #[cfg(target_os = "windows")]
1079        mod windows {
1080            mod issues {
1081                // The test uses Url::to_file_path(), but it seems that the Url crate doesn't
1082                // support relative file IRIs.
1083                #[test]
1084                #[should_panic(
1085                    expected = r#"Failed to interpret file IRI `file:/test/cool/index.rs` as a path"#
1086                )]
1087                fn issue_relative_file_iri() {
1088                    test_file_iri!("file:/test/cool/index.rs");
1089                    test_file_iri!("file:/test/cool/");
1090                }
1091
1092                // See https://en.wikipedia.org/wiki/File_URI_scheme
1093                // https://github.com/zed-industries/zed/issues/39189
1094                #[test]
1095                #[should_panic(
1096                    expected = r#"Path = ยซC:\\test\\cool\\index.rsยป, at grid cells (0, 0)..=(9, 1)"#
1097                )]
1098                fn issue_39189() {
1099                    test_file_iri!("file:///C:/test/cool/index.rs");
1100                    test_file_iri!("file:///C:/test/cool/");
1101                }
1102
1103                #[test]
1104                #[should_panic(
1105                    expected = r#"Path = ยซC:\\test\\แฟฌฯŒฮดฮฟฯ‚\\ยป, at grid cells (0, 0)..=(16, 1)"#
1106                )]
1107                fn issue_file_iri_with_percent_encoded_characters() {
1108                    // Non-space characters
1109                    // file:///test/แฟฌฯŒฮดฮฟฯ‚/
1110                    test_file_iri!("file:///C:/test/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82/"); // URI
1111
1112                    // Spaces
1113                    test_file_iri!("file:///C:/te%20st/co%20ol/index.rs");
1114                    test_file_iri!("file:///C:/te%20st/co%20ol/");
1115                }
1116            }
1117        }
1118    }
1119
1120    mod iri {
1121        /// [**`cโ‚€, cโ‚, โ€ฆ, cโ‚™;`**]โ‚’โ‚šโ‚œ := use specified terminal widths of `cโ‚€, cโ‚, โ€ฆ, cโ‚™` **columns**
1122        /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
1123        ///
1124        macro_rules! test_iri {
1125            ($iri:literal) => { { test_hyperlink!(concat!("โ€นยซ๐Ÿ‘‰", $iri, "ยปโ€บ"); Iri) } };
1126        }
1127
1128        #[test]
1129        fn simple() {
1130            // In the order they appear in URL_REGEX, except 'file://' which is treated as a path
1131            test_iri!("ipfs://test/cool.ipfs");
1132            test_iri!("ipns://test/cool.ipns");
1133            test_iri!("magnet://test/cool.git");
1134            test_iri!("mailto:someone@somewhere.here");
1135            test_iri!("gemini://somewhere.here");
1136            test_iri!("gopher://somewhere.here");
1137            test_iri!("http://test/cool/index.html");
1138            test_iri!("http://10.10.10.10:1111/cool.html");
1139            test_iri!("http://test/cool/index.html?amazing=1");
1140            test_iri!("http://test/cool/index.html#right%20here");
1141            test_iri!("http://test/cool/index.html?amazing=1#right%20here");
1142            test_iri!("https://test/cool/index.html");
1143            test_iri!("https://10.10.10.10:1111/cool.html");
1144            test_iri!("https://test/cool/index.html?amazing=1");
1145            test_iri!("https://test/cool/index.html#right%20here");
1146            test_iri!("https://test/cool/index.html?amazing=1#right%20here");
1147            test_iri!("news://test/cool.news");
1148            test_iri!("git://test/cool.git");
1149            test_iri!("ssh://user@somewhere.over.here:12345/test/cool.git");
1150            test_iri!("ftp://test/cool.ftp");
1151        }
1152
1153        #[test]
1154        fn wide_chars() {
1155            // In the order they appear in URL_REGEX, except 'file://' which is treated as a path
1156            test_iri!("ipfs://ไพ‹๐Ÿƒ๐Ÿฆ€/cool.ipfs");
1157            test_iri!("ipns://ไพ‹๐Ÿƒ๐Ÿฆ€/cool.ipns");
1158            test_iri!("magnet://ไพ‹๐Ÿƒ๐Ÿฆ€/cool.git");
1159            test_iri!("mailto:someone@somewhere.here");
1160            test_iri!("gemini://somewhere.here");
1161            test_iri!("gopher://somewhere.here");
1162            test_iri!("http://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html");
1163            test_iri!("http://10.10.10.10:1111/cool.html");
1164            test_iri!("http://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html?amazing=1");
1165            test_iri!("http://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html#right%20here");
1166            test_iri!("http://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html?amazing=1#right%20here");
1167            test_iri!("https://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html");
1168            test_iri!("https://10.10.10.10:1111/cool.html");
1169            test_iri!("https://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html?amazing=1");
1170            test_iri!("https://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html#right%20here");
1171            test_iri!("https://ไพ‹๐Ÿƒ๐Ÿฆ€/cool/index.html?amazing=1#right%20here");
1172            test_iri!("news://ไพ‹๐Ÿƒ๐Ÿฆ€/cool.news");
1173            test_iri!("git://ไพ‹/cool.git");
1174            test_iri!("ssh://user@somewhere.over.here:12345/ไพ‹๐Ÿƒ๐Ÿฆ€/cool.git");
1175            test_iri!("ftp://ไพ‹๐Ÿƒ๐Ÿฆ€/cool.ftp");
1176        }
1177
1178        // There are likely more tests needed for IRI vs URI
1179        #[test]
1180        fn iris() {
1181            // These refer to the same location, see example here:
1182            // <https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier#Compatibility>
1183            test_iri!("https://en.wiktionary.org/wiki/แฟฌฯŒฮดฮฟฯ‚"); // IRI
1184            test_iri!("https://en.wiktionary.org/wiki/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82"); // URI
1185        }
1186
1187        #[test]
1188        #[should_panic(expected = "Expected a path, but was a iri")]
1189        fn file_is_a_path() {
1190            test_iri!("file://test/cool/index.rs");
1191        }
1192    }
1193
1194    #[derive(Debug, PartialEq)]
1195    enum HyperlinkKind {
1196        FileIri,
1197        Iri,
1198        Path,
1199    }
1200
1201    struct ExpectedHyperlink {
1202        hovered_grid_point: AlacPoint,
1203        hovered_char: char,
1204        hyperlink_kind: HyperlinkKind,
1205        iri_or_path: String,
1206        row: Option<u32>,
1207        column: Option<u32>,
1208        hyperlink_match: RangeInclusive<AlacPoint>,
1209    }
1210
1211    /// Converts to Windows style paths on Windows, like path!(), but at runtime for improved test
1212    /// readability.
1213    fn build_term_from_test_lines<'a>(
1214        hyperlink_kind: HyperlinkKind,
1215        term_size: TermSize,
1216        test_lines: impl Iterator<Item = &'a str>,
1217    ) -> (Term<VoidListener>, ExpectedHyperlink) {
1218        #[derive(Default, Eq, PartialEq)]
1219        enum HoveredState {
1220            #[default]
1221            HoveredScan,
1222            HoveredNextChar,
1223            Done,
1224        }
1225
1226        #[derive(Default, Eq, PartialEq)]
1227        enum MatchState {
1228            #[default]
1229            MatchScan,
1230            MatchNextChar,
1231            Match(AlacPoint),
1232            Done,
1233        }
1234
1235        #[derive(Default, Eq, PartialEq)]
1236        enum CapturesState {
1237            #[default]
1238            PathScan,
1239            PathNextChar,
1240            Path(AlacPoint),
1241            RowScan,
1242            Row(String),
1243            ColumnScan,
1244            Column(String),
1245            Done,
1246        }
1247
1248        fn prev_input_point_from_term(term: &Term<VoidListener>) -> AlacPoint {
1249            let grid = term.grid();
1250            let cursor = &grid.cursor;
1251            let mut point = cursor.point;
1252
1253            if !cursor.input_needs_wrap {
1254                point = point.sub(term, Boundary::Grid, 1);
1255            }
1256
1257            if grid.index(point).flags.contains(Flags::WIDE_CHAR_SPACER) {
1258                point.column -= 1;
1259            }
1260
1261            point
1262        }
1263
1264        fn end_point_from_prev_input_point(
1265            term: &Term<VoidListener>,
1266            prev_input_point: AlacPoint,
1267        ) -> AlacPoint {
1268            if term
1269                .grid()
1270                .index(prev_input_point)
1271                .flags
1272                .contains(Flags::WIDE_CHAR)
1273            {
1274                prev_input_point.add(term, Boundary::Grid, 1)
1275            } else {
1276                prev_input_point
1277            }
1278        }
1279
1280        fn process_input(term: &mut Term<VoidListener>, c: char) {
1281            match c {
1282                '\t' => term.put_tab(1),
1283                c @ _ => term.input(c),
1284            }
1285        }
1286
1287        let mut hovered_grid_point: Option<AlacPoint> = None;
1288        let mut hyperlink_match = AlacPoint::default()..=AlacPoint::default();
1289        let mut iri_or_path = String::default();
1290        let mut row = None;
1291        let mut column = None;
1292        let mut prev_input_point = AlacPoint::default();
1293        let mut hovered_state = HoveredState::default();
1294        let mut match_state = MatchState::default();
1295        let mut captures_state = CapturesState::default();
1296        let mut term = Term::new(Config::default(), &term_size, VoidListener);
1297
1298        for text in test_lines {
1299            let chars: Box<dyn Iterator<Item = char>> =
1300                if cfg!(windows) && hyperlink_kind == HyperlinkKind::Path {
1301                    Box::new(text.chars().map(|c| if c == '/' { '\\' } else { c })) as _
1302                } else {
1303                    Box::new(text.chars()) as _
1304                };
1305            let mut chars = chars.peekable();
1306            while let Some(c) = chars.next() {
1307                match c {
1308                    '๐Ÿ‘‰' => {
1309                        hovered_state = HoveredState::HoveredNextChar;
1310                    }
1311                    '๐Ÿ‘ˆ' => {
1312                        hovered_grid_point = Some(prev_input_point.add(&term, Boundary::Grid, 1));
1313                    }
1314                    'ยซ' | 'ยป' => {
1315                        captures_state = match captures_state {
1316                            CapturesState::PathScan => CapturesState::PathNextChar,
1317                            CapturesState::PathNextChar => {
1318                                panic!("Should have been handled by char input")
1319                            }
1320                            CapturesState::Path(start_point) => {
1321                                iri_or_path = term.bounds_to_string(
1322                                    start_point,
1323                                    end_point_from_prev_input_point(&term, prev_input_point),
1324                                );
1325                                CapturesState::RowScan
1326                            }
1327                            CapturesState::RowScan => CapturesState::Row(String::new()),
1328                            CapturesState::Row(number) => {
1329                                row = Some(number.parse::<u32>().unwrap());
1330                                CapturesState::ColumnScan
1331                            }
1332                            CapturesState::ColumnScan => CapturesState::Column(String::new()),
1333                            CapturesState::Column(number) => {
1334                                column = Some(number.parse::<u32>().unwrap());
1335                                CapturesState::Done
1336                            }
1337                            CapturesState::Done => {
1338                                panic!("Extra 'ยซ', 'ยป'")
1339                            }
1340                        }
1341                    }
1342                    'โ€น' | 'โ€บ' => {
1343                        match_state = match match_state {
1344                            MatchState::MatchScan => MatchState::MatchNextChar,
1345                            MatchState::MatchNextChar => {
1346                                panic!("Should have been handled by char input")
1347                            }
1348                            MatchState::Match(start_point) => {
1349                                hyperlink_match = start_point
1350                                    ..=end_point_from_prev_input_point(&term, prev_input_point);
1351                                MatchState::Done
1352                            }
1353                            MatchState::Done => {
1354                                panic!("Extra 'โ€น', 'โ€บ'")
1355                            }
1356                        }
1357                    }
1358                    _ => {
1359                        if let CapturesState::Row(number) | CapturesState::Column(number) =
1360                            &mut captures_state
1361                        {
1362                            number.push(c)
1363                        }
1364
1365                        let is_windows_abs_path_start = captures_state
1366                            == CapturesState::PathNextChar
1367                            && cfg!(windows)
1368                            && hyperlink_kind == HyperlinkKind::Path
1369                            && c == '\\'
1370                            && chars.peek().is_some_and(|c| *c != '\\');
1371
1372                        if is_windows_abs_path_start {
1373                            // Convert Unix abs path start into Windows abs path start so that the
1374                            // same test can be used for both OSes.
1375                            term.input('C');
1376                            prev_input_point = prev_input_point_from_term(&term);
1377                            term.input(':');
1378                            process_input(&mut term, c);
1379                        } else {
1380                            process_input(&mut term, c);
1381                            prev_input_point = prev_input_point_from_term(&term);
1382                        }
1383
1384                        if hovered_state == HoveredState::HoveredNextChar {
1385                            hovered_grid_point = Some(prev_input_point);
1386                            hovered_state = HoveredState::Done;
1387                        }
1388                        if captures_state == CapturesState::PathNextChar {
1389                            captures_state = CapturesState::Path(prev_input_point);
1390                        }
1391                        if match_state == MatchState::MatchNextChar {
1392                            match_state = MatchState::Match(prev_input_point);
1393                        }
1394                    }
1395                }
1396            }
1397            term.move_down_and_cr(1);
1398        }
1399
1400        if hyperlink_kind == HyperlinkKind::FileIri {
1401            let Ok(url) = Url::parse(&iri_or_path) else {
1402                panic!("Failed to parse file IRI `{iri_or_path}`");
1403            };
1404            let Ok(path) = url.to_file_path() else {
1405                panic!("Failed to interpret file IRI `{iri_or_path}` as a path");
1406            };
1407            iri_or_path = path.to_string_lossy().into_owned();
1408        }
1409
1410        let hovered_grid_point = hovered_grid_point.expect("Missing hovered point (๐Ÿ‘‰ or ๐Ÿ‘ˆ)");
1411        let hovered_char = term.grid().index(hovered_grid_point).c;
1412        (
1413            term,
1414            ExpectedHyperlink {
1415                hovered_grid_point,
1416                hovered_char,
1417                hyperlink_kind,
1418                iri_or_path,
1419                row,
1420                column,
1421                hyperlink_match,
1422            },
1423        )
1424    }
1425
1426    fn line_cells_count(line: &str) -> usize {
1427        // This avoids taking a dependency on the unicode-width crate
1428        fn width(c: char) -> usize {
1429            match c {
1430                // Fullwidth unicode characters used in tests
1431                'ไพ‹' | '๐Ÿƒ' | '๐Ÿฆ€' | '๐Ÿ”ฅ' => 2,
1432                '\t' => 8, // it's really 0-8, use the max always
1433                _ => 1,
1434            }
1435        }
1436        const CONTROL_CHARS: &str = "โ€นยซ๐Ÿ‘‰๐Ÿ‘ˆยปโ€บ";
1437        line.chars()
1438            .filter(|c| !CONTROL_CHARS.contains(*c))
1439            .map(width)
1440            .sum::<usize>()
1441    }
1442
1443    struct CheckHyperlinkMatch<'a> {
1444        term: &'a Term<VoidListener>,
1445        expected_hyperlink: &'a ExpectedHyperlink,
1446        source_location: &'a str,
1447    }
1448
1449    impl<'a> CheckHyperlinkMatch<'a> {
1450        fn new(
1451            term: &'a Term<VoidListener>,
1452            expected_hyperlink: &'a ExpectedHyperlink,
1453            source_location: &'a str,
1454        ) -> Self {
1455            Self {
1456                term,
1457                expected_hyperlink,
1458                source_location,
1459            }
1460        }
1461
1462        fn check_path_with_position_and_match(
1463            &self,
1464            path_with_position: PathWithPosition,
1465            hyperlink_match: &Match,
1466        ) {
1467            let format_path_with_position_and_match =
1468                |path_with_position: &PathWithPosition, hyperlink_match: &Match| {
1469                    let mut result =
1470                        format!("Path = ยซ{}ยป", &path_with_position.path.to_string_lossy());
1471                    if let Some(row) = path_with_position.row {
1472                        result += &format!(", line = {row}");
1473                        if let Some(column) = path_with_position.column {
1474                            result += &format!(", column = {column}");
1475                        }
1476                    }
1477
1478                    result += &format!(
1479                        ", at grid cells {}",
1480                        Self::format_hyperlink_match(hyperlink_match)
1481                    );
1482                    result
1483                };
1484
1485            assert_ne!(
1486                self.expected_hyperlink.hyperlink_kind,
1487                HyperlinkKind::Iri,
1488                "\n    at {}\nExpected a path, but was a iri:\n{}",
1489                self.source_location,
1490                self.format_renderable_content()
1491            );
1492
1493            assert_eq!(
1494                format_path_with_position_and_match(
1495                    &PathWithPosition {
1496                        path: PathBuf::from(self.expected_hyperlink.iri_or_path.clone()),
1497                        row: self.expected_hyperlink.row,
1498                        column: self.expected_hyperlink.column
1499                    },
1500                    &self.expected_hyperlink.hyperlink_match
1501                ),
1502                format_path_with_position_and_match(&path_with_position, hyperlink_match),
1503                "\n    at {}:\n{}",
1504                self.source_location,
1505                self.format_renderable_content()
1506            );
1507        }
1508
1509        fn check_iri_and_match(&self, iri: String, hyperlink_match: &Match) {
1510            let format_iri_and_match = |iri: &String, hyperlink_match: &Match| {
1511                format!(
1512                    "Url = ยซ{iri}ยป, at grid cells {}",
1513                    Self::format_hyperlink_match(hyperlink_match)
1514                )
1515            };
1516
1517            assert_eq!(
1518                self.expected_hyperlink.hyperlink_kind,
1519                HyperlinkKind::Iri,
1520                "\n    at {}\nExpected a iri, but was a path:\n{}",
1521                self.source_location,
1522                self.format_renderable_content()
1523            );
1524
1525            assert_eq!(
1526                format_iri_and_match(
1527                    &self.expected_hyperlink.iri_or_path,
1528                    &self.expected_hyperlink.hyperlink_match
1529                ),
1530                format_iri_and_match(&iri, hyperlink_match),
1531                "\n    at {}:\n{}",
1532                self.source_location,
1533                self.format_renderable_content()
1534            );
1535        }
1536
1537        fn format_hyperlink_match(hyperlink_match: &Match) -> String {
1538            format!(
1539                "({}, {})..=({}, {})",
1540                hyperlink_match.start().line.0,
1541                hyperlink_match.start().column.0,
1542                hyperlink_match.end().line.0,
1543                hyperlink_match.end().column.0
1544            )
1545        }
1546
1547        fn format_renderable_content(&self) -> String {
1548            let mut result = format!("\nHovered on '{}'\n", self.expected_hyperlink.hovered_char);
1549
1550            let mut first_header_row = String::new();
1551            let mut second_header_row = String::new();
1552            let mut marker_header_row = String::new();
1553            for index in 0..self.term.columns() {
1554                let remainder = index % 10;
1555                if index > 0 && remainder == 0 {
1556                    first_header_row.push_str(&format!("{:>10}", (index / 10)));
1557                }
1558                second_header_row += &remainder.to_string();
1559                if index == self.expected_hyperlink.hovered_grid_point.column.0 {
1560                    marker_header_row.push('โ†“');
1561                } else {
1562                    marker_header_row.push(' ');
1563                }
1564            }
1565
1566            let remainder = (self.term.columns() - 1) % 10;
1567            if remainder != 0 {
1568                first_header_row.push_str(&" ".repeat(remainder));
1569            }
1570
1571            result += &format!("\n      [ {}]\n", first_header_row);
1572            result += &format!("      [{}]\n", second_header_row);
1573            result += &format!("       {}", marker_header_row);
1574
1575            for cell in self
1576                .term
1577                .renderable_content()
1578                .display_iter
1579                .filter(|cell| !cell.flags.intersects(WIDE_CHAR_SPACERS))
1580            {
1581                if cell.point.column.0 == 0 {
1582                    let prefix =
1583                        if cell.point.line == self.expected_hyperlink.hovered_grid_point.line {
1584                            'โ†’'
1585                        } else {
1586                            ' '
1587                        };
1588                    result += &format!("\n{prefix}[{:>3}] ", cell.point.line.to_string());
1589                }
1590
1591                match cell.c {
1592                    '\t' => result.push(' '),
1593                    c @ _ => result.push(c),
1594                }
1595            }
1596
1597            result
1598        }
1599    }
1600
1601    fn test_hyperlink<'a>(
1602        columns: usize,
1603        total_cells: usize,
1604        test_lines: impl Iterator<Item = &'a str>,
1605        hyperlink_kind: HyperlinkKind,
1606        source_location: &str,
1607    ) {
1608        const CARGO_DIR_REGEX: &str =
1609            r#"\s+(Compiling|Checking|Documenting) [^(]+\((?<link>(?<path>.+))\)"#;
1610        const RUST_DIAGNOSTIC_REGEX: &str = r#"\s+(-->|:::|at) (?<link>(?<path>.+?))(:$|$)"#;
1611        const ISSUE_12338_REGEX: &str =
1612            r#"[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2} (?<link>(?<path>.+))"#;
1613        const MULTIPLE_SAME_LINE_REGEX: &str =
1614            r#"(?<link>(?<path>๐Ÿฆ€ multiple_same_line ๐Ÿฆ€) ๐Ÿšฃ(?<line>[0-9]+) ๐Ÿ›(?<column>[0-9]+)):"#;
1615        const PATH_HYPERLINK_TIMEOUT_MS: u64 = 1000;
1616
1617        thread_local! {
1618            static TEST_REGEX_SEARCHES: RefCell<RegexSearches> =
1619                RefCell::new({
1620                    let default_settings_content: Rc<SettingsContent> =
1621                        settings::parse_json_with_comments(&settings::default_settings()).unwrap();
1622                    let default_terminal_settings = TerminalSettings::from_settings(&default_settings_content);
1623
1624                    RegexSearches::new([
1625                        RUST_DIAGNOSTIC_REGEX,
1626                        CARGO_DIR_REGEX,
1627                        ISSUE_12338_REGEX,
1628                        MULTIPLE_SAME_LINE_REGEX,
1629                    ]
1630                        .into_iter()
1631                        .chain(default_terminal_settings.path_hyperlink_regexes
1632                            .iter()
1633                            .map(AsRef::as_ref)),
1634                    PATH_HYPERLINK_TIMEOUT_MS)
1635                });
1636        }
1637
1638        let term_size = TermSize::new(columns, total_cells / columns + 2);
1639        let (term, expected_hyperlink) =
1640            build_term_from_test_lines(hyperlink_kind, term_size, test_lines);
1641        let hyperlink_found = TEST_REGEX_SEARCHES.with(|regex_searches| {
1642            find_from_grid_point(
1643                &term,
1644                expected_hyperlink.hovered_grid_point,
1645                &mut regex_searches.borrow_mut(),
1646            )
1647        });
1648        let check_hyperlink_match =
1649            CheckHyperlinkMatch::new(&term, &expected_hyperlink, source_location);
1650        match hyperlink_found {
1651            Some((hyperlink_word, false, hyperlink_match)) => {
1652                check_hyperlink_match.check_path_with_position_and_match(
1653                    PathWithPosition::parse_str(&hyperlink_word),
1654                    &hyperlink_match,
1655                );
1656            }
1657            Some((hyperlink_word, true, hyperlink_match)) => {
1658                check_hyperlink_match.check_iri_and_match(hyperlink_word, &hyperlink_match);
1659            }
1660            None => {
1661                if expected_hyperlink.hyperlink_match.start()
1662                    != expected_hyperlink.hyperlink_match.end()
1663                {
1664                    assert!(
1665                        false,
1666                        "No hyperlink found\n     at {source_location}:\n{}",
1667                        check_hyperlink_match.format_renderable_content()
1668                    )
1669                }
1670            }
1671        }
1672    }
1673}