Skip to main content

arb/
fzf.rs

1//! fzf option compatibility: everything `arb --fzf` needs to paint the picker the
2//! `fzf` binary would paint for the same environment.
3//!
4//! Two halves:
5//!
6//! 1. **Config ingestion** — `$FZF_DEFAULT_OPTS_FILE` and `$FZF_DEFAULT_OPTS`.
7//!    A drop-in (`ZPWR_FZF='arb --fzf'`) inherits the user's fzf configuration
8//!    exactly like the real binary does, so the prompt string, layout, border,
9//!    colors and key bindings come out identical without touching the call site.
10//! 2. **Look parsing** — the presentation flags (`--layout`, `--border`,
11//!    `--info`, `--pointer`, `--marker`, `--color`, `--bind`, `--cycle`) that
12//!    used to be dropped as "cosmetic". They are the look, so they are honored.
13//!
14//! The default palettes are not invented: they were read off fzf 0.74.2's own
15//! output by running it under a pty and decoding the SGR sequences it emitted
16//! (`dark`, `light` and `base16` each captured separately). Each constant below
17//! is the color index fzf actually wrote for that slot.
18
19use ratatui::style::{Color, Modifier, Style};
20use ratatui::widgets::{BorderType, Borders};
21
22/// Split a shell-style option string into words, honoring `'…'`, `"…"` and `\`.
23/// `$FZF_DEFAULT_OPTS` is written as a shell fragment — e.g.
24/// `--prompt='<<)ZPWR(>> ' --reverse` — so splitting on whitespace alone would
25/// tear the prompt in half and lose its trailing space.
26pub fn shell_split(s: &str) -> Vec<String> {
27    let mut out = Vec::new();
28    let mut cur = String::new();
29    let mut started = false; // `--prompt=''` is an empty word, not no word
30    let mut quote: Option<char> = None;
31    let mut chars = s.chars();
32    while let Some(c) = chars.next() {
33        match quote {
34            // Inside single quotes everything is literal (shell rules).
35            Some('\'') if c == '\'' => quote = None,
36            Some('\'') => cur.push(c),
37            Some('"') if c == '"' => quote = None,
38            Some('"') if c == '\\' => match chars.next() {
39                // In double quotes a backslash only escapes these four.
40                Some(n @ ('"' | '\\' | '$' | '`')) => cur.push(n),
41                Some(n) => {
42                    cur.push('\\');
43                    cur.push(n);
44                }
45                None => cur.push('\\'),
46            },
47            Some('"') => cur.push(c),
48            Some(_) => unreachable!("quote is only ever ' or \""),
49            None => match c {
50                '\'' | '"' => {
51                    started = true;
52                    quote = Some(c);
53                }
54                '\\' => {
55                    started = true;
56                    if let Some(n) = chars.next() {
57                        cur.push(n);
58                    }
59                }
60                c if c.is_whitespace() => {
61                    if started {
62                        out.push(std::mem::take(&mut cur));
63                        started = false;
64                    }
65                }
66                _ => {
67                    started = true;
68                    cur.push(c);
69                }
70            },
71        }
72    }
73    if started {
74        out.push(cur);
75    }
76    out
77}
78
79/// The user's fzf configuration as argv words: `$FZF_DEFAULT_OPTS_FILE` first,
80/// then `$FZF_DEFAULT_OPTS` — fzf's own precedence, with the command line
81/// (spliced after these by the caller) winning over both.
82pub fn env_args() -> Vec<String> {
83    let mut out = Vec::new();
84    if let Ok(path) = std::env::var("FZF_DEFAULT_OPTS_FILE") {
85        let path = match (path.strip_prefix("~/"), std::env::var("HOME")) {
86            (Some(rest), Ok(home)) => format!("{home}/{rest}"),
87            _ => path,
88        };
89        if let Ok(body) = std::fs::read_to_string(path) {
90            out.extend(shell_split(&body));
91        }
92    }
93    if let Ok(opts) = std::env::var("FZF_DEFAULT_OPTS") {
94        out.extend(shell_split(&opts));
95    }
96    out
97}
98
99/// One `--color` slot: an optional color (None = the terminal's default) plus
100/// text attributes, e.g. fzf's `hl+:151:bold`.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub struct Ent {
103    pub color: Option<Color>,
104    pub attrs: Modifier,
105}
106
107impl Ent {
108    /// A plain colored slot.
109    fn c(idx: u8) -> Self {
110        Ent {
111            color: Some(Color::Indexed(idx)),
112            attrs: Modifier::empty(),
113        }
114    }
115    /// A bold colored slot (fzf bolds the pointer, the current line and hl+).
116    fn b(idx: u8) -> Self {
117        Ent {
118            color: Some(Color::Indexed(idx)),
119            attrs: Modifier::BOLD,
120        }
121    }
122    /// Attributes only — the terminal's default color (fzf's `-1`).
123    fn attr(attrs: Modifier) -> Self {
124        Ent { color: None, attrs }
125    }
126    /// As a foreground style.
127    pub fn fg(self) -> Style {
128        let s = Style::default().add_modifier(self.attrs);
129        match self.color {
130            Some(c) => s.fg(c),
131            None => s,
132        }
133    }
134    /// As a background style (used for `bg`/`bg+`, where attrs don't apply).
135    pub fn bg(self) -> Style {
136        match self.color {
137            Some(c) => Style::default().bg(c),
138            None => Style::default(),
139        }
140    }
141}
142
143/// fzf's color slots. Field names track fzf's option names (`fg+` → `fg_plus`).
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct Colors {
146    pub fg: Ent,
147    pub bg: Ent,
148    pub hl: Ent,
149    pub fg_plus: Ent,
150    pub bg_plus: Ent,
151    pub hl_plus: Ent,
152    pub gutter: Ent,
153    pub pointer: Ent,
154    pub marker: Ent,
155    pub prompt: Ent,
156    pub query: Ent,
157    pub info: Ent,
158    pub spinner: Ent,
159    pub header: Ent,
160    pub border: Ent,
161    pub separator: Ent,
162    pub scrollbar: Ent,
163}
164
165impl Default for Colors {
166    fn default() -> Self {
167        Colors::dark()
168    }
169}
170
171impl Colors {
172    /// fzf's `dark` scheme (its default on a 256-color terminal), as measured
173    /// from fzf 0.74.2's SGR output.
174    pub fn dark() -> Self {
175        Colors {
176            fg: Ent::default(),
177            bg: Ent::default(),
178            hl: Ent::c(108),
179            fg_plus: Ent::b(254),
180            bg_plus: Ent::c(236),
181            hl_plus: Ent::b(151),
182            gutter: Ent::c(236),
183            pointer: Ent::b(161),
184            marker: Ent::c(168),
185            prompt: Ent::b(110),
186            query: Ent::attr(Modifier::BOLD),
187            info: Ent::c(144),
188            spinner: Ent::b(148),
189            header: Ent::c(109),
190            border: Ent::c(59),
191            separator: Ent::c(59),
192            scrollbar: Ent::c(59),
193        }
194    }
195
196    /// fzf's `light` scheme.
197    pub fn light() -> Self {
198        Colors {
199            hl: Ent::c(66),
200            fg_plus: Ent::b(237),
201            bg_plus: Ent::c(251),
202            hl_plus: Ent::b(23),
203            gutter: Ent::c(251),
204            pointer: Ent::b(161),
205            marker: Ent::c(168),
206            prompt: Ent::b(25),
207            info: Ent::c(101),
208            border: Ent::c(145),
209            separator: Ent::c(145),
210            scrollbar: Ent::c(145),
211            ..Colors::dark()
212        }
213    }
214
215    /// fzf's `base16`/`16` scheme — the basic ANSI palette instead of 256 colors.
216    pub fn base16() -> Self {
217        Colors {
218            hl: Ent {
219                color: Some(Color::Green),
220                attrs: Modifier::empty(),
221            },
222            fg_plus: Ent {
223                color: Some(Color::White),
224                attrs: Modifier::BOLD,
225            },
226            bg_plus: Ent {
227                color: Some(Color::DarkGray),
228                attrs: Modifier::empty(),
229            },
230            hl_plus: Ent {
231                color: Some(Color::LightGreen),
232                attrs: Modifier::BOLD,
233            },
234            gutter: Ent {
235                color: Some(Color::DarkGray),
236                attrs: Modifier::empty(),
237            },
238            pointer: Ent {
239                color: Some(Color::Red),
240                attrs: Modifier::BOLD,
241            },
242            marker: Ent {
243                color: Some(Color::Magenta),
244                attrs: Modifier::empty(),
245            },
246            prompt: Ent {
247                color: Some(Color::Blue),
248                attrs: Modifier::BOLD,
249            },
250            info: Ent {
251                color: Some(Color::Yellow),
252                attrs: Modifier::empty(),
253            },
254            border: Ent::attr(Modifier::DIM),
255            separator: Ent::attr(Modifier::DIM),
256            scrollbar: Ent::attr(Modifier::DIM),
257            ..Colors::dark()
258        }
259    }
260
261    /// fzf's `bw` scheme (`--no-color`, or `$NO_COLOR` set): attributes only.
262    pub fn bw() -> Self {
263        Colors {
264            fg: Ent::default(),
265            bg: Ent::default(),
266            hl: Ent::attr(Modifier::UNDERLINED),
267            fg_plus: Ent::attr(Modifier::BOLD),
268            bg_plus: Ent::default(),
269            hl_plus: Ent::attr(Modifier::BOLD | Modifier::UNDERLINED),
270            gutter: Ent::default(),
271            pointer: Ent::attr(Modifier::BOLD),
272            marker: Ent::attr(Modifier::BOLD),
273            prompt: Ent::default(),
274            query: Ent::attr(Modifier::BOLD),
275            info: Ent::default(),
276            spinner: Ent::default(),
277            header: Ent::default(),
278            border: Ent::default(),
279            separator: Ent::default(),
280            scrollbar: Ent::default(),
281        }
282    }
283
284    /// Look up a base scheme by fzf's name.
285    fn scheme(name: &str) -> Option<Self> {
286        match name {
287            "dark" => Some(Colors::dark()),
288            "light" => Some(Colors::light()),
289            "16" | "base16" => Some(Colors::base16()),
290            "bw" | "no" => Some(Colors::bw()),
291            _ => None,
292        }
293    }
294
295    /// Assign one slot by its fzf name (aliases included). Unknown names — the
296    /// preview/label/scrollbar family arb has no analog for — are ignored, so a
297    /// rich `--color` line from a themed setup still applies the slots that do
298    /// map instead of failing the whole spec.
299    fn set(&mut self, name: &str, ent: Ent) {
300        match name {
301            "fg" | "list-fg" => self.fg = ent,
302            "bg" | "list-bg" => self.bg = ent,
303            "hl" => self.hl = ent,
304            "fg+" | "current-fg" | "selected-fg" => self.fg_plus = ent,
305            "bg+" | "current-bg" | "selected-bg" => self.bg_plus = ent,
306            "hl+" | "current-hl" | "selected-hl" => self.hl_plus = ent,
307            "gutter" => self.gutter = ent,
308            "pointer" => self.pointer = ent,
309            "marker" => self.marker = ent,
310            "prompt" => self.prompt = ent,
311            "query" | "input-fg" => self.query = ent,
312            "info" => self.info = ent,
313            "spinner" => self.spinner = ent,
314            "header" => self.header = ent,
315            "border" => {
316                self.border = ent;
317                self.separator = ent;
318            }
319            "separator" => self.separator = ent,
320            _ => {}
321        }
322    }
323}
324
325/// Parse one fzf color token: an index (`161`), `-1` for the terminal default,
326/// `#rrggbb`, or an ANSI color name.
327fn parse_color(tok: &str) -> Option<Option<Color>> {
328    if tok == "-1" || tok == "default" {
329        return Some(None);
330    }
331    if let Some(hex) = tok.strip_prefix('#') {
332        if hex.len() == 6 {
333            let n = u32::from_str_radix(hex, 16).ok()?;
334            return Some(Some(Color::Rgb((n >> 16) as u8, (n >> 8) as u8, n as u8)));
335        }
336        return None;
337    }
338    if let Ok(idx) = tok.parse::<u8>() {
339        return Some(Some(Color::Indexed(idx)));
340    }
341    let named = match tok {
342        "black" => Color::Black,
343        "red" => Color::Red,
344        "green" => Color::Green,
345        "yellow" => Color::Yellow,
346        "blue" => Color::Blue,
347        "magenta" => Color::Magenta,
348        "cyan" => Color::Cyan,
349        "white" => Color::Gray,
350        "bright-black" | "gray" | "grey" => Color::DarkGray,
351        "bright-red" => Color::LightRed,
352        "bright-green" => Color::LightGreen,
353        "bright-yellow" => Color::LightYellow,
354        "bright-blue" => Color::LightBlue,
355        "bright-magenta" => Color::LightMagenta,
356        "bright-cyan" => Color::LightCyan,
357        "bright-white" => Color::White,
358        _ => return None,
359    };
360    Some(Some(named))
361}
362
363/// Parse one fzf attribute token.
364fn parse_attr(tok: &str) -> Option<Modifier> {
365    match tok {
366        "bold" => Some(Modifier::BOLD),
367        "dim" => Some(Modifier::DIM),
368        "italic" => Some(Modifier::ITALIC),
369        "underline" => Some(Modifier::UNDERLINED),
370        "blink" => Some(Modifier::SLOW_BLINK),
371        "reverse" => Some(Modifier::REVERSED),
372        "strikethrough" => Some(Modifier::CROSSED_OUT),
373        "regular" => Some(Modifier::empty()),
374        _ => None,
375    }
376}
377
378/// Apply one `--color=…` value: an optional leading base scheme followed by
379/// `name:color[:attr…]` entries, separated by commas and/or whitespace.
380fn apply_color_spec(colors: &mut Colors, spec: &str) {
381    for entry in spec.split([',', ' ', '\t']).filter(|e| !e.is_empty()) {
382        let mut parts = entry.split(':');
383        let Some(name) = parts.next() else { continue };
384        if let Some(scheme) = Colors::scheme(name) {
385            // A base scheme resets every slot; later entries customize it.
386            *colors = scheme;
387            continue;
388        }
389        let mut ent = Ent::default();
390        let mut saw = false;
391        for tok in parts {
392            if let Some(c) = parse_color(tok) {
393                ent.color = c;
394                saw = true;
395            } else if let Some(a) = parse_attr(tok) {
396                ent.attrs |= a;
397                saw = true;
398            }
399        }
400        if saw {
401            colors.set(name, ent);
402        }
403    }
404}
405
406/// One `--nth`/`--with-nth` field range. `1` is the first field, `-1` the last,
407/// and [`Nth::ELLIPSIS`] is the open end of `2..` / `..3` / `..`.
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409pub struct Nth {
410    pub begin: i32,
411    pub end: i32,
412}
413
414impl Nth {
415    pub const ELLIPSIS: i32 = i32::MIN;
416
417    /// Parse one range in fzf's syntax (`ParseRange` in tokenizer.go).
418    pub fn parse(s: &str) -> Option<Nth> {
419        let n = |v: &str| v.parse::<i32>().ok().filter(|n| *n != 0);
420        if s == ".." {
421            return Some(Nth {
422                begin: Nth::ELLIPSIS,
423                end: Nth::ELLIPSIS,
424            });
425        }
426        if let Some(rest) = s.strip_prefix("..") {
427            return n(rest).map(|end| Nth {
428                begin: Nth::ELLIPSIS,
429                end,
430            });
431        }
432        if let Some(rest) = s.strip_suffix("..") {
433            return n(rest).map(|begin| Nth {
434                begin,
435                end: Nth::ELLIPSIS,
436            });
437        }
438        if let Some((a, b)) = s.split_once("..") {
439            let (begin, end) = (n(a)?, n(b)?);
440            // fzf rejects a negative start paired with a positive end.
441            return (!(begin < 0 && end > 0)).then_some(Nth { begin, end });
442        }
443        n(s).map(|v| Nth { begin: v, end: v })
444    }
445
446    /// Parse a comma-separated list (`--nth 1,3..`). Any bad entry drops the
447    /// whole list, as fzf treats it as an option error.
448    pub fn parse_list(s: &str) -> Vec<Nth> {
449        let mut out = Vec::new();
450        for part in s.split(',').filter(|p| !p.is_empty()) {
451            match Nth::parse(part) {
452                Some(r) => out.push(r),
453                None => return Vec::new(),
454            }
455        }
456        out
457    }
458}
459
460/// Split a line into fields the way fzf's `Tokenize` does: with no
461/// `--delimiter`, AWK-style — each token is a run of non-space plus the
462/// whitespace that follows it, and leading whitespace belongs to no token. With
463/// a delimiter, each token keeps its trailing delimiter so ranges rejoin
464/// exactly as they appeared.
465pub fn tokenize<'a>(text: &'a str, delimiter: Option<&str>) -> Vec<&'a str> {
466    let Some(d) = delimiter else {
467        let mut out = Vec::new();
468        let bytes = text.as_bytes();
469        let (mut start, mut i) = (0usize, 0usize);
470        // Skip the leading whitespace — fzf counts it as a prefix, not a token.
471        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
472            i += 1;
473        }
474        start = start.max(i);
475        while i < bytes.len() {
476            // A token runs to the end of the whitespace that follows it.
477            while i < bytes.len() && bytes[i] != b' ' && bytes[i] != b'\t' {
478                i += 1;
479            }
480            while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
481                i += 1;
482            }
483            out.push(&text[start..i]);
484            start = i;
485        }
486        return out;
487    };
488    if d.is_empty() {
489        return vec![text];
490    }
491    let mut out = Vec::new();
492    let mut rest = text;
493    while let Some(pos) = rest.find(d) {
494        let (head, tail) = rest.split_at(pos + d.len());
495        out.push(head);
496        rest = tail;
497    }
498    if !rest.is_empty() {
499        out.push(rest);
500    }
501    out
502}
503
504/// The text a `--nth`/`--with-nth` range selects: the chosen tokens rejoined.
505/// With an explicit delimiter the trailing one is dropped (`--nth 1` on
506/// `a:b:c` matches `a`, not `a:`, while `--nth 1..2` matches `a:b`); AWK-style
507/// tokens keep their trailing whitespace.
508pub fn transform(tokens: &[&str], ranges: &[Nth], delimiter: Option<&str>) -> String {
509    if ranges.is_empty() {
510        return tokens.concat();
511    }
512    let mut out = String::new();
513    for r in ranges {
514        let part = transform_join(tokens, std::slice::from_ref(r));
515        match delimiter {
516            Some(d) => out.push_str(part.strip_suffix(d).unwrap_or(&part)),
517            None => out.push_str(&part),
518        }
519    }
520    out
521}
522
523/// fzf's `JoinTokens(Transform(...))`: the selected tokens concatenated as they
524/// were, delimiters and all. A token carries the separator that followed it, so
525/// joining fields 2 and 3 of `a:b:c` gives `b:c` — [`transform`] instead trims
526/// each range, which is what `--nth` matching wants and what `--accept-nth`
527/// printing must not do (fzf strips only the very last delimiter, once).
528pub fn transform_join(tokens: &[&str], ranges: &[Nth]) -> String {
529    if ranges.is_empty() {
530        return tokens.concat();
531    }
532    let n = tokens.len() as i32;
533    let resolve = |v: i32| if v < 0 { v + n + 1 } else { v };
534    let mut out = String::new();
535    for r in ranges {
536        let (begin, end) = match (r.begin, r.end) {
537            (Nth::ELLIPSIS, Nth::ELLIPSIS) => (1, n),
538            (Nth::ELLIPSIS, e) => (1, resolve(e)),
539            (b, Nth::ELLIPSIS) => (resolve(b), n),
540            (b, e) => (resolve(b), resolve(e)),
541        };
542        for idx in begin.max(1)..=end.min(n) {
543            out.push_str(tokens[(idx - 1) as usize]);
544        }
545    }
546    out
547}
548
549/// Strip SGR escape sequences, leaving the text `--ansi` should match against.
550pub fn strip_ansi(s: &str) -> String {
551    if !s.contains('\u{1b}') {
552        return s.to_string();
553    }
554    let mut out = String::with_capacity(s.len());
555    let mut chars = s.chars();
556    while let Some(c) = chars.next() {
557        if c != '\u{1b}' {
558            out.push(c);
559            continue;
560        }
561        // `ESC [ … <final>` — drop the whole sequence.
562        if chars.next() != Some('[') {
563            continue;
564        }
565        for t in chars.by_ref() {
566            if t.is_ascii_alphabetic() {
567                break;
568            }
569        }
570    }
571    out
572}
573
574/// Where the prompt sits relative to the list (fzf `--layout`).
575#[derive(Clone, Copy, Debug, PartialEq, Eq)]
576pub enum Layout {
577    /// fzf's default: prompt at the bottom, list growing upward from it.
578    Default,
579    /// `--reverse` / `--layout=reverse`: prompt at the top, list below.
580    Reverse,
581    /// `--layout=reverse-list`: prompt at the bottom, list top-down.
582    ReverseList,
583}
584
585/// Where the match counter goes (fzf `--info`).
586#[derive(Clone, Debug, PartialEq, Eq)]
587pub enum Info {
588    /// Own line, on the left of a horizontal separator (fzf's default).
589    Default,
590    /// Own line, on the right of the separator.
591    Right,
592    /// No counter at all (`--info=hidden` / `--no-info`).
593    Hidden,
594    /// After the query, with the given prefix (default ` < `).
595    Inline(String),
596    /// At the right end of the prompt line.
597    InlineRight(String),
598}
599
600/// Where `--preview-window` puts the preview box relative to the list.
601#[derive(Clone, Copy, Debug, PartialEq, Eq)]
602pub enum PreviewPos {
603    Up,
604    Down,
605    Left,
606    /// fzf's default.
607    Right,
608}
609
610/// How much room the preview box takes: a share of the body, or a fixed number
611/// of columns (`left`/`right`) or rows (`up`/`down`).
612#[derive(Clone, Copy, Debug, PartialEq, Eq)]
613pub enum PreviewSize {
614    Percent(u16),
615    Cells(u16),
616}
617
618/// What `+SCROLL` of `--preview-window` takes as its base line: a number, or a
619/// field index expression (`{2}`) read from the cursor line.
620#[derive(Clone, Debug, PartialEq, Eq)]
621pub enum ScrollBase {
622    Line(i64),
623    Field(Vec<Nth>),
624}
625
626/// `--preview-window=+SCROLL[OFFSETS][/DENOM]`: the line the preview starts at
627/// for each new cursor line. `+{2}+3/2` is field 2, plus 3, placed half a
628/// window down.
629#[derive(Clone, Debug, PartialEq, Eq)]
630pub struct PreviewScroll {
631    pub base: ScrollBase,
632    /// Sum of the signed `+N`/`-N` adjustments.
633    pub offset: i64,
634    /// `/DENOM`: the line sits `rows / denom` below the top; 0 = at the top.
635    pub denom: usize,
636}
637
638impl PreviewScroll {
639    /// Parse the part after the leading `+` (`{2}-5`, `10/2`, `{1}+3/2`).
640    fn parse(spec: &str) -> Option<PreviewScroll> {
641        let (spec, denom) = match spec.split_once('/') {
642            Some((s, d)) => (s, d.parse::<usize>().ok()?),
643            None => (spec, 0),
644        };
645        let (base, mut rest) = match spec.strip_prefix('{') {
646            Some(r) => {
647                let (inner, tail) = r.split_once('}')?;
648                (ScrollBase::Field(Nth::parse_list(inner)), tail)
649            }
650            None => {
651                let end = spec
652                    .find(|c: char| !c.is_ascii_digit())
653                    .unwrap_or(spec.len());
654                (ScrollBase::Line(spec[..end].parse().ok()?), &spec[end..])
655            }
656        };
657        if matches!(&base, ScrollBase::Field(n) if n.is_empty()) {
658            return None;
659        }
660        let mut offset = 0i64;
661        while !rest.is_empty() {
662            let sign = match rest.as_bytes()[0] {
663                b'+' => 1,
664                b'-' => -1,
665                _ => return None,
666            };
667            let end = rest[1..]
668                .find(|c: char| !c.is_ascii_digit())
669                .map_or(rest.len(), |i| i + 1);
670            offset += sign * rest[1..end].parse::<i64>().ok()?;
671            rest = &rest[end..];
672        }
673        Some(PreviewScroll {
674            base,
675            offset,
676            denom,
677        })
678    }
679
680    /// The one-based line this spec points at for `line`, or `None` when the
681    /// field is not a number.
682    pub fn target(&self, line: &str, delimiter: Option<&str>) -> Option<i64> {
683        let base = match &self.base {
684            ScrollBase::Line(n) => *n,
685            ScrollBase::Field(nth) => {
686                let tokens = tokenize(line, delimiter);
687                let field = strip_last_delimiter(&transform_join(&tokens, nth), delimiter);
688                field.trim().parse::<i64>().ok()?
689            }
690        };
691        Some(base + self.offset)
692    }
693
694    /// First preview line (zero-based) to show for a pane of `rows` rows.
695    pub fn top(&self, target: i64, rows: usize) -> usize {
696        let above = rows.checked_div(self.denom).unwrap_or(0) as i64;
697        (target - 1 - above).max(0) as usize
698    }
699}
700
701/// `--preview-window=[POSITION][,SIZE[%]][,[no]wrap][,[no]hidden][,+SCROLL][,…]`.
702///
703/// The flags arb can act on are modeled; the rest of fzf's grammar
704/// (`border-STYLE`, `follow`, `cycle`, `info`, `~HEADER_LINES`, `default`,
705/// `<THRESHOLD(ALT)`) parses without error and is ignored, so a spec written
706/// for fzf never fails here — it just may not be honored in full.
707#[derive(Clone, Debug, PartialEq, Eq)]
708pub struct PreviewWindow {
709    pub pos: PreviewPos,
710    pub size: PreviewSize,
711    /// `hidden`: the box is not drawn (the command still runs, as in fzf).
712    pub hidden: bool,
713    /// `wrap`: long preview lines wrap instead of being truncated.
714    pub wrap: bool,
715    /// `+SCROLL…`: where each cursor line's preview starts.
716    pub scroll: Option<PreviewScroll>,
717}
718
719impl Default for PreviewWindow {
720    fn default() -> Self {
721        // fzf(1): "POSITION: (default: right)", and its default size is half the
722        // window.
723        Self {
724            pos: PreviewPos::Right,
725            size: PreviewSize::Percent(50),
726            hidden: false,
727            wrap: false,
728            scroll: None,
729        }
730    }
731}
732
733impl PreviewWindow {
734    /// Parse one `--preview-window` spec. fzf accepts the parts in any order,
735    /// separated by `,`; the older `:` form (`right:55%`) is still widely
736    /// written, so both separators are taken.
737    pub fn parse(spec: &str) -> PreviewWindow {
738        let mut w = PreviewWindow::default();
739        w.apply(spec);
740        w
741    }
742
743    /// Apply a spec on top of the current settings: fzf folds repeated
744    /// `--preview-window` options into one, so `--preview-window right:50%
745    /// --preview-window +{2}` keeps the position and size.
746    pub fn apply(&mut self, spec: &str) {
747        let w = self;
748        for part in spec.split([',', ':']).map(str::trim) {
749            match part {
750                "" => {}
751                "up" | "top" => w.pos = PreviewPos::Up,
752                "down" | "bottom" => w.pos = PreviewPos::Down,
753                "left" => w.pos = PreviewPos::Left,
754                // `next` places the preview on the list side of the input. arb
755                // draws the input at the top in every fzf layout it models, so
756                // that is the same side as `down`.
757                "right" | "next" => w.pos = PreviewPos::Right,
758                "hidden" => w.hidden = true,
759                "nohidden" => w.hidden = false,
760                "wrap" | "wrap-word" => w.wrap = true,
761                "nowrap" => w.wrap = false,
762                _ if part.starts_with('+') => w.scroll = PreviewScroll::parse(&part[1..]),
763                _ => {
764                    if let Some(n) = part.strip_suffix('%') {
765                        if let Ok(pct) = n.parse::<u16>() {
766                            w.size = PreviewSize::Percent(pct.min(100));
767                        }
768                    } else if let Ok(cells) = part.parse::<u16>() {
769                        w.size = PreviewSize::Cells(cells);
770                    }
771                    // Anything else is a part of fzf's grammar arb does not act
772                    // on (border-*, follow, cycle, info, ~N, default,
773                    // <THRESHOLD(ALT)). Ignored rather than rejected.
774                }
775            }
776        }
777    }
778
779    /// Split `body` into (list, preview) rectangles. `None` means the preview is
780    /// not drawn — `hidden`, or a size of zero, which fzf documents as "preview
781    /// window will not be visible, but fzf will still execute the command".
782    pub fn split(
783        &self,
784        body: ratatui::layout::Rect,
785    ) -> (ratatui::layout::Rect, Option<ratatui::layout::Rect>) {
786        use ratatui::layout::{Constraint, Layout};
787        if self.hidden {
788            return (body, None);
789        }
790        let vertical = matches!(self.pos, PreviewPos::Up | PreviewPos::Down);
791        let total = match vertical {
792            true => body.height,
793            false => body.width,
794        };
795        let want = match self.size {
796            PreviewSize::Percent(p) => (u32::from(total) * u32::from(p) / 100) as u16,
797            PreviewSize::Cells(c) => c,
798        };
799        // Leave at least one cell for the list itself, or there is nothing to
800        // pick from.
801        let want = want.min(total.saturating_sub(1));
802        if want == 0 {
803            return (body, None);
804        }
805        let rest = total - want;
806        let constraints = match self.pos {
807            PreviewPos::Up | PreviewPos::Left => {
808                [Constraint::Length(want), Constraint::Length(rest)]
809            }
810            PreviewPos::Down | PreviewPos::Right => {
811                [Constraint::Length(rest), Constraint::Length(want)]
812            }
813        };
814        let chunks = match vertical {
815            true => Layout::vertical(constraints).split(body),
816            false => Layout::horizontal(constraints).split(body),
817        };
818        match self.pos {
819            PreviewPos::Up | PreviewPos::Left => (chunks[1], Some(chunks[0])),
820            PreviewPos::Down | PreviewPos::Right => (chunks[0], Some(chunks[1])),
821        }
822    }
823}
824
825/// How the query's case is read. fzf's default is smart-case — a query typed
826/// in lowercase matches either case, and one uppercase character anywhere makes
827/// the whole query case-sensitive. `-i`/`--ignore-case` and `+i`/
828/// `--no-ignore-case` pin it either way; `--smart-case` restores the default.
829#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
830pub enum Case {
831    #[default]
832    Smart,
833    Ignore,
834    Respect,
835}
836
837/// The resolved presentation of the picker: everything the renderer and the key
838/// handler need in order to match fzf.
839#[derive(Clone, Debug)]
840pub struct Look {
841    pub layout: Layout,
842    pub info: Info,
843    /// `None` = borderless (fzf's default). `Some((type, sides))` maps straight
844    /// onto ratatui's `Block`.
845    pub border: Option<(BorderType, Borders)>,
846    pub pointer: String,
847    pub marker: String,
848    /// `--ellipsis`: what a truncated row ends with (fzf's default is `··`).
849    pub ellipsis: String,
850    pub colors: Colors,
851    /// `--cycle`: moving past either end wraps around.
852    pub cycle: bool,
853    /// `--tac`: present the list in reverse input order.
854    pub tac: bool,
855    /// `--ansi`: the input carries SGR colour codes — render them, and match
856    /// against the text with the codes removed.
857    pub ansi: bool,
858    /// `--delimiter`: what splits a line into fields. `None` = fzf's AWK-style
859    /// splitting (a run of non-space plus the whitespace after it).
860    pub delimiter: Option<String>,
861    /// `--nth`: which fields the query matches against (the row still shows,
862    /// and Enter still emits, the whole line).
863    pub nth: Vec<Nth>,
864    /// `--with-nth`: which fields the row SHOWS (and, absent `--nth`, matches).
865    pub with_nth: Vec<Nth>,
866    /// `--header-lines`: the first N input lines are a header, not candidates.
867    pub header_lines: usize,
868    /// `--with-shell`: how child processes (a `--preview` command, an `execute`
869    /// binding) are started. fzf defaults to `$SHELL -c`, NOT `sh -c` — a
870    /// preview written against the user's shell (zsh's `print`, a function from
871    /// their rc) fails outright under `sh`.
872    pub with_shell: Option<String>,
873    /// `--print-query`: the query is written before the selection.
874    pub print_query: bool,
875    /// `--expect=KEYS`: these keys also accept, and the one that did is written
876    /// before the selection (an empty line when plain Enter accepted). This is
877    /// how fzf-tab drives continuous completion.
878    pub expect: Vec<(Key, String)>,
879    /// `--min-height=N[+]`: the floor for a percentage `--height`. fzf's default
880    /// is `10+` — ten LIST rows, with the chrome added on top (the `+`).
881    pub min_height: u16,
882    pub min_height_plus: bool,
883    /// `--no-scrollbar`: give the list its last column back.
884    pub scrollbar: bool,
885    /// `--scroll-off`: screen lines kept above/below the cursor while scrolling
886    /// (fzf's default is 3, which is why its list starts sliding well before the
887    /// cursor reaches the edge).
888    pub scroll_off: usize,
889    /// `--tiebreak`: the ranking criteria after score, in order, with the
890    /// item's input index as the implicit last one. Defaults to what the
891    /// `--scheme` implies (`length` for `default`).
892    pub tiebreak: Vec<crate::pattern::Criterion>,
893    /// `--preview-window`: where the preview box goes and how big it is.
894    pub preview_window: PreviewWindow,
895    /// `--bind` bindings, in declaration order (later wins for the same key).
896    pub binds: Vec<(Key, Vec<Action>)>,
897    /// `-i`/`--ignore-case`, `+i`/`--no-ignore-case`, `--smart-case`.
898    pub case: Case,
899    /// `--algo=v1|v2`: which fuzzy matcher runs. `v2` (the default) is the
900    /// score-matrix one; `v1` is fzf's older greedy scan, kept because it finds
901    /// a different alignment and so ranks differently.
902    pub algo_v1: bool,
903    /// `--scheme=default|path|history`: which characters count as boundaries
904    /// and what a match just after one is worth (fzf's `Init`, algo.go:176).
905    /// `path` also changes the default tiebreak order.
906    pub scheme: crate::algo::Scheme,
907    /// `--tail=N`: keep only the last N candidates. fzf applies this to the
908    /// candidate list, so the dropped lines are not matched, not merely hidden.
909    pub tail: Option<usize>,
910    /// `--read0`: input records are separated by NUL rather than newline —
911    /// what `fd -0` and `find -print0` produce.
912    pub read0: bool,
913    /// `--print0`: output records are terminated by NUL rather than newline —
914    /// what `xargs -0` expects.
915    pub print0: bool,
916    /// `--accept-nth=EXPR`: print only these fields of the accepted line
917    /// instead of the whole line.
918    pub accept_nth: Option<AcceptNth>,
919    /// `-x`/`--extended` (fzf's DEFAULT) vs `+x`/`--no-extended`. Extended makes
920    /// the query a term list — space-separated terms are AND'd, `|` ORs them,
921    /// and `'exact` / `^prefix` / `suffix$` / `!inverse` change how a term
922    /// matches. `+x` makes the whole query one literal fuzzy term.
923    pub extended: bool,
924}
925
926impl Default for Look {
927    fn default() -> Self {
928        Look {
929            layout: Layout::Default,
930            info: Info::Default,
931            border: None,
932            // fzf 0.74's default pointer/marker glyphs.
933            pointer: "\u{258c}".to_string(),
934            marker: "\u{2503}".to_string(),
935            ellipsis: "\u{b7}\u{b7}".to_string(),
936            colors: Colors::dark(),
937            cycle: false,
938            tac: false,
939            ansi: false,
940            delimiter: None,
941            nth: Vec::new(),
942            with_nth: Vec::new(),
943            header_lines: 0,
944            with_shell: None,
945            print_query: false,
946            expect: Vec::new(),
947            min_height: 10,
948            min_height_plus: true,
949            scrollbar: true,
950            scroll_off: 3,
951            tiebreak: vec![
952                crate::pattern::Criterion::Score,
953                crate::pattern::Criterion::Length,
954            ],
955            preview_window: PreviewWindow::default(),
956            binds: Vec::new(),
957            case: Case::Smart,
958            algo_v1: false,
959            scheme: crate::algo::Scheme::DEFAULT,
960            tail: None,
961            read0: false,
962            print0: false,
963            accept_nth: None,
964            extended: true,
965        }
966    }
967}
968
969/// Expand a `--preview` command template for `line`: `{}` is the whole line,
970/// `{2}` / `{1,3}` / `{-1}` are fields (the `--nth` grammar). Each value goes
971/// through `quote`, so the shell sees it as one word. Any other brace text is
972/// left as written.
973pub fn expand_preview(
974    template: &str,
975    line: &str,
976    delimiter: Option<&str>,
977    quote: impl Fn(&str) -> String,
978) -> String {
979    let tokens = tokenize(line, delimiter);
980    let mut out = String::new();
981    let mut rest = template;
982    while let Some(open) = rest.find('{') {
983        out.push_str(&rest[..open]);
984        let tail = &rest[open..];
985        let Some(close) = tail.find('}') else { break };
986        let inner = &tail[1..close];
987        let is_fields = !inner.is_empty()
988            && inner
989                .chars()
990                .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.'));
991        if inner.is_empty() {
992            out.push_str(&quote(line));
993        } else if is_fields {
994            let nth = Nth::parse_list(inner);
995            out.push_str(&quote(&strip_last_delimiter(
996                &transform_join(&tokens, &nth),
997                delimiter,
998            )));
999        } else {
1000            out.push_str(&tail[..=close]);
1001        }
1002        rest = &tail[close + 1..];
1003    }
1004    out.push_str(rest);
1005    out
1006}
1007
1008/// `--accept-nth=EXPR` — what an accepted line prints instead of itself
1009/// (fzf's `nthTransformer`, options.go:1265). Two forms: a bare field list, or
1010/// a template of literal text with `{FIELDS}` and `{n}` placeholders.
1011#[derive(Clone, Debug, PartialEq)]
1012pub enum AcceptNth {
1013    /// `--accept-nth=2,4..`: the joined fields, nothing else.
1014    Fields(Vec<Nth>),
1015    /// `--accept-nth='[{n}] {2}'`: literal text with placeholders spliced in.
1016    Template(Vec<AcceptPart>),
1017}
1018
1019/// One piece of an `--accept-nth` template.
1020#[derive(Clone, Debug, PartialEq)]
1021pub enum AcceptPart {
1022    Literal(String),
1023    Fields(Vec<Nth>),
1024    /// `{n}` — the line's zero-based input index.
1025    Index,
1026}
1027
1028impl AcceptNth {
1029    /// fzf's `nthTransformer`: a spec of only digits, `,`, `-` and `.` is a
1030    /// field list; anything else is a template and must hold a placeholder.
1031    pub fn parse(spec: &str) -> Option<AcceptNth> {
1032        if !spec.is_empty()
1033            && spec
1034                .chars()
1035                .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.'))
1036        {
1037            let nth = Nth::parse_list(spec);
1038            if !nth.is_empty() {
1039                return Some(AcceptNth::Fields(nth));
1040            }
1041        }
1042        let mut parts = Vec::new();
1043        let mut rest = spec;
1044        let mut saw_placeholder = false;
1045        while let Some(open) = rest.find('{') {
1046            let Some(close) = rest[open..].find('}').map(|i| open + i) else {
1047                break;
1048            };
1049            let inner = &rest[open + 1..close];
1050            let ok = inner == "n"
1051                || (!inner.is_empty()
1052                    && inner
1053                        .chars()
1054                        .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.')));
1055            if !ok {
1056                // Not a placeholder — keep scanning past this brace.
1057                let (lit, tail) = rest.split_at(close + 1);
1058                parts.push(AcceptPart::Literal(lit.to_string()));
1059                rest = tail;
1060                continue;
1061            }
1062            if open > 0 {
1063                parts.push(AcceptPart::Literal(rest[..open].to_string()));
1064            }
1065            parts.push(match inner {
1066                "n" => AcceptPart::Index,
1067                f => AcceptPart::Fields(Nth::parse_list(f)),
1068            });
1069            saw_placeholder = true;
1070            rest = &rest[close + 1..];
1071        }
1072        if !saw_placeholder {
1073            return None;
1074        }
1075        if !rest.is_empty() {
1076            parts.push(AcceptPart::Literal(rest.to_string()));
1077        }
1078        Some(AcceptNth::Template(parts))
1079    }
1080
1081    /// Render one line through the spec. `index` backs `{n}`.
1082    pub fn render(&self, line: &str, delimiter: Option<&str>, index: usize) -> String {
1083        let tokens = tokenize(line, delimiter);
1084        match self {
1085            AcceptNth::Fields(nth) => {
1086                strip_last_delimiter(&transform_join(&tokens, nth), delimiter)
1087            }
1088            AcceptNth::Template(parts) => parts
1089                .iter()
1090                .map(|p| match p {
1091                    AcceptPart::Literal(s) => s.clone(),
1092                    AcceptPart::Index => index.to_string(),
1093                    AcceptPart::Fields(nth) => {
1094                        strip_last_delimiter(&transform_join(&tokens, nth), delimiter)
1095                    }
1096                })
1097                .collect(),
1098        }
1099    }
1100}
1101
1102/// fzf's `StripLastDelimiter` (tokenizer.go): a field slice keeps the delimiter
1103/// that followed its last token, and that trailing separator is dropped before
1104/// the line is printed.
1105pub fn strip_last_delimiter(s: &str, delimiter: Option<&str>) -> String {
1106    match delimiter {
1107        Some(d) => s.strip_suffix(d).unwrap_or(s).to_string(),
1108        None => s.trim_end().to_string(),
1109    }
1110}
1111
1112/// Map an fzf `--border` style name onto ratatui's border type + sides.
1113fn parse_border(style: &str) -> Option<(BorderType, Borders)> {
1114    let all = Borders::ALL;
1115    match style {
1116        "rounded" | "" => Some((BorderType::Rounded, all)),
1117        "sharp" | "block" | "thinblock" => Some((BorderType::Plain, all)),
1118        "bold" | "double" => Some((BorderType::Double, all)),
1119        "horizontal" => Some((BorderType::Plain, Borders::TOP | Borders::BOTTOM)),
1120        "vertical" => Some((BorderType::Plain, Borders::LEFT | Borders::RIGHT)),
1121        "top" | "up" => Some((BorderType::Plain, Borders::TOP)),
1122        "bottom" | "down" => Some((BorderType::Plain, Borders::BOTTOM)),
1123        "left" => Some((BorderType::Plain, Borders::LEFT)),
1124        "right" => Some((BorderType::Plain, Borders::RIGHT)),
1125        "none" => None,
1126        _ => Some((BorderType::Rounded, all)),
1127    }
1128}
1129
1130/// A key an fzf `--bind` can name. Only keys arb's `/dev/tty` reader can
1131/// actually deliver are modeled; anything else parses to `None` and its binding
1132/// is dropped rather than silently mis-firing on a different key.
1133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1134pub enum Key {
1135    /// `ctrl-x` — the letter, lowercased.
1136    Ctrl(char),
1137    /// `alt-x` — the character after Esc.
1138    Alt(char),
1139    Tab,
1140    BTab,
1141    Enter,
1142    Esc,
1143    Up,
1144    Down,
1145    Left,
1146    Right,
1147    PageUp,
1148    PageDown,
1149    Home,
1150    End,
1151    Backspace,
1152    Delete,
1153    Space,
1154    /// `shift-up`: fzf's default for scrolling the preview up.
1155    ShiftUp,
1156    /// `shift-down`: fzf's default for scrolling the preview down.
1157    ShiftDown,
1158    /// A plain printable key (`--bind=?:toggle-preview`).
1159    Char(char),
1160}
1161
1162/// The fzf actions arb can carry out. fzf has many more (`execute`,
1163/// `reload`, `toggle-preview` …); a binding naming one of those is dropped whole
1164/// so the key keeps its built-in behavior instead of half-working.
1165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1166pub enum Action {
1167    Up,
1168    Down,
1169    PageUp,
1170    PageDown,
1171    HalfPageUp,
1172    HalfPageDown,
1173    First,
1174    Last,
1175    Toggle,
1176    ToggleAll,
1177    Accept,
1178    Abort,
1179    ClearQuery,
1180    BackwardDeleteChar,
1181    PreviewUp,
1182    PreviewDown,
1183    PreviewPageUp,
1184    PreviewPageDown,
1185    PreviewHalfPageUp,
1186    PreviewHalfPageDown,
1187    PreviewTop,
1188    PreviewBottom,
1189    Ignore,
1190}
1191
1192/// Parse an fzf key name.
1193fn parse_key(name: &str) -> Option<Key> {
1194    let n = name.trim().to_ascii_lowercase();
1195    if let Some(rest) = n.strip_prefix("ctrl-") {
1196        let mut ch = rest.chars();
1197        let c = ch.next()?;
1198        return ch.next().is_none().then_some(Key::Ctrl(c));
1199    }
1200    if let Some(rest) = n.strip_prefix("alt-") {
1201        let mut ch = rest.chars();
1202        let c = ch.next()?;
1203        return ch.next().is_none().then_some(Key::Alt(c));
1204    }
1205    Some(match n.as_str() {
1206        "tab" => Key::Tab,
1207        "btab" | "shift-tab" => Key::BTab,
1208        "enter" | "return" => Key::Enter,
1209        "esc" => Key::Esc,
1210        "up" => Key::Up,
1211        "down" => Key::Down,
1212        "left" => Key::Left,
1213        "right" => Key::Right,
1214        "pgup" | "page-up" => Key::PageUp,
1215        "pgdn" | "page-down" => Key::PageDown,
1216        "home" => Key::Home,
1217        "end" => Key::End,
1218        "bspace" | "bs" | "backspace" => Key::Backspace,
1219        "del" | "delete" => Key::Delete,
1220        "shift-up" => Key::ShiftUp,
1221        "shift-down" => Key::ShiftDown,
1222        "space" => Key::Space,
1223        s if s.chars().count() == 1 => Key::Char(s.chars().next()?),
1224        _ => return None,
1225    })
1226}
1227
1228/// Parse an fzf action name. `None` = arb has no equivalent.
1229fn parse_action(name: &str) -> Option<Action> {
1230    Some(match name.trim() {
1231        "up" | "prev-history" => Action::Up,
1232        "down" | "next-history" => Action::Down,
1233        "page-up" => Action::PageUp,
1234        "page-down" => Action::PageDown,
1235        "half-page-up" => Action::HalfPageUp,
1236        "half-page-down" => Action::HalfPageDown,
1237        "first" | "top" | "beginning-of-line" => Action::First,
1238        "last" => Action::Last,
1239        "toggle" | "toggle+up" => Action::Toggle,
1240        "toggle-all" | "select-all" | "deselect-all" => Action::ToggleAll,
1241        "accept" | "accept-non-empty" => Action::Accept,
1242        "abort" | "cancel" => Action::Abort,
1243        "clear-query" | "unix-line-discard" | "kill-line" => Action::ClearQuery,
1244        "backward-delete-char" => Action::BackwardDeleteChar,
1245        "preview-up" => Action::PreviewUp,
1246        "preview-down" => Action::PreviewDown,
1247        "preview-page-up" => Action::PreviewPageUp,
1248        "preview-page-down" => Action::PreviewPageDown,
1249        "preview-half-page-up" => Action::PreviewHalfPageUp,
1250        "preview-half-page-down" => Action::PreviewHalfPageDown,
1251        "preview-top" => Action::PreviewTop,
1252        "preview-bottom" => Action::PreviewBottom,
1253        "ignore" => Action::Ignore,
1254        _ => return None,
1255    })
1256}
1257
1258/// Split on `sep`, ignoring separators inside `(…)` — fzf action arguments
1259/// (`execute(grep -r {} .)`) routinely contain commas and plus signs.
1260fn split_top(s: &str, sep: char) -> Vec<String> {
1261    let mut out = Vec::new();
1262    let mut cur = String::new();
1263    let mut depth = 0i32;
1264    for c in s.chars() {
1265        match c {
1266            '(' => {
1267                depth += 1;
1268                cur.push(c);
1269            }
1270            ')' => {
1271                depth -= 1;
1272                cur.push(c);
1273            }
1274            c if c == sep && depth <= 0 => out.push(std::mem::take(&mut cur)),
1275            _ => cur.push(c),
1276        }
1277    }
1278    out.push(cur);
1279    out
1280}
1281
1282/// Parse one `--bind` value (`tab:toggle+down,ctrl-n:page-down`) into bindings.
1283/// A binding whose key or any action arb doesn't implement is skipped entirely.
1284fn parse_bind_spec(spec: &str) -> Vec<(Key, Vec<Action>)> {
1285    let mut out = Vec::new();
1286    for one in split_top(spec, ',') {
1287        let one = one.trim();
1288        if one.is_empty() {
1289            continue;
1290        }
1291        let Some((keyname, actions)) = one.split_once(':') else {
1292            continue;
1293        };
1294        let Some(key) = parse_key(keyname) else {
1295            continue;
1296        };
1297        let acts: Option<Vec<Action>> = split_top(actions, '+')
1298            .iter()
1299            .map(|a| parse_action(a))
1300            .collect();
1301        if let Some(acts) = acts {
1302            out.push((key, acts));
1303        }
1304    }
1305    out
1306}
1307
1308/// The value of `--flag VALUE` / `--flag=VALUE`, consuming the next argv word
1309/// when the value is separate.
1310fn flag_value(arg: &str, next: Option<&String>) -> (Option<String>, bool) {
1311    match arg.split_once('=') {
1312        Some((_, v)) => (Some(v.to_string()), false),
1313        None => (next.cloned(), true),
1314    }
1315}
1316
1317impl Look {
1318    /// Resolve the picker's look from a full argv (env options first, command
1319    /// line after — later wins, exactly like fzf).
1320    pub fn parse(args: &[String]) -> Look {
1321        let mut look = Look::default();
1322        // fzf honors $NO_COLOR by starting from the `bw` scheme.
1323        if std::env::var_os("NO_COLOR").is_some() {
1324            look.colors = Colors::bw();
1325        }
1326        let mut i = 0;
1327        while i < args.len() {
1328            let a = args[i].as_str();
1329            // fzf's short flags take an attached value (`-d:`, `-n3..`), so the
1330            // key is just the flag itself and the rest is the value.
1331            let key = match a.as_bytes() {
1332                [b'-', b'd', rest @ ..] if !rest.is_empty() => "-d",
1333                [b'-', b'n', rest @ ..] if !rest.is_empty() && rest[0] != b'o' => "-n",
1334                _ => a.split('=').next().unwrap_or(a),
1335            };
1336            let attached = match key {
1337                "-d" | "-n" if a.len() > 2 => Some(a[2..].to_string()),
1338                _ => None,
1339            };
1340            let next = args.get(i + 1);
1341            match key {
1342                "--reverse" => look.layout = Layout::Reverse,
1343                "--no-reverse" => look.layout = Layout::Default,
1344                "--layout" => {
1345                    let (v, sep) = flag_value(a, next);
1346                    look.layout = match v.as_deref() {
1347                        Some("reverse") => Layout::Reverse,
1348                        Some("reverse-list") => Layout::ReverseList,
1349                        _ => Layout::Default,
1350                    };
1351                    i += usize::from(sep);
1352                }
1353                "--preview-window" => {
1354                    let (v, sep) = flag_value(a, next);
1355                    if let Some(spec) = v {
1356                        look.preview_window.apply(&spec);
1357                    }
1358                    i += usize::from(sep);
1359                }
1360                "--border" => {
1361                    // `--border` alone is fzf's rounded box; `--border=STYLE` picks.
1362                    let style = a.split_once('=').map(|(_, v)| v.to_string());
1363                    look.border = parse_border(style.as_deref().unwrap_or("rounded"));
1364                }
1365                "--no-border" => look.border = None,
1366                "--info" => {
1367                    let (v, sep) = flag_value(a, next);
1368                    look.info = match v.as_deref() {
1369                        Some("hidden") => Info::Hidden,
1370                        Some("right") => Info::Right,
1371                        Some("inline") => Info::Inline(" < ".to_string()),
1372                        Some("inline-right") => Info::InlineRight(String::new()),
1373                        Some(s) if s.starts_with("inline-right:") => {
1374                            Info::InlineRight(s["inline-right:".len()..].to_string())
1375                        }
1376                        Some(s) if s.starts_with("inline:") => {
1377                            Info::Inline(s["inline:".len()..].to_string())
1378                        }
1379                        _ => Info::Default,
1380                    };
1381                    i += usize::from(sep);
1382                }
1383                "--no-info" => look.info = Info::Hidden,
1384                "--inline-info" => look.info = Info::Inline(" < ".to_string()),
1385                "--no-inline-info" => look.info = Info::Default,
1386                "--pointer" => {
1387                    let (v, sep) = flag_value(a, next);
1388                    if let Some(v) = v {
1389                        look.pointer = v;
1390                    }
1391                    i += usize::from(sep);
1392                }
1393                "--marker" => {
1394                    let (v, sep) = flag_value(a, next);
1395                    if let Some(v) = v {
1396                        look.marker = v;
1397                    }
1398                    i += usize::from(sep);
1399                }
1400                "--ellipsis" => {
1401                    let (v, sep) = flag_value(a, next);
1402                    if let Some(v) = v {
1403                        look.ellipsis = v;
1404                    }
1405                    i += usize::from(sep);
1406                }
1407                "--color" => {
1408                    let (v, sep) = flag_value(a, next);
1409                    if let Some(v) = v {
1410                        apply_color_spec(&mut look.colors, &v);
1411                    }
1412                    i += usize::from(sep);
1413                }
1414                "--no-color" => look.colors = Colors::bw(),
1415                "--tiebreak" => {
1416                    let (v, sep) = flag_value(a, next);
1417                    // A spec fzf would reject leaves the current criteria alone.
1418                    if let Some(c) = v.as_deref().and_then(crate::pattern::parse_tiebreak) {
1419                        look.tiebreak = c;
1420                    }
1421                    i += usize::from(sep);
1422                }
1423                "--scroll-off" => {
1424                    let (v, sep) = flag_value(a, next);
1425                    if let Some(n) = v.and_then(|v| v.parse::<usize>().ok()) {
1426                        look.scroll_off = n;
1427                    }
1428                    i += usize::from(sep);
1429                }
1430                "--cycle" => look.cycle = true,
1431                "--no-cycle" => look.cycle = false,
1432                "--tac" => look.tac = true,
1433                "--no-tac" => look.tac = false,
1434                "--ansi" => look.ansi = true,
1435                "--print-query" => look.print_query = true,
1436                "--no-print-query" => look.print_query = false,
1437                // fzf's case flags. The default is smart-case, so `--smart-case`
1438                // after an `-i` from `$FZF_DEFAULT_OPTS` puts it back.
1439                "-i" | "--ignore-case" => look.case = Case::Ignore,
1440                "+i" | "--no-ignore-case" => look.case = Case::Respect,
1441                "--smart-case" => look.case = Case::Smart,
1442                // fzf's query language. Extended is the DEFAULT — `+x` is what
1443                // turns the query back into a single literal fuzzy term.
1444                "-x" | "--extended" => look.extended = true,
1445                "+x" | "--no-extended" => look.extended = false,
1446                // fzf's `--extended-exact` is `-x -e` in one flag (and has no
1447                // negation of its own). The exact half is applied in `cli.rs`.
1448                "--extended-exact" => look.extended = true,
1449                "--algo" => {
1450                    let (v, sep) = flag_value(a, next);
1451                    match v.as_deref() {
1452                        Some("v1") => look.algo_v1 = true,
1453                        Some("v2") => look.algo_v1 = false,
1454                        // An unknown algo keeps the default, as fzf rejects it.
1455                        _ => {}
1456                    }
1457                    i += usize::from(sep);
1458                }
1459                "--scheme" => {
1460                    let (v, sep) = flag_value(a, next);
1461                    // An unrecognized scheme keeps the default, the way fzf
1462                    // rejects it rather than scoring with something else.
1463                    if let Some(s) = v.as_deref().and_then(crate::algo::Scheme::by_name) {
1464                        look.scheme = s;
1465                        // A scheme carries its own tiebreak order, and fzf lets
1466                        // whichever of `--scheme`/`--tiebreak` comes last win.
1467                        look.tiebreak = crate::pattern::scheme_criteria(&s);
1468                    }
1469                    i += usize::from(sep);
1470                }
1471                // Record framing: NUL in, NUL out.
1472                "--read0" => look.read0 = true,
1473                "--no-read0" => look.read0 = false,
1474                "--print0" => look.print0 = true,
1475                "--no-print0" => look.print0 = false,
1476                "--tail" => {
1477                    let (v, sep) = flag_value(a, next);
1478                    look.tail = v.and_then(|v| v.parse::<usize>().ok()).filter(|n| *n > 0);
1479                    i += usize::from(sep);
1480                }
1481                "--no-tail" => look.tail = None,
1482                "--accept-nth" => {
1483                    let (v, sep) = flag_value(a, next);
1484                    look.accept_nth = v.as_deref().and_then(AcceptNth::parse);
1485                    i += usize::from(sep);
1486                }
1487                "--with-shell" => {
1488                    let (v, sep) = flag_value(a, next);
1489                    look.with_shell = v.filter(|v| !v.is_empty());
1490                    i += usize::from(sep);
1491                }
1492                "--expect" => {
1493                    let (v, sep) = flag_value(a, next);
1494                    if let Some(v) = v {
1495                        look.expect = v
1496                            .split(',')
1497                            .filter(|k| !k.is_empty())
1498                            .filter_map(|k| parse_key(k).map(|p| (p, k.to_string())))
1499                            .collect();
1500                    }
1501                    i += usize::from(sep);
1502                }
1503                "--no-ansi" => look.ansi = false,
1504                "--no-expect" => look.expect.clear(),
1505                "--no-header-lines" => look.header_lines = 0,
1506                // `--scrollbar[=CHARS]` puts the bar back after a `--no-scrollbar`.
1507                // arb draws fzf's default glyph, so only the on/off state is read.
1508                "--scrollbar" => look.scrollbar = true,
1509                "--delimiter" | "-d" => {
1510                    let (v, sep) = match attached {
1511                        Some(v) => (Some(v), false),
1512                        None => flag_value(a, next),
1513                    };
1514                    look.delimiter = v.filter(|v| !v.is_empty());
1515                    i += usize::from(sep);
1516                }
1517                "--nth" | "-n" => {
1518                    let (v, sep) = match attached {
1519                        Some(v) => (Some(v), false),
1520                        None => flag_value(a, next),
1521                    };
1522                    if let Some(v) = v {
1523                        look.nth = Nth::parse_list(&v);
1524                    }
1525                    i += usize::from(sep);
1526                }
1527                "--with-nth" => {
1528                    let (v, sep) = flag_value(a, next);
1529                    if let Some(v) = v {
1530                        look.with_nth = Nth::parse_list(&v);
1531                    }
1532                    i += usize::from(sep);
1533                }
1534                "--header-lines" => {
1535                    let (v, sep) = flag_value(a, next);
1536                    if let Some(n) = v.and_then(|v| v.parse::<usize>().ok()) {
1537                        look.header_lines = n;
1538                    }
1539                    i += usize::from(sep);
1540                }
1541                "--min-height" => {
1542                    let (v, sep) = flag_value(a, next);
1543                    if let Some(v) = v {
1544                        let plus = v.ends_with('+');
1545                        if let Ok(n) = v.trim_end_matches('+').parse::<u16>() {
1546                            look.min_height = n;
1547                            look.min_height_plus = plus;
1548                        }
1549                    }
1550                    i += usize::from(sep);
1551                }
1552                "--no-scrollbar" => look.scrollbar = false,
1553                "--bind" => {
1554                    let (v, sep) = flag_value(a, next);
1555                    if let Some(v) = v {
1556                        look.binds.extend(parse_bind_spec(&v));
1557                    }
1558                    i += usize::from(sep);
1559                }
1560                _ => {}
1561            }
1562            i += 1;
1563        }
1564        look
1565    }
1566
1567    /// The command and flags a child process starts with: `--with-shell` if
1568    /// given, else `$SHELL -c`, else `sh -c` — fzf's rule, so a preview that
1569    /// works under `fzf` works here.
1570    pub fn shell(&self) -> Vec<String> {
1571        if let Some(w) = &self.with_shell {
1572            let words = shell_split(w);
1573            if !words.is_empty() {
1574                return words;
1575            }
1576        }
1577        match std::env::var("SHELL") {
1578            Ok(sh) if !sh.is_empty() => vec![sh, "-c".to_string()],
1579            _ => vec!["sh".to_string(), "-c".to_string()],
1580        }
1581    }
1582
1583    /// The actions bound to `key`, if any. Later bindings win, so the command
1584    /// line overrides `$FZF_DEFAULT_OPTS` for the same key.
1585    pub fn bound(&self, key: Key) -> Option<&[Action]> {
1586        self.binds
1587            .iter()
1588            .rev()
1589            .find(|(k, _)| *k == key)
1590            .map(|(_, a)| a.as_slice())
1591    }
1592
1593    /// The actions `key` runs: the user's binding, else fzf's built-in preview
1594    /// scrolling (`shift-up`/`shift-down`).
1595    pub fn bound_or_default(&self, key: Key) -> Option<Vec<Action>> {
1596        self.bound(key).map(<[_]>::to_vec).or(match key {
1597            Key::ShiftUp => Some(vec![Action::PreviewUp]),
1598            Key::ShiftDown => Some(vec![Action::PreviewDown]),
1599            _ => None,
1600        })
1601    }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606    use super::*;
1607
1608    #[test]
1609    fn shell_split_keeps_quoted_prompt_intact() {
1610        // The real $FZF_DEFAULT_OPTS from a themed zsh setup: the prompt has a
1611        // trailing space and parentheses, so quoting must survive the split.
1612        let v = shell_split("--prompt='<<)ZPWR(>> ' --reverse --height 100%");
1613        assert_eq!(
1614            v,
1615            vec!["--prompt=<<)ZPWR(>> ", "--reverse", "--height", "100%"]
1616        );
1617    }
1618
1619    #[test]
1620    fn shell_split_handles_double_quotes_and_escapes() {
1621        let v = shell_split(r#"--prompt="a b" --header=c\ d"#);
1622        assert_eq!(v, vec!["--prompt=a b", "--header=c d"]);
1623        // An empty quoted value is a word, not nothing.
1624        assert_eq!(shell_split("--prompt=''"), vec!["--prompt="]);
1625    }
1626
1627    #[test]
1628    fn later_options_win() {
1629        // env options are spliced first, so a command-line flag must override.
1630        let args: Vec<String> = ["--layout=reverse", "--layout=default"]
1631            .iter()
1632            .map(|s| s.to_string())
1633            .collect();
1634        assert_eq!(Look::parse(&args).layout, Layout::Default);
1635    }
1636
1637    #[test]
1638    fn parses_layout_border_info_pointer() {
1639        let args: Vec<String> = [
1640            "--reverse",
1641            "--border",
1642            "--info=inline",
1643            "--pointer",
1644            ">",
1645            "--marker",
1646            "*",
1647        ]
1648        .iter()
1649        .map(|s| s.to_string())
1650        .collect();
1651        let look = Look::parse(&args);
1652        assert_eq!(look.layout, Layout::Reverse);
1653        assert_eq!(look.border, Some((BorderType::Rounded, Borders::ALL)));
1654        assert_eq!(look.info, Info::Inline(" < ".to_string()));
1655        assert_eq!(look.pointer, ">");
1656        assert_eq!(look.marker, "*");
1657    }
1658
1659    #[test]
1660    fn color_spec_overrides_scheme_slots() {
1661        let args: Vec<String> = ["--color=light,hl:#ff0000,fg+:2:bold:underline"]
1662            .iter()
1663            .map(|s| s.to_string())
1664            .collect();
1665        let c = Look::parse(&args).colors;
1666        // The base scheme applied…
1667        assert_eq!(c.prompt, Ent::b(25));
1668        // …then the per-slot overrides on top of it.
1669        assert_eq!(c.hl.color, Some(Color::Rgb(0xff, 0, 0)));
1670        // `2` is a palette index, not a name — fzf writes it as `38;5;2`.
1671        assert_eq!(c.fg_plus.color, Some(Color::Indexed(2)));
1672        assert!(c.fg_plus.attrs.contains(Modifier::BOLD));
1673        assert!(c.fg_plus.attrs.contains(Modifier::UNDERLINED));
1674    }
1675
1676    #[test]
1677    fn binds_map_fzf_actions() {
1678        let args: Vec<String> =
1679            ["--bind=ctrl-n:page-down,ctrl-p:page-up,tab:toggle+down,ctrl-j:down,ctrl-k:up"]
1680                .iter()
1681                .map(|s| s.to_string())
1682                .collect();
1683        let look = Look::parse(&args);
1684        assert_eq!(look.bound(Key::Ctrl('n')), Some(&[Action::PageDown][..]));
1685        assert_eq!(look.bound(Key::Ctrl('p')), Some(&[Action::PageUp][..]));
1686        assert_eq!(
1687            look.bound(Key::Tab),
1688            Some(&[Action::Toggle, Action::Down][..])
1689        );
1690        assert_eq!(look.bound(Key::Ctrl('j')), Some(&[Action::Down][..]));
1691        assert_eq!(look.bound(Key::Ctrl('k')), Some(&[Action::Up][..]));
1692    }
1693
1694    #[test]
1695    fn unsupported_action_drops_only_that_binding() {
1696        // `execute(...)` has no arb analog: that key keeps its built-in meaning,
1697        // while the other binding in the same spec still applies.
1698        let args: Vec<String> = ["--bind=ctrl-o:execute(vim {}),ctrl-k:up"]
1699            .iter()
1700            .map(|s| s.to_string())
1701            .collect();
1702        let look = Look::parse(&args);
1703        assert_eq!(look.bound(Key::Ctrl('o')), None);
1704        assert_eq!(look.bound(Key::Ctrl('k')), Some(&[Action::Up][..]));
1705    }
1706
1707    #[test]
1708    fn preview_scroll_actions_parse_and_shift_arrows_default_to_them() {
1709        let args: Vec<String> = ["--bind=ctrl-d:preview-half-page-down,ctrl-b:preview-page-up,alt-t:preview-top+preview-down"]
1710            .iter()
1711            .map(|s| s.to_string())
1712            .collect();
1713        let look = Look::parse(&args);
1714        assert_eq!(
1715            look.bound(Key::Ctrl('d')),
1716            Some(&[Action::PreviewHalfPageDown][..])
1717        );
1718        assert_eq!(
1719            look.bound(Key::Ctrl('b')),
1720            Some(&[Action::PreviewPageUp][..])
1721        );
1722        assert_eq!(
1723            look.bound(Key::Alt('t')),
1724            Some(&[Action::PreviewTop, Action::PreviewDown][..])
1725        );
1726        // fzf's built-in shift-up/shift-down, overridable by a binding.
1727        let plain = Look::default();
1728        assert_eq!(
1729            plain.bound_or_default(Key::ShiftUp),
1730            Some(vec![Action::PreviewUp])
1731        );
1732        assert_eq!(
1733            plain.bound_or_default(Key::ShiftDown),
1734            Some(vec![Action::PreviewDown])
1735        );
1736        assert_eq!(plain.bound_or_default(Key::Char('x')), None);
1737        let own = Look::parse(&["--bind=shift-up:up".to_string()]);
1738        assert_eq!(own.bound_or_default(Key::ShiftUp), Some(vec![Action::Up]));
1739    }
1740
1741    #[test]
1742    fn preview_scroll_spec_parses_base_offsets_and_denominator() {
1743        let w = PreviewWindow::parse("right,60%,+{2}+3/2");
1744        assert_eq!(w.size, PreviewSize::Percent(60));
1745        let sc = w.scroll.expect("scroll");
1746        assert_eq!(sc.base, ScrollBase::Field(Nth::parse_list("2")));
1747        assert_eq!((sc.offset, sc.denom), (3, 2));
1748        let n = PreviewWindow::parse("+10-4").scroll.expect("scroll");
1749        assert_eq!((n.base, n.offset, n.denom), (ScrollBase::Line(10), -4, 0));
1750        assert_eq!(PreviewWindow::parse("+{x}").scroll, None);
1751        assert_eq!(PreviewWindow::parse("+{2}*").scroll, None);
1752    }
1753
1754    #[test]
1755    fn preview_scroll_targets_the_field_line_and_centres_it() {
1756        let sc = PreviewWindow::parse("+{2}-5").scroll.unwrap();
1757        assert_eq!(sc.target("main.rs:120:fn x", Some(":")), Some(115));
1758        assert_eq!(sc.target("main.rs:abc:fn x", Some(":")), None);
1759        // One-based line 115 is index 114 at the top …
1760        assert_eq!(sc.top(115, 20), 114);
1761        // … or half a window lower with `/2`, clamped at the first line.
1762        let mid = PreviewWindow::parse("+{2}/2").scroll.unwrap();
1763        assert_eq!(mid.top(120, 20), 109);
1764        assert_eq!(mid.top(3, 20), 0);
1765    }
1766
1767    #[test]
1768    fn preview_template_expands_whole_line_and_fields() {
1769        let q = |s: &str| format!("<{s}>");
1770        assert_eq!(
1771            expand_preview("bat {1} --highlight-line {2}", "a.rs:7:x", Some(":"), q),
1772            "bat <a.rs> --highlight-line <7>"
1773        );
1774        assert_eq!(expand_preview("echo {}", "a b", None, q), "echo <a b>");
1775        assert_eq!(
1776            expand_preview("awk '{print $1}' {}", "z", None, q),
1777            "awk '{print $1}' <z>"
1778        );
1779    }
1780
1781    #[test]
1782    fn repeated_preview_window_options_fold_together() {
1783        let look = Look::parse(
1784            &[
1785                "--preview-window=down:40%:wrap",
1786                "--preview-window",
1787                "+{2}+3/3",
1788            ]
1789            .map(String::from),
1790        );
1791        let w = look.preview_window;
1792        assert_eq!(
1793            (w.pos, w.size, w.wrap),
1794            (PreviewPos::Down, PreviewSize::Percent(40), true)
1795        );
1796        assert!(w.scroll.is_some());
1797    }
1798
1799    #[test]
1800    fn preview_window_defaults_are_fzfs() {
1801        // fzf(1): "POSITION: (default: right)", half the window.
1802        let w = PreviewWindow::default();
1803        assert_eq!(w.pos, PreviewPos::Right);
1804        assert_eq!(w.size, PreviewSize::Percent(50));
1805        assert!(!w.hidden && !w.wrap);
1806    }
1807
1808    #[test]
1809    fn preview_window_takes_both_separators_in_any_order() {
1810        // The modern comma form and the older colon form are both in the wild.
1811        let a = PreviewWindow::parse("down,30%,wrap");
1812        assert_eq!(a.pos, PreviewPos::Down);
1813        assert_eq!(a.size, PreviewSize::Percent(30));
1814        assert!(a.wrap);
1815        let b = PreviewWindow::parse("right:55%");
1816        assert_eq!(b.pos, PreviewPos::Right);
1817        assert_eq!(b.size, PreviewSize::Percent(55));
1818        // Order does not matter to fzf, so it must not matter here.
1819        assert_eq!(PreviewWindow::parse("20,up"), PreviewWindow::parse("up,20"));
1820        assert_eq!(PreviewWindow::parse("up,20").size, PreviewSize::Cells(20));
1821    }
1822
1823    #[test]
1824    fn unmodeled_parts_of_the_spec_are_ignored_not_rejected() {
1825        // A spec written for fzf must never fail here just because arb does not
1826        // act on every part of the grammar.
1827        let w = PreviewWindow::parse("left,40%,border-sharp,follow,cycle,+3/2,~2,noinfo");
1828        assert_eq!(w.pos, PreviewPos::Left);
1829        assert_eq!(w.size, PreviewSize::Percent(40));
1830    }
1831
1832    #[test]
1833    fn hidden_and_zero_size_draw_no_pane() {
1834        use ratatui::layout::Rect;
1835        let body = Rect {
1836            x: 0,
1837            y: 0,
1838            width: 100,
1839            height: 30,
1840        };
1841        let (list, pane) = PreviewWindow::parse("hidden").split(body);
1842        assert!(pane.is_none(), "hidden draws nothing");
1843        assert_eq!(list, body, "and the list takes the whole body");
1844        // fzf(1): "If size is given as 0, preview window will not be visible,
1845        // but fzf will still execute the command in the background."
1846        assert!(PreviewWindow::parse("right,0").split(body).1.is_none());
1847        assert!(PreviewWindow::parse("right,0%").split(body).1.is_none());
1848    }
1849
1850    #[test]
1851    fn the_split_places_and_sizes_the_pane() {
1852        use ratatui::layout::Rect;
1853        let body = Rect {
1854            x: 0,
1855            y: 0,
1856            width: 100,
1857            height: 30,
1858        };
1859
1860        let (list, pane) = PreviewWindow::parse("right,60%").split(body);
1861        let pane = pane.expect("drawn");
1862        assert_eq!((list.width, pane.width), (40, 60));
1863        assert_eq!(pane.x, 40, "right means after the list");
1864
1865        let (list, pane) = PreviewWindow::parse("left,25").split(body);
1866        let pane = pane.expect("drawn");
1867        assert_eq!((pane.width, list.width), (25, 75));
1868        assert_eq!(pane.x, 0, "left means before the list");
1869
1870        let (list, pane) = PreviewWindow::parse("up,10").split(body);
1871        let pane = pane.expect("drawn");
1872        assert_eq!((pane.height, list.height), (10, 20));
1873        assert_eq!(pane.y, 0);
1874
1875        let (list, pane) = PreviewWindow::parse("down,3").split(body);
1876        let pane = pane.expect("drawn");
1877        assert_eq!((list.height, pane.height), (27, 3));
1878        assert_eq!(pane.y, 27);
1879    }
1880
1881    #[test]
1882    fn the_list_always_keeps_a_cell() {
1883        use ratatui::layout::Rect;
1884        let body = Rect {
1885            x: 0,
1886            y: 0,
1887            width: 10,
1888            height: 4,
1889        };
1890        // An oversized request must not leave zero columns to pick from.
1891        let (list, pane) = PreviewWindow::parse("right,100%").split(body);
1892        assert_eq!(list.width, 1);
1893        assert_eq!(pane.expect("drawn").width, 9);
1894    }
1895
1896    #[test]
1897    fn look_parses_the_flag_in_both_spellings() {
1898        let attached = Look::parse(&["arb".into(), "--fzf".into(), "--preview-window=up,7".into()]);
1899        assert_eq!(attached.preview_window.pos, PreviewPos::Up);
1900        assert_eq!(attached.preview_window.size, PreviewSize::Cells(7));
1901        let separate = Look::parse(&[
1902            "arb".into(),
1903            "--fzf".into(),
1904            "--preview-window".into(),
1905            "down,20%".into(),
1906        ]);
1907        assert_eq!(separate.preview_window.pos, PreviewPos::Down);
1908        assert_eq!(separate.preview_window.size, PreviewSize::Percent(20));
1909    }
1910}