rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! URLs and file paths in terminal output: Ctrl+hover underlines them, Ctrl+click opens them.
//!
//! Finds explicit OSC 8 hyperlinks as well as plain `http(s)://` URLs and paths that exist
//! on disk (absolute, `~/`, Git Bash `/c/...`, or relative to the pane's folder, with an
//! optional `:line:col` suffix). A link never spans a wrapped line.

use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};

use alacritty_terminal::index::{Column, Point};
use alacritty_terminal::term::Term;

use crate::terminal::search::row_chars;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
    Url(String),
    Path(PathBuf),
    /// A bare name in the pane's folder, as `ls` prints them. `name` is how you'd type it.
    Entry {
        path: PathBuf,
        name: String,
    },
    /// A place in a file, from a compiler error or stack trace: `src/main.rs:12:5`.
    Location {
        path: PathBuf,
        pos: Pos,
    },
}

/// A line (and maybe column) in a file, counted from 1.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pos {
    pub line: u32,
    pub col: Option<u32>,
}

/// A link on one grid row: columns `start..end`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Link {
    pub line: i32,
    pub start: usize,
    pub end: usize,
    pub target: Target,
}

fn is_delimiter(c: char) -> bool {
    c.is_whitespace() || matches!(c, '\0' | '"' | '\'' | '<' | '>' | '|' | '`')
}

/// Bounds (inclusive) of the word around `idx`, without the punctuation that usually
/// surrounds a link in prose: `(see https://x.y/z).` is just `https://x.y/z`.
fn word_bounds(chars: &[char], idx: usize) -> Option<(usize, usize)> {
    if chars.get(idx).is_none_or(|&c| is_delimiter(c)) {
        return None;
    }
    let (mut lo, mut hi) = (idx, idx);
    while lo > 0 && !is_delimiter(chars[lo - 1]) {
        lo -= 1;
    }
    while hi + 1 < chars.len() && !is_delimiter(chars[hi + 1]) {
        hi += 1;
    }
    while lo < hi && matches!(chars[lo], '(' | '[' | '{') {
        lo += 1;
    }
    while hi > lo {
        let last = chars[hi];
        let opener = match last {
            ')' => '(',
            ']' => '[',
            '}' => '{',
            '.' | ',' | ';' | ':' | '!' | '?' => {
                hi -= 1;
                continue;
            }
            _ => break,
        };
        // Keep a closing bracket that belongs to the link itself, as in wiki/Foo_(bar).
        let word = &chars[lo..=hi];
        if word.iter().filter(|&&c| c == last).count() > word.iter().filter(|&&c| c == opener).count() {
            hi -= 1;
        } else {
            break;
        }
    }
    (lo..=hi).contains(&idx).then_some((lo, hi))
}

fn is_web_url(s: &str) -> bool {
    let lower = s.to_ascii_lowercase();
    ["http://", "https://"].iter().any(|p| lower.starts_with(p) && lower.len() > p.len())
}

/// Split a trailing position off a path: `file.rs:12:5`, `file.ts(12,5)` or `file.ts(12)`.
/// The colon of a drive (`C:\x`) is not a position.
pub fn split_position(text: &str) -> (&str, Option<Pos>) {
    if let Some(inner) = text.strip_suffix(')')
        && let Some(open) = text.rfind('(')
        && open > 0
    {
        let mut nums = inner[open + 1..].split(',').map(|n| n.trim().parse::<u32>());
        if let (Some(Ok(line)), col, None) = (nums.next(), nums.next(), nums.next())
            && col.as_ref().is_none_or(|c| c.is_ok())
        {
            return (&text[..open], Some(Pos { line, col: col.and_then(Result::ok) }));
        }
    }
    let mut rest = text;
    let mut nums = Vec::new();
    for _ in 0..2 {
        match rest.rfind(':') {
            Some(i) if i > 1 && rest.len() > i + 1 && rest[i + 1..].bytes().all(|b| b.is_ascii_digit()) => {
                let Ok(n) = rest[i + 1..].parse::<u32>() else { break };
                nums.push(n);
                rest = &rest[..i];
            }
            _ => break,
        }
    }
    let pos = match nums.as_slice() {
        [line] => Some(Pos { line: *line, col: None }),
        [col, line] => Some(Pos { line: *line, col: Some(*col) }),
        _ => None,
    };
    (rest, pos)
}

#[cfg(test)]
fn strip_position(text: &str) -> &str {
    split_position(text).0
}

/// Turn text into a path, if it names a file or folder that exists. This also covers the
/// names `ls` prints: bare names in the pane's folder, with an optional `-F` marker
/// (`dir/`, `tool*`, `link@`). Paths with folders in them are also looked for in the parent
/// folders of the pane's folder, since build errors are relative to the project root.
#[cfg(test)]
fn existing_path(text: &str, cwd: Option<&Path>) -> Option<PathBuf> {
    existing_path_with(text, cwd).map(|(path, ..)| path)
}

