1use alacritty_terminal::{
2 Term,
3 event::EventListener,
4 grid::Dimensions,
5 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
6 term::search::{Match, RegexIter, RegexSearch},
7};
8use regex::Regex;
9use std::{ops::Index, sync::LazyLock};
10
11const 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{-}\^⟨⟩`']+"#;
12// Optional suffix matches MSBuild diagnostic suffixes for path parsing in PathLikeWithPosition
13// https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks
14const WORD_REGEX: &str =
15 r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))|[\$\+\w.\[\]:/\\@\-~()]+"#;
16
17const PYTHON_FILE_LINE_REGEX: &str = r#"File "(?P<file>[^"]+)", line (?P<line>\d+)"#;
18
19static PYTHON_FILE_LINE_MATCHER: LazyLock<Regex> =
20 LazyLock::new(|| Regex::new(PYTHON_FILE_LINE_REGEX).unwrap());
21
22fn python_extract_path_and_line(input: &str) -> Option<(&str, u32)> {
23 if let Some(captures) = PYTHON_FILE_LINE_MATCHER.captures(input) {
24 let path_part = captures.name("file")?.as_str();
25
26 let line_number: u32 = captures.name("line")?.as_str().parse().ok()?;
27 return Some((path_part, line_number));
28 }
29 None
30}
31
32pub(super) struct RegexSearches {
33 url_regex: RegexSearch,
34 word_regex: RegexSearch,
35 python_file_line_regex: RegexSearch,
36}
37
38impl RegexSearches {
39 pub(super) fn new() -> Self {
40 Self {
41 url_regex: RegexSearch::new(URL_REGEX).unwrap(),
42 word_regex: RegexSearch::new(WORD_REGEX).unwrap(),
43 python_file_line_regex: RegexSearch::new(PYTHON_FILE_LINE_REGEX).unwrap(),
44 }
45 }
46}
47
48pub(super) fn find_from_grid_point<T: EventListener>(
49 term: &Term<T>,
50 point: AlacPoint,
51 regex_searches: &mut RegexSearches,
52) -> Option<(String, bool, Match)> {
53 let grid = term.grid();
54 let link = grid.index(point).hyperlink();
55 let found_word = if let Some(ref url) = link {
56 let mut min_index = point;
57 loop {
58 let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
59 if new_min_index == min_index || grid.index(new_min_index).hyperlink() != link {
60 break;
61 } else {
62 min_index = new_min_index
63 }
64 }
65
66 let mut max_index = point;
67 loop {
68 let new_max_index = max_index.add(term, Boundary::Cursor, 1);
69 if new_max_index == max_index || grid.index(new_max_index).hyperlink() != link {
70 break;
71 } else {
72 max_index = new_max_index
73 }
74 }
75
76 let url = url.uri().to_owned();
77 let url_match = min_index..=max_index;
78
79 Some((url, true, url_match))
80 } else if let Some(url_match) = regex_match_at(term, point, &mut regex_searches.url_regex) {
81 let url = term.bounds_to_string(*url_match.start(), *url_match.end());
82 Some((url, true, url_match))
83 } else if let Some(python_match) =
84 regex_match_at(term, point, &mut regex_searches.python_file_line_regex)
85 {
86 let matching_line = term.bounds_to_string(*python_match.start(), *python_match.end());
87 python_extract_path_and_line(&matching_line).map(|(file_path, line_number)| {
88 (format!("{file_path}:{line_number}"), false, python_match)
89 })
90 } else if let Some(word_match) = regex_match_at(term, point, &mut regex_searches.word_regex) {
91 let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
92
93 let (sanitized_match, sanitized_word) = 'sanitize: {
94 let mut word_match = word_match;
95 let mut file_path = file_path;
96
97 if is_path_surrounded_by_common_symbols(&file_path) {
98 word_match = Match::new(
99 word_match.start().add(term, Boundary::Grid, 1),
100 word_match.end().sub(term, Boundary::Grid, 1),
101 );
102 file_path = file_path[1..file_path.len() - 1].to_owned();
103 }
104
105 while file_path.ends_with(':') {
106 file_path.pop();
107 word_match = Match::new(
108 *word_match.start(),
109 word_match.end().sub(term, Boundary::Grid, 1),
110 );
111 }
112 let mut colon_count = 0;
113 for c in file_path.chars() {
114 if c == ':' {
115 colon_count += 1;
116 }
117 }
118 // strip trailing comment after colon in case of
119 // file/at/path.rs:row:column:description or error message
120 // so that the file path is `file/at/path.rs:row:column`
121 if colon_count > 2 {
122 let last_index = file_path.rfind(':').unwrap();
123 let prev_is_digit = last_index > 0
124 && file_path
125 .chars()
126 .nth(last_index - 1)
127 .is_some_and(|c| c.is_ascii_digit());
128 let next_is_digit = last_index < file_path.len() - 1
129 && file_path
130 .chars()
131 .nth(last_index + 1)
132 .is_none_or(|c| c.is_ascii_digit());
133 if prev_is_digit && !next_is_digit {
134 let stripped_len = file_path.len() - last_index;
135 word_match = Match::new(
136 *word_match.start(),
137 word_match.end().sub(term, Boundary::Grid, stripped_len),
138 );
139 file_path = file_path[0..last_index].to_owned();
140 }
141 }
142
143 break 'sanitize (word_match, file_path);
144 };
145
146 Some((sanitized_word, false, sanitized_match))
147 } else {
148 None
149 };
150
151 found_word.map(|(maybe_url_or_path, is_url, word_match)| {
152 if is_url {
153 // Treat "file://" IRIs like file paths to ensure
154 // that line numbers at the end of the path are
155 // handled correctly
156 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
157 (path.to_string(), false, word_match)
158 } else {
159 (maybe_url_or_path, true, word_match)
160 }
161 } else {
162 (maybe_url_or_path, false, word_match)
163 }
164 })
165}
166
167fn is_path_surrounded_by_common_symbols(path: &str) -> bool {
168 // Avoid detecting `[]` or `()` strings as paths, surrounded by common symbols
169 path.len() > 2
170 // The rest of the brackets and various quotes cannot be matched by the [`WORD_REGEX`] hence not checked for.
171 && (path.starts_with('[') && path.ends_with(']')
172 || path.starts_with('(') && path.ends_with(')'))
173}
174
175/// Based on alacritty/src/display/hint.rs > regex_match_at
176/// Retrieve the match, if the specified point is inside the content matching the regex.
177fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
178 visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
179}
180
181/// Copied from alacritty/src/display/hint.rs:
182/// Iterate over all visible regex matches.
183fn visible_regex_match_iter<'a, T>(
184 term: &'a Term<T>,
185 regex: &'a mut RegexSearch,
186) -> impl Iterator<Item = Match> + 'a {
187 const MAX_SEARCH_LINES: usize = 100;
188
189 let viewport_start = Line(-(term.grid().display_offset() as i32));
190 let viewport_end = viewport_start + term.bottommost_line();
191 let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
192 let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
193 start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
194 end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
195
196 RegexIter::new(start, end, AlacDirection::Right, term, regex)
197 .skip_while(move |rm| rm.end().line < viewport_start)
198 .take_while(move |rm| rm.start().line <= viewport_end)
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use alacritty_terminal::{
205 event::VoidListener,
206 index::{Boundary, Point as AlacPoint},
207 term::{Config, cell::Flags, test::TermSize},
208 vte::ansi::Handler,
209 };
210 use std::{cell::RefCell, ops::RangeInclusive, path::PathBuf};
211 use url::Url;
212 use util::paths::PathWithPosition;
213
214 fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
215 let results: Vec<_> = regex::Regex::new(re)
216 .unwrap()
217 .find_iter(hay)
218 .map(|m| m.as_str())
219 .collect();
220 assert_eq!(results, expected);
221 }
222
223 #[test]
224 fn test_url_regex() {
225 re_test(
226 URL_REGEX,
227 "test http://example.com test 'https://website1.com' test mailto:bob@example.com train",
228 vec![
229 "http://example.com",
230 "https://website1.com",
231 "mailto:bob@example.com",
232 ],
233 );
234 }
235
236 #[test]
237 fn test_word_regex() {
238 re_test(
239 WORD_REGEX,
240 "hello, world! \"What\" is this?",
241 vec!["hello", "world", "What", "is", "this"],
242 );
243 }
244
245 #[test]
246 fn test_word_regex_with_linenum() {
247 // filename(line) and filename(line,col) as used in MSBuild output
248 // should be considered a single "word", even though comma is
249 // usually a word separator
250 re_test(WORD_REGEX, "a Main.cs(20) b", vec!["a", "Main.cs(20)", "b"]);
251 re_test(
252 WORD_REGEX,
253 "Main.cs(20,5) Error desc",
254 vec!["Main.cs(20,5)", "Error", "desc"],
255 );
256 // filename:line:col is a popular format for unix tools
257 re_test(
258 WORD_REGEX,
259 "a Main.cs:20:5 b",
260 vec!["a", "Main.cs:20:5", "b"],
261 );
262 // Some tools output "filename:line:col:message", which currently isn't
263 // handled correctly, but might be in the future
264 re_test(
265 WORD_REGEX,
266 "Main.cs:20:5:Error desc",
267 vec!["Main.cs:20:5:Error", "desc"],
268 );
269 }
270
271 #[test]
272 fn test_python_file_line_regex() {
273 re_test(
274 PYTHON_FILE_LINE_REGEX,
275 "hay File \"/zed/bad_py.py\", line 8 stack",
276 vec!["File \"/zed/bad_py.py\", line 8"],
277 );
278 re_test(PYTHON_FILE_LINE_REGEX, "unrelated", vec![]);
279 }
280
281 #[test]
282 fn test_python_file_line() {
283 let inputs: Vec<(&str, Option<(&str, u32)>)> = vec![
284 (
285 "File \"/zed/bad_py.py\", line 8",
286 Some(("/zed/bad_py.py", 8u32)),
287 ),
288 ("File \"path/to/zed/bad_py.py\"", None),
289 ("unrelated", None),
290 ("", None),
291 ];
292 let actual = inputs
293 .iter()
294 .map(|input| python_extract_path_and_line(input.0))
295 .collect::<Vec<_>>();
296 let expected = inputs.iter().map(|(_, output)| *output).collect::<Vec<_>>();
297 assert_eq!(actual, expected);
298 }
299
300 // We use custom columns in many tests to workaround this issue by ensuring a wrapped
301 // line never ends on a wide char:
302 //
303 // <https://github.com/alacritty/alacritty/issues/8586>
304 //
305 // This issue was recently fixed, as soon as we update to a version containing the fix we
306 // can remove all the custom columns from these tests.
307 //
308 macro_rules! test_hyperlink {
309 ($($lines:expr),+; $hyperlink_kind:ident) => { {
310 use crate::terminal_hyperlinks::tests::line_cells_count;
311 use std::cmp;
312
313 let test_lines = vec![$($lines),+];
314 let (total_cells, longest_line_cells) =
315 test_lines.iter().copied()
316 .map(line_cells_count)
317 .fold((0, 0), |state, cells| (state.0 + cells, cmp::max(state.1, cells)));
318
319 test_hyperlink!(
320 // Alacritty has issues with 2 columns, use 3 as the minimum for now.
321 [3, longest_line_cells / 2, longest_line_cells + 1];
322 total_cells;
323 test_lines.iter().copied();
324 $hyperlink_kind
325 )
326 } };
327
328 ([ $($columns:expr),+ ]; $total_cells:expr; $lines:expr; $hyperlink_kind:ident) => { {
329 use crate::terminal_hyperlinks::tests::{ test_hyperlink, HyperlinkKind };
330
331 let source_location = format!("{}:{}", std::file!(), std::line!());
332 for columns in vec![ $($columns),+] {
333 test_hyperlink(columns, $total_cells, $lines, HyperlinkKind::$hyperlink_kind,
334 &source_location);
335 }
336 } };
337 }
338
339 mod path {
340 /// 👉 := **hovered** on following char
341 ///
342 /// 👈 := **hovered** on wide char spacer of previous full width char
343 ///
344 /// **`‹›`** := expected **hyperlink** match
345 ///
346 /// **`«»`** := expected **path**, **row**, and **column** capture groups
347 ///
348 /// [**`c₀, c₁, …, cₙ;`**]ₒₚₜ := use specified terminal widths of `c₀, c₁, …, cₙ` **columns**
349 /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
350 ///
351 macro_rules! test_path {
352 ($($lines:literal),+) => { test_hyperlink!($($lines),+; Path) };
353 }
354
355 #[test]
356 fn simple() {
357 // Rust paths
358 // Just the path
359 test_path!("‹«/👉test/cool.rs»›");
360 test_path!("‹«/test/cool👉.rs»›");
361
362 // path and line
363 test_path!("‹«/👉test/cool.rs»:«4»›");
364 test_path!("‹«/test/cool.rs»👉:«4»›");
365 test_path!("‹«/test/cool.rs»:«👉4»›");
366 test_path!("‹«/👉test/cool.rs»(«4»)›");
367 test_path!("‹«/test/cool.rs»👉(«4»)›");
368 test_path!("‹«/test/cool.rs»(«👉4»)›");
369 test_path!("‹«/test/cool.rs»(«4»👉)›");
370
371 // path, line, and column
372 test_path!("‹«/👉test/cool.rs»:«4»:«2»›");
373 test_path!("‹«/test/cool.rs»:«4»:«👉2»›");
374 test_path!("‹«/👉test/cool.rs»(«4»,«2»)›");
375 test_path!("‹«/test/cool.rs»(«4»👉,«2»)›");
376
377 // path, line, column, and ':' suffix
378 test_path!("‹«/👉test/cool.rs»:«4»:«2»›:");
379 test_path!("‹«/test/cool.rs»:«4»:«👉2»›:");
380 test_path!("‹«/👉test/cool.rs»(«4»,«2»)›:");
381 test_path!("‹«/test/cool.rs»(«4»,«2»👉)›:");
382
383 // path, line, column, and description
384 test_path!("‹«/test/cool.rs»:«4»:«2»›👉:Error!");
385 test_path!("‹«/test/cool.rs»:«4»:«2»›:👉Error!");
386 test_path!("‹«/test/co👉ol.rs»(«4»,«2»)›:Error!");
387
388 // Cargo output
389 test_path!(" Compiling Cool 👉(‹«/test/Cool»›)");
390 test_path!(" Compiling Cool (‹«/👉test/Cool»›)");
391 test_path!(" Compiling Cool (‹«/test/Cool»›👉)");
392
393 // Python
394 test_path!("‹«awe👉some.py»›");
395
396 test_path!(" ‹F👉ile \"«/awesome.py»\", line «42»›: Wat?");
397 test_path!(" ‹File \"«/awe👉some.py»\", line «42»›: Wat?");
398 test_path!(" ‹File \"«/awesome.py»👉\", line «42»›: Wat?");
399 test_path!(" ‹File \"«/awesome.py»\", line «4👉2»›: Wat?");
400 }
401
402 #[test]
403 fn colons_galore() {
404 test_path!("‹«/test/co👉ol.rs»:«4»›");
405 test_path!("‹«/test/co👉ol.rs»:«4»›:");
406 test_path!("‹«/test/co👉ol.rs»:«4»:«2»›");
407 test_path!("‹«/test/co👉ol.rs»:«4»:«2»›:");
408 test_path!("‹«/test/co👉ol.rs»(«1»)›");
409 test_path!("‹«/test/co👉ol.rs»(«1»)›:");
410 test_path!("‹«/test/co👉ol.rs»(«1»,«618»)›");
411 test_path!("‹«/test/co👉ol.rs»(«1»,«618»)›:");
412 test_path!("‹«/test/co👉ol.rs»::«42»›");
413 test_path!("‹«/test/co👉ol.rs»::«42»›:");
414 test_path!("‹«/test/co👉ol.rs:4:2»(«1»,«618»)›");
415 test_path!("‹«/test/co👉ol.rs»(«1»,«618»)›::");
416 }
417
418 #[test]
419 fn quotes_and_brackets() {
420 test_path!("\"‹«/test/co👉ol.rs»:«4»›\"");
421 test_path!("'‹«/test/co👉ol.rs»:«4»›'");
422 test_path!("`‹«/test/co👉ol.rs»:«4»›`");
423
424 test_path!("[‹«/test/co👉ol.rs»:«4»›]");
425 test_path!("(‹«/test/co👉ol.rs»:«4»›)");
426 test_path!("{‹«/test/co👉ol.rs»:«4»›}");
427 test_path!("<‹«/test/co👉ol.rs»:«4»›>");
428
429 test_path!("[\"‹«/test/co👉ol.rs»:«4»›\"]");
430 test_path!("'(‹«/test/co👉ol.rs»:«4»›)'");
431 }
432
433 #[test]
434 fn word_wide_chars() {
435 // Rust paths
436 test_path!("‹«/👉例/cool.rs»›");
437 test_path!("‹«/例👈/cool.rs»›");
438 test_path!("‹«/例/cool.rs»:«👉4»›");
439 test_path!("‹«/例/cool.rs»:«4»:«👉2»›");
440
441 // Cargo output
442 test_path!(" Compiling Cool (‹«/👉例/Cool»›)");
443 test_path!(" Compiling Cool (‹«/例👈/Cool»›)");
444
445 // Python
446 test_path!("‹«👉例wesome.py»›");
447 test_path!("‹«例👈wesome.py»›");
448 test_path!(" ‹File \"«/👉例wesome.py»\", line «42»›: Wat?");
449 test_path!(" ‹File \"«/例👈wesome.py»\", line «42»›: Wat?");
450 }
451
452 #[test]
453 fn non_word_wide_chars() {
454 // Mojo diagnostic message
455 test_path!(" ‹File \"«/awe👉some.🔥»\", line «42»›: Wat?");
456 test_path!(" ‹File \"«/awesome👉.🔥»\", line «42»›: Wat?");
457 test_path!(" ‹File \"«/awesome.👉🔥»\", line «42»›: Wat?");
458 test_path!(" ‹File \"«/awesome.🔥👈»\", line «42»›: Wat?");
459 }
460
461 /// These likely rise to the level of being worth fixing.
462 mod issues {
463 #[test]
464 // <https://github.com/alacritty/alacritty/issues/8586>
465 fn issue_alacritty_8586() {
466 // Rust paths
467 test_path!("‹«/👉例/cool.rs»›");
468 test_path!("‹«/例👈/cool.rs»›");
469 test_path!("‹«/例/cool.rs»:«👉4»›");
470 test_path!("‹«/例/cool.rs»:«4»:«👉2»›");
471
472 // Cargo output
473 test_path!(" Compiling Cool (‹«/👉例/Cool»›)");
474 test_path!(" Compiling Cool (‹«/例👈/Cool»›)");
475
476 // Python
477 test_path!("‹«👉例wesome.py»›");
478 test_path!("‹«例👈wesome.py»›");
479 test_path!(" ‹File \"«/👉例wesome.py»\", line «42»›: Wat?");
480 test_path!(" ‹File \"«/例👈wesome.py»\", line «42»›: Wat?");
481 }
482
483 #[test]
484 #[should_panic(expected = "No hyperlink found")]
485 // <https://github.com/zed-industries/zed/issues/12338>
486 fn issue_12338() {
487 // Issue #12338
488 test_path!(".rw-r--r-- 0 staff 05-27 14:03 ‹«test👉、2.txt»›");
489 test_path!(".rw-r--r-- 0 staff 05-27 14:03 ‹«test、👈2.txt»›");
490 test_path!(".rw-r--r-- 0 staff 05-27 14:03 ‹«test👉。3.txt»›");
491 test_path!(".rw-r--r-- 0 staff 05-27 14:03 ‹«test。👈3.txt»›");
492
493 // Rust paths
494 test_path!("‹«/👉🏃/🦀.rs»›");
495 test_path!("‹«/🏃👈/🦀.rs»›");
496 test_path!("‹«/🏃/👉🦀.rs»:«4»›");
497 test_path!("‹«/🏃/🦀👈.rs»:«4»:«2»›");
498
499 // Cargo output
500 test_path!(" Compiling Cool (‹«/👉🏃/Cool»›)");
501 test_path!(" Compiling Cool (‹«/🏃👈/Cool»›)");
502
503 // Python
504 test_path!("‹«👉🏃wesome.py»›");
505 test_path!("‹«🏃👈wesome.py»›");
506 test_path!(" ‹File \"«/👉🏃wesome.py»\", line «42»›: Wat?");
507 test_path!(" ‹File \"«/🏃👈wesome.py»\", line «42»›: Wat?");
508
509 // Mojo
510 test_path!("‹«/awe👉some.🔥»› is some good Mojo!");
511 test_path!("‹«/awesome👉.🔥»› is some good Mojo!");
512 test_path!("‹«/awesome.👉🔥»› is some good Mojo!");
513 test_path!("‹«/awesome.🔥👈»› is some good Mojo!");
514 test_path!(" ‹File \"«/👉🏃wesome.🔥»\", line «42»›: Wat?");
515 test_path!(" ‹File \"«/🏃👈wesome.🔥»\", line «42»›: Wat?");
516 }
517
518 #[test]
519 #[cfg_attr(
520 not(target_os = "windows"),
521 should_panic(
522 expected = "Path = «test/controllers/template_items_controller_test.rb», line = 20, at grid cells (0, 0)..=(17, 1)"
523 )
524 )]
525 #[cfg_attr(
526 target_os = "windows",
527 should_panic(
528 expected = r#"Path = «test\\controllers\\template_items_controller_test.rb», line = 20, at grid cells (0, 0)..=(17, 1)"#
529 )
530 )]
531 // <https://github.com/zed-industries/zed/issues/28194>
532 //
533 // #28194 was closed, but the link includes the description part (":in" here), which
534 // seems wrong...
535 fn issue_28194() {
536 test_path!(
537 "‹«test/c👉ontrollers/template_items_controller_test.rb»:«20»›:in 'block (2 levels) in <class:TemplateItemsControllerTest>'"
538 );
539 test_path!(
540 "‹«test/controllers/template_items_controller_test.rb»:«19»›:i👉n 'block in <class:TemplateItemsControllerTest>'"
541 );
542 }
543 }
544
545 /// Minor issues arguably not important enough to fix/workaround...
546 mod nits {
547 #[test]
548 fn alacritty_bugs_with_two_columns() {
549 test_path!("‹«/👉test/cool.rs»(«4»)›");
550 test_path!("‹«/test/cool.rs»(«👉4»)›");
551 test_path!("‹«/test/cool.rs»(«4»,«👉2»)›");
552
553 // Python
554 test_path!("‹«awe👉some.py»›");
555 }
556
557 #[test]
558 #[cfg_attr(
559 not(target_os = "windows"),
560 should_panic(
561 expected = "Path = «/test/cool.rs», line = 1, at grid cells (0, 0)..=(9, 0)"
562 )
563 )]
564 #[cfg_attr(
565 target_os = "windows",
566 should_panic(
567 expected = r#"Path = «C:\\test\\cool.rs», line = 1, at grid cells (0, 0)..=(9, 2)"#
568 )
569 )]
570 fn invalid_row_column_should_be_part_of_path() {
571 test_path!("‹«/👉test/cool.rs:1:618033988749»›");
572 test_path!("‹«/👉test/cool.rs(1,618033988749)»›");
573 }
574
575 #[test]
576 #[should_panic(expected = "Path = «»")]
577 fn colon_suffix_succeeds_in_finding_an_empty_maybe_path() {
578 test_path!("‹«/test/cool.rs»:«4»:«2»›👉:", "What is this?");
579 test_path!("‹«/test/cool.rs»(«4»,«2»)›👉:", "What is this?");
580 }
581
582 #[test]
583 #[cfg_attr(
584 not(target_os = "windows"),
585 should_panic(expected = "Path = «/test/cool.rs»")
586 )]
587 #[cfg_attr(
588 target_os = "windows",
589 should_panic(expected = r#"Path = «C:\\test\\cool.rs»"#)
590 )]
591 fn many_trailing_colons_should_be_parsed_as_part_of_the_path() {
592 test_path!("‹«/test/cool.rs:::👉:»›");
593 test_path!("‹«/te:st/👉co:ol.r:s:4:2::::::»›");
594 }
595 }
596
597 #[cfg(target_os = "windows")]
598 mod windows {
599 // Lots of fun to be had with long file paths (verbatim) and UNC paths on Windows.
600 // See <https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation>
601 // See <https://users.rust-lang.org/t/understanding-windows-paths/58583>
602 // See <https://github.com/rust-lang/cargo/issues/13919>
603
604 #[test]
605 fn unc() {
606 test_path!(r#"‹«\\server\share\👉test\cool.rs»›"#);
607 test_path!(r#"‹«\\server\share\test\cool👉.rs»›"#);
608 }
609
610 mod issues {
611 #[test]
612 #[should_panic(
613 expected = r#"Path = «C:\\test\\cool.rs», at grid cells (0, 0)..=(6, 0)"#
614 )]
615 fn issue_verbatim() {
616 test_path!(r#"‹«\\?\C:\👉test\cool.rs»›"#);
617 test_path!(r#"‹«\\?\C:\test\cool👉.rs»›"#);
618 }
619
620 #[test]
621 #[should_panic(
622 expected = r#"Path = «\\\\server\\share\\test\\cool.rs», at grid cells (0, 0)..=(10, 2)"#
623 )]
624 fn issue_verbatim_unc() {
625 test_path!(r#"‹«\\?\UNC\server\share\👉test\cool.rs»›"#);
626 test_path!(r#"‹«\\?\UNC\server\share\test\cool👉.rs»›"#);
627 }
628 }
629 }
630 }
631
632 mod file_iri {
633 // File IRIs have a ton of use cases, most of which we currently do not support. A few of
634 // those cases are documented here as tests which are expected to fail.
635 // See https://en.wikipedia.org/wiki/File_URI_scheme
636
637 /// [**`c₀, c₁, …, cₙ;`**]ₒₚₜ := use specified terminal widths of `c₀, c₁, …, cₙ` **columns**
638 /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
639 ///
640 macro_rules! test_file_iri {
641 ($file_iri:literal) => { { test_hyperlink!(concat!("‹«👉", $file_iri, "»›"); FileIri) } };
642 }
643
644 #[cfg(not(target_os = "windows"))]
645 #[test]
646 fn absolute_file_iri() {
647 test_file_iri!("file:///test/cool/index.rs");
648 test_file_iri!("file:///test/cool/");
649 }
650
651 mod issues {
652 #[cfg(not(target_os = "windows"))]
653 #[test]
654 #[should_panic(expected = "Path = «/test/Ῥόδος/», at grid cells (0, 0)..=(15, 1)")]
655 fn issue_file_iri_with_percent_encoded_characters() {
656 // Non-space characters
657 // file:///test/Ῥόδος/
658 test_file_iri!("file:///test/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82/"); // URI
659
660 // Spaces
661 test_file_iri!("file:///te%20st/co%20ol/index.rs");
662 test_file_iri!("file:///te%20st/co%20ol/");
663 }
664 }
665
666 #[cfg(target_os = "windows")]
667 mod windows {
668 mod issues {
669 // The test uses Url::to_file_path(), but it seems that the Url crate doesn't
670 // support relative file IRIs.
671 #[test]
672 #[should_panic(
673 expected = r#"Failed to interpret file IRI `file:/test/cool/index.rs` as a path"#
674 )]
675 fn issue_relative_file_iri() {
676 test_file_iri!("file:/test/cool/index.rs");
677 test_file_iri!("file:/test/cool/");
678 }
679
680 // See https://en.wikipedia.org/wiki/File_URI_scheme
681 #[test]
682 #[should_panic(
683 expected = r#"Path = «C:\\test\\cool\\index.rs», at grid cells (0, 0)..=(9, 1)"#
684 )]
685 fn issue_absolute_file_iri() {
686 test_file_iri!("file:///C:/test/cool/index.rs");
687 test_file_iri!("file:///C:/test/cool/");
688 }
689
690 #[test]
691 #[should_panic(
692 expected = r#"Path = «C:\\test\\Ῥόδος\\», at grid cells (0, 0)..=(16, 1)"#
693 )]
694 fn issue_file_iri_with_percent_encoded_characters() {
695 // Non-space characters
696 // file:///test/Ῥόδος/
697 test_file_iri!("file:///C:/test/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82/"); // URI
698
699 // Spaces
700 test_file_iri!("file:///C:/te%20st/co%20ol/index.rs");
701 test_file_iri!("file:///C:/te%20st/co%20ol/");
702 }
703 }
704 }
705 }
706
707 mod iri {
708 /// [**`c₀, c₁, …, cₙ;`**]ₒₚₜ := use specified terminal widths of `c₀, c₁, …, cₙ` **columns**
709 /// (defaults to `3, longest_line_cells / 2, longest_line_cells + 1;`)
710 ///
711 macro_rules! test_iri {
712 ($iri:literal) => { { test_hyperlink!(concat!("‹«👉", $iri, "»›"); Iri) } };
713 }
714
715 #[test]
716 fn simple() {
717 // In the order they appear in URL_REGEX, except 'file://' which is treated as a path
718 test_iri!("ipfs://test/cool.ipfs");
719 test_iri!("ipns://test/cool.ipns");
720 test_iri!("magnet://test/cool.git");
721 test_iri!("mailto:someone@somewhere.here");
722 test_iri!("gemini://somewhere.here");
723 test_iri!("gopher://somewhere.here");
724 test_iri!("http://test/cool/index.html");
725 test_iri!("http://10.10.10.10:1111/cool.html");
726 test_iri!("http://test/cool/index.html?amazing=1");
727 test_iri!("http://test/cool/index.html#right%20here");
728 test_iri!("http://test/cool/index.html?amazing=1#right%20here");
729 test_iri!("https://test/cool/index.html");
730 test_iri!("https://10.10.10.10:1111/cool.html");
731 test_iri!("https://test/cool/index.html?amazing=1");
732 test_iri!("https://test/cool/index.html#right%20here");
733 test_iri!("https://test/cool/index.html?amazing=1#right%20here");
734 test_iri!("news://test/cool.news");
735 test_iri!("git://test/cool.git");
736 test_iri!("ssh://user@somewhere.over.here:12345/test/cool.git");
737 test_iri!("ftp://test/cool.ftp");
738 }
739
740 #[test]
741 fn wide_chars() {
742 // In the order they appear in URL_REGEX, except 'file://' which is treated as a path
743 test_iri!("ipfs://例🏃🦀/cool.ipfs");
744 test_iri!("ipns://例🏃🦀/cool.ipns");
745 test_iri!("magnet://例🏃🦀/cool.git");
746 test_iri!("mailto:someone@somewhere.here");
747 test_iri!("gemini://somewhere.here");
748 test_iri!("gopher://somewhere.here");
749 test_iri!("http://例🏃🦀/cool/index.html");
750 test_iri!("http://10.10.10.10:1111/cool.html");
751 test_iri!("http://例🏃🦀/cool/index.html?amazing=1");
752 test_iri!("http://例🏃🦀/cool/index.html#right%20here");
753 test_iri!("http://例🏃🦀/cool/index.html?amazing=1#right%20here");
754 test_iri!("https://例🏃🦀/cool/index.html");
755 test_iri!("https://10.10.10.10:1111/cool.html");
756 test_iri!("https://例🏃🦀/cool/index.html?amazing=1");
757 test_iri!("https://例🏃🦀/cool/index.html#right%20here");
758 test_iri!("https://例🏃🦀/cool/index.html?amazing=1#right%20here");
759 test_iri!("news://例🏃🦀/cool.news");
760 test_iri!("git://例/cool.git");
761 test_iri!("ssh://user@somewhere.over.here:12345/例🏃🦀/cool.git");
762 test_iri!("ftp://例🏃🦀/cool.ftp");
763 }
764
765 // There are likely more tests needed for IRI vs URI
766 #[test]
767 fn iris() {
768 // These refer to the same location, see example here:
769 // <https://en.wikipedia.org/wiki/Internationalized_Resource_Identifier#Compatibility>
770 test_iri!("https://en.wiktionary.org/wiki/Ῥόδος"); // IRI
771 test_iri!("https://en.wiktionary.org/wiki/%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82"); // URI
772 }
773
774 #[test]
775 #[should_panic(expected = "Expected a path, but was a iri")]
776 fn file_is_a_path() {
777 test_iri!("file://test/cool/index.rs");
778 }
779 }
780
781 #[derive(Debug, PartialEq)]
782 enum HyperlinkKind {
783 FileIri,
784 Iri,
785 Path,
786 }
787
788 struct ExpectedHyperlink {
789 hovered_grid_point: AlacPoint,
790 hovered_char: char,
791 hyperlink_kind: HyperlinkKind,
792 iri_or_path: String,
793 row: Option<u32>,
794 column: Option<u32>,
795 hyperlink_match: RangeInclusive<AlacPoint>,
796 }
797
798 /// Converts to Windows style paths on Windows, like path!(), but at runtime for improved test
799 /// readability.
800 fn build_term_from_test_lines<'a>(
801 hyperlink_kind: HyperlinkKind,
802 term_size: TermSize,
803 test_lines: impl Iterator<Item = &'a str>,
804 ) -> (Term<VoidListener>, ExpectedHyperlink) {
805 #[derive(Default, Eq, PartialEq)]
806 enum HoveredState {
807 #[default]
808 HoveredScan,
809 HoveredNextChar,
810 Done,
811 }
812
813 #[derive(Default, Eq, PartialEq)]
814 enum MatchState {
815 #[default]
816 MatchScan,
817 MatchNextChar,
818 Match(AlacPoint),
819 Done,
820 }
821
822 #[derive(Default, Eq, PartialEq)]
823 enum CapturesState {
824 #[default]
825 PathScan,
826 PathNextChar,
827 Path(AlacPoint),
828 RowScan,
829 Row(String),
830 ColumnScan,
831 Column(String),
832 Done,
833 }
834
835 fn prev_input_point_from_term(term: &Term<VoidListener>) -> AlacPoint {
836 let grid = term.grid();
837 let cursor = &grid.cursor;
838 let mut point = cursor.point;
839
840 if !cursor.input_needs_wrap {
841 point.column -= 1;
842 }
843
844 if grid.index(point).flags.contains(Flags::WIDE_CHAR_SPACER) {
845 point.column -= 1;
846 }
847
848 point
849 }
850
851 fn end_point_from_prev_input_point(
852 term: &Term<VoidListener>,
853 prev_input_point: AlacPoint,
854 ) -> AlacPoint {
855 if term
856 .grid()
857 .index(prev_input_point)
858 .flags
859 .contains(Flags::WIDE_CHAR)
860 {
861 prev_input_point.add(term, Boundary::Grid, 1)
862 } else {
863 prev_input_point
864 }
865 }
866
867 let mut hovered_grid_point: Option<AlacPoint> = None;
868 let mut hyperlink_match = AlacPoint::default()..=AlacPoint::default();
869 let mut iri_or_path = String::default();
870 let mut row = None;
871 let mut column = None;
872 let mut prev_input_point = AlacPoint::default();
873 let mut hovered_state = HoveredState::default();
874 let mut match_state = MatchState::default();
875 let mut captures_state = CapturesState::default();
876 let mut term = Term::new(Config::default(), &term_size, VoidListener);
877
878 for text in test_lines {
879 let chars: Box<dyn Iterator<Item = char>> =
880 if cfg!(windows) && hyperlink_kind == HyperlinkKind::Path {
881 Box::new(text.chars().map(|c| if c == '/' { '\\' } else { c })) as _
882 } else {
883 Box::new(text.chars()) as _
884 };
885 let mut chars = chars.peekable();
886 while let Some(c) = chars.next() {
887 match c {
888 '👉' => {
889 hovered_state = HoveredState::HoveredNextChar;
890 }
891 '👈' => {
892 hovered_grid_point = Some(prev_input_point.add(&term, Boundary::Grid, 1));
893 }
894 '«' | '»' => {
895 captures_state = match captures_state {
896 CapturesState::PathScan => CapturesState::PathNextChar,
897 CapturesState::PathNextChar => {
898 panic!("Should have been handled by char input")
899 }
900 CapturesState::Path(start_point) => {
901 iri_or_path = term.bounds_to_string(
902 start_point,
903 end_point_from_prev_input_point(&term, prev_input_point),
904 );
905 CapturesState::RowScan
906 }
907 CapturesState::RowScan => CapturesState::Row(String::new()),
908 CapturesState::Row(number) => {
909 row = Some(number.parse::<u32>().unwrap());
910 CapturesState::ColumnScan
911 }
912 CapturesState::ColumnScan => CapturesState::Column(String::new()),
913 CapturesState::Column(number) => {
914 column = Some(number.parse::<u32>().unwrap());
915 CapturesState::Done
916 }
917 CapturesState::Done => {
918 panic!("Extra '«', '»'")
919 }
920 }
921 }
922 '‹' | '›' => {
923 match_state = match match_state {
924 MatchState::MatchScan => MatchState::MatchNextChar,
925 MatchState::MatchNextChar => {
926 panic!("Should have been handled by char input")
927 }
928 MatchState::Match(start_point) => {
929 hyperlink_match = start_point
930 ..=end_point_from_prev_input_point(&term, prev_input_point);
931 MatchState::Done
932 }
933 MatchState::Done => {
934 panic!("Extra '‹', '›'")
935 }
936 }
937 }
938 _ => {
939 if let CapturesState::Row(number) | CapturesState::Column(number) =
940 &mut captures_state
941 {
942 number.push(c)
943 }
944
945 let is_windows_abs_path_start = captures_state
946 == CapturesState::PathNextChar
947 && cfg!(windows)
948 && hyperlink_kind == HyperlinkKind::Path
949 && c == '\\'
950 && chars.peek().is_some_and(|c| *c != '\\');
951
952 if is_windows_abs_path_start {
953 // Convert Unix abs path start into Windows abs path start so that the
954 // same test can be used for both OSes.
955 term.input('C');
956 prev_input_point = prev_input_point_from_term(&term);
957 term.input(':');
958 term.input(c);
959 } else {
960 term.input(c);
961 prev_input_point = prev_input_point_from_term(&term);
962 }
963
964 if hovered_state == HoveredState::HoveredNextChar {
965 hovered_grid_point = Some(prev_input_point);
966 hovered_state = HoveredState::Done;
967 }
968 if captures_state == CapturesState::PathNextChar {
969 captures_state = CapturesState::Path(prev_input_point);
970 }
971 if match_state == MatchState::MatchNextChar {
972 match_state = MatchState::Match(prev_input_point);
973 }
974 }
975 }
976 }
977 term.move_down_and_cr(1);
978 }
979
980 if hyperlink_kind == HyperlinkKind::FileIri {
981 let Ok(url) = Url::parse(&iri_or_path) else {
982 panic!("Failed to parse file IRI `{iri_or_path}`");
983 };
984 let Ok(path) = url.to_file_path() else {
985 panic!("Failed to interpret file IRI `{iri_or_path}` as a path");
986 };
987 iri_or_path = path.to_string_lossy().to_string();
988 }
989
990 if cfg!(windows) {
991 // Handle verbatim and UNC paths for Windows
992 if let Some(stripped) = iri_or_path.strip_prefix(r#"\\?\UNC\"#) {
993 iri_or_path = format!(r#"\\{stripped}"#);
994 } else if let Some(stripped) = iri_or_path.strip_prefix(r#"\\?\"#) {
995 iri_or_path = stripped.to_string();
996 }
997 }
998
999 let hovered_grid_point = hovered_grid_point.expect("Missing hovered point (👉 or 👈)");
1000 let hovered_char = term.grid().index(hovered_grid_point).c;
1001 (
1002 term,
1003 ExpectedHyperlink {
1004 hovered_grid_point,
1005 hovered_char,
1006 hyperlink_kind,
1007 iri_or_path,
1008 row,
1009 column,
1010 hyperlink_match,
1011 },
1012 )
1013 }
1014
1015 fn line_cells_count(line: &str) -> usize {
1016 // This avoids taking a dependency on the unicode-width crate
1017 fn width(c: char) -> usize {
1018 match c {
1019 // Fullwidth unicode characters used in tests
1020 '例' | '🏃' | '🦀' | '🔥' => 2,
1021 _ => 1,
1022 }
1023 }
1024 const CONTROL_CHARS: &str = "‹«👉👈»›";
1025 line.chars()
1026 .filter(|c| !CONTROL_CHARS.contains(*c))
1027 .map(width)
1028 .sum::<usize>()
1029 }
1030
1031 struct CheckHyperlinkMatch<'a> {
1032 term: &'a Term<VoidListener>,
1033 expected_hyperlink: &'a ExpectedHyperlink,
1034 source_location: &'a str,
1035 }
1036
1037 impl<'a> CheckHyperlinkMatch<'a> {
1038 fn new(
1039 term: &'a Term<VoidListener>,
1040 expected_hyperlink: &'a ExpectedHyperlink,
1041 source_location: &'a str,
1042 ) -> Self {
1043 Self {
1044 term,
1045 expected_hyperlink,
1046 source_location,
1047 }
1048 }
1049
1050 fn check_path_with_position_and_match(
1051 &self,
1052 path_with_position: PathWithPosition,
1053 hyperlink_match: &Match,
1054 ) {
1055 let format_path_with_position_and_match =
1056 |path_with_position: &PathWithPosition, hyperlink_match: &Match| {
1057 let mut result =
1058 format!("Path = «{}»", &path_with_position.path.to_string_lossy());
1059 if let Some(row) = path_with_position.row {
1060 result += &format!(", line = {row}");
1061 if let Some(column) = path_with_position.column {
1062 result += &format!(", column = {column}");
1063 }
1064 }
1065
1066 result += &format!(
1067 ", at grid cells {}",
1068 Self::format_hyperlink_match(hyperlink_match)
1069 );
1070 result
1071 };
1072
1073 assert_ne!(
1074 self.expected_hyperlink.hyperlink_kind,
1075 HyperlinkKind::Iri,
1076 "\n at {}\nExpected a path, but was a iri:\n{}",
1077 self.source_location,
1078 self.format_renderable_content()
1079 );
1080
1081 assert_eq!(
1082 format_path_with_position_and_match(
1083 &PathWithPosition {
1084 path: PathBuf::from(self.expected_hyperlink.iri_or_path.clone()),
1085 row: self.expected_hyperlink.row,
1086 column: self.expected_hyperlink.column
1087 },
1088 &self.expected_hyperlink.hyperlink_match
1089 ),
1090 format_path_with_position_and_match(&path_with_position, hyperlink_match),
1091 "\n at {}:\n{}",
1092 self.source_location,
1093 self.format_renderable_content()
1094 );
1095 }
1096
1097 fn check_iri_and_match(&self, iri: String, hyperlink_match: &Match) {
1098 let format_iri_and_match = |iri: &String, hyperlink_match: &Match| {
1099 format!(
1100 "Url = «{iri}», at grid cells {}",
1101 Self::format_hyperlink_match(hyperlink_match)
1102 )
1103 };
1104
1105 assert_eq!(
1106 self.expected_hyperlink.hyperlink_kind,
1107 HyperlinkKind::Iri,
1108 "\n at {}\nExpected a iri, but was a path:\n{}",
1109 self.source_location,
1110 self.format_renderable_content()
1111 );
1112
1113 assert_eq!(
1114 format_iri_and_match(
1115 &self.expected_hyperlink.iri_or_path,
1116 &self.expected_hyperlink.hyperlink_match
1117 ),
1118 format_iri_and_match(&iri, hyperlink_match),
1119 "\n at {}:\n{}",
1120 self.source_location,
1121 self.format_renderable_content()
1122 );
1123 }
1124
1125 fn format_hyperlink_match(hyperlink_match: &Match) -> String {
1126 format!(
1127 "({}, {})..=({}, {})",
1128 hyperlink_match.start().line.0,
1129 hyperlink_match.start().column.0,
1130 hyperlink_match.end().line.0,
1131 hyperlink_match.end().column.0
1132 )
1133 }
1134
1135 fn format_renderable_content(&self) -> String {
1136 let mut result = format!("\nHovered on '{}'\n", self.expected_hyperlink.hovered_char);
1137
1138 let mut first_header_row = String::new();
1139 let mut second_header_row = String::new();
1140 let mut marker_header_row = String::new();
1141 for index in 0..self.term.columns() {
1142 let remainder = index % 10;
1143 first_header_row.push_str(
1144 &(index > 0 && remainder == 0)
1145 .then_some((index / 10).to_string())
1146 .unwrap_or(" ".into()),
1147 );
1148 second_header_row += &remainder.to_string();
1149 if index == self.expected_hyperlink.hovered_grid_point.column.0 {
1150 marker_header_row.push('↓');
1151 } else {
1152 marker_header_row.push(' ');
1153 }
1154 }
1155
1156 result += &format!("\n [{}]\n", first_header_row);
1157 result += &format!(" [{}]\n", second_header_row);
1158 result += &format!(" {}", marker_header_row);
1159
1160 let spacers: Flags = Flags::LEADING_WIDE_CHAR_SPACER | Flags::WIDE_CHAR_SPACER;
1161 for cell in self
1162 .term
1163 .renderable_content()
1164 .display_iter
1165 .filter(|cell| !cell.flags.intersects(spacers))
1166 {
1167 if cell.point.column.0 == 0 {
1168 let prefix =
1169 if cell.point.line == self.expected_hyperlink.hovered_grid_point.line {
1170 '→'
1171 } else {
1172 ' '
1173 };
1174 result += &format!("\n{prefix}[{:>3}] ", cell.point.line.to_string());
1175 }
1176
1177 result.push(cell.c);
1178 }
1179
1180 result
1181 }
1182 }
1183
1184 fn test_hyperlink<'a>(
1185 columns: usize,
1186 total_cells: usize,
1187 test_lines: impl Iterator<Item = &'a str>,
1188 hyperlink_kind: HyperlinkKind,
1189 source_location: &str,
1190 ) {
1191 thread_local! {
1192 static TEST_REGEX_SEARCHES: RefCell<RegexSearches> = RefCell::new(RegexSearches::new());
1193 }
1194
1195 let term_size = TermSize::new(columns, total_cells / columns + 2);
1196 let (term, expected_hyperlink) =
1197 build_term_from_test_lines(hyperlink_kind, term_size, test_lines);
1198 let hyperlink_found = TEST_REGEX_SEARCHES.with(|regex_searches| {
1199 find_from_grid_point(
1200 &term,
1201 expected_hyperlink.hovered_grid_point,
1202 &mut regex_searches.borrow_mut(),
1203 )
1204 });
1205 let check_hyperlink_match =
1206 CheckHyperlinkMatch::new(&term, &expected_hyperlink, source_location);
1207 match hyperlink_found {
1208 Some((hyperlink_word, false, hyperlink_match)) => {
1209 check_hyperlink_match.check_path_with_position_and_match(
1210 PathWithPosition::parse_str(&hyperlink_word),
1211 &hyperlink_match,
1212 );
1213 }
1214 Some((hyperlink_word, true, hyperlink_match)) => {
1215 check_hyperlink_match.check_iri_and_match(hyperlink_word, &hyperlink_match);
1216 }
1217 _ => {
1218 assert!(
1219 false,
1220 "No hyperlink found\n at {source_location}:\n{}",
1221 check_hyperlink_match.format_renderable_content()
1222 )
1223 }
1224 }
1225 }
1226}