1use ratatui::style::{Color, Modifier, Style};
20use ratatui::widgets::{BorderType, Borders};
21
22pub fn shell_split(s: &str) -> Vec<String> {
27 let mut out = Vec::new();
28 let mut cur = String::new();
29 let mut started = false; let mut quote: Option<char> = None;
31 let mut chars = s.chars();
32 while let Some(c) = chars.next() {
33 match quote {
34 Some('\'') if c == '\'' => quote = None,
36 Some('\'') => cur.push(c),
37 Some('"') if c == '"' => quote = None,
38 Some('"') if c == '\\' => match chars.next() {
39 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
79pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub struct Ent {
103 pub color: Option<Color>,
104 pub attrs: Modifier,
105}
106
107impl Ent {
108 fn c(idx: u8) -> Self {
110 Ent {
111 color: Some(Color::Indexed(idx)),
112 attrs: Modifier::empty(),
113 }
114 }
115 fn b(idx: u8) -> Self {
117 Ent {
118 color: Some(Color::Indexed(idx)),
119 attrs: Modifier::BOLD,
120 }
121 }
122 fn attr(attrs: Modifier) -> Self {
124 Ent { color: None, attrs }
125 }
126 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 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#[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 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 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 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 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 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 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
325fn 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
363fn 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
378fn 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 *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#[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 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 return (!(begin < 0 && end > 0)).then_some(Nth { begin, end });
442 }
443 n(s).map(|v| Nth { begin: v, end: v })
444 }
445
446 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
460pub 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 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 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
504pub 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
523pub 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
549pub 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
576pub enum Layout {
577 Default,
579 Reverse,
581 ReverseList,
583}
584
585#[derive(Clone, Debug, PartialEq, Eq)]
587pub enum Info {
588 Default,
590 Right,
592 Hidden,
594 Inline(String),
596 InlineRight(String),
598}
599
600#[derive(Clone, Copy, Debug, PartialEq, Eq)]
602pub enum PreviewPos {
603 Up,
604 Down,
605 Left,
606 Right,
608}
609
610#[derive(Clone, Copy, Debug, PartialEq, Eq)]
613pub enum PreviewSize {
614 Percent(u16),
615 Cells(u16),
616}
617
618#[derive(Clone, Debug, PartialEq, Eq)]
621pub enum ScrollBase {
622 Line(i64),
623 Field(Vec<Nth>),
624}
625
626#[derive(Clone, Debug, PartialEq, Eq)]
630pub struct PreviewScroll {
631 pub base: ScrollBase,
632 pub offset: i64,
634 pub denom: usize,
636}
637
638impl PreviewScroll {
639 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
708pub struct PreviewWindow {
709 pub pos: PreviewPos,
710 pub size: PreviewSize,
711 pub hidden: bool,
713 pub wrap: bool,
715 pub scroll: Option<PreviewScroll>,
717}
718
719impl Default for PreviewWindow {
720 fn default() -> Self {
721 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 pub fn parse(spec: &str) -> PreviewWindow {
738 let mut w = PreviewWindow::default();
739 w.apply(spec);
740 w
741 }
742
743 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 "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 }
775 }
776 }
777 }
778
779 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
830pub enum Case {
831 #[default]
832 Smart,
833 Ignore,
834 Respect,
835}
836
837#[derive(Clone, Debug)]
840pub struct Look {
841 pub layout: Layout,
842 pub info: Info,
843 pub border: Option<(BorderType, Borders)>,
846 pub pointer: String,
847 pub marker: String,
848 pub ellipsis: String,
850 pub colors: Colors,
851 pub cycle: bool,
853 pub tac: bool,
855 pub ansi: bool,
858 pub delimiter: Option<String>,
861 pub nth: Vec<Nth>,
864 pub with_nth: Vec<Nth>,
866 pub header_lines: usize,
868 pub with_shell: Option<String>,
873 pub print_query: bool,
875 pub expect: Vec<(Key, String)>,
879 pub min_height: u16,
882 pub min_height_plus: bool,
883 pub scrollbar: bool,
885 pub scroll_off: usize,
889 pub tiebreak: Vec<crate::pattern::Criterion>,
893 pub preview_window: PreviewWindow,
895 pub binds: Vec<(Key, Vec<Action>)>,
897 pub case: Case,
899 pub algo_v1: bool,
903 pub scheme: crate::algo::Scheme,
907 pub tail: Option<usize>,
910 pub read0: bool,
913 pub print0: bool,
916 pub accept_nth: Option<AcceptNth>,
919 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 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
969pub 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("e(line));
993 } else if is_fields {
994 let nth = Nth::parse_list(inner);
995 out.push_str("e(&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#[derive(Clone, Debug, PartialEq)]
1012pub enum AcceptNth {
1013 Fields(Vec<Nth>),
1015 Template(Vec<AcceptPart>),
1017}
1018
1019#[derive(Clone, Debug, PartialEq)]
1021pub enum AcceptPart {
1022 Literal(String),
1023 Fields(Vec<Nth>),
1024 Index,
1026}
1027
1028impl AcceptNth {
1029 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 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 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
1102pub 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
1112fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1134pub enum Key {
1135 Ctrl(char),
1137 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 ShiftUp,
1156 ShiftDown,
1158 Char(char),
1160}
1161
1162#[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
1192fn 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
1228fn 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
1258fn 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
1282fn 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
1308fn 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 pub fn parse(args: &[String]) -> Look {
1321 let mut look = Look::default();
1322 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 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 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 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 "-i" | "--ignore-case" => look.case = Case::Ignore,
1440 "+i" | "--no-ignore-case" => look.case = Case::Respect,
1441 "--smart-case" => look.case = Case::Smart,
1442 "-x" | "--extended" => look.extended = true,
1445 "+x" | "--no-extended" => look.extended = false,
1446 "--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 _ => {}
1456 }
1457 i += usize::from(sep);
1458 }
1459 "--scheme" => {
1460 let (v, sep) = flag_value(a, next);
1461 if let Some(s) = v.as_deref().and_then(crate::algo::Scheme::by_name) {
1464 look.scheme = s;
1465 look.tiebreak = crate::pattern::scheme_criteria(&s);
1468 }
1469 i += usize::from(sep);
1470 }
1471 "--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" => 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 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 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 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 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 assert_eq!(shell_split("--prompt=''"), vec!["--prompt="]);
1625 }
1626
1627 #[test]
1628 fn later_options_win() {
1629 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 assert_eq!(c.prompt, Ent::b(25));
1668 assert_eq!(c.hl.color, Some(Color::Rgb(0xff, 0, 0)));
1670 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 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 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 assert_eq!(sc.top(115, 20), 114);
1761 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 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 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 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 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 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 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}