/// Like `existing_path`, and also returns the part of `text` that matched and the position
/// that followed it.
fn existing_path_with<'a>(text: &'a str, cwd: Option<&Path>) -> Option<(PathBuf, &'a str, Option<Pos>)> {
    let (s, pos) = split_position(text);
    let marked = s.trim_end_matches(['*', '@', '=']);
    let diff_stripped = marked.strip_prefix("a/").or_else(|| marked.strip_prefix("b/"));
    for cand in [s, marked].into_iter().chain(diff_stripped) {
        let b = cand.as_bytes();
        let drive = b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/');
        if (cand.len() < 2 && cand != "~")
            || cand.contains(['*', '?', '"', '<', '>', '|'])
            || (!drive && cand.contains(':'))
        {
            continue;
        }
        let path = if cand == "~" {
            dirs::home_dir()?
        } else if let Some(rest) = cand.strip_prefix("~/").or_else(|| cand.strip_prefix("~\\")) {
            dirs::home_dir()?.join(rest.replace('/', "\\"))
        } else if b.len() >= 2 && b[0] == b'/' && b[1].is_ascii_alphabetic() && (b.len() == 2 || b[2] == b'/') {
            // Git Bash: /c/Users/me -> C:\Users\me
            PathBuf::from(format!(
                "{}:\\{}",
                (b[1] as char).to_ascii_uppercase(),
                cand.get(3..).unwrap_or("").replace('/', "\\")
            ))
        } else if drive {
            PathBuf::from(cand.replace('/', "\\"))
        } else {
            let rel = cand.replace('/', "\\");
            let base = cwd?;
            if cand.contains(['/', '\\']) {
                base.ancestors()
                    .take(8)
                    .map(|dir| dir.join(&rel))
                    .find(|p| p.exists())
                    .unwrap_or_else(|| base.join(&rel))
            } else {
                base.join(&rel)
            }
        };
        if path.exists() {
            return Some((path, cand, pos));
        }
    }
    None
}

/// A path link: a place in a file if a position followed it, a bare name in the pane's folder
/// (no folders, `~` or drive) is an `Entry`, anything else a `Path`.
fn path_target(text: &str, cwd: Option<&Path>) -> Option<Target> {
    let (path, matched, pos) = existing_path_with(text, cwd)?;
    if let Some(pos) = pos
        && path.is_file()
    {
        return Some(Target::Location { path, pos });
    }
    let name = matched.trim_end_matches('/');
    let bare = pos.is_none() && !name.is_empty() && !name.starts_with('~') && !name.contains(['/', '\\', ':']);
    Some(if bare { Target::Entry { path, name: name.to_string() } } else { Target::Path(path) })
}

/// Bounds (inclusive) of the text inside the single quotes around `idx`: `ls` prints
/// names with spaces as 'My Folder'.
fn quoted_bounds(chars: &[char], idx: usize) -> Option<(usize, usize)> {
    // A name starts after a space or the line's start and ends before one, or before the
    // marker `ls -F` adds (`'My Folder'/`). That keeps an apostrophe inside a name
    // ("it's here", which `ls` wraps in double quotes) from throwing off the pairing of the
    // quotes after it.
    let ends_here = |at: usize| chars.get(at + 1).is_none_or(|n| n.is_whitespace() || "/*@=|>".contains(*n));
    let mut i = 0;
    while i < chars.len() {
        let quote = chars[i];
        if (quote == '\'' || quote == '"') && (i == 0 || chars[i - 1].is_whitespace()) {
            if let Some(close) = (i + 1..chars.len()).find(|&j| chars[j] == quote && ends_here(j)) {
                if idx > i && idx < close {
                    return (close > i + 1).then_some((i + 1, close - 1));
                }
                i = close + 1;
                continue;
            }
        }
        i += 1;
    }
    None
}

/// A file or folder of `cwd` with a space in its name, printed in the row where `idx` is
/// without quotes (`ls` doesn't quote when it is told not to, and other tools never do).
/// Returns the first and last cell of the name; the longest wins when names overlap.
fn spaced_entry(chars: &[char], idx: usize, cwd: Option<&Path>) -> Option<(usize, usize)> {
    let names = std::fs::read_dir(cwd?).ok()?;
    let boundary_before = |at: usize| at == 0 || matches!(chars[at - 1], ' ' | '\'' | '"');
    let boundary_after = |at: usize| chars.get(at + 1).is_none_or(|n| " '\"/*@=|>".contains(*n));
    let mut best: Option<(usize, usize)> = None;
    for entry in names.flatten() {
        let name: Vec<char> = entry.file_name().to_string_lossy().chars().collect();
        if !name.contains(&' ') || name.len() > chars.len() {
            continue;
        }
        for start in 0..=chars.len() - name.len() {
            let end = start + name.len() - 1;
            if (start..=end).contains(&idx)
                && chars[start..=end] == name[..]
                && boundary_before(start)
                && boundary_after(end)
                && best.is_none_or(|(s, e)| end - start > e - s)
            {
                best = Some((start, end));
            }
        }
    }
    best
}

