Ian Fiddes
Ian Fiddes

Reputation: 3011

How can I get clap to wrap long help messages?

Here is an example:

extern crate clap;
use clap::{Arg, App};

fn main() {
let args = App::new("test")
    .arg(Arg::with_name("scoring_method")
            .short("s")
            .long("scoring-method")
            .help("Very very very very very very long long long long long help help help help help message message message message message message message"))
    .get_matches();
}

Leads to the help text formatting like this:

console example

(pasting in code mode causes Stack Overflow to fix the formatting issue)

The exact string produced is:

'USAGE:\n    play [FLAGS]\n\nFLAGS:\n    -h, --help              Prints help information\n    -s, --scoring-method    Very very very very very very long long long long long help help help help help message\n                            message message message message message message\n    -V, --version           Prints version information'

Upvotes: 6

Views: 1782

Answers (3)

George
George

Reputation: 2821

Currently, clap auto-magically does wrap the help text output within the terminal width if the wrap_help feature is enabled as shown with the following snippet of Cargo.toml:

clap = {version = "4.0.18", features=["derive","wrap_help"]}

Upvotes: 4

Jack O'Connor
Jack O'Connor

Reputation: 10926

Today (Clap v4.0.26) you can enable the wrap_help feature. This takes a dependency on terminal_size internally.

Upvotes: 8

loganfsmyth
loganfsmyth

Reputation: 161597

Clap has a max_term_width that it uses to wrap the text that it outputs. As mentioned in that documentation, it defaults to 120 characters, which is why you see the text split eventually, but not where you'd hoped.

If you have a certain width that you'd like to set, you can use set_term_width with a specific value. Alternatively, you can use a crate like terminal_size to get the size of the current terminal, and use that to set the width for clap to use.

As a full example:

extern crate clap;
extern crate terminal_size;

use clap::{App, Arg};
use terminal_size::{terminal_size, Width};

fn main() {
    let args = App::new("test")
    .set_term_width(if let Some((Width(w), _)) = terminal_size() { w as usize } else { 120 })
    .arg(Arg::with_name("scoring_method")
      .short("s")
      .long("scoring-method")
      .help("Very very very very very very long long long long long help help help help help message message message message message message message"))
    .get_matches();
}

Upvotes: 5

Related Questions