Skip to content

Customizing usage and help

gershnik edited this page Apr 6, 2022 · 5 revisions

Elsewhere on this wiki the usage and help text for a parser are obtained via parser's formatUsage and formatHelp methods. These are convenience methods, however, that delegate their functionality to [W]HelpFormatter class. This class in turn delegates printing of individual options and positional arguments data to the Option and Positional classes.

Using HelpFormatter directly allows you to customize its output. You can also re-use some of HelpFormatter, Option and Positional formatting functionality in producing output of your own.

Using HelpFormatter

To construct HelpFormatter you need to give it a parser (held by reference so it should remain alive while HelpFormatter is alive), a name of the program (used in producing usage mstring) and an optional instance of HelpFormatter::Layout class that is described later on this page.

Parser parser;
...
//use default layout
HelpFormatter formatter(parser, argc ? argv[0] : "prog");
//use default layout explicitly
HelpFormatter formatter1(parser, argc ? argv[0] : "prog", HelpFormatter::defaultLayout);

Methods

Public methods of HelpFormatter are described below:

string formatSyntax(const optional<string> & subCommand = nullopt)
Produces syntax string. This is the part of usage string following the program name. If the argument is nullopt produces syntax for the main parser. Otherwise, (if the parser has a subcommand registered via addSubcommand) produces syntax for the specified subcommand.
string formatUsage(const optional<string> & subCommand = nullopt)
Produces usage string. Usage string consists of "Usage: <program name> <syntax>". If the argument is nullopt produces usage for the main parser. Otherwise, (if the parser has a subcommand registered via addSubcommand) produces usage for the specified subcommand.
string formatHelp(const optional<string> & subCommand = nullopt)
Produces help content. Unlike Parsers method formatHelp() it does not include the usage string. If the argument is nullopt produces help for the main parser. Otherwise, (if the parser has a subcommand registered via addSubcommand) produces help for the specified subcommand.
HelpContent calculateHelpContent(bool forSubCommand)
string formatItemHelp(string_view name, string_view description, unsigned maxNameLen)

Layout

Formatting options and positionals

TBD