/// Decode `%20` and friends in a `file:///` URL.
fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%'
            && let Some(hex) = s.get(i + 1..i + 3)
            && let Ok(v) = u8::from_str_radix(hex, 16)
        {
            out.push(v);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// The path inside a stack frame like `Foo.bar(Foo.java:12)`.
fn paren_inner(word: &str) -> Option<&str> {
    let inner = word.strip_suffix(')')?;
    let open = inner.rfind('(')?;
    (open > 0).then(|| &inner[open + 1..])
}

fn classify(word: &str, cwd: Option<&Path>) -> Option<Target> {
    if is_web_url(word) {
        return Some(Target::Url(word.to_string()));
    }
    if word.len() > 4 && word[..4].eq_ignore_ascii_case("www.") && word[4..].contains('.') {
        return Some(Target::Url(format!("https://{word}")));
    }
    // Node ES module traces: file:///C:/proj/a.js:12:5
    if word.len() > 8 && word[..8].eq_ignore_ascii_case("file:///") {
        return path_target(&percent_decode(&word[8..]), cwd);
    }
    path_target(word, cwd).or_else(|| paren_inner(word).and_then(|inner| path_target(inner, cwd)))
}

/// A position written after a path rather than glued to it: Python's `File "a.py", line 12`
/// and webpack's `./a.js 12:5-20`. `hi` is the index of the path's last character.
fn following_position(chars: &[char], hi: usize) -> Option<Pos> {
    fn number(s: &str) -> Option<(u32, &str)> {
        let digits = s.bytes().take_while(u8::is_ascii_digit).count();
        (digits > 0).then(|| (s[..digits].parse().ok(), &s[digits..])).and_then(|(n, rest)| Some((n?, rest)))
    }
    let rest: String = chars.get(hi + 1..)?.iter().collect();
    let rest = rest.trim_start_matches(['"', '\'', ',']).trim_start();
    if let Some(after) = rest.strip_prefix("line ") {
        return number(after.trim_start()).map(|(line, _)| Pos { line, col: None });
    }
    let (line, after) = number(rest)?;
    let col = after.strip_prefix(':').and_then(number).map(|(c, _)| c)?;
    Some(Pos { line, col: Some(col) })
}

/// The link under `point`, if any. `cwd` resolves relative paths.
pub fn find<T>(term: &Term<T>, point: Point, cwd: Option<&Path>) -> Option<Link> {
    let row = row_chars(term, point.line);
    let idx = row.iter().position(|&(col, _, w)| (col..col + w).contains(&point.column.0))?;
    let span = |lo: usize, hi: usize| (row[lo].0, row[hi].0 + row[hi].2);

    // Explicit hyperlinks (OSC 8) win over guessing from the text.
    let cell = &term.grid()[point.line][Column(row[idx].0)];
    if let Some(link) = cell.hyperlink() {
        let uri = link.uri().to_string();
        let same = |i: usize| term.grid()[point.line][Column(row[i].0)].hyperlink().is_some_and(|h| h.uri() == uri);
        let (mut lo, mut hi) = (idx, idx);
        while lo > 0 && same(lo - 1) {
            lo -= 1;
        }
        while hi + 1 < row.len() && same(hi + 1) {
            hi += 1;
        }
        let (start, end) = span(lo, hi);
        return is_web_url(&uri).then_some(Link { line: point.line.0, start, end, target: Target::Url(uri) });
    }

    let chars: Vec<char> = row.iter().map(|&(_, c, _)| c).collect();
    if let Some((lo, hi)) = quoted_bounds(&chars, idx) {
        let name: String = chars[lo..=hi].iter().collect();
        if let Some(target) = path_target(&name, cwd) {
            let (start, end) = span(lo, hi);
            return Some(Link { line: point.line.0, start, end, target });
        }
    }
    if let Some((lo, hi)) = spaced_entry(&chars, idx, cwd) {
        let name: String = chars[lo..=hi].iter().collect();
        if let Some(target) = path_target(&name, cwd) {
            let (start, end) = span(lo, hi);
            return Some(Link { line: point.line.0, start, end, target });
        }
    }
    let (lo, hi) = word_bounds(&chars, idx)?;
    let word: String = chars[lo..=hi].iter().collect();
    let mut target = classify(&word, cwd)?;
    if let Target::Path(path) | Target::Entry { path, .. } = &target
        && path.is_file()
        && let Some(pos) = following_position(&chars, hi)
    {
        target = Target::Location { path: path.clone(), pos };
    }
    let (start, end) = span(lo, hi);
    Some(Link { line: point.line.0, start, end, target })
}

#[link(name = "shell32")]
unsafe extern "system" {
    fn ShellExecuteW(
        hwnd: isize,
        op: *const u16,
        file: *const u16,
        params: *const u16,
        dir: *const u16,
        show: i32,
    ) -> isize;
}

fn wide(s: &OsStr) -> Vec<u16> {
    s.encode_wide().chain(std::iter::once(0)).collect()
}

pub fn shell_open(what: &OsStr) {
    // SAFETY: both strings are NUL-terminated and outlive the call.
    unsafe {
        ShellExecuteW(0, wide(OsStr::new("open")).as_ptr(), wide(what).as_ptr(), std::ptr::null(), std::ptr::null(), 1);
    }
}

/// Files that would run something when "opened". Show these in Explorer instead, so a
/// click on text in terminal output can never launch a program.
fn runs_code(path: &Path) -> bool {
    const EXTS: &[&str] = &[
        "exe", "com", "bat", "cmd", "ps1", "psm1", "vbs", "vbe", "js", "jse", "wsf", "wsh", "msi", "msp", "scr", "lnk",
        "url", "hta", "reg", "cpl", "jar", "dll", "sys", "pif", "appx", "msix",
    ];
    path.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
}

/// Open a place in a file in the editor. `template` is the command, with `{file}`, `{line}`
/// and `{col}`; empty means the default app (without the line).
fn open_in_editor(path: &Path, pos: Pos, template: &str) {
    let (path, template) = (path.to_path_buf(), template.to_string());
    // Wait for it off the UI thread.
    std::thread::spawn(move || open_in_editor_blocking(&path, pos, &template));
}

/// Like `open_in_editor`, but returns when the editor command has finished. A command that
/// fails (no `code` on PATH, say) falls back to the default app, and a file that would run
/// code is never "opened", only shown in Explorer.
pub fn open_in_editor_blocking(path: &Path, pos: Pos, template: &str) {
    let default_app = |path: &Path| if runs_code(path) { reveal(path) } else { shell_open(path.as_os_str()) };
    let template = if template.trim() == BUILT_IN_EDITOR { OUTSIDE_EDITOR } else { template };
    if template.trim().is_empty() {
        default_app(path);
        return;
    }
    let command = template
        .replace("{file}", &path.to_string_lossy())
        .replace("{line}", &pos.line.to_string())
        .replace("{col}", &pos.col.unwrap_or(1).to_string());
    let ok = std::process::Command::new("cmd.exe")
        .raw_arg(format!("/S /C \"{command}\""))
        .creation_flags(0x0800_0000) // no console window
        .status()
        .is_ok_and(|s| s.success());
    if !ok {
        default_app(path);
    }
}

pub fn open(target: &Target, editor: &str) {
    match target {
        Target::Url(url) if is_web_url(url) => shell_open(OsStr::new(url)),
        Target::Url(_) => {}
        Target::Location { path, pos } => open_in_editor(path, *pos, editor),
        Target::Path(path) | Target::Entry { path, .. } if path.is_dir() || !runs_code(path) => {
            shell_open(path.as_os_str())
        }
        Target::Path(path) | Target::Entry { path, .. } => reveal(path),
    }
}

/// Show a file selected in an Explorer window.
pub fn reveal(path: &Path) {
    let _ = std::process::Command::new("explorer.exe").raw_arg(format!("/select,\"{}\"", path.display())).spawn();
}

/// The file or folder a link points at, if it points at one.
pub fn path_of(target: &Target) -> Option<&Path> {
    match target {
        Target::Path(path) | Target::Entry { path, .. } | Target::Location { path, .. } => Some(path),
        Target::Url(_) => None,
    }
}

/// Extensions of files that are worth printing in the terminal.
const TEXT_EXTS: &[&str] = &[
    "txt",
    "md",
    "markdown",
    "rst",
    "json",
    "jsonc",
    "json5",
    "jsx",
    "js",
    "mjs",
    "cjs",
    "ts",
    "tsx",
    "css",
    "scss",
    "sass",
    "less",
    "html",
    "htm",
    "xml",
    "svg",
    "yml",
    "yaml",
    "toml",
    "ini",
    "cfg",
    "conf",
    "env",
    "log",
    "csv",
    "tsv",
    "rs",
    "py",
    "go",
    "java",
    "kt",
    "c",
    "h",
    "cpp",
    "hpp",
    "cc",
    "cs",
    "rb",
    "php",
    "sh",
    "bash",
    "zsh",
    "fish",
    "ps1",
    "bat",
    "cmd",
    "lua",
    "sql",
    "vue",
    "svelte",
    "gradle",
    "lock",
    "gitignore",
    "gitattributes",
    "editorconfig",
    "dockerfile",
    "mk",
    "cmake",
    "tex",
    "diff",
    "patch",
    "properties",
];

/// Biggest file a click will print.
const MAX_CAT_BYTES: u64 = 1 << 20;

/// What a click on a listing entry does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntryAction {
    /// `cd` into the folder, then `ls`.
    Enter,
    /// `cat` the file.
    Print,
    /// Not something to print: open it like any other link.
    Open,
}

