winnow-args 0.1.0

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

use std::fmt::Write as _;

use crate::color::Paint;
pub use crate::color::{Depth, Palette, Theme};

/// One command's help: what it is, what it takes, what it contains.
///
/// Written by the derive, as [`Item`] and [`Sub`] are: fields are added as
/// help learns to show more, so a hand-written one tracks the release.
#[derive(Debug)]
pub struct Command {
    /// The command's own name; empty for a root that leaves it to `argv[0]`.
    pub name: &'static str,
    /// First paragraph of the description.
    pub about: &'static str,
    /// The whole description, for `--help`.
    pub long_about: &'static str,
    /// Text after the lists, for `-h`.
    pub after_help: &'static str,
    /// Text after the lists, for `--help`.
    pub after_long_help: &'static str,
    /// Flags and positionals, in declaration order.
    pub items: &'static [Item],
    /// Subcommands, in declaration order.
    pub subcommands: &'static [Sub],
    /// Whether a subcommand must be given.
    pub subcommand_required: bool,
    /// Whether `--help` is supplied (not declared or disabled).
    pub help_flag: bool,
    /// Whether the supplied help flag has `-h` as well as `--help`.
    pub help_short: bool,
    /// The version, when `-V`/`--version` are supplied.
    pub version: Option<&'static str>,
}

/// A flag or positional.
#[derive(Debug, Clone, Copy)]
pub struct Item {
    /// `-c`.
    pub short: Option<char>,
    /// `--name`.
    pub long: Option<&'static str>,
    /// Other long names it answers to, not shown.
    pub aliases: &'static [&'static str],
    /// `--no-name`, the spelling that sets it false.
    pub negate: Option<&'static str>,
    /// The value's placeholder; `None` for a switch.
    pub value_name: Option<&'static str>,
    /// First paragraph of the description.
    pub help: &'static str,
    /// The whole description.
    pub long_help: &'static str,
    /// Section to list it under instead of "Options".
    pub heading: Option<&'static str>,
    /// Left out of help.
    pub hide: bool,
    /// A positional rather than a flag.
    pub positional: bool,
    /// Must be given.
    pub required: bool,
    /// Takes several values or occurrences.
    pub multiple: bool,
    /// A positional that only takes words after `--`.
    pub trailing: bool,
    /// The value used when none is given.
    pub default: Option<&'static str>,
    /// The environment variable consulted.
    pub env: Option<&'static str>,
    /// The only values accepted.
    pub choices: &'static [&'static str],
    /// The value is only taken attached (`--name=value`), never the next word.
    pub require_equals: bool,
    /// Also accepted by every subcommand below.
    pub global: bool,
    /// Other letters it answers to: `-l`, `-L`.
    pub more_shorts: &'static [char],
    /// The letter of its `+c` spelling.
    pub plus: Option<char>,
    /// The value may be left out.
    pub optional_value: bool,
    /// Words each occurrence takes; 1 unless declared `values = N`.
    pub values: usize,
    /// It may take more than `values` (`values = 1..`): shown as `<V>...`.
    pub more_values: bool,
}

impl Item {
    /// No flag at all: what [`concat_items`]'s array starts from.
    const EMPTY: Item = Item {
        short: None,
        long: None,
        aliases: &[],
        negate: None,
        value_name: None,
        help: "",
        long_help: "",
        heading: None,
        hide: false,
        positional: false,
        required: false,
        multiple: false,
        trailing: false,
        default: None,
        env: None,
        choices: &[],
        require_equals: false,
        global: false,
        more_shorts: &[],
        plus: None,
        optional_value: false,
        values: 1,
        more_values: false,
    };
}

