1#![allow(clippy::write_with_newline)]
5
6use std::borrow::Cow;
8use std::cmp;
9use std::collections::BTreeMap;
10
11use 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
24pub(crate) struct AutoHelp<'cmd, 'writer> {
26 template: HelpTemplate<'cmd, 'writer>,
27}
28
29impl<'cmd, 'writer> AutoHelp<'cmd, 'writer> {
31 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; pub(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
92impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
94 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 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 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
255impl HelpTemplate<'_, '_> {
257 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 #[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 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
369impl HelpTemplate<'_, '_> {
371 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 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 fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
470 debug!("HelpTemplate::write_args {_category}");
471 let mut longest = 2;
473 let mut longest_without_short = 2;
474 let mut has_short = false;
475 let mut ord_v = BTreeMap::new();
476
477 for &arg in args.iter().filter(|arg| {
479 should_show_arg(self.use_long, arg)
483 }) {
484 if !has_short && arg.get_short().is_some() {
485 has_short = true;
486 }
487
488 if longest_filter(arg) {
489 let width = display_width(&arg.to_string());
490 let actual_width = if arg.is_positional() {
491 width
492 } else {
493 width + SHORT_SIZE
494 };
495 longest = longest.max(actual_width);
496 if !has_short {
497 longest_without_short = longest_without_short.max(width);
498 }
499 debug!(
500 "HelpTemplate::write_args: arg={:?} longest={}",
501 arg.get_id(),
502 longest
503 );
504 }
505
506 let key = (sort_key)(arg);
507 ord_v.insert(key, arg);
508 }
509
510 if !has_short {
511 longest = longest_without_short;
512 }
513
514 let next_line_help = self.will_args_wrap(args, longest);
515
516 for (i, (_, arg)) in ord_v.iter().enumerate() {
517 if i != 0 {
518 self.writer.push_str("\n");
519 if next_line_help && self.use_long {
520 self.writer.push_str("\n");
521 }
522 }
523 self.write_arg(arg, next_line_help, longest, has_short);
524 }
525 }
526
527 fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize, has_short: bool) {
529 let spec_vals = &self.spec_vals(arg);
530
531 self.writer.push_str(TAB);
532 if has_short {
533 self.short(arg);
534 }
535 self.long(arg);
536 self.writer
537 .push_styled(&arg.stylize_arg_suffix(self.styles, None));
538 self.align_to_about(arg, next_line_help, longest, has_short);
539
540 let about = if self.use_long {
541 arg.get_long_help()
542 .or_else(|| arg.get_help())
543 .unwrap_or_default()
544 } else {
545 arg.get_help()
546 .or_else(|| arg.get_long_help())
547 .unwrap_or_default()
548 };
549
550 self.help(Some(arg), about, spec_vals, next_line_help, longest);
551 }
552
553 fn short(&mut self, arg: &Arg) {
555 debug!("HelpTemplate::short");
556 use std::fmt::Write as _;
557 let literal = &self.styles.get_literal();
558
559 if let Some(s) = arg.get_short() {
560 let _ = write!(self.writer, "{literal}-{s}{literal:#}",);
561 } else if arg.get_long().is_some() {
562 self.writer.push_str(" ");
563 }
564 }
565
566 fn long(&mut self, arg: &Arg) {
568 debug!("HelpTemplate::long");
569 use std::fmt::Write as _;
570 let literal = &self.styles.get_literal();
571
572 if let Some(long) = arg.get_long() {
573 if arg.get_short().is_some() {
574 self.writer.push_str(", ");
575 }
576 let _ = write!(self.writer, "{literal}--{long}{literal:#}",);
577 }
578 }
579
580 fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize, has_short: bool) {
582 debug!(
583 "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
584 arg.get_id(),
585 next_line_help,
586 longest
587 );
588 let padding = if self.use_long || next_line_help {
589 debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
591 0
592 } else if !arg.is_positional() {
593 let mut self_len = display_width(&arg.to_string());
594 if has_short {
595 self_len += SHORT_SIZE;
596 }
597 let padding = if arg.get_long().is_some() {
600 TAB_WIDTH
602 } else {
603 TAB_WIDTH + 4
605 };
606 let spcs = longest + padding - self_len;
607 debug!(
608 "HelpTemplate::align_to_about: positional=false arg_len={self_len}, spaces={spcs}"
609 );
610
611 spcs
612 } else {
613 let self_len = display_width(&arg.to_string());
614 let padding = TAB_WIDTH;
615 let spcs = longest + padding - self_len;
616 debug!(
617 "HelpTemplate::align_to_about: positional=true arg_len={self_len}, spaces={spcs}",
618 );
619
620 spcs
621 };
622
623 self.write_padding(padding);
624 }
625
626 fn help(
628 &mut self,
629 arg: Option<&Arg>,
630 about: &StyledStr,
631 spec_vals: &str,
632 next_line_help: bool,
633 longest: usize,
634 ) {
635 debug!("HelpTemplate::help");
636 use std::fmt::Write as _;
637 let literal = &self.styles.get_literal();
638
639 if next_line_help {
641 debug!("HelpTemplate::help: Next Line...{next_line_help:?}");
642 self.writer.push_str("\n");
643 self.writer.push_str(TAB);
644 self.writer.push_str(NEXT_LINE_INDENT);
645 }
646
647 let spaces = if next_line_help {
648 TAB.len() + NEXT_LINE_INDENT.len()
649 } else {
650 longest + TAB_WIDTH * 2
651 };
652 let trailing_indent = spaces; let trailing_indent = self.get_spaces(trailing_indent);
654
655 let mut help = about.clone();
656 help.replace_newline_var();
657 if !spec_vals.is_empty() {
658 if !help.is_empty() {
659 let sep = if self.use_long && arg.is_some() {
660 "\n\n"
661 } else {
662 " "
663 };
664 help.push_str(sep);
665 }
666 help.push_str(spec_vals);
667 }
668 let avail_chars = self.term_w.saturating_sub(spaces);
669 debug!(
670 "HelpTemplate::help: help_width={}, spaces={}, avail={}",
671 spaces,
672 help.display_width(),
673 avail_chars
674 );
675 help.wrap(avail_chars);
676 help.indent("", &trailing_indent);
677 let help_is_empty = help.is_empty();
678 self.writer.push_styled(&help);
679 if let Some(arg) = arg {
680 if !arg.is_hide_possible_values_set() && self.use_long_pv(arg) {
681 const DASH_SPACE: usize = "- ".len();
682 let possible_vals = arg.get_possible_values();
683 if !possible_vals.is_empty() {
684 debug!("HelpTemplate::help: Found possible vals...{possible_vals:?}");
685 let longest = possible_vals
686 .iter()
687 .filter(|f| !f.is_hide_set())
688 .map(|f| display_width(f.get_name()))
689 .max()
690 .expect("Only called with possible value");
691
692 let spaces = spaces + TAB_WIDTH - DASH_SPACE;
693 let trailing_indent = spaces + DASH_SPACE;
694 let trailing_indent = self.get_spaces(trailing_indent);
695
696 if !help_is_empty {
697 let _ = write!(self.writer, "\n\n{:spaces$}", "");
698 }
699 self.writer.push_str("Possible values:");
700 for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
701 let name = pv.get_name();
702
703 let mut descr = StyledStr::new();
704 let _ = write!(&mut descr, "{literal}{name}{literal:#}",);
705 if let Some(help) = pv.get_help() {
706 debug!("HelpTemplate::help: Possible Value help");
707 let padding = longest - display_width(name);
709 let _ = write!(&mut descr, ": {:padding$}", "");
710 descr.push_styled(help);
711 }
712
713 let avail_chars = if self.term_w > trailing_indent.len() {
714 self.term_w - trailing_indent.len()
715 } else {
716 usize::MAX
717 };
718 descr.replace_newline_var();
719 descr.wrap(avail_chars);
720 descr.indent("", &trailing_indent);
721
722 let _ = write!(self.writer, "\n{:spaces$}- ", "",);
723 self.writer.push_styled(&descr);
724 }
725 }
726 }
727 }
728 }
729
730 fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
732 args.iter()
733 .filter(|arg| should_show_arg(self.use_long, arg))
734 .any(|arg| {
735 let spec_vals = &self.spec_vals(arg);
736 self.arg_next_line_help(arg, spec_vals, longest)
737 })
738 }
739
740 fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
741 if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
742 true
744 } else {
745 let h = arg
747 .get_help()
748 .or_else(|| arg.get_long_help())
749 .unwrap_or_default();
750 let h_w = h.display_width() + display_width(spec_vals);
751 let taken = longest + TAB_WIDTH * 2;
752 self.term_w >= taken
753 && (taken as f32 / self.term_w as f32) > 0.40
754 && h_w > (self.term_w - taken)
755 }
756 }
757
758 fn spec_vals(&self, a: &Arg) -> String {
759 debug!("HelpTemplate::spec_vals: a={a}");
760 let mut spec_vals = Vec::new();
761 #[cfg(feature = "env")]
762 if let Some(ref env) = a.env {
763 if !a.is_hide_env_set() {
764 debug!(
765 "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
766 env.0, env.1
767 );
768 let env_val = if !a.is_hide_env_values_set() {
769 format!(
770 "={}",
771 env.1
772 .as_ref()
773 .map(|s| s.to_string_lossy())
774 .unwrap_or_default()
775 )
776 } else {
777 Default::default()
778 };
779 let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
780 spec_vals.push(env_info);
781 }
782 }
783 if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
784 debug!(
785 "HelpTemplate::spec_vals: Found default value...[{:?}]",
786 a.default_vals
787 );
788
789 let pvs = a
790 .default_vals
791 .iter()
792 .map(|pvs| pvs.to_string_lossy())
793 .map(|pvs| {
794 if pvs.contains(char::is_whitespace) {
795 Cow::from(format!("{pvs:?}"))
796 } else {
797 pvs
798 }
799 })
800 .collect::<Vec<_>>()
801 .join(" ");
802
803 spec_vals.push(format!("[default: {pvs}]"));
804 }
805
806 let als = a
807 .aliases
808 .iter()
809 .filter(|&als| als.1) .map(|als| als.0.as_str()) .collect::<Vec<_>>()
812 .join(", ");
813 if !als.is_empty() {
814 debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
815 spec_vals.push(format!("[aliases: {als}]"));
816 }
817
818 let als = a
819 .short_aliases
820 .iter()
821 .filter(|&als| als.1) .map(|&als| als.0.to_string()) .collect::<Vec<_>>()
824 .join(", ");
825 if !als.is_empty() {
826 debug!(
827 "HelpTemplate::spec_vals: Found short aliases...{:?}",
828 a.short_aliases
829 );
830 spec_vals.push(format!("[short aliases: {als}]"));
831 }
832
833 if !a.is_hide_possible_values_set() && !self.use_long_pv(a) {
834 let possible_vals = a.get_possible_values();
835 if !possible_vals.is_empty() {
836 debug!("HelpTemplate::spec_vals: Found possible vals...{possible_vals:?}");
837
838 let pvs = possible_vals
839 .iter()
840 .filter_map(PossibleValue::get_visible_quoted_name)
841 .collect::<Vec<_>>()
842 .join(", ");
843
844 spec_vals.push(format!("[possible values: {pvs}]"));
845 }
846 }
847 let connector = if self.use_long { "\n" } else { " " };
848 spec_vals.join(connector)
849 }
850
851 fn get_spaces(&self, n: usize) -> String {
852 " ".repeat(n)
853 }
854
855 fn write_padding(&mut self, amount: usize) {
856 use std::fmt::Write as _;
857 let _ = write!(self.writer, "{:amount$}", "");
858 }
859
860 fn use_long_pv(&self, arg: &Arg) -> bool {
861 self.use_long
862 && arg
863 .get_possible_values()
864 .iter()
865 .any(PossibleValue::should_show_help)
866 }
867}
868
869impl HelpTemplate<'_, '_> {
871 fn write_flat_subcommands(&mut self, cmd: &Command, first: &mut bool) {
873 debug!(
874 "HelpTemplate::write_flat_subcommands, cmd={}, first={}",
875 cmd.get_name(),
876 *first
877 );
878 use std::fmt::Write as _;
879 let header = &self.styles.get_header();
880
881 let mut ord_v = BTreeMap::new();
882 for subcommand in cmd
883 .get_subcommands()
884 .filter(|subcommand| should_show_subcommand(subcommand))
885 {
886 ord_v.insert(
887 (subcommand.get_display_order(), subcommand.get_name()),
888 subcommand,
889 );
890 }
891 for (_, subcommand) in ord_v {
892 if !*first {
893 self.writer.push_str("\n\n");
894 }
895 *first = false;
896
897 let heading = subcommand.get_usage_name_fallback();
898 let about = subcommand
899 .get_about()
900 .or_else(|| subcommand.get_long_about())
901 .unwrap_or_default();
902
903 let _ = write!(self.writer, "{header}{heading}:{header:#}",);
904 if !about.is_empty() {
905 let _ = write!(self.writer, "\n{about}",);
906 }
907
908 let args = subcommand
909 .get_arguments()
910 .filter(|arg| should_show_arg(self.use_long, arg) && !arg.is_global_set())
911 .collect::<Vec<_>>();
912 if !args.is_empty() {
913 self.writer.push_str("\n");
914 }
915
916 let mut sub_help = HelpTemplate {
917 writer: self.writer,
918 cmd: subcommand,
919 styles: self.styles,
920 usage: self.usage,
921 next_line_help: self.next_line_help,
922 term_w: self.term_w,
923 use_long: self.use_long,
924 };
925 sub_help.write_args(&args, heading, option_sort_key);
926 if subcommand.is_flatten_help_set() {
927 sub_help.write_flat_subcommands(subcommand, first);
928 }
929 }
930 }
931
932 fn write_subcommands(&mut self, cmd: &Command) {
934 debug!("HelpTemplate::write_subcommands");
935 use std::fmt::Write as _;
936 let literal = &self.styles.get_literal();
937
938 let mut longest = 2;
940 let mut ord_v = BTreeMap::new();
941 for subcommand in cmd
942 .get_subcommands()
943 .filter(|subcommand| should_show_subcommand(subcommand))
944 {
945 let mut styled = StyledStr::new();
946 let name = subcommand.get_name();
947 let _ = write!(styled, "{literal}{name}{literal:#}",);
948 if let Some(short) = subcommand.get_short_flag() {
949 let _ = write!(styled, ", {literal}-{short}{literal:#}",);
950 }
951 if let Some(long) = subcommand.get_long_flag() {
952 let _ = write!(styled, ", {literal}--{long}{literal:#}",);
953 }
954 longest = longest.max(styled.display_width());
955 ord_v.insert((subcommand.get_display_order(), styled), subcommand);
956 }
957
958 debug!("HelpTemplate::write_subcommands longest = {longest}");
959
960 let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
961
962 for (i, (sc_str, sc)) in ord_v.into_iter().enumerate() {
963 if 0 < i {
964 self.writer.push_str("\n");
965 }
966 self.write_subcommand(sc_str.1, sc, next_line_help, longest);
967 }
968 }
969
970 fn will_subcommands_wrap<'a>(
972 &self,
973 subcommands: impl IntoIterator<Item = &'a Command>,
974 longest: usize,
975 ) -> bool {
976 subcommands
977 .into_iter()
978 .filter(|&subcommand| should_show_subcommand(subcommand))
979 .any(|subcommand| {
980 let spec_vals = &self.sc_spec_vals(subcommand);
981 self.subcommand_next_line_help(subcommand, spec_vals, longest)
982 })
983 }
984
985 fn write_subcommand(
986 &mut self,
987 sc_str: StyledStr,
988 cmd: &Command,
989 next_line_help: bool,
990 longest: usize,
991 ) {
992 debug!("HelpTemplate::write_subcommand");
993
994 let spec_vals = &self.sc_spec_vals(cmd);
995
996 let about = cmd
997 .get_about()
998 .or_else(|| cmd.get_long_about())
999 .unwrap_or_default();
1000
1001 self.subcmd(sc_str, next_line_help, longest);
1002 self.help(None, about, spec_vals, next_line_help, longest);
1003 }
1004
1005 fn sc_spec_vals(&self, a: &Command) -> String {
1006 debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
1007 let mut spec_vals = vec![];
1008
1009 let mut short_als = a
1010 .get_visible_short_flag_aliases()
1011 .map(|a| format!("-{a}"))
1012 .collect::<Vec<_>>();
1013 let als = a.get_visible_aliases().map(|s| s.to_string());
1014 short_als.extend(als);
1015 let all_als = short_als.join(", ");
1016 if !all_als.is_empty() {
1017 debug!(
1018 "HelpTemplate::spec_vals: Found aliases...{:?}",
1019 a.get_all_aliases().collect::<Vec<_>>()
1020 );
1021 debug!(
1022 "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
1023 a.get_all_short_flag_aliases().collect::<Vec<_>>()
1024 );
1025 spec_vals.push(format!("[aliases: {all_als}]"));
1026 }
1027
1028 spec_vals.join(" ")
1029 }
1030
1031 fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
1032 if self.next_line_help {
1034 true
1036 } else {
1037 let h = cmd
1039 .get_about()
1040 .or_else(|| cmd.get_long_about())
1041 .unwrap_or_default();
1042 let h_w = h.display_width() + display_width(spec_vals);
1043 let taken = longest + TAB_WIDTH * 2;
1044 self.term_w >= taken
1045 && (taken as f32 / self.term_w as f32) > 0.40
1046 && h_w > (self.term_w - taken)
1047 }
1048 }
1049
1050 fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) {
1052 self.writer.push_str(TAB);
1053 self.writer.push_styled(&sc_str);
1054 if !next_line_help {
1055 let width = sc_str.display_width();
1056 let padding = longest + TAB_WIDTH - width;
1057 self.write_padding(padding);
1058 }
1059 }
1060}
1061
1062const NEXT_LINE_INDENT: &str = " ";
1063
1064type ArgSortKey = fn(arg: &Arg) -> (usize, String);
1065
1066fn positional_sort_key(arg: &Arg) -> (usize, String) {
1067 (arg.get_index().unwrap_or(0), String::new())
1068}
1069
1070fn option_sort_key(arg: &Arg) -> (usize, String) {
1071 let key = if let Some(x) = arg.get_short() {
1080 let mut s = x.to_ascii_lowercase().to_string();
1081 s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
1082 s
1083 } else if let Some(x) = arg.get_long() {
1084 x.to_string()
1085 } else {
1086 let mut s = '{'.to_string();
1087 s.push_str(arg.get_id().as_str());
1088 s
1089 };
1090 (arg.get_display_order(), key)
1091}
1092
1093pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) {
1094 #[cfg(not(feature = "wrap_help"))]
1095 return (None, None);
1096
1097 #[cfg(feature = "wrap_help")]
1098 terminal_size::terminal_size()
1099 .map(|(w, h)| (Some(w.0.into()), Some(h.0.into())))
1100 .unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES")))
1101}
1102
1103#[cfg(feature = "wrap_help")]
1104fn parse_env(var: &str) -> Option<usize> {
1105 some!(some!(std::env::var_os(var)).to_str())
1106 .parse::<usize>()
1107 .ok()
1108}
1109
1110fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
1111 debug!(
1112 "should_show_arg: use_long={:?}, arg={}",
1113 use_long,
1114 arg.get_id()
1115 );
1116 if arg.is_hide_set() {
1117 return false;
1118 }
1119 (!arg.is_hide_long_help_set() && use_long)
1120 || (!arg.is_hide_short_help_set() && !use_long)
1121 || arg.is_next_line_help_set()
1122}
1123
1124fn should_show_subcommand(subcommand: &Command) -> bool {
1125 !subcommand.is_hide_set()
1126}
1127
1128fn longest_filter(arg: &Arg) -> bool {
1129 arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none()
1130}
1131
1132#[cfg(test)]
1133mod test {
1134 #[test]
1135 #[cfg(feature = "wrap_help")]
1136 fn wrap_help_last_word() {
1137 use super::*;
1138
1139 let help = String::from("foo bar baz");
1140 assert_eq!(wrap(&help, 5), "foo\nbar\nbaz");
1141 }
1142
1143 #[test]
1144 #[cfg(feature = "unicode")]
1145 fn display_width_handles_non_ascii() {
1146 use super::*;
1147
1148 let text = "rødgrød med fløde";
1150 assert_eq!(display_width(text), 17);
1151 assert_eq!(text.len(), 20);
1154 }
1155
1156 #[test]
1157 #[cfg(feature = "unicode")]
1158 fn display_width_handles_emojis() {
1159 use super::*;
1160
1161 let text = "😂";
1162 assert_eq!(text.chars().count(), 1);
1164 assert_eq!(display_width(text), 2);
1166 assert_eq!(text.len(), 4);
1168 }
1169}