/// Is this a text file of a sensible size? Known text extensions and files without an
/// extension (LICENSE, Makefile, .gitignore) qualify, if they contain no NUL bytes.
fn readable_text(path: &Path) -> bool {
    use std::io::Read;
    let Ok(meta) = std::fs::metadata(path) else { return false };
    if !meta.is_file() || meta.len() > MAX_CAT_BYTES {
        return false;
    }
    let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
    if ext.as_deref().is_some_and(|e| !TEXT_EXTS.contains(&e)) {
        return false;
    }
    let mut buf = [0u8; 4096];
    let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut buf)).unwrap_or(0);
    !buf[..n].contains(&0)
}

/// The `editor` setting that opens files in VS Code inside rustimal.
pub const BUILT_IN_EDITOR: &str = "rustimal";
/// What is used instead where there is no pane to show it in.
const OUTSIDE_EDITOR: &str = r#"code -g "{file}:{line}:{col}""#;

/// Is this a file to edit, rather than one for another app? Web pages and drawings are
/// for the browser.
pub fn opens_in_editor(path: &Path) -> bool {
    let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
    !matches!(ext.as_deref(), Some("html" | "htm" | "svg")) && readable_text(path)
}

pub fn entry_action(path: &Path) -> EntryAction {
    if path.is_dir() {
        EntryAction::Enter
    } else if readable_text(path) {
        EntryAction::Print
    } else {
        EntryAction::Open
    }
}

