clap_builder/output/
help_template.rs

1// HACK: for rust 1.64 (1.68 doesn't need this since this is in lib.rs)
2//
3// Wanting consistency in our calls
4#![allow(clippy::write_with_newline)]
5
6// Std
7use std::borrow::Cow;
8use std::cmp;
9use std::collections::BTreeMap;
10
11// Internal
12use crate::builder::PossibleValue;
13use crate::builder::Str;
14use crate::builder::StyledStr;
15use crate::builder::Styles;
16use crate::builder::{Arg, Command};
17use crate::output::display_width;
18use crate::output::wrap;
19use crate::output::Usage;
20use crate::output::TAB;
21use crate::output::TAB_WIDTH;
22use crate::util::FlatSet;
23
24/// `clap` auto-generated help writer
25pub(crate) struct AutoHelp<'cmd, 'writer> {
26    template: HelpTemplate<'cmd, 'writer>,
27}
28
29// Public Functions
30impl<'cmd, 'writer> AutoHelp<'cmd, 'writer> {
31    /// Create a new `HelpTemplate` instance.
32    pub(crate) fn new(
33        writer: &'writer mut StyledStr,
34        cmd: &'cmd Command,
35        usage: &'cmd Usage<'cmd>,
36        use_long: bool,
37    ) -> Self {
38        Self {
39            template: HelpTemplate::new(writer, cmd, usage, use_long),
40        }
41    }
42
43    pub(crate) fn write_help(&mut self) {
44        let pos = self
45            .template
46            .cmd
47            .get_positionals()
48            .any(|arg| should_show_arg(self.template.use_long, arg));
49        let non_pos = self
50            .template
51            .cmd
52            .get_non_positionals()
53            .any(|arg| should_show_arg(self.template.use_long, arg));
54        let subcmds = self.template.cmd.has_visible_subcommands();
55
56        let template = if non_pos || pos || subcmds {
57            DEFAULT_TEMPLATE
58        } else {
59            DEFAULT_NO_ARGS_TEMPLATE
60        };
61        self.template.write_templated_help(template);
62    }
63}
64
65const DEFAULT_TEMPLATE: &str = "\
66{before-help}{about-with-newline}
67{usage-heading} {usage}
68
69{all-args}{after-help}\
70    ";
71
72const DEFAULT_NO_ARGS_TEMPLATE: &str = "\
73{before-help}{about-with-newline}
74{usage-heading} {usage}{after-help}\
75    ";
76
77const SHORT_SIZE: usize = 4; // See `fn short` for the 4
78
79/// Help template writer
80///
81/// Wraps a writer stream providing different methods to generate help for `clap` objects.
82pub(crate) struct HelpTemplate<'cmd, 'writer> {
83    writer: &'writer mut StyledStr,
84    cmd: &'cmd Command,
85    styles: &'cmd Styles,
86    usage: &'cmd Usage<'cmd>,
87    next_line_help: bool,
88    term_w: usize,
89    use_long: bool,
90}
91
92// Public Functions
93impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
94    /// Create a new `HelpTemplate` instance.
95    pub(crate) fn new(
96        writer: &'writer mut StyledStr,
97        cmd: &'cmd Command,
98        usage: &'cmd Usage<'cmd>,
99        use_long: bool,
100    ) -> Self {
101        debug!(
102            "HelpTemplate::new cmd={}, use_long={}",
103            cmd.get_name(),
104            use_long
105        );
106        let term_w = Self::term_w(cmd);
107        let next_line_help = cmd.is_next_line_help_set();
108
109        HelpTemplate {
110            writer,
111            cmd,
112            styles: cmd.get_styles(),
113            usage,
114            next_line_help,
115            term_w,
116            use_long,
117        }
118    }
119
120    #[cfg(not(feature = "unstable-v5"))]
121    fn term_w(cmd: &'cmd Command) -> usize {
122        match cmd.get_term_width() {
123            Some(0) => usize::MAX,
124            Some(w) => w,
125            None => {
126                let (current_width, _h) = dimensions();
127                let current_width = current_width.unwrap_or(100);
128                let max_width = match cmd.get_max_term_width() {
129                    None | Some(0) => usize::MAX,
130                    Some(mw) => mw,
131                };
132                cmp::min(current_width, max_width)
133            }
134        }
135    }
136
137    #[cfg(feature = "unstable-v5")]
138    fn term_w(cmd: &'cmd Command) -> usize {
139        let term_w = match cmd.get_term_width() {
140            Some(0) => usize::MAX,
141            Some(w) => w,
142            None => {
143                let (current_width, _h) = dimensions();
144                current_width.unwrap_or(usize::MAX)
145            }
146        };
147
148        let max_term_w = match cmd.get_max_term_width() {
149            Some(0) => usize::MAX,
150            Some(mw) => mw,
151            None => 100,
152        };
153
154        cmp::min(term_w, max_term_w)
155    }
156
157    /// Write help to stream for the parser in the format defined by the template.
158    ///
159    /// For details about the template language see [`Command::help_template`].
160    ///
161    /// [`Command::help_template`]: Command::help_template()
162    pub(crate) fn write_templated_help(&mut self, template: &str) {
163        debug!("HelpTemplate::write_templated_help");
164        use std::fmt::Write as _;
165
166        let mut parts = template.split('{');
167        if let Some(first) = parts.next() {
168            self.writer.push_str(first);
169        }
170        for part in parts {
171            if let Some((tag, rest)) = part.split_once('}') {
172                match tag {
173                    "name" => {
174                        self.write_display_name();
175                    }
176                    #[cfg(not(feature = "unstable-v5"))]
177                    "bin" => {
178                        self.write_bin_name();
179                    }
180                    "version" => {
181                        self.write_version();
182                    }
183                    "author" => {
184                        self.write_author(false, false);
185                    }
186                    "author-with-newline" => {
187                        self.write_author(false, true);
188                    }
189                    "author-section" => {
190                        self.write_author(true, true);
191                    }
192                    "about" => {
193                        self.write_about(false, false);
194                    }
195                    "about-with-newline" => {
196                        self.write_about(false, true);
197                    }
198                    "about-section" => {
199                        self.write_about(true, true);
200                    }
201                    "usage-heading" => {
202                        let _ = write!(
203                            self.writer,
204                            "{}Usage:{}",
205                            self.styles.get_usage().render(),
206                            self.styles.get_usage().render_reset()
207                        );
208                    }
209                    "usage" => {
210                        self.writer.push_styled(
211                            &self.usage.create_usage_no_title(&[]).unwrap_or_default(),
212                        );
213                    }
214                    "all-args" => {
215                        self.write_all_args();
216                    }
217                    "options" => {
218                        // Include even those with a heading as we don't have a good way of
219                        // handling help_heading in the template.
220                        self.write_args(
221                            &self.cmd.get_non_positionals().collect::<Vec<_>>(),
222                            "options",
223                            option_sort_key,
224                        );
225                    }
226                    "positionals" => {
227                        self.write_args(
228                            &self.cmd.get_positionals().collect::<Vec<_>>(),
229                            "positionals",
230                            positional_sort_key,
231                        );
232                    }
233                    "subcommands" => {
234                        self.write_subcommands(self.cmd);
235                    }
236                    "tab" => {
237                        self.writer.push_str(TAB);
238                    }
239                    "after-help" => {
240                        self.write_after_help();
241                    }
242                    "before-help" => {
243                        self.write_before_help();
244                    }
245                    _ => {
246                        let _ = write!(self.writer, "{{{tag}}}");
247                    }
248                }
249                self.writer.push_str(rest);
250            }
251        }
252    }
253}
254
255/// Basic template methods
256impl HelpTemplate<'_, '_> {
257    /// Writes binary name of a Parser Object to the wrapped stream.
258    fn write_display_name(&mut self) {
259        debug!("HelpTemplate::write_display_name");
260
261        let display_name = wrap(
262            &self
263                .cmd
264                .get_display_name()
265                .unwrap_or_else(|| self.cmd.get_name())
266                .replace("{n}", "\n"),
267            self.term_w,
268        );
269        self.writer.push_string(display_name);
270    }
271
272    /// Writes binary name of a Parser Object to the wrapped stream.
273    #[cfg(not(feature = "unstable-v5"))]
274    fn write_bin_name(&mut self) {
275        debug!("HelpTemplate::write_bin_name");
276
277        let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
278            if bn.contains(' ') {
279                // In case we're dealing with subcommands i.e. git mv is translated to git-mv
280                bn.replace(' ', "-")
281            } else {
282                wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
283            }
284        } else {
285            wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
286        };
287        self.writer.push_string(bin_name);
288    }
289
290    fn write_version(&mut self) {
291        let version = self
292            .cmd
293            .get_version()
294            .or_else(|| self.cmd.get_long_version());
295        if let Some(output) = version {
296            self.writer.push_string(wrap(output, self.term_w));
297        }
298    }
299
300    fn write_author(&mut self, before_new_line: bool, after_new_line: bool) {
301        if let Some(author) = self.cmd.get_author() {
302            if before_new_line {
303                self.writer.push_str("\n");
304            }
305            self.writer.push_string(wrap(author, self.term_w));
306            if after_new_line {
307                self.writer.push_str("\n");
308            }
309        }
310    }
311
312    fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
313        let about = if self.use_long {
314            self.cmd.get_long_about().or_else(|| self.cmd.get_about())
315        } else {
316            self.cmd.get_about()
317        };
318        if let Some(output) = about {
319            if before_new_line {
320                self.writer.push_str("\n");
321            }
322            let mut output = output.clone();
323            output.replace_newline_var();
324            output.wrap(self.term_w);
325            self.writer.push_styled(&output);
326            if after_new_line {
327                self.writer.push_str("\n");
328            }
329        }
330    }
331
332    fn write_before_help(&mut self) {
333        debug!("HelpTemplate::write_before_help");
334        let before_help = if self.use_long {
335            self.cmd
336                .get_before_long_help()
337                .or_else(|| self.cmd.get_before_help())
338        } else {
339            self.cmd.get_before_help()
340        };
341        if let Some(output) = before_help {
342            let mut output = output.clone();
343            output.replace_newline_var();
344            output.wrap(self.term_w);
345            self.writer.push_styled(&output);
346            self.writer.push_str("\n\n");
347        }
348    }
349
350    fn write_after_help(&mut self) {
351        debug!("HelpTemplate::write_after_help");
352        let after_help = if self.use_long {
353            self.cmd
354                .get_after_long_help()
355                .or_else(|| self.cmd.get_after_help())
356        } else {
357            self.cmd.get_after_help()
358        };
359        if let Some(output) = after_help {
360            self.writer.push_str("\n\n");
361            let mut output = output.clone();
362            output.replace_newline_var();
363            output.wrap(self.term_w);
364            self.writer.push_styled(&output);
365        }
366    }
367}
368
369/// Arg handling
370impl HelpTemplate<'_, '_> {
371    /// Writes help for all arguments (options, flags, args, subcommands)
372    /// including titles of a Parser Object to the wrapped stream.
373    pub(crate) fn write_all_args(&mut self) {
374        debug!("HelpTemplate::write_all_args");
375        use std::fmt::Write as _;
376        let header = &self.styles.get_header();
377
378        let pos = self
379            .cmd
380            .get_positionals()
381            .filter(|a| a.get_help_heading().is_none())
382            .filter(|arg| should_show_arg(self.use_long, arg))
383            .collect::<Vec<_>>();
384        let non_pos = self
385            .cmd
386            .get_non_positionals()
387            .filter(|a| a.get_help_heading().is_none())
388            .filter(|arg| should_show_arg(self.use_long, arg))
389            .collect::<Vec<_>>();
390        let subcmds = self.cmd.has_visible_subcommands();
391
392        let custom_headings = self
393            .cmd
394            .get_arguments()
395            .filter_map(|arg| arg.get_help_heading())
396            .collect::<FlatSet<_>>();
397
398        let flatten = self.cmd.is_flatten_help_set();
399
400        let mut first = true;
401
402        if subcmds && !flatten {
403            if !first {
404                self.writer.push_str("\n\n");
405            }
406            first = false;
407            let default_help_heading = Str::from("Commands");
408            let help_heading = self
409                .cmd
410                .get_subcommand_help_heading()
411                .unwrap_or(&default_help_heading);
412            let _ = write!(self.writer, "{header}{help_heading}:{header:#}\n",);
413
414            self.write_subcommands(self.cmd);
415        }
416
417        if !pos.is_empty() {
418            if !first {
419                self.writer.push_str("\n\n");
420            }
421            first = false;
422            // Write positional args if any
423            let help_heading = "Arguments";
424            let _ = write!(self.writer, "{header}{help_heading}:{header:#}\n",);
425            self.write_args(&pos, "Arguments", positional_sort_key);
426        }
427
428        if !non_pos.is_empty() {
429            if !first {
430                self.writer.push_str("\n\n");
431            }
432            first = false;
433            let help_heading = "Options";
434            let _ = write!(self.writer, "{header}{help_heading}:{header:#}\n",);
435            self.write_args(&non_pos, "Options", option_sort_key);
436        }
437        if !custom_headings.is_empty() {
438            for heading in custom_headings {
439                let args = self
440                    .cmd
441                    .get_arguments()
442                    .filter(|a| {
443                        if let Some(help_heading) = a.get_help_heading() {
444                            return help_heading == heading;
445                        }
446                        false
447                    })
448                    .filter(|arg| should_show_arg(self.use_long, arg))
449                    .collect::<Vec<_>>();
450
451                if !args.is_empty() {
452                    if !first {
453                        self.writer.push_str("\n\n");
454                    }
455                    first = false;
456                    let _ = write!(self.writer, "{header}{heading}:{header:#}\n",);
457                    self.write_args(&args, heading, option_sort_key);
458                }
459            }
460        }
461        if subcmds && flatten {
462            let mut cmd = self.cmd.clone();
463            cmd.build();
464            self.write_flat_subcommands(&cmd, &mut first);
465        }
466    }
467
468    /// Sorts arguments by length and display order and write their help to the wrapped stream.
469    fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
470        debug!("HelpTemplate::write_args {_category}");
471        // The shortest an arg can legally be is 2 (i.e. '-x')
472        let mut longest = 2;
473        let mut ord_v = BTreeMap::new();
474
475        // Determine the longest
476        for &arg in args.iter().filter(|arg| {
477            // If it's NextLineHelp we don't care to compute how long it is because it may be
478            // NextLineHelp on purpose simply *because* it's so long and would throw off all other
479            // args alignment
480            should_show_arg(self.use_long, arg)
481        }) {
482            let width = display_width(&arg.to_string());
483            let actual_width = if arg.get_long().is_some() {
484                width + SHORT_SIZE
485            } else {
486                width
487            };
488            longest = longest.max(actual_width);
489            debug!(
490                "HelpTemplate::write_args: arg={:?} longest={}",
491                arg.get_id(),
492                longest
493            );
494
495            let key = (sort_key)(arg);
496            ord_v.insert(key, arg);
497        }
498
499        let next_line_help = self.will_args_wrap(args, longest);
500
501        for (i, (_, arg)) in ord_v.iter().enumerate() {
502            if i != 0 {
503                self.writer.push_str("\n");
504                if next_line_help && self.use_long {
505                    self.writer.push_str("\n");
506                }
507            }
508            self.write_arg(arg, next_line_help, longest);
509        }
510    }
511
512    /// Writes help for an argument to the wrapped stream.
513    fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
514        let spec_vals = &self.spec_vals(arg);
515
516        self.writer.push_str(TAB);
517        self.short(arg);
518        self.long(arg);
519        self.writer
520            .push_styled(&arg.stylize_arg_suffix(self.styles, None));
521        self.align_to_about(arg, next_line_help, longest);
522
523        let about = if self.use_long {
524            arg.get_long_help()
525                .or_else(|| arg.get_help())
526                .unwrap_or_default()
527        } else {
528            arg.get_help()
529                .or_else(|| arg.get_long_help())
530                .unwrap_or_default()
531        };
532
533        self.help(Some(arg), about, spec_vals, next_line_help, longest);
534    }
535
536    /// Writes argument's short command to the wrapped stream.
537    fn short(&mut self, arg: &Arg) {
538        debug!("HelpTemplate::short");
539        use std::fmt::Write as _;
540        let literal = &self.styles.get_literal();
541
542        if let Some(s) = arg.get_short() {
543            let _ = write!(self.writer, "{literal}-{s}{literal:#}",);
544        } else if arg.get_long().is_some() {
545            self.writer.push_str("    ");
546        }
547    }
548
549    /// Writes argument's long command to the wrapped stream.
550    fn long(&mut self, arg: &Arg) {
551        debug!("HelpTemplate::long");
552        use std::fmt::Write as _;
553        let literal = &self.styles.get_literal();
554
555        if let Some(long) = arg.get_long() {
556            if arg.get_short().is_some() {
557                self.writer.push_str(", ");
558            }
559            let _ = write!(self.writer, "{literal}--{long}{literal:#}",);
560        }
561    }
562
563    /// Write alignment padding between arg's switches/values and its about message.
564    fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
565        debug!(
566            "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
567            arg.get_id(),
568            next_line_help,
569            longest
570        );
571        let padding = if self.use_long || next_line_help {
572            // long help prints messages on the next line so it doesn't need to align text
573            debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
574            0
575        } else if !arg.is_positional() {
576            let self_len = display_width(&arg.to_string()) + SHORT_SIZE;
577            // Since we're writing spaces from the tab point we first need to know if we
578            // had a long and short, or just short
579            let padding = if arg.get_long().is_some() {
580                // Only account 4 after the val
581                TAB_WIDTH
582            } else {
583                // Only account for ', --' + 4 after the val
584                TAB_WIDTH + 4
585            };
586            let spcs = longest + padding - self_len;
587            debug!(
588                "HelpTemplate::align_to_about: positional=false arg_len={self_len}, spaces={spcs}"
589            );
590
591            spcs
592        } else {
593            let self_len = display_width(&arg.to_string());
594            let padding = TAB_WIDTH;
595            let spcs = longest + padding - self_len;
596            debug!(
597                "HelpTemplate::align_to_about: positional=true arg_len={self_len}, spaces={spcs}",
598            );
599
600            spcs
601        };
602
603        self.write_padding(padding);
604    }
605
606    /// Writes argument's help to the wrapped stream.
607    fn help(
608        &mut self,
609        arg: Option<&Arg>,
610        about: &StyledStr,
611        spec_vals: &str,
612        next_line_help: bool,
613        longest: usize,
614    ) {
615        debug!("HelpTemplate::help");
616        use std::fmt::Write as _;
617        let literal = &self.styles.get_literal();
618
619        // Is help on next line, if so then indent
620        if next_line_help {
621            debug!("HelpTemplate::help: Next Line...{next_line_help:?}");
622            self.writer.push_str("\n");
623            self.writer.push_str(TAB);
624            self.writer.push_str(NEXT_LINE_INDENT);
625        }
626
627        let spaces = if next_line_help {
628            TAB.len() + NEXT_LINE_INDENT.len()
629        } else {
630            longest + TAB_WIDTH * 2
631        };
632        let trailing_indent = spaces; // Don't indent any further than the first line is indented
633        let trailing_indent = self.get_spaces(trailing_indent);
634
635        let mut help = about.clone();
636        let mut help_is_empty = help.is_empty();
637        help.replace_newline_var();
638
639        let next_line_specs = self.use_long && arg.is_some();
640        if !spec_vals.is_empty() && !next_line_specs {
641            if !help_is_empty {
642                let sep = " ";
643                help.push_str(sep);
644            }
645            help.push_str(spec_vals);
646            help_is_empty = help.is_empty();
647        }
648
649        let avail_chars = self.term_w.saturating_sub(spaces);
650        debug!(
651            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
652            spaces,
653            help.display_width(),
654            avail_chars
655        );
656        help.wrap(avail_chars);
657        help.indent("", &trailing_indent);
658        self.writer.push_styled(&help);
659
660        if let Some(arg) = arg {
661            if !arg.is_hide_possible_values_set() && self.use_long_pv(arg) {
662                const DASH_SPACE: usize = "- ".len();
663                let possible_vals = arg.get_possible_values();
664                if !possible_vals.is_empty() {
665                    debug!("HelpTemplate::help: Found possible vals...{possible_vals:?}");
666                    let longest = possible_vals
667                        .iter()
668                        .filter(|f| !f.is_hide_set())
669                        .map(|f| display_width(f.get_name()))
670                        .max()
671                        .expect("Only called with possible value");
672
673                    let spaces = spaces + TAB_WIDTH - DASH_SPACE;
674                    let trailing_indent = spaces + DASH_SPACE;
675                    let trailing_indent = self.get_spaces(trailing_indent);
676
677                    if !help_is_empty {
678                        let _ = write!(self.writer, "\n\n{:spaces$}", "");
679                    }
680                    self.writer.push_str("Possible values:");
681                    for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
682                        let name = pv.get_name();
683
684                        let mut descr = StyledStr::new();
685                        let _ = write!(&mut descr, "{literal}{name}{literal:#}",);
686                        if let Some(help) = pv.get_help() {
687                            debug!("HelpTemplate::help: Possible Value help");
688                            // To align help messages
689                            let padding = longest - display_width(name);
690                            let _ = write!(&mut descr, ": {:padding$}", "");
691                            descr.push_styled(help);
692                        }
693
694                        let avail_chars = if self.term_w > trailing_indent.len() {
695                            self.term_w - trailing_indent.len()
696                        } else {
697                            usize::MAX
698                        };
699                        descr.replace_newline_var();
700                        descr.wrap(avail_chars);
701                        descr.indent("", &trailing_indent);
702
703                        let _ = write!(self.writer, "\n{:spaces$}- ", "",);
704                        self.writer.push_styled(&descr);
705                    }
706                }
707            }
708        }
709
710        if !spec_vals.is_empty() && next_line_specs {
711            let mut help = StyledStr::new();
712            if !help_is_empty {
713                let sep = "\n\n";
714                help.push_str(sep);
715            }
716            help.push_str(spec_vals);
717
718            help.wrap(avail_chars);
719            help.indent("", &trailing_indent);
720            self.writer.push_styled(&help);
721        }
722    }
723
724    /// Will use next line help on writing args.
725    fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
726        args.iter()
727            .filter(|arg| should_show_arg(self.use_long, arg))
728            .any(|arg| {
729                let spec_vals = &self.spec_vals(arg);
730                self.arg_next_line_help(arg, spec_vals, longest)
731            })
732    }
733
734    fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
735        if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
736            // setting_next_line
737            true
738        } else {
739            // force_next_line
740            let h = arg
741                .get_help()
742                .or_else(|| arg.get_long_help())
743                .unwrap_or_default();
744            let h_w = h.display_width() + display_width(spec_vals);
745            let taken = longest + TAB_WIDTH * 2;
746            self.term_w >= taken
747                && (taken as f32 / self.term_w as f32) > 0.40
748                && h_w > (self.term_w - taken)
749        }
750    }
751
752    fn spec_vals(&self, a: &Arg) -> String {
753        debug!("HelpTemplate::spec_vals: a={a}");
754        let ctx = &self.styles.get_context();
755        let ctx_val = &self.styles.get_context_value();
756        let val_sep = format!("{ctx}, {ctx:#}"); // context values styled separator
757
758        let mut spec_vals = Vec::new();
759        #[cfg(feature = "env")]
760        if let Some(ref env) = a.env {
761            if !a.is_hide_env_set() {
762                debug!(
763                    "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
764                    env.0, env.1
765                );
766                let env_val = if !a.is_hide_env_values_set() {
767                    format!(
768                        "={}",
769                        env.1
770                            .as_ref()
771                            .map(|s| s.to_string_lossy())
772                            .unwrap_or_default()
773                    )
774                } else {
775                    Default::default()
776                };
777                let env_info = format!(
778                    "{ctx}[env: {ctx:#}{ctx_val}{}{}{ctx_val:#}{ctx}]{ctx:#}",
779                    env.0.to_string_lossy(),
780                    env_val
781                );
782                spec_vals.push(env_info);
783            }
784        }
785        if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
786            debug!(
787                "HelpTemplate::spec_vals: Found default value...[{:?}]",
788                a.default_vals
789            );
790
791            let dvs = a
792                .default_vals
793                .iter()
794                .map(|dv| dv.to_string_lossy())
795                .map(|dv| {
796                    if dv.contains(char::is_whitespace) {
797                        Cow::from(format!("{dv:?}"))
798                    } else {
799                        dv
800                    }
801                })
802                .collect::<Vec<_>>()
803                .join(" ");
804
805            spec_vals.push(format!(
806                "{ctx}[default: {ctx:#}{ctx_val}{dvs}{ctx_val:#}{ctx}]{ctx:#}"
807            ));
808        }
809
810        let mut als = Vec::new();
811
812        let short_als = a
813            .short_aliases
814            .iter()
815            .filter(|&als| als.1) // visible
816            .map(|als| format!("{ctx_val}-{}{ctx_val:#}", als.0)); // name
817        debug!(
818            "HelpTemplate::spec_vals: Found short aliases...{:?}",
819            a.short_aliases
820        );
821        als.extend(short_als);
822
823        let long_als = a
824            .aliases
825            .iter()
826            .filter(|&als| als.1) // visible
827            .map(|als| format!("{ctx_val}--{}{ctx_val:#}", als.0)); // name
828        debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
829        als.extend(long_als);
830
831        if !als.is_empty() {
832            let als = als.join(&val_sep);
833            spec_vals.push(format!("{ctx}[aliases: {ctx:#}{als}{ctx}]{ctx:#}"));
834        }
835
836        if !a.is_hide_possible_values_set() && !self.use_long_pv(a) {
837            let possible_vals = a.get_possible_values();
838            if !possible_vals.is_empty() {
839                debug!("HelpTemplate::spec_vals: Found possible vals...{possible_vals:?}");
840
841                let pvs = possible_vals
842                    .iter()
843                    .filter_map(PossibleValue::get_visible_quoted_name)
844                    .map(|pv| format!("{ctx_val}{pv}{ctx_val:#}"))
845                    .collect::<Vec<_>>()
846                    .join(&val_sep);
847
848                spec_vals.push(format!("{ctx}[possible values: {ctx:#}{pvs}{ctx}]{ctx:#}"));
849            }
850        }
851        let connector = if self.use_long { "\n" } else { " " };
852        spec_vals.join(connector)
853    }
854
855    fn get_spaces(&self, n: usize) -> String {
856        " ".repeat(n)
857    }
858
859    fn write_padding(&mut self, amount: usize) {
860        use std::fmt::Write as _;
861        let _ = write!(self.writer, "{:amount$}", "");
862    }
863
864    fn use_long_pv(&self, arg: &Arg) -> bool {
865        self.use_long
866            && arg
867                .get_possible_values()
868                .iter()
869                .any(PossibleValue::should_show_help)
870    }
871}
872
873/// Subcommand handling
874impl HelpTemplate<'_, '_> {
875    /// Writes help for subcommands of a Parser Object to the wrapped stream.
876    fn write_flat_subcommands(&mut self, cmd: &Command, first: &mut bool) {
877        debug!(
878            "HelpTemplate::write_flat_subcommands, cmd={}, first={}",
879            cmd.get_name(),
880            *first
881        );
882        use std::fmt::Write as _;
883        let header = &self.styles.get_header();
884
885        let mut ord_v = BTreeMap::new();
886        for subcommand in cmd
887            .get_subcommands()
888            .filter(|subcommand| should_show_subcommand(subcommand))
889        {
890            ord_v.insert(
891                (subcommand.get_display_order(), subcommand.get_name()),
892                subcommand,
893            );
894        }
895        for (_, subcommand) in ord_v {
896            if !*first {
897                self.writer.push_str("\n\n");
898            }
899            *first = false;
900
901            let heading = subcommand.get_usage_name_fallback();
902            let about = subcommand
903                .get_about()
904                .or_else(|| subcommand.get_long_about())
905                .unwrap_or_default();
906
907            let _ = write!(self.writer, "{header}{heading}:{header:#}",);
908            if !about.is_empty() {
909                let _ = write!(self.writer, "\n{about}",);
910            }
911
912            let args = subcommand
913                .get_arguments()
914                .filter(|arg| should_show_arg(self.use_long, arg) && !arg.is_global_set())
915                .collect::<Vec<_>>();
916            if !args.is_empty() {
917                self.writer.push_str("\n");
918            }
919
920            let mut sub_help = HelpTemplate {
921                writer: self.writer,
922                cmd: subcommand,
923                styles: self.styles,
924                usage: self.usage,
925                next_line_help: self.next_line_help,
926                term_w: self.term_w,
927                use_long: self.use_long,
928            };
929            sub_help.write_args(&args, heading, option_sort_key);
930            if subcommand.is_flatten_help_set() {
931                sub_help.write_flat_subcommands(subcommand, first);
932            }
933        }
934    }
935
936    /// Writes help for subcommands of a Parser Object to the wrapped stream.
937    fn write_subcommands(&mut self, cmd: &Command) {
938        debug!("HelpTemplate::write_subcommands");
939        use std::fmt::Write as _;
940        let literal = &self.styles.get_literal();
941
942        // The shortest an arg can legally be is 2 (i.e. '-x')
943        let mut longest = 2;
944        let mut ord_v = BTreeMap::new();
945        for subcommand in cmd
946            .get_subcommands()
947            .filter(|subcommand| should_show_subcommand(subcommand))
948        {
949            let mut styled = StyledStr::new();
950            let name = subcommand.get_name();
951            let _ = write!(styled, "{literal}{name}{literal:#}",);
952            if let Some(short) = subcommand.get_short_flag() {
953                let _ = write!(styled, ", {literal}-{short}{literal:#}",);
954            }
955            if let Some(long) = subcommand.get_long_flag() {
956                let _ = write!(styled, ", {literal}--{long}{literal:#}",);
957            }
958            longest = longest.max(styled.display_width());
959            ord_v.insert((subcommand.get_display_order(), styled), subcommand);
960        }
961
962        debug!("HelpTemplate::write_subcommands longest = {longest}");
963
964        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
965
966        for (i, (sc_str, sc)) in ord_v.into_iter().enumerate() {
967            if 0 < i {
968                self.writer.push_str("\n");
969            }
970            self.write_subcommand(sc_str.1, sc, next_line_help, longest);
971        }
972    }
973
974    /// Will use next line help on writing subcommands.
975    fn will_subcommands_wrap<'a>(
976        &self,
977        subcommands: impl IntoIterator<Item = &'a Command>,
978        longest: usize,
979    ) -> bool {
980        subcommands
981            .into_iter()
982            .filter(|&subcommand| should_show_subcommand(subcommand))
983            .any(|subcommand| {
984                let spec_vals = &self.sc_spec_vals(subcommand);
985                self.subcommand_next_line_help(subcommand, spec_vals, longest)
986            })
987    }
988
989    fn write_subcommand(
990        &mut self,
991        sc_str: StyledStr,
992        cmd: &Command,
993        next_line_help: bool,
994        longest: usize,
995    ) {
996        debug!("HelpTemplate::write_subcommand");
997
998        let spec_vals = &self.sc_spec_vals(cmd);
999
1000        let about = cmd
1001            .get_about()
1002            .or_else(|| cmd.get_long_about())
1003            .unwrap_or_default();
1004
1005        self.subcmd(sc_str, next_line_help, longest);
1006        self.help(None, about, spec_vals, next_line_help, longest);
1007    }
1008
1009    fn sc_spec_vals(&self, a: &Command) -> String {
1010        debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
1011        let ctx = &self.styles.get_context();
1012        let ctx_val = &self.styles.get_context_value();
1013        let val_sep = format!("{ctx}, {ctx:#}"); // context values styled separator
1014        let mut spec_vals = vec![];
1015
1016        let mut short_als = a
1017            .get_visible_short_flag_aliases()
1018            .map(|s| format!("{ctx_val}-{s}{ctx_val:#}"))
1019            .collect::<Vec<_>>();
1020        let long_als = a
1021            .get_visible_long_flag_aliases()
1022            .map(|s| format!("{ctx_val}--{s}{ctx_val:#}"));
1023        short_als.extend(long_als);
1024        let als = a
1025            .get_visible_aliases()
1026            .map(|s| format!("{ctx_val}{s}{ctx_val:#}"));
1027        short_als.extend(als);
1028        let all_als = short_als.join(&val_sep);
1029        if !all_als.is_empty() {
1030            debug!(
1031                "HelpTemplate::spec_vals: Found aliases...{:?}",
1032                a.get_all_aliases().collect::<Vec<_>>()
1033            );
1034            debug!(
1035                "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
1036                a.get_all_short_flag_aliases().collect::<Vec<_>>()
1037            );
1038            debug!(
1039                "HelpTemplate::spec_vals: Found long flag aliases...{:?}",
1040                a.get_all_long_flag_aliases().collect::<Vec<_>>()
1041            );
1042            spec_vals.push(format!("{ctx}[aliases: {ctx:#}{all_als}{ctx}]{ctx:#}"));
1043        }
1044
1045        spec_vals.join(" ")
1046    }
1047
1048    fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
1049        // Ignore `self.use_long` since subcommands are only shown as short help
1050        if self.next_line_help {
1051            // setting_next_line
1052            true
1053        } else {
1054            // force_next_line
1055            let h = cmd
1056                .get_about()
1057                .or_else(|| cmd.get_long_about())
1058                .unwrap_or_default();
1059            let h_w = h.display_width() + display_width(spec_vals);
1060            let taken = longest + TAB_WIDTH * 2;
1061            self.term_w >= taken
1062                && (taken as f32 / self.term_w as f32) > 0.40
1063                && h_w > (self.term_w - taken)
1064        }
1065    }
1066
1067    /// Writes subcommand to the wrapped stream.
1068    fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) {
1069        self.writer.push_str(TAB);
1070        self.writer.push_styled(&sc_str);
1071        if !next_line_help {
1072            let width = sc_str.display_width();
1073            let padding = longest + TAB_WIDTH - width;
1074            self.write_padding(padding);
1075        }
1076    }
1077}
1078
1079const NEXT_LINE_INDENT: &str = "        ";
1080
1081type ArgSortKey = fn(arg: &Arg) -> (usize, String);
1082
1083fn positional_sort_key(arg: &Arg) -> (usize, String) {
1084    (arg.get_index().unwrap_or(0), String::new())
1085}
1086
1087fn option_sort_key(arg: &Arg) -> (usize, String) {
1088    // Formatting key like this to ensure that:
1089    // 1. Argument has long flags are printed just after short flags.
1090    // 2. For two args both have short flags like `-c` and `-C`, the
1091    //    `-C` arg is printed just after the `-c` arg
1092    // 3. For args without short or long flag, print them at last(sorted
1093    //    by arg name).
1094    // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
1095
1096    let key = if let Some(x) = arg.get_short() {
1097        let mut s = x.to_ascii_lowercase().to_string();
1098        s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
1099        s
1100    } else if let Some(x) = arg.get_long() {
1101        x.to_string()
1102    } else {
1103        let mut s = '{'.to_string();
1104        s.push_str(arg.get_id().as_str());
1105        s
1106    };
1107    (arg.get_display_order(), key)
1108}
1109
1110pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) {
1111    #[cfg(not(feature = "wrap_help"))]
1112    return (None, None);
1113
1114    #[cfg(feature = "wrap_help")]
1115    terminal_size::terminal_size()
1116        .map(|(w, h)| (Some(w.0.into()), Some(h.0.into())))
1117        .unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES")))
1118}
1119
1120#[cfg(feature = "wrap_help")]
1121fn parse_env(var: &str) -> Option<usize> {
1122    some!(some!(std::env::var_os(var)).to_str())
1123        .parse::<usize>()
1124        .ok()
1125}
1126
1127fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
1128    debug!(
1129        "should_show_arg: use_long={:?}, arg={}",
1130        use_long,
1131        arg.get_id()
1132    );
1133    if arg.is_hide_set() {
1134        return false;
1135    }
1136    (!arg.is_hide_long_help_set() && use_long)
1137        || (!arg.is_hide_short_help_set() && !use_long)
1138        || arg.is_next_line_help_set()
1139}
1140
1141fn should_show_subcommand(subcommand: &Command) -> bool {
1142    !subcommand.is_hide_set()
1143}
1144
1145#[cfg(test)]
1146mod test {
1147    #[test]
1148    #[cfg(feature = "wrap_help")]
1149    fn wrap_help_last_word() {
1150        use super::*;
1151
1152        let help = String::from("foo bar baz");
1153        assert_eq!(wrap(&help, 5), "foo\nbar\nbaz");
1154    }
1155
1156    #[test]
1157    #[cfg(feature = "unicode")]
1158    fn display_width_handles_non_ascii() {
1159        use super::*;
1160
1161        // Popular Danish tongue-twister, the name of a fruit dessert.
1162        let text = "rødgrød med fløde";
1163        assert_eq!(display_width(text), 17);
1164        // Note that the string width is smaller than the string
1165        // length. This is due to the precomposed non-ASCII letters:
1166        assert_eq!(text.len(), 20);
1167    }
1168
1169    #[test]
1170    #[cfg(feature = "unicode")]
1171    fn display_width_handles_emojis() {
1172        use super::*;
1173
1174        let text = "😂";
1175        // There is a single `char`...
1176        assert_eq!(text.chars().count(), 1);
1177        // but it is double-width:
1178        assert_eq!(display_width(text), 2);
1179        // This is much less than the byte length:
1180        assert_eq!(text.len(), 4);
1181    }
1182}