/// Whether two items of different `parts` are spelled alike (a short letter,
/// a long name or its negation): a struct and what it flattens, checked at
/// compile time.
#[doc(hidden)]
pub const fn items_clash(parts: &[&[Item]]) -> bool {
    const fn same(a: Option<&str>, b: Option<&str>) -> bool {
        let (Some(a), Some(b)) = (a, b) else {
            return false;
        };
        let (a, b) = (a.as_bytes(), b.as_bytes());
        if a.len() != b.len() {
            return false;
        }
        let mut i = 0;
        while i < a.len() {
            if a[i] != b[i] {
                return false;
            }
            i += 1;
        }
        true
    }
    /// Whether `item` answers to the letter.
    const fn has_short(item: &Item, letter: char) -> bool {
        if matches!(item.short, Some(c) if c == letter) {
            return true;
        }
        let mut i = 0;
        while i < item.more_shorts.len() {
            if item.more_shorts[i] == letter {
                return true;
            }
            i += 1;
        }
        false
    }
    /// Whether `item` answers to the long name: its own, its negation, an alias.
    const fn has_long(item: &Item, name: Option<&str>) -> bool {
        if same(item.long, name) || same(item.negate, name) {
            return true;
        }
        let mut i = 0;
        while i < item.aliases.len() {
            if same(Some(item.aliases[i]), name) {
                return true;
            }
            i += 1;
        }
        false
    }
    const fn clash(a: &Item, b: &Item) -> bool {
        if a.positional || b.positional {
            return false;
        }
        if matches!(a.short, Some(c) if has_short(b, c)) {
            return true;
        }
        let mut i = 0;
        while i < a.more_shorts.len() {
            if has_short(b, a.more_shorts[i]) {
                return true;
            }
            i += 1;
        }
        if has_long(b, a.long) || has_long(b, a.negate) {
            return true;
        }
        let mut i = 0;
        while i < a.aliases.len() {
            if has_long(b, Some(a.aliases[i])) {
                return true;
            }
            i += 1;
        }
        false
    }
    let mut p = 0;
    while p < parts.len() {
        let mut q = p + 1;
        while q < parts.len() {
            let (mut i, a, b) = (0, parts[p], parts[q]);
            while i < a.len() {
                let mut j = 0;
                while j < b.len() {
                    if clash(&a[i], &b[j]) {
                        return true;
                    }
                    j += 1;
                }
                i += 1;
            }
            q += 1;
        }
        p += 1;
    }
    false
}

/// `parts`, one after another, as one array: a struct's own items and those
/// of the structs it flattens, joined at compile time. `N` is their total
/// length.
///
/// # Panics
///
/// At compile time, if `N` is not the total length.
#[doc(hidden)]
pub const fn concat_items<const N: usize>(parts: &[&[Item]]) -> [Item; N] {
    let mut out = [Item::EMPTY; N];
    let (mut n, mut p) = (0, 0);
    while p < parts.len() {
        let part = parts[p];
        let mut i = 0;
        while i < part.len() {
            out[n] = part[i];
            n += 1;
            i += 1;
        }
        p += 1;
    }
    assert!(n == N, "concat_items: the length is not the parts' total");
    out
}

/// A subcommand as its parent lists it.
#[derive(Debug)]
pub struct Sub {
    /// Its name.
    pub name: &'static str,
    /// Other spellings shown beside it.
    pub aliases: &'static [&'static str],
    /// Every spelling it answers to, hidden aliases included, for `help <name>`.
    pub names: &'static [&'static str],
    /// Its own help.
    pub command: &'static Command,
    /// One line about it.
    pub about: &'static str,
    /// Left out of the list.
    pub hide: bool,
}

/// The command a `help a b …` line asks about: follow each word through
/// `root`'s subcommands until one names none. Gives it and the names followed.
pub fn resolve<'w>(
    root: &'static Command,
    words: impl IntoIterator<Item = &'w [u8]>,
) -> (&'static Command, Vec<&'static str>) {
    let (mut command, mut path) = (root, Vec::new());
    for word in words {
        let Some(sub) = command
            .subcommands
            .iter()
            .find(|s| s.names.iter().any(|n| n.as_bytes() == word))
        else {
            break;
        };
        path.push(sub.name);
        command = sub.command;
    }
    (command, path)
}