/// A Windows path the way Git Bash writes it: `C:\Users\me` becomes `/c/Users/me`.
pub fn msys_path(path: &Path) -> String {
    let s = path.to_string_lossy();
    let b = s.as_bytes();
    if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
        format!("/{}{}", (b[0] as char).to_ascii_lowercase(), s[2..].replace('\\', "/"))
    } else {
        s.replace('\\', "/")
    }
}

/// Quote text for bash only if it has anything the shell would treat specially.
pub fn shell_word(text: &str) -> String {
    let plain = !text.is_empty() && text.bytes().all(|b| b.is_ascii_alphanumeric() || b"_./:@%+=,~-".contains(&b));
    if plain { text.to_string() } else { shell_quote(text) }
}

/// Quote a name for bash: 'it'\''s'.
fn shell_quote(name: &str) -> String {
    format!("'{}'", name.replace('\'', "'\\''"))
}

/// The command a click on a listing entry types into the shell, or `None` if the entry
/// should just be opened.
pub fn entry_command(path: &Path, name: &str) -> Option<String> {
    let q = shell_quote(name);
    match entry_action(path) {
        EntryAction::Enter => Some(format!("cd -- {q} && ls")),
        EntryAction::Print => Some(format!("cat -- {q}")),
        EntryAction::Open => None,
    }
}

/// What a click does with the thing it is on, by how it is made: a plain click does what is
/// handiest, and the keys pick one of three ways to deal with a program, file or folder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClickMode {
    /// A plain click: enter a folder, print a text file, show a program in Explorer.
    Open,
    /// Ctrl+click: show it in Explorer.
    Explorer,
    /// Alt+click: run it, in the shell.
    Run,
    /// Shift+click: show it inside the pane: a program's window, VS Code, the browser.
    Embed,
}

/// A path as a Windows program wants it, quoted for bash.
fn windows_word(path: &Path) -> String {
    shell_quote(&path.display().to_string())
}

/// What a program is, for running it from the shell.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Program {
    Exe,
    Batch,
    PowerShell,
    /// Runs through Windows rather than directly: shortcuts, installers, scripts.
    Shell,
}

fn program_kind(path: &Path) -> Option<Program> {
    if !path.is_file() || !runs_code(path) {
        return None;
    }
    let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();
    Some(match ext.as_str() {
        "exe" | "com" => Program::Exe,
        "bat" | "cmd" => Program::Batch,
        "ps1" => Program::PowerShell,
        _ => Program::Shell,
    })
}

/// What Alt+click on `path` types into the shell: a program runs, a folder is entered, a text
/// file printed, and anything else is handed to Windows to open. `None` when there is
/// nothing to type and it should be opened instead.
pub fn run_command(path: &Path, name: &str) -> Option<String> {
    let q = windows_word(path);
    // A script is text too, but Alt+click runs it rather than printing it.
    match program_kind(path) {
        Some(Program::Exe) => return Some(q),
        Some(Program::Batch) => return Some(format!("cmd.exe //c {q}")),
        Some(Program::PowerShell) => return Some(format!("powershell.exe -NoProfile -File {q}")),
        Some(Program::Shell) => return Some(format!("cmd.exe //c start \"\" {q}")),
        None => {}
    }
    entry_command(path, name).or_else(|| Some(format!("cmd.exe //c start \"\" {q}")))
}

/// What Shift+click on `path` types into the shell: a program gets a pane of its own with
/// `embed`, and a folder or a text file opens in VS Code in the pane. `None` for what has no
/// window to show (a picture, an installer) and should be opened instead.
pub fn embed_command(path: &Path) -> Option<String> {
    let q = windows_word(path);
    match program_kind(path) {
        Some(Program::Exe) => Some(format!("embed {q}")),
        Some(Program::Batch) => Some(format!("embed cmd.exe //c {q}")),
        Some(Program::PowerShell) => Some(format!("embed powershell.exe -NoProfile -File {q}")),
        // Shortcuts and installers hand off to another process, whose window can't be found.
        Some(Program::Shell) => None,
        None if path.is_dir() || opens_in_editor(path) => Some(format!("vscode {q}")),
        None => None,
    }
}

/// What Shift+click on an address types: the browser, in the pane.
pub fn embed_url_command(url: &str) -> String {
    format!("zen {}", shell_quote(url))
}

