Skip to main content

tess/
cli.rs

1use std::path::PathBuf;
2use clap::Parser;
3use clap::builder::styling::{AnsiColor, Color, Style};
4use clap::builder::Styles;
5
6const HELP_STYLES: Styles = Styles::styled()
7    .header(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
8    .usage(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
9    .literal(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))))
10    .placeholder(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))));
11
12#[derive(Parser, Debug, Clone)]
13#[command(name = "tess", version, about = "A less-style terminal pager.", styles = HELP_STYLES)]
14// Fields are ordered alphabetically by long-flag name (case-insensitive) so
15// that `--help` lists them in that order — clap's derive renders options in
16// field-declaration order. The `help_lists_flags_in_alphabetical_order` test
17// enforces this; keep new flags in their sorted slot.
18//
19// `IGNORE_CASE` (-I) and `QUIT_AT_EOF` (-E) are intentionally upper-case to
20// mirror less's case-distinguished flag pairs (`-i`/`-I`, `-e`/`-E`) and to
21// stay distinct from their lower-case `ignore_case`/`quit_at_eof` siblings.
22#[allow(non_snake_case)]
23pub struct Args {
24    /// Render images with Unicode half-blocks (▀, fg=top pixel, bg=bottom
25    /// pixel) for ~2× vertical detail instead of the default character ramp.
26    #[arg(long = "blocks")]
27    pub blocks: bool,
28
29    /// Chop long lines instead of wrapping.
30    #[arg(short = 'S', long = "chop-long-lines")]
31    pub chop: bool,
32
33    /// Force the content type for `--prettify` (otherwise auto-detected from
34    /// the filename extension and the first bytes). Values:
35    /// `auto`, `raw`, `json`, `yaml`, `toml`, `xml`, `html`, `csv`.
36    /// Setting this implies `--prettify` (unless the value is `raw`/`auto`).
37    #[arg(long = "content-type", value_name = "TYPE")]
38    pub content_type: Option<String>,
39
40    /// With `--filter`, dim non-matching lines instead of hiding them. Keeps
41    /// surrounding context visible.
42    #[arg(long = "dim")]
43    pub dim: bool,
44
45    /// Render each parsed line through this template instead of showing the
46    /// raw line. Syntax: `<fieldname>` placeholders, `\<` for literal `<`,
47    /// `\\` for literal `\`. Example: `--display '[<time>] <status> <msg>'`.
48    /// Overrides the format's `display` key (if set). Requires `--format`.
49    /// Search still matches against the raw line.
50    #[arg(long = "display", value_name = "TEMPLATE")]
51    pub display: Option<String>,
52
53    /// Print a curated list of usage examples and exit.
54    #[arg(long = "examples")]
55    pub examples: bool,
56
57    /// In follow mode with piped stdin, exit when the upstream writer
58    /// closes the pipe. Default behavior (off): tess remains open on
59    /// the captured content after stdin EOF. Mirrors
60    /// `less --exit-follow-on-close`.
61    #[arg(long = "exit-follow-on-close")]
62    pub exit_follow_on_close: bool,
63
64    /// Filter visible lines by parsed field. Repeatable; multiple filters AND.
65    /// Operators: `=` (exact), `!=` (exact ≠), `~` (regex), `!~` (regex ≠),
66    /// `<`, `<=`, `>`, `>=` (numeric if both sides parse as numbers, else
67    /// lexicographic). Examples: `--filter status=500`, `--filter ip~^10\.`,
68    /// `--filter 'status>=500'` (quote `<` and `>` to avoid shell redirection).
69    /// Requires `--format`.
70    #[arg(long = "filter", value_name = "FIELD<op>VALUE")]
71    pub filter: Vec<String>,
72
73    /// Follow mode: keep watching the source for new bytes (like `tail -f`).
74    /// Jumps to the bottom on startup. Toggle with Shift-F at runtime.
75    #[arg(short = 'f', long = "follow")]
76    pub follow: bool,
77
78    /// Follow the file by path rather than by descriptor (matches
79    /// `tail -F` / `less --follow-name`). `tess` already does this —
80    /// rotation and truncation are detected on every poll and the
81    /// source re-opens by path (since 0.25.0). This flag is accepted
82    /// for compatibility and currently has no behavioral effect.
83    #[arg(long = "follow-name")]
84    pub follow_name: bool,
85
86    /// In follow mode, any user motion (scroll, page, goto-line) suspends
87    /// following. Re-engage with Shift-F. Default off: today's behavior
88    /// (movement keeps follow on; auto-scroll suspended while the viewport
89    /// is not at bottom). Matches `less +F` semantics when enabled.
90    #[arg(long = "follow-suspend-on-motion")]
91    pub follow_suspend_on_motion: bool,
92
93    /// Apply a named log format (built-in or user-defined in
94    /// ~/.config/tess/formats.toml). Required by `--filter`.
95    #[arg(long = "format", value_name = "NAME")]
96    pub format: Option<String>,
97
98    /// Filter visible lines by regex against the raw line. Repeatable;
99    /// multiple `--grep` arguments AND. Works on any input — no `--format`
100    /// required. Composes with `--filter` (both must match) and with
101    /// `--dim` (non-matches stay visible but faded).
102    /// Example: `--grep error --grep '^\['`.
103    #[arg(long = "grep", value_name = "PATTERN")]
104    pub grep: Vec<String>,
105
106    /// Show only the first N lines of the source. Mutually exclusive with --tail.
107    #[arg(long = "head", value_name = "N", conflicts_with = "tail")]
108    pub head: Option<usize>,
109
110    /// Pin the top L source lines (and the left C columns, when
111    /// horizontal scroll is supported) at the top of the viewport.
112    /// Form: `L` or `L,C`. Default `0,0` (off). Mirrors `less --header`.
113    /// Runtime adjustment: `:header L [C]`.
114    #[arg(long = "header", value_name = "L[,C]")]
115    pub header: Option<String>,
116
117    /// Render the source as an xxd-style hex dump instead of byte-faithful
118    /// text. 16 bytes per row, offset prefix, ASCII gutter. Mutually
119    /// exclusive with parsing- and rendering-oriented flags.
120    #[arg(
121        long = "hex",
122        conflicts_with_all = ["filter", "grep", "prettify", "format", "display", "record_start", "prompt", "preprocess"],
123    )]
124    pub hex: bool,
125
126    /// Hex characters per group in `--hex` mode. One of 2, 4, 8, 16, 32
127    /// (default 4, matching `xxd`). 32 means the whole row as a single
128    /// group with no spacing between hex pairs. Requires `--hex`. Can be
129    /// changed at runtime with `:hex N`.
130    #[arg(
131        long = "hex-group",
132        value_name = "N",
133        default_value_t = 4,
134        requires = "hex",
135    )]
136    pub hex_group: usize,
137
138    /// Smart-case search. `/`, `?`, `--grep`, and `--filter`'s `~` / `!~`
139    /// operators match case-insensitively unless the pattern contains an
140    /// uppercase character. Mirrors `less -i` / ripgrep / vim smartcase.
141    /// Mutually exclusive with `-I`. Runtime toggle: `:case`.
142    #[arg(short = 'i', long = "ignore-case", conflicts_with = "IGNORE_CASE")]
143    pub ignore_case: bool,
144
145    /// Force case-insensitive search regardless of pattern case. Mirrors
146    /// `less -I`. Mutually exclusive with `-i`.
147    #[arg(short = 'I', long = "IGNORE-CASE")]
148    pub IGNORE_CASE: bool,
149
150    /// Target width in columns for image rendering. Defaults to the terminal
151    /// width interactively, or 80 when exporting to a file/stdout.
152    #[arg(long = "image-width", value_name = "N")]
153    pub image_width: Option<usize>,
154
155    /// Show line numbers.
156    #[arg(short = 'N', long = "LINE-NUMBERS")]
157    pub line_numbers: bool,
158
159    /// Print available log formats and their named fields, then exit.
160    #[arg(long = "list-formats")]
161    pub list_formats: bool,
162
163    /// Live mode: re-read the file when its on-disk content changes (mtime,
164    /// size, or inode). Use this for files rewritten in place — source files
165    /// being edited, files saved by an editor or AI agent. Different from
166    /// `--follow` (which watches for *appended* bytes); the two are mutually
167    /// exclusive. Press `R` inside the pager to force a reload.
168    #[arg(long = "live", conflicts_with = "follow")]
169    pub live: bool,
170
171    /// Print the full user manual and exit.
172    #[arg(long = "manual")]
173    pub manual: bool,
174
175    /// Enable mouse capture: click rows in the file picker / help overlay,
176    /// and scrollwheel scrolls the body. Trade-off: most terminals disable
177    /// their native text selection while mouse capture is on.
178    #[arg(long = "mouse")]
179    pub mouse: bool,
180
181    /// Show raw control bytes as `^X` glyphs (pre-0.18 default). Disables
182    /// SGR / OSC interpretation. Honoured also by the `NO_COLOR` environment
183    /// variable (any non-empty value) and `CLICOLOR=0`.
184    #[arg(long = "no-color")]
185    pub no_color: bool,
186
187    /// Disable search-match highlighting by default. Search still
188    /// navigates (`n` / `N` jump to matches); the visual reverse-video
189    /// highlight is suppressed. Runtime toggle: `:hlsearch` / `:nohlsearch`.
190    /// Mirrors `less -G`.
191    #[arg(short = 'G', long = "no-hilite-search")]
192    pub no_hilite_search: bool,
193
194    /// Treat a detected image file as raw/normal text instead of rendering it
195    /// as ASCII art. Has no effect on non-image inputs.
196    #[arg(long = "no-image")]
197    pub no_image: bool,
198
199    /// Don't enter the alt-screen on startup. Content remains in
200    /// terminal scrollback after exit. Crucial for piped use and
201    /// debugging. Mirrors `less -X` / `--no-init`.
202    #[arg(short = 'X', long = "no-init")]
203    pub no_init: bool,
204
205    /// Ignore $LESSOPEN. Useful when LESSOPEN is exported but not wanted
206    /// for one invocation.
207    #[arg(long = "no-preprocess", conflicts_with = "preprocess")]
208    pub no_preprocess: bool,
209
210    /// Non-interactive batch mode: apply --filter / --grep / --head / --tail / --prettify
211    /// to the source and write the resulting raw bytes to FILE, then exit.
212    /// Use `-` for stdout (`--stdout` is a synonym). Skips the alt-screen and
213    /// raw mode entirely. With `--follow`, doesn't exit — keeps appending
214    /// matching new bytes to FILE as they arrive (Ctrl-C to stop). Not
215    /// compatible with `--live`.
216    #[arg(short = 'o', long = "output", value_name = "FILE")]
217    pub output: Option<String>,
218
219    /// Pipe the source file through this command before rendering.
220    /// Must start with `|`; `%s` is substituted with the file path.
221    /// Example: `--preprocess '|pdftotext %s -'`. Overrides $LESSOPEN.
222    #[arg(
223        long = "preprocess",
224        value_name = "CMD",
225        conflicts_with_all = ["no_preprocess", "hex", "follow", "live"],
226    )]
227    pub preprocess: Option<String>,
228
229    /// Pretty-print structured content (JSON, YAML, TOML, XML, HTML, CSV).
230    /// Detects the type from the filename extension or the first bytes; use
231    /// `--content-type=NAME` to override. Static files only — not allowed
232    /// with `--follow`, `--live`, or `--filter`. Toggle interactively with
233    /// `Shift-P`; force a type with `-P` then a letter (j/y/t/x/h/c).
234    #[arg(long = "prettify")]
235    pub prettify: bool,
236
237    /// Replace the hardcoded status format with a templated string.
238    /// Uses the same `<field>` syntax as `--display`. Available fields:
239    /// label, top, bottom, total, pct, rec-top, rec-bottom, rec-total,
240    /// rec-block, wrap-offset, format-tag, filter-tag, grep-tag,
241    /// hide-tag, search-tag, pretty-tag, live-tag, follow-tag.
242    /// Per-format default can be set via `prompt = '...'` in formats.toml.
243    /// Mutually exclusive with --hex.
244    #[arg(long = "prompt", value_name = "TEMPLATE", conflicts_with = "hex")]
245    pub prompt: Option<String>,
246
247    /// Style for `--prompt` output (and per-format `prompt_style`). Same
248    /// grammar as `--status-style`. Default: empty (no extra styling on top
249    /// of what the prompt template itself emits).
250    #[arg(long = "prompt-style", value_name = "SPEC", default_value = "")]
251    pub prompt_style: String,
252
253    /// Quit when the user tries to scroll forward past end-of-file for
254    /// the second time. Mirrors `less -e`. Mutually exclusive with `-E`.
255    #[arg(short = 'e', long = "quit-at-eof", conflicts_with = "QUIT_AT_EOF")]
256    pub quit_at_eof: bool,
257
258    /// Quit the first time end-of-file is reached. Mirrors `less -E`.
259    #[arg(short = 'E', long = "QUIT-AT-EOF")]
260    pub QUIT_AT_EOF: bool,
261
262    /// Exit immediately (without paging) if the entire source fits on
263    /// one screen. Ignored with piped stdin in follow mode. Mirrors
264    /// `less -F`.
265    #[arg(short = 'F', long = "quit-if-one-screen")]
266    pub quit_if_one_screen: bool,
267
268    /// Accepted for `less` compatibility. tess always exits on Ctrl-C
269    /// (Ctrl-C → Command::Quit in the input table), so this flag is a
270    /// no-op. Provided so existing `less` invocations work unchanged.
271    #[arg(short = 'K', long = "quit-on-intr")]
272    pub quit_on_intr: bool,
273
274    /// Pass every byte to the terminal raw, including cursor moves and
275    /// non-SGR escape sequences. Risky: scroll math may break on long lines.
276    /// Less-style -r. Mutually exclusive with --no-color.
277    #[arg(short = 'r', long = "raw-control-chars", conflicts_with = "no_color")]
278    pub raw_control_chars: bool,
279
280    /// Treat lines matching REGEX as record boundaries. Lines that don't
281    /// match are joined to the preceding record. Affects search, filter,
282    /// grep, and the status line — all operate on whole records when set.
283    /// Overrides the active --format's record_start if both are present.
284    /// Without --format, this is the only way to enable records mode for
285    /// plain text. Example: --record-start '^\['
286    #[arg(long = "record-start", value_name = "REGEX")]
287    pub record_start: Option<String>,
288
289    /// Character to show at the right edge of a chopped line (`-S` chop
290    /// mode) indicating "more content right". Default `>`. Pass an empty
291    /// string to disable. Mirrors `less --rscroll=c`.
292    #[arg(long = "rscroll", value_name = "CHAR", default_value = ">")]
293    pub rscroll: String,
294
295    /// Collapse runs of two or more consecutive blank lines into a
296    /// single blank line at display time. Real line numbers, search,
297    /// and tag jumps are unaffected (they reference the original
298    /// count). Mirrors `less -s`.
299    #[arg(short = 's', long = "squeeze-blank-lines")]
300    pub squeeze_blanks: bool,
301
302    /// Style for the status row. Comma-separated tokens: `bold`, `dim`,
303    /// `italic`, `underline`, `reverse`, `fg=COLOR`, `bg=COLOR`. COLOR is a
304    /// named color (`black`..`white`, optional `bright-` prefix), `#RRGGBB`,
305    /// or an indexed value (0–255). Empty string disables theming.
306    /// Default: `reverse`.
307    #[arg(long = "status-style", value_name = "SPEC", default_value = "reverse")]
308    pub status_style: String,
309
310    /// Synonym for `--output -`: write the batch-mode output to stdout.
311    #[arg(long = "stdout", conflicts_with = "output")]
312    pub stdout: bool,
313
314    /// Tab stop width (default 8).
315    #[arg(long = "tab-width", default_value_t = 8)]
316    pub tab_width: u8,
317
318    /// Jump to the tag NAME at startup (requires a tags file).
319    #[arg(short = 't', long = "tag", value_name = "NAME")]
320    pub tag: Option<String>,
321
322    /// Path to the tags file. Default: walk up from CWD looking for `tags`.
323    #[arg(short = 'T', long = "tag-file", value_name = "PATH")]
324    pub tag_file: Option<std::path::PathBuf>,
325
326    /// Show only the last N lines of the source. For files this skips most of
327    /// the index work — useful for huge logs. Combine with `-f` for `tail -f`.
328    /// Mutually exclusive with --head. Streaming stdin is not supported.
329    #[arg(long = "tail", value_name = "N", conflicts_with = "head")]
330    pub tail: Option<usize>,
331
332    /// Truecolor (24-bit RGB) handling. `auto` (default) checks `$COLORTERM`
333    /// and downsamples when truecolor isn't advertised; `never` always
334    /// downsamples to the 256-color palette; `always` passes RGB through
335    /// regardless of terminal capability.
336    #[arg(long = "truecolor", value_name = "MODE", default_value = "auto")]
337    pub truecolor: String,
338
339    /// PageDown / PageUp step size in lines. Default: full screen
340    /// height (body rows). Half-page commands always advance by half
341    /// the screen regardless. Mirrors `less -zn` / `--window=n`.
342    #[arg(short = 'z', long = "window", value_name = "N")]
343    pub window: Option<u16>,
344
345    /// In wrap mode, break lines on whitespace boundaries instead of
346    /// mid-character when possible. Falls back to mid-character break
347    /// when no whitespace fits in the row. Mirrors `less --wordwrap`.
348    #[arg(long = "wordwrap")]
349    pub word_wrap: bool,
350
351    /// Files to view (only the first is opened in MVP).
352    pub files: Vec<PathBuf>,
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358
359    #[test]
360    fn parses_no_flags_no_files() {
361        let a = Args::parse_from(["tess"]);
362        assert!(!a.line_numbers);
363        assert!(!a.chop);
364        assert_eq!(a.tab_width, 8);
365        assert!(a.files.is_empty());
366    }
367
368    #[test]
369    fn parses_short_flags_and_file() {
370        let a = Args::parse_from(["tess", "-N", "-S", "foo.txt"]);
371        assert!(a.line_numbers);
372        assert!(a.chop);
373        assert_eq!(a.files, vec![PathBuf::from("foo.txt")]);
374    }
375
376    #[test]
377    fn parses_tab_width() {
378        let a = Args::parse_from(["tess", "--tab-width", "4", "x"]);
379        assert_eq!(a.tab_width, 4);
380    }
381
382    #[test]
383    fn collects_multiple_files() {
384        let a = Args::parse_from(["tess", "a", "b", "c"]);
385        assert_eq!(a.files.len(), 3);
386    }
387
388    #[test]
389    fn parses_follow_short_flag() {
390        let a = Args::parse_from(["tess", "-f", "log.txt"]);
391        assert!(a.follow);
392        assert_eq!(a.files, vec![PathBuf::from("log.txt")]);
393    }
394
395    #[test]
396    fn parses_follow_long_flag() {
397        let a = Args::parse_from(["tess", "--follow"]);
398        assert!(a.follow);
399    }
400
401    #[test]
402    fn follow_defaults_off() {
403        let a = Args::parse_from(["tess", "x"]);
404        assert!(!a.follow);
405    }
406
407    #[test]
408    fn parses_head() {
409        let a = Args::parse_from(["tess", "--head", "100", "x"]);
410        assert_eq!(a.head, Some(100));
411        assert_eq!(a.tail, None);
412    }
413
414    #[test]
415    fn parses_tail() {
416        let a = Args::parse_from(["tess", "--tail", "50", "x"]);
417        assert_eq!(a.tail, Some(50));
418        assert_eq!(a.head, None);
419    }
420
421    #[test]
422    fn head_and_tail_are_mutually_exclusive() {
423        let r = Args::try_parse_from(["tess", "--head", "10", "--tail", "20", "x"]);
424        assert!(r.is_err(), "clap should reject combining --head and --tail");
425    }
426
427    #[test]
428    fn head_tail_default_to_none() {
429        let a = Args::parse_from(["tess", "x"]);
430        assert!(a.head.is_none());
431        assert!(a.tail.is_none());
432    }
433
434    #[test]
435    fn parses_grep_repeatable_and_no_format_required() {
436        let a = Args::parse_from([
437            "tess",
438            "--grep", "error",
439            "--grep", r"^\[",
440            "log",
441        ]);
442        assert_eq!(a.grep.len(), 2);
443        assert_eq!(a.grep[0], "error");
444        assert_eq!(a.grep[1], r"^\[");
445        assert_eq!(a.format, None);
446    }
447
448    #[test]
449    fn parses_format_and_filter() {
450        let a = Args::parse_from([
451            "tess", "--format", "apache-combined",
452            "--filter", "status=500",
453            "--filter", "ip~^10\\.",
454            "log",
455        ]);
456        assert_eq!(a.format.as_deref(), Some("apache-combined"));
457        assert_eq!(a.filter.len(), 2);
458        assert_eq!(a.filter[0], "status=500");
459    }
460
461    #[test]
462    fn parses_dim() {
463        let a = Args::parse_from(["tess", "--format", "x", "--filter", "y=z", "--dim", "f"]);
464        assert!(a.dim);
465    }
466
467    #[test]
468    fn parses_list_formats() {
469        let a = Args::parse_from(["tess", "--list-formats"]);
470        assert!(a.list_formats);
471    }
472
473    #[test]
474    fn parses_manual() {
475        let a = Args::parse_from(["tess", "--manual"]);
476        assert!(a.manual);
477    }
478
479    #[test]
480    fn parses_examples() {
481        let a = Args::parse_from(["tess", "--examples"]);
482        assert!(a.examples);
483    }
484
485    #[test]
486    fn parses_live() {
487        let a = Args::parse_from(["tess", "--live", "f"]);
488        assert!(a.live);
489        assert!(!a.follow);
490    }
491
492    #[test]
493    fn live_and_follow_are_mutually_exclusive() {
494        let r = Args::try_parse_from(["tess", "--live", "--follow", "f"]);
495        assert!(r.is_err(), "clap should reject combining --live and --follow");
496    }
497
498    #[test]
499    fn parses_prettify() {
500        let a = Args::parse_from(["tess", "--prettify", "f.json"]);
501        assert!(a.prettify);
502        assert_eq!(a.content_type, None);
503    }
504
505    #[test]
506    fn parses_content_type() {
507        let a = Args::parse_from(["tess", "--content-type", "json", "f"]);
508        assert_eq!(a.content_type.as_deref(), Some("json"));
509    }
510
511    #[test]
512    fn parses_output_long_and_short() {
513        let a = Args::parse_from(["tess", "-o", "/tmp/out.txt", "f"]);
514        assert_eq!(a.output.as_deref(), Some("/tmp/out.txt"));
515        let b = Args::parse_from(["tess", "--output", "/tmp/out.txt", "f"]);
516        assert_eq!(b.output.as_deref(), Some("/tmp/out.txt"));
517    }
518
519    #[test]
520    fn parses_stdout_flag() {
521        let a = Args::parse_from(["tess", "--stdout", "f"]);
522        assert!(a.stdout);
523        assert_eq!(a.output, None);
524    }
525
526    #[test]
527    fn output_and_stdout_are_mutually_exclusive() {
528        let r = Args::try_parse_from(["tess", "-o", "x", "--stdout", "f"]);
529        assert!(r.is_err(), "clap should reject combining --output and --stdout");
530    }
531
532    #[test]
533    fn parses_mouse_flag() {
534        let a = Args::parse_from(["tess", "--mouse", "f"]);
535        assert!(a.mouse);
536    }
537
538    #[test]
539    fn mouse_defaults_off() {
540        let a = Args::parse_from(["tess", "f"]);
541        assert!(!a.mouse);
542    }
543
544    #[test]
545    fn parses_no_image_flag() {
546        let a = Args::parse_from(["tess", "--no-image", "cat.png"]);
547        assert!(a.no_image);
548    }
549
550    #[test]
551    fn parses_blocks_flag() {
552        let a = Args::parse_from(["tess", "--blocks", "cat.png"]);
553        assert!(a.blocks);
554    }
555
556    #[test]
557    fn parses_image_width() {
558        let a = Args::parse_from(["tess", "--image-width", "120", "cat.png"]);
559        assert_eq!(a.image_width, Some(120));
560    }
561
562    #[test]
563    fn image_flags_default_off() {
564        let a = Args::parse_from(["tess", "f"]);
565        assert!(!a.no_image);
566        assert!(!a.blocks);
567        assert_eq!(a.image_width, None);
568    }
569
570    #[test]
571    fn help_lists_flags_in_alphabetical_order() {
572        use clap::CommandFactory;
573        let mut cmd = Args::command();
574        let help = cmd.render_help().to_string();
575
576        // The full set of long flags, in the order we expect `--help` to list
577        // them: alphabetical by long name, case-insensitive. clap's auto-added
578        // --help / --version are excluded (they're not in this list, so the
579        // first-token scan below skips their lines).
580        let expected = [
581            "--blocks",
582            "--chop-long-lines",
583            "--content-type",
584            "--dim",
585            "--display",
586            "--examples",
587            "--exit-follow-on-close",
588            "--filter",
589            "--follow",
590            "--follow-name",
591            "--follow-suspend-on-motion",
592            "--format",
593            "--grep",
594            "--head",
595            "--header",
596            "--hex",
597            "--hex-group",
598            "--ignore-case",
599            "--IGNORE-CASE",
600            "--image-width",
601            "--LINE-NUMBERS",
602            "--list-formats",
603            "--live",
604            "--manual",
605            "--mouse",
606            "--no-color",
607            "--no-hilite-search",
608            "--no-image",
609            "--no-init",
610            "--no-preprocess",
611            "--output",
612            "--preprocess",
613            "--prettify",
614            "--prompt",
615            "--prompt-style",
616            "--quit-at-eof",
617            "--QUIT-AT-EOF",
618            "--quit-if-one-screen",
619            "--quit-on-intr",
620            "--raw-control-chars",
621            "--record-start",
622            "--rscroll",
623            "--squeeze-blank-lines",
624            "--status-style",
625            "--stdout",
626            "--tab-width",
627            "--tag",
628            "--tag-file",
629            "--tail",
630            "--truecolor",
631            "--window",
632            "--wordwrap",
633        ];
634
635        // Confirm `expected` is itself sorted case-insensitively — this guards
636        // against a typo here masking a real ordering regression in the struct.
637        let mut sorted = expected.to_vec();
638        sorted.sort_by_key(|s| s.trim_start_matches('-').to_ascii_lowercase());
639        assert_eq!(
640            expected.to_vec(),
641            sorted,
642            "the `expected` list must itself be in case-insensitive alphabetical order"
643        );
644
645        // Walk the rendered help line by line. For each option line (after
646        // trimming, it starts with '-'), take the first `--long` token that is
647        // one of our flags. Because the flag name always precedes its own
648        // description on the line, embedded `--flag` references in descriptions
649        // are never matched first.
650        let listed: Vec<&str> = help
651            .lines()
652            .map(str::trim_start)
653            .filter(|l| l.starts_with('-'))
654            .filter_map(|l| {
655                l.split(|c: char| c.is_whitespace() || c == ',')
656                    .find(|tok| expected.contains(tok))
657            })
658            .collect();
659        assert_eq!(listed, expected, "help long-flag order should be alphabetical");
660    }
661}