/// The width help wraps to: `COLUMNS` when it is a positive number, so a user
/// or a test can say what to assume; else, with the `terminal-size` feature,
/// the width of the terminal on standard output; else 100.
///
/// Under [`with_env`](crate::with_env) the terminal is not asked: the page
/// depends only on the environment given.
pub fn width() -> usize {
    crate::env::var("COLUMNS")
        .and_then(|columns| columns.to_str()?.trim().parse().ok())
        .filter(|&columns| columns > 0)
        .or_else(terminal_width)
        .unwrap_or(100)
}

#[cfg(feature = "terminal-size")]
fn terminal_width() -> Option<usize> {
    if crate::env::overridden() {
        return None;
    }
    terminal_size::terminal_size()
        .map(|(width, _)| usize::from(width.0))
        .filter(|&width| width > 0)
}

#[cfg(not(feature = "terminal-size"))]
fn terminal_width() -> Option<usize> {
    None
}

/// How help and errors are painted: a [`Palette`] for a terminal of some
/// [`Depth`]. The escapes never count toward a column's width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Style {
    /// The paint for each kind of text.
    pub palette: Palette,
    /// What the terminal shows; colors deeper than this are mapped down.
    pub depth: Depth,
}

/// A paint resolved for a depth: what the renderer writes with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Ink {
    paint: Paint,
    depth: Depth,
}

impl Ink {
    /// Plain text.
    const NONE: Ink = Ink {
        paint: Paint::NONE,
        depth: Depth::None,
    };
}

impl Style {
    /// Nothing painted: for pipes, files and tests.
    pub const PLAIN: Style = Style::at(Palette::PLAIN, Depth::None);

    /// [`Palette::DEFAULT`] in the 16 basic colors.
    pub const COLORED: Style = Style::at(Palette::DEFAULT, Depth::Ansi16);

    /// [`Palette::CLAP`]: bold and underline in help, color only in errors.
    pub const CLAP: Style = Style::at(Palette::CLAP, Depth::Ansi16);

    /// `palette` on a terminal of `depth`.
    pub const fn at(palette: Palette, depth: Depth) -> Style {
        Style { palette, depth }
    }

    /// [`Theme::DEFAULT`] for standard output, at the depth
    /// [`Depth::detect`] finds.
    pub fn auto() -> Style {
        use std::io::IsTerminal as _;
        Style::themed(&Theme::DEFAULT, std::io::stdout().is_terminal())
    }

    /// [`Style::auto`] for standard error, where errors go.
    pub fn auto_stderr() -> Style {
        use std::io::IsTerminal as _;
        Style::themed(&Theme::DEFAULT, std::io::stderr().is_terminal())
    }

    /// [`Theme::DEFAULT`] for a stream that is (or is not) a terminal.
    pub fn auto_for(is_terminal: bool) -> Style {
        Style::themed(&Theme::DEFAULT, is_terminal)
    }

    /// `theme`'s palette for the depth [`Depth::detect`] finds for a stream
    /// that is (or is not) a terminal.
    pub fn themed(theme: &Theme, is_terminal: bool) -> Style {
        let depth = Depth::detect(is_terminal);
        Style::at(theme.palette(depth), depth)
    }

    fn ink(self, paint: Paint) -> Ink {
        Ink {
            paint,
            depth: self.depth,
        }
    }

    pub(crate) fn header(self) -> Ink {
        self.ink(self.palette.header)
    }

    pub(crate) fn program(self) -> Ink {
        self.ink(self.palette.program)
    }

    pub(crate) fn flag(self) -> Ink {
        self.ink(self.palette.flag)
    }

    pub(crate) fn command(self) -> Ink {
        self.ink(self.palette.command)
    }

    pub(crate) fn dim(self) -> Ink {
        self.ink(self.palette.dim)
    }

    pub(crate) fn code(self) -> Ink {
        self.ink(self.palette.code)
    }

    pub(crate) fn placeholder(self) -> Ink {
        self.ink(self.palette.placeholder)
    }

    pub(crate) fn error(self) -> Ink {
        self.ink(self.palette.error)
    }

    pub(crate) fn invalid(self) -> Ink {
        self.ink(self.palette.invalid)
    }

    pub(crate) fn valid(self) -> Ink {
        self.ink(self.palette.valid)
    }

    pub(crate) fn env(self) -> Ink {
        self.ink(self.palette.env)
    }