/// Show a folder's place in Explorer: a folder opens, a file is selected in its folder.
pub fn show_in_explorer(path: &Path) {
    if path.is_dir() {
        shell_open(path.as_os_str());
    } else {
        reveal(path);
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn each_click_mode_types_its_own_command() {
        let dir = std::env::temp_dir().join(format!("rustimal-modes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("my folder")).unwrap();
        for file in ["brave.exe", "tool.bat", "setup.ps1", "link.lnk", "notes.txt", "photo.png"] {
            std::fs::write(dir.join(file), if file.ends_with("png") { &[0u8, 1, 2][..] } else { b"x" }).unwrap();
        }
        let at = |name: &str| dir.join(name);
        // A path as it is typed: Windows' own, in single quotes.
        let q = |name: &str| format!("'{}'", dir.join(name).display());
        // Alt+click runs: a program as itself, scripts through their interpreter, shortcuts
        // through Windows; a folder is entered and a text file printed, as a plain click does.
        assert_eq!(run_command(&at("brave.exe"), "brave.exe"), Some(q("brave.exe")));
        assert_eq!(run_command(&at("tool.bat"), "tool.bat"), Some(format!("cmd.exe //c {}", q("tool.bat"))));
        assert_eq!(
            run_command(&at("setup.ps1"), "setup.ps1"),
            Some(format!("powershell.exe -NoProfile -File {}", q("setup.ps1")))
        );
        assert_eq!(run_command(&at("link.lnk"), "link.lnk"), Some(format!("cmd.exe //c start \"\" {}", q("link.lnk"))));
        assert_eq!(run_command(&at("my folder"), "my folder"), Some("cd -- 'my folder' && ls".to_string()));
        assert_eq!(run_command(&at("notes.txt"), "notes.txt"), Some("cat -- 'notes.txt'".to_string()));
        assert_eq!(
            run_command(&at("photo.png"), "photo.png"),
            Some(format!("cmd.exe //c start \"\" {}", q("photo.png")))
        );
        // Shift+click shows it in the pane: a program with `embed`, the rest in VS Code.
        assert_eq!(embed_command(&at("brave.exe")), Some(format!("embed {}", q("brave.exe"))));
        assert_eq!(embed_command(&at("tool.bat")), Some(format!("embed cmd.exe //c {}", q("tool.bat"))));
        assert_eq!(embed_command(&at("my folder")), Some(format!("vscode {}", q("my folder"))));
        assert_eq!(embed_command(&at("notes.txt")), Some(format!("vscode {}", q("notes.txt"))));
        assert_eq!(embed_command(&at("link.lnk")), None, "a shortcut hands off to another process");
        assert_eq!(embed_command(&at("photo.png")), None, "nothing to edit or run");
        assert_eq!(embed_url_command("https://a.b/?x=1"), "zen 'https://a.b/?x=1'");
        assert_eq!(embed_url_command("it's"), "zen 'it'\\''s'");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn the_editor_command_gets_file_line_and_column() {
        let dir = std::env::temp_dir().join(format!("rustimal-editor-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("app.css");
        let out = dir.join("out.txt");
        std::fs::write(&file, "a{}").unwrap();
        let template = format!("echo {{file}}^|{{line}}^|{{col}} > \"{}\"", out.display());
        open_in_editor_blocking(&file, Pos { line: 20, col: None }, &template);
        let got = std::fs::read_to_string(&out).unwrap();
        assert_eq!(got.trim(), format!("{}|20|1", file.display()).as_str());
        let _ = std::fs::remove_dir_all(&dir);
    }
    use super::*;

    fn bounds(text: &str, at: usize) -> Option<String> {
        let chars: Vec<char> = text.chars().collect();
        word_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect())
    }

    #[test]
    fn trims_punctuation_around_urls() {
        assert_eq!(bounds("see (https://a.io/x).", 8).as_deref(), Some("https://a.io/x"));
        assert_eq!(bounds("go to https://a.io/x, then", 10).as_deref(), Some("https://a.io/x"));
        assert_eq!(
            bounds("https://en.wikipedia.org/wiki/Foo_(bar)", 5).as_deref(),
            Some("https://en.wikipedia.org/wiki/Foo_(bar)")
        );
    }

    #[test]
    fn no_word_on_whitespace_or_quotes() {
        assert_eq!(bounds("a  b", 1), None);
        assert_eq!(bounds("say \"hi\"", 4), None);
        assert_eq!(bounds("abc", 9), None);
    }

    #[test]
    fn classifies_urls() {
        assert_eq!(classify("https://a.io", None), Some(Target::Url("https://a.io".into())));
        assert_eq!(classify("HTTP://A.IO/x", None), Some(Target::Url("HTTP://A.IO/x".into())));
        assert_eq!(classify("www.rust-lang.org", None), Some(Target::Url("https://www.rust-lang.org".into())));
        assert_eq!(classify("https://", None), None);
        assert_eq!(classify("ftp://a.io", None), None);
    }

    #[test]
    fn position_suffix_is_removed_but_not_the_drive() {
        assert_eq!(strip_position("src/app.rs:12:5"), "src/app.rs");
        assert_eq!(strip_position("src/app.rs:12"), "src/app.rs");
        assert_eq!(strip_position("C:\\x\\y.rs:3"), "C:\\x\\y.rs");
        assert_eq!(strip_position("C:\\x"), "C:\\x");
        assert_eq!(strip_position("note:abc"), "note:abc");
    }

    #[test]
    fn finds_files_that_exist_only() {
        let here = std::env::current_dir().unwrap();
        assert_eq!(existing_path("Cargo.toml:3:1", Some(&here)), Some(here.join("Cargo.toml")));
        assert_eq!(existing_path("a/src/main.rs", Some(&here)), Some(here.join("src\\main.rs")));
        assert_eq!(existing_path("src/no_such_file.rs", Some(&here)), None);
        assert_eq!(existing_path("hello", Some(&here)), None);
        assert_eq!(existing_path("Cargo.toml", None), None);
        let abs = here.join("Cargo.toml");
        assert_eq!(existing_path(&abs.to_string_lossy().replace('\\', "/"), None), Some(abs));
    }

    #[test]
    fn finds_names_as_ls_prints_them() {
        let here = std::env::current_dir().unwrap();
        // Bare names, and the markers from `ls -F`.
        assert_eq!(existing_path("src", Some(&here)), Some(here.join("src")));
        assert_eq!(existing_path("src/", Some(&here)), Some(here.join("src")));
        assert_eq!(existing_path("Cargo.toml*", Some(&here)), Some(here.join("Cargo.toml")));
        assert_eq!(existing_path("Cargo.toml@", Some(&here)), Some(here.join("Cargo.toml")));
        assert_eq!(existing_path("no_such_thing", Some(&here)), None);
        // The folder in the prompt.
        assert_eq!(existing_path("~", None), dirs::home_dir());
        assert_eq!(existing_path("a:b", Some(&here)), None);
    }

    #[test]
    fn quoted_names_with_spaces() {
        let chars: Vec<char> = "ls  'My Folder'  'x y'  it's".chars().collect();
        let inner = |at: usize| quoted_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
        assert_eq!(inner(7).as_deref(), Some("My Folder")); // on "Folder"
        assert_eq!(inner(18).as_deref(), Some("x y"));
        assert_eq!(inner(14), None); // on the closing quote
        assert_eq!(inner(15), None); // between the two names
        assert_eq!(inner(0), None);
    }

    #[test]
    fn an_apostrophe_in_a_name_does_not_shift_the_quotes_after_it() {
        // What `ls -F` prints: names with an apostrophe get double quotes.
        let chars: Vec<char> = "'a b.txt'  c.txt  \"it's here\"/  'my folder'/  plain/".chars().collect();
        let inner = |at: usize| quoted_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
        assert_eq!(inner(2).as_deref(), Some("a b.txt"));
        assert_eq!(inner(21).as_deref(), Some("it's here"));
        assert_eq!(inner(23).as_deref(), Some("it's here"), "on the apostrophe itself");
        let at = chars.iter().position(|&c| c == 'f').unwrap();
        assert_eq!(inner(at).as_deref(), Some("my folder"), "after the apostrophe's name");
        assert_eq!(inner(chars.len() - 3), None, "plain/ has no quotes");
    }

    #[test]
    fn unquoted_names_with_spaces_are_found_from_the_folder() {
        let dir = std::env::temp_dir().join(format!("rustimal-spaced-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("my folder")).unwrap();
        std::fs::create_dir_all(dir.join("my folder two")).unwrap();
        std::fs::write(dir.join("a b.txt"), "x").unwrap();
        let chars: Vec<char> = "a b.txt   my folder/   my folder two   other".chars().collect();
        let found =
            |at: usize| spaced_entry(&chars, at, Some(&dir)).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
        assert_eq!(found(2).as_deref(), Some("a b.txt"));
        assert_eq!(found(14).as_deref(), Some("my folder"), "a marker after the name is not part of it");
        assert_eq!(found(26).as_deref(), Some("my folder two"), "the longest name that covers the cell");
        assert_eq!(found(chars.len() - 2), None);
        assert_eq!(spaced_entry(&chars, 2, None), None);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn bare_names_are_entries() {
        let here = std::env::current_dir().unwrap();
        let entry = |name: &str| Some(Target::Entry { path: here.join(name), name: name.to_string() });
        assert_eq!(path_target("src", Some(&here)), entry("src"));
        assert_eq!(path_target("src/", Some(&here)), entry("src"));
        assert_eq!(path_target("Cargo.toml*", Some(&here)), entry("Cargo.toml"));
        // Anything with a folder, a line number, a drive or ~ is a plain path.
        assert_eq!(path_target("src/main.rs", Some(&here)), Some(Target::Path(here.join("src\\main.rs"))));
        assert_eq!(
            path_target("Cargo.toml:3", Some(&here)),
            Some(Target::Location { path: here.join("Cargo.toml"), pos: Pos { line: 3, col: None } })
        );
        assert_eq!(path_target("~", None), dirs::home_dir().map(Target::Path));
    }

    #[test]
    fn click_actions_by_file_kind() {
        let dir = std::env::temp_dir().join(format!("rustimal-links-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let write = |name: &str, bytes: &[u8]| {
            let p = dir.join(name);
            std::fs::write(&p, bytes).unwrap();
            p
        };
        assert_eq!(entry_action(&dir), EntryAction::Enter);
        assert_eq!(entry_action(&write("a.json", b"{}")), EntryAction::Print);
        assert_eq!(entry_action(&write("App.JSX", b"<a/>")), EntryAction::Print);
        assert_eq!(entry_action(&write("LICENSE", b"MIT")), EntryAction::Print);
        assert_eq!(entry_action(&write(".gitignore", b"target")), EntryAction::Print);
        assert_eq!(entry_action(&write("pic.png", b"png")), EntryAction::Open);
        assert_eq!(entry_action(&write("tool.exe", b"MZ")), EntryAction::Open);
        assert_eq!(entry_action(&write("nul.json", b"a\0b")), EntryAction::Open);
        assert_eq!(entry_action(&write("no_ext_binary", &[1, 0, 2])), EntryAction::Open);
        assert_eq!(entry_action(&write("big.txt", &vec![b'x'; (MAX_CAT_BYTES + 1) as usize])), EntryAction::Open);
        assert_eq!(entry_command(&dir, "my dir").as_deref(), Some("cd -- 'my dir' && ls"));
        assert_eq!(entry_command(&dir.join("a.json"), "a.json").as_deref(), Some("cat -- 'a.json'"));
        assert_eq!(entry_command(&dir.join("pic.png"), "pic.png"), None);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn dropped_paths_are_written_for_git_bash() {
        let word = |p: &str| shell_word(&msys_path(Path::new(p)));
        assert_eq!(word("C:\\Users\\me\\a.txt"), "/c/Users/me/a.txt");
        assert_eq!(word("C:\\Users\\me\\a b.txt"), "'/c/Users/me/a b.txt'");
        assert_eq!(word("D:\\"), "/d/");
        assert_eq!(word("\\\\server\\share\\f.txt"), "//server/share/f.txt");
        assert_eq!(word("C:\\it's.txt"), "'/c/it'\\''s.txt'");
        assert_eq!(word("C:\\a&b.txt"), "'/c/a&b.txt'");
    }

    #[test]
    fn names_are_quoted_for_bash() {
        assert_eq!(shell_quote("plain"), "'plain'");
        assert_eq!(shell_quote("it's"), "'it'\\''s'");
        assert_eq!(shell_quote("a b; rm -rf *"), "'a b; rm -rf *'");
    }

    #[test]
    fn splits_positions_in_every_style() {
        let pos = |line, col| Some(Pos { line, col });
        assert_eq!(split_position("src/app.rs:12:5"), ("src/app.rs", pos(12, Some(5))));
        assert_eq!(split_position("src/app.rs:12"), ("src/app.rs", pos(12, None)));
        assert_eq!(split_position("src/app.ts(12,5)"), ("src/app.ts", pos(12, Some(5))));
        assert_eq!(split_position("src/app.ts(12)"), ("src/app.ts", pos(12, None)));
        assert_eq!(split_position("C:\\proj\\a.js:3:9"), ("C:\\proj\\a.js", pos(3, Some(9))));
        assert_eq!(split_position("C:\\proj\\a.js"), ("C:\\proj\\a.js", None));
        assert_eq!(split_position("Foo.bar(Foo.java:12)"), ("Foo.bar(Foo.java:12)", None));
        assert_eq!(split_position("f(1,2,3)"), ("f(1,2,3)", None));
    }

    #[test]
    fn positions_after_a_path() {
        let after = |text: &str| {
            let chars: Vec<char> = text.chars().collect();
            let hi = chars.iter().position(|&c| c == ']').unwrap();
            following_position(&chars, hi)
        };
        // Python: File "x.py", line 12, in f      (the path is the part before `]`)
        assert_eq!(after("x.py]\", line 12, in f"), Some(Pos { line: 12, col: None }));
        // webpack: ERROR in ./src/a.js 12:5-20
        assert_eq!(after("a.js] 12:5-20"), Some(Pos { line: 12, col: Some(5) }));
        // A count of something else is not a line number.
        assert_eq!(after("main.rs] 12 files changed"), None);
        assert_eq!(after("main.rs]"), None);
    }

    #[test]
    fn error_traces_become_locations() {
        let here = std::env::current_dir().unwrap();
        let main = here.join("src").join("main.rs");
        let loc = |line, col| Some(Target::Location { path: main.clone(), pos: Pos { line, col } });
        // rustc, Node and C compilers all write path:line:col.
        assert_eq!(classify("src/main.rs:12:5", Some(&here)), loc(12, Some(5)));
        // tsc
        assert_eq!(classify("src/main.rs(12,5)", Some(&here)), loc(12, Some(5)));
        // A Java-style frame.
        assert_eq!(classify("Foo.bar(src/main.rs:30)", Some(&here)), loc(30, None));
        // Node ES modules.
        let url = format!("file:///{}:7:3", main.to_string_lossy().replace('\\', "/").replace(' ', "%20"));
        assert_eq!(classify(&url, None), loc(7, Some(3)));
        // From a subfolder, a path relative to the project root is still found.
        let sub = here.join("src");
        assert_eq!(classify("src/main.rs:12:5", Some(&sub)), loc(12, Some(5)));
        // A folder with a line number is just the folder.
        assert_eq!(classify("src:3", Some(&here)), Some(Target::Path(here.join("src"))));
        // Nothing there.
        assert_eq!(classify("src/nope.rs:3:1", Some(&here)), None);
    }

    #[test]
    fn executables_are_revealed_not_run() {
        assert!(runs_code(Path::new("C:\\x\\tool.EXE")));
        assert!(runs_code(Path::new("setup.ps1")));
        assert!(!runs_code(Path::new("notes.md")));
        assert!(!runs_code(Path::new("Makefile")));
    }
}