    pub(crate) fn default(self) -> Ink {
        self.ink(self.palette.default)
    }

    pub(crate) fn choice(self) -> Ink {
        self.ink(self.palette.choice)
    }

    /// `text` in `ink`, reset after.
    pub(crate) fn paint(ink: Ink, text: &str) -> String {
        let mut out = String::new();
        push_painted(&mut out, ink, text);
        out
    }
}

/// Append `text` in `ink` (plain if it paints nothing), reset after.
fn push_painted(out: &mut String, ink: Ink, text: &str) {
    ink.paint.write(out, ink.depth, text);
}

/// Painted text and how many columns it takes on screen.
#[derive(Default)]
struct Cell {
    text: String,
    width: usize,
}

impl Cell {
    fn push(&mut self, ink: Ink, text: &str) {
        push_painted(&mut self.text, ink, text);
        self.width += text.chars().count();
    }

    /// `<NAME>` painted whole, or `[NAME]` with only the name painted: square
    /// brackets say "optional", they are not part of the value.
    fn push_placeholder(&mut self, style: Style, required: bool, name: &str) {
        if required {
            self.push(style.placeholder(), &format!("<{name}>"));
        } else {
            self.push(style.dim(), "[");
            self.push(style.placeholder(), name);
            self.push(style.dim(), "]");
        }
    }
}

/// Render `command`'s help, plain, wrapped to [`width`]. `path` is the command
/// line leading to it (program name, then subcommand names); `long` selects
/// `--help` over `-h`.
pub fn render(command: &Command, path: &[&str], long: bool) -> String {
    render_styled(command, path, long, width(), Style::PLAIN)
}

/// [`render`], wrapped to `width` columns.
pub fn render_width(command: &Command, path: &[&str], long: bool, width: usize) -> String {
    render_styled(command, path, long, width, Style::PLAIN)
}

/// [`render`], wrapped to `width` columns and painted with `style`.
pub fn render_styled(
    command: &Command,
    path: &[&str],
    long: bool,
    width: usize,
    style: Style,
) -> String {
    let mut out = String::new();
    let about = if long && !command.long_about.is_empty() {
        command.long_about
    } else {
        command.about
    };
    if !about.is_empty() {
        let _ = writeln!(out, "{}\n", wrap_text(about, width));
    }
    push_painted(&mut out, style.header(), "Usage:");
    let _ = writeln!(out, " {}\n", usage(command, path, style));

    let visible_subs: Vec<&Sub> = command.subcommands.iter().filter(|s| !s.hide).collect();
    if !visible_subs.is_empty() {
        let rows: Vec<(Cell, String)> = visible_subs
            .iter()
            .map(|s| {
                let mut name = Cell::default();
                name.push(style.command(), s.name);
                for alias in s.aliases {
                    name.push(Ink::NONE, ", ");
                    name.push(style.command(), alias);
                }
                (name, painted_code(s.about, style))
            })
            .collect();
        section(&mut out, "Commands", &rows, false, width, style);
    }

    let visible: Vec<&Item> = command.items.iter().filter(|i| !i.hide).collect();
    let arguments: Vec<(Cell, String)> = visible
        .iter()
        .filter(|i| i.positional)
        .map(|i| {
            let mut cell = Cell::default();
            push_item_placeholder(&mut cell, style, i);
            (cell, describe(i, long, style))
        })
        .collect();
    section(&mut out, "Arguments", &arguments, long, width, style);

    let mut headings: Vec<Option<&str>> = vec![None];
    for item in visible.iter().filter(|i| !i.positional) {
        if !headings.contains(&item.heading) {
            headings.push(item.heading);
        }
    }
    let builtin = |short: &str, long_name: &str| {
        let mut cell = Cell::default();
        cell.push(style.flag(), short);
        cell.push(Ink::NONE, ", ");
        cell.push(style.flag(), long_name);
        cell
    };
    for heading in headings {
        let mut rows: Vec<(Cell, String)> = visible
            .iter()
            .filter(|i| !i.positional && i.heading == heading)
            .map(|i| (flag_spec(i, style), describe(i, long, style)))
            .collect();
        if heading.is_none() {
            if command.help_flag {
                let what = if long {
                    "Print help (see a summary with '-h')"
                } else {
                    "Print help (see more with '--help')"
                };
                let cell = if command.help_short {
                    builtin("-h", "--help")
                } else {
                    let mut cell = Cell::default();
                    cell.push(Ink::NONE, "    ");
                    cell.push(style.flag(), "--help");
                    cell
                };
                let what = if command.help_short {
                    what
                } else {
                    "Print help"
                };
                rows.push((cell, what.into()));
            }
            if command.version.is_some() {
                rows.push((builtin("-V", "--version"), "Print version".into()));
            }
        }
        section(
            &mut out,
            heading.unwrap_or("Options"),
            &rows,
            long,
            width,
            style,
        );
    }

    let after = if long && !command.after_long_help.is_empty() {
        command.after_long_help
    } else {
        command.after_help
    };
    if !after.is_empty() {
        let _ = writeln!(out, "{}", wrap_text(after, width));
    }
    while out.ends_with("\n\n") {
        out.pop();
    }
    out
}

/// `prog [OPTIONS] <A> [B]... [COMMAND]`.
pub(crate) fn usage(command: &Command, path: &[&str], style: Style) -> String {
    let mut line = Style::paint(style.program(), &path.join(" "));
    let mut cell = Cell::default();
    if command.items.iter().any(|i| !i.positional && !i.hide) || command.help_flag {
        cell.push(Ink::NONE, " ");
        cell.push_placeholder(style, false, "OPTIONS");
    }
    for item in command
        .items
        .iter()
        .filter(|i| i.positional && !i.hide && !i.trailing)
    {
        cell.push(Ink::NONE, " ");
        push_item_placeholder(&mut cell, style, item);
    }
    if !command.subcommands.is_empty() {
        cell.push(Ink::NONE, " ");
        cell.push_placeholder(style, command.subcommand_required, "COMMAND");
    }
    line.push_str(&cell.text);
    for item in command
        .items
        .iter()
        .filter(|i| i.positional && !i.hide && i.trailing)
    {
        // The brackets and `--` are typed, so they are painted as literals.
        let mut cell = Cell::default();
        cell.push(Ink::NONE, " ");
        cell.push(style.dim(), "[");
        cell.push(style.flag(), "--");
        cell.push(Ink::NONE, " ");
        push_item_placeholder(&mut cell, style, item);
        cell.push(style.dim(), "]");
        line.push_str(&cell.text);
    }
    line
}

/// A positional's placeholder: `<NAME>` or `[NAME]`, then `...` if repeated.
fn push_item_placeholder(cell: &mut Cell, style: Style, item: &Item) {
    cell.push_placeholder(style, item.required, item.value_name.unwrap_or("VALUE"));
    if item.multiple {
        cell.push(style.dim(), "...");
    }
}

fn flag_spec(item: &Item, style: Style) -> Cell {
    let mut spec = Cell::default();
    // Every spelling: `-l, -L`, `-e, +e`, `+o`, `-v, --verbose`; a long name
    // alone is indented to line up with those after a short one.
    let shorts = item.short.iter().chain(item.more_shorts);
    let mut names: Vec<String> = shorts.map(|s| format!("-{s}")).collect();
    names.extend(item.plus.map(|c| format!("+{c}")));
    if names.is_empty() && item.long.is_some() {
        spec.push(Ink::NONE, "    ");
    }
    names.extend(item.long.map(|l| format!("--{l}")));
    for (i, name) in names.iter().enumerate() {
        if i > 0 {
            spec.push(Ink::NONE, ", ");
        }
        spec.push(style.flag(), name);
    }
    if let Some(no) = item.negate {
        spec.push(Ink::NONE, " / ");
        spec.push(style.flag(), &format!("--{no}"));
    }
    if let Some(value) = item.value_name {
        // `<V>`, `=<V>` when only attached, in brackets when optional, and
        // once a word for `values = N`.
        let more = if item.more_values { "..." } else { "" };
        let value = vec![format!("<{value}>"); item.values.max(1)].join(" ") + more;
        let (open, close) = match (item.require_equals, item.optional_value) {
            (true, true) => ("[=", "]"),
            (true, false) => ("=", ""),
            (false, true) => (" [", "]"),
            (false, false) => (" ", ""),
        };
        spec.push(Ink::NONE, open);
        spec.push(style.placeholder(), &value);
        spec.push(Ink::NONE, close);
    }
    if item.multiple {
        spec.push(style.dim(), "...");
    }
    spec
}

/// An item's description, then `[env: …]`, `[default: …]` and
/// `[possible values: …]`, each value painted on its own (so a line never
/// breaks inside a painted span).
fn describe(item: &Item, long: bool, style: Style) -> String {
    let help = if long && !item.long_help.is_empty() {
        item.long_help
    } else {
        item.help
    };
    let mut text = painted_code(help, style);
    let mut add = |extra: String| {
        if !text.is_empty() {
            text.push(if long { '\n' } else { ' ' });
        }
        text.push_str(&extra);
    };
    let label = |label: &str| Style::paint(style.dim(), label);
    let close = || Style::paint(style.dim(), "]");
    if let Some(env) = item.env {
        let env = Style::paint(style.env(), env);
        add(format!("{}{env}{}", label("[env: "), close()));
    }
    if let Some(default) = item.default {
        let default = Style::paint(style.default(), default);
        add(format!("{}{default}{}", label("[default: "), close()));
    }
    if !item.choices.is_empty() {
        let choices: Vec<String> = item
            .choices
            .iter()
            .map(|c| Style::paint(style.choice(), c))
            .collect();
        add(format!(
            "{}{}{}",
            label("[possible values: "),
            choices.join(", "),
            close()
        ));
    }
    text
}

/// `text` with each `` `quoted` `` span painted as code, backticks kept (so
/// the painted page is the plain one plus escapes). Each word of a span is
/// painted on its own, so wrapping never breaks inside a painted run; an
/// unpaired backtick is left alone.
fn painted_code(text: &str, style: Style) -> String {
    let ink = style.code();
    if ink.paint == Paint::NONE || ink.depth == Depth::None || !text.contains('`') {
        return text.to_owned();
    }
    let mut out = String::with_capacity(text.len() + 16);
    for (n, line) in text.split('\n').enumerate() {
        if n > 0 {
            out.push('\n');
        }
        let mut rest = line;
        while let Some(open) = rest.find('`') {
            let Some(len) = rest[open + 1..].find('`') else {
                break;
            };
            let close = open + 1 + len;
            out.push_str(&rest[..open]);
            for (i, word) in rest[open..=close].split(' ').enumerate() {
                if i > 0 {
                    out.push(' ');
                }
                push_painted(&mut out, ink, word);
            }
            rest = &rest[close + 1..];
        }
        out.push_str(rest);
    }
    out
}

/// A titled two-column list; long help puts each description under its item.
///
/// Descriptions wrap to `width`. The column is at most two fifths of the
/// page, so one long spelling does not squeeze every
/// description; an item wider than that has its description on the next line.
fn section(
    out: &mut String,
    title: &str,
    rows: &[(Cell, String)],
    long: bool,
    width: usize,
    style: Style,
) {
    if rows.is_empty() {
        return;
    }
    push_painted(out, style.header(), &format!("{title}:"));
    out.push('\n');
    let longest = rows.iter().map(|(left, _)| left.width).max().unwrap_or(0);
    let available = width.saturating_sub(4);
    let column = longest.min(available / 5 * 2 + available % 5 * 2 / 5);
    // Where descriptions start, and how much room they get (never too little to read).
    let (indent, room) = if long {
        (10, width.saturating_sub(10).max(20))
    } else {
        (column + 4, width.saturating_sub(column + 4).max(20))
    };
    for (left, right) in rows {
        let beside = !long && !right.is_empty() && left.width <= column;
        out.push_str("  ");
        out.push_str(&left.text);
        if beside {
            // Padded by what shows, not by the escapes' bytes.
            let _ = write!(out, "{:pad$}  ", "", pad = column - left.width);
        } else {
            out.push('\n');
        }
        let mut first = beside;
        for line in right.lines() {
            if line.is_empty() {
                out.push('\n');
                continue;
            }
            for piece in Wrap::new(line, room) {
                if !first {
                    let _ = write!(out, "{:indent$}", "");
                }
                first = false;
                out.push_str(piece);
                out.push('\n');
            }
        }
        if long {
            // A blank line between items.
            out.push('\n');
        }
    }
    if !long {
        out.push('\n');
    }
}

/// Each line of `text` wrapped to `width`, blank lines kept.
fn wrap_text(text: &str, width: usize) -> String {
    let mut out = String::with_capacity(text.len() + text.len() / width.max(1));
    for (i, line) in text.lines().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        for (j, piece) in Wrap::new(line, width.max(20)).enumerate() {
            if j > 0 {
                out.push('\n');
            }
            out.push_str(piece);
        }
    }
    out
}

/// The pieces of `line` broken at spaces into at most `width` characters; a
/// word longer than that stands alone. Leading indentation stays on the first
/// piece. Borrowed slices, so a line that fits costs one scan.
struct Wrap<'a> {
    rest: &'a str,
    width: usize,
}

impl<'a> Wrap<'a> {
    fn new(line: &'a str, width: usize) -> Self {
        Wrap {
            rest: line.trim_end(),
            width,
        }
    }
}

impl<'a> Iterator for Wrap<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.rest.is_empty() {
            return None;
        }
        // The byte after the last character that fits, and the last space before it.
        let (mut end, mut space, mut count, mut text) = (self.rest.len(), None, 0, false);
        let mut escape = false;
        for (at, c) in self.rest.char_indices() {
            // SGR sequences (`ESC [ … m`) take no columns.
            if escape {
                escape = c != 'm';
                continue;
            }
            if c == '\u{1b}' {
                escape = true;
                continue;
            }
            if count == self.width {
                end = at;
                break;
            }
            // Spaces before the first word are indentation, not a place to break.
            if c != ' ' {
                text = true;
            } else if text {
                space = Some(at);
            }
            count += 1;
        }
        let cut = match (end == self.rest.len(), space) {
            (true, _) => end,
            // The next character is a space: break right there.
            (false, _) if self.rest[end..].starts_with(' ') => end,
            (false, Some(at)) => at,
            // One long word: up to its end.
            (false, None) => self.rest[end..]
                .find(' ')
                .map_or(self.rest.len(), |at| end + at),
        };
        let piece = self.rest[..cut].trim_end();
        self.rest = self.rest[cut..].trim_start();
        Some(piece)
    }
}

#[cfg(test)]
mod tests {
    use super::Wrap;

    fn wrap(line: &str, width: usize) -> Vec<&str> {
        Wrap::new(line, width).collect()
    }

    #[test]
    fn pieces_break_at_spaces_within_the_width() {
        assert_eq!(wrap("aa bb cc", 5), ["aa bb", "cc"]);
        assert_eq!(wrap("aa bb", 5), ["aa bb"]);
        assert_eq!(wrap("aa  bb   cc", 6), ["aa  bb", "cc"]);
    }

    #[test]
    fn a_long_word_stands_alone() {
        assert_eq!(wrap("a verylongword b", 5), ["a", "verylongword", "b"]);
    }

    #[test]
    fn indentation_stays_on_the_first_piece() {
        assert_eq!(wrap("    $ mise use node", 12), ["    $ mise", "use node"]);
    }

    #[test]
    fn escapes_take_no_columns() {
        let green = |s: &str| format!("\u{1b}[32m{s}\u{1b}[0m");
        let line = format!("[possible values: {}, {}]", green("auto"), green("never"));
        let pieces = wrap(&line, 24);
        assert_eq!(
            pieces,
            [
                format!("[possible values: {},", green("auto")),
                format!("{}]", green("never"))
            ]
        );
    }

    #[test]
    fn width_counts_characters() {
        assert_eq!(wrap("éé éé éé", 5), ["éé éé", "éé"]);
    }
}