CLI11
C++11 Command Line Interface Parser
Loading...
Searching...
No Matches
Formatter_inl.hpp
1// Copyright (c) 2017-2026, University of Cincinnati, developed by Henry Schreiner
2// under NSF AWARD 1414736 and by the respective contributors.
3// All rights reserved.
4//
5// SPDX-License-Identifier: BSD-3-Clause
6
7#pragma once
8
9// IWYU pragma: private, include "CLI/CLI.hpp"
10
11// This include is only needed for IDEs to discover symbols
12#include "../Formatter.hpp"
13
14// [CLI11:public_includes:set]
15#include <algorithm>
16#include <set>
17#include <string>
18#include <utility>
19#include <vector>
20// [CLI11:public_includes:end]
21
22namespace CLI {
23// [CLI11:formatter_inl_hpp:verbatim]
24CLI11_INLINE std::string
25Formatter::make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const {
26 std::stringstream out;
27
28 out << "\n" << group << ":\n";
29 for(const Option *opt : opts) {
30 out << make_option(opt, is_positional);
31 }
32
33 return out.str();
34}
35
36CLI11_INLINE std::string Formatter::make_positionals(const App *app) const {
37 std::vector<const Option *> opts =
38 app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
39
40 if(opts.empty())
41 return {};
42
43 return make_group(get_label("POSITIONALS"), true, opts);
44}
45
46CLI11_INLINE std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
47 std::stringstream out;
48 std::vector<std::string> groups = app->get_groups();
49
50 // Options
51 for(const std::string &group : groups) {
52 std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
53 return opt->get_group() == group // Must be in the right group
54 && opt->nonpositional() // Must not be a positional
55 && (mode != AppFormatMode::Sub // If mode is Sub, then
56 || (app->get_help_ptr() != opt // Ignore help pointer
57 && app->get_help_all_ptr() != opt)); // Ignore help all pointer
58 });
59 if(!group.empty() && !opts.empty()) {
60 out << make_group(group, false, opts);
61
62 // Removed double newline between groups for consistency of help text
63 // if(group != groups.back())
64 // out << "\n";
65 }
66 }
67
68 return out.str();
69}
70
71CLI11_INLINE std::string Formatter::make_description(const App *app) const {
72 std::string desc = app->get_description();
73 auto min_options = app->get_require_option_min();
74 auto max_options = app->get_require_option_max();
75
76 if(app->get_required()) {
77 desc += " " + get_label("REQUIRED") + " ";
78 }
79
80 if(min_options > 0) {
81 if(max_options == min_options) {
82 desc += " \n[Exactly " + std::to_string(min_options) + " of the following options are required]";
83 } else if(max_options > 0) {
84 desc += " \n[Between " + std::to_string(min_options) + " and " + std::to_string(max_options) +
85 " of the following options are required]";
86 } else {
87 desc += " \n[At least " + std::to_string(min_options) + " of the following options are required]";
88 }
89 } else if(max_options > 0) {
90 desc += " \n[At most " + std::to_string(max_options) + " of the following options are allowed]";
91 }
92
93 return (!desc.empty()) ? desc + "\n\n" : std::string{};
94}
95
96CLI11_INLINE std::string Formatter::make_usage(const App *app, std::string name) const {
97 std::string usage = app->get_usage();
98 if(!usage.empty()) {
99 return usage + "\n\n";
100 }
101
102 std::stringstream out;
103 out << '\n';
104
105 if(name.empty())
106 out << get_label("Usage") << ':';
107 else
108 out << name;
109
110 std::vector<std::string> groups = app->get_groups();
111
112 // Print an Options badge if any options exist
113 std::vector<const Option *> non_pos_options =
114 app->get_options([](const Option *opt) { return opt->nonpositional(); });
115 if(!non_pos_options.empty())
116 out << " [" << get_label("OPTIONS") << "]";
117
118 // Positionals need to be listed here
119 std::vector<const Option *> positionals = app->get_options([](const Option *opt) { return opt->get_positional(); });
120
121 // Print out positionals if any are left
122 if(!positionals.empty()) {
123 // Convert to help names
124 std::vector<std::string> positional_names;
125 positional_names.reserve(positionals.size());
126 for(const auto *opt : positionals) {
127 positional_names.push_back(make_option_usage(opt));
128 }
129
130 out << " " << detail::join(positional_names, " ");
131 }
132
133 // Add a marker if subcommands are expected or optional
134 if(!app->get_subcommands(
135 [](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
136 .empty()) {
137 out << ' ' << (app->get_require_subcommand_min() == 0 ? "[" : "")
138 << get_label(app->get_require_subcommand_max() == 1 ? "SUBCOMMAND" : "SUBCOMMANDS")
139 << (app->get_require_subcommand_min() == 0 ? "]" : "");
140 }
141
142 out << "\n\n";
143
144 return out.str();
145}
146
147CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
148 std::string footer = app->get_footer();
149 if(footer.empty()) {
150 return std::string{};
151 }
152 return '\n' + footer + '\n';
153}
154
155CLI11_INLINE std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
156 // This immediately forwards to the make_expanded method. This is done this way so that subcommands can
157 // have overridden formatters
158 if(mode == AppFormatMode::Sub)
159 return make_expanded(app, mode);
160
161 std::stringstream out;
162 if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
163 if(app->get_group() != "SUBCOMMANDS") {
164 out << app->get_group() << ':';
165 }
166 }
168 detail::streamOutAsParagraph(
169 out, make_description(app), description_paragraph_width_, ""); // Format description as paragraph
170 } else {
171 out << make_description(app) << '\n';
172 }
173 out << make_usage(app, name);
174 out << make_positionals(app);
175 out << make_groups(app, mode);
176 out << make_subcommands(app, mode);
177 std::string footer_string = make_footer(app);
178
180 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
181 } else {
182 out << footer_string;
183 }
184
185 return out.str();
186}
187
188CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
189 std::stringstream out;
190
191 std::vector<const App *> subcommands = app->get_subcommands({});
192
193 // Make a list in definition order of the groups seen
194 std::vector<std::string> subcmd_groups_seen;
195 for(const App *com : subcommands) {
196 if(com->get_name().empty()) {
197 if(!com->get_group().empty() && com->get_group().front() != '+') {
198 out << make_expanded(com, mode);
199 }
200 continue;
201 }
202 std::string group_key = com->get_group();
203 if(!group_key.empty() &&
204 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
205 return detail::to_lower(a) == detail::to_lower(group_key);
206 }) == subcmd_groups_seen.end())
207 subcmd_groups_seen.push_back(group_key);
208 }
209
210 // For each group, filter out and print subcommands
211 for(const std::string &group : subcmd_groups_seen) {
212 out << '\n' << group << ":\n";
213 std::vector<const App *> subcommands_group = app->get_subcommands(
214 [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
215 for(const App *new_com : subcommands_group) {
216 if(new_com->get_name().empty())
217 continue;
218 if(mode != AppFormatMode::All) {
219 out << make_subcommand(new_com);
220 } else {
221 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
222 out << '\n';
223 }
224 }
225 }
226
227 return out.str();
228}
229
230CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
231 std::stringstream out;
232 std::string name = " " + sub->get_display_name(true) + (sub->get_required() ? " " + get_label("REQUIRED") : "");
233
234 out << std::setw(static_cast<int>(column_width_)) << std::left << name;
235 detail::streamOutAsParagraph(
236 out, sub->get_description(), right_column_width_, std::string(column_width_, ' '), true);
237 out << '\n';
238 return out.str();
239}
240
241CLI11_INLINE std::string Formatter::make_expanded(const App *sub, AppFormatMode mode) const {
242 std::stringstream out;
243 out << sub->get_display_name(true) << '\n';
244
246 detail::streamOutAsParagraph(
247 out, make_description(sub), description_paragraph_width_, " "); // Format description as paragraph
248 } else {
249 out << make_description(sub) << '\n';
250 }
251
252 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
253 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
254 }
255
256 out << make_positionals(sub);
257 out << make_groups(sub, mode);
258 out << make_subcommands(sub, mode);
259 std::string footer_string = make_footer(sub);
260
261 if(mode == AppFormatMode::Sub && !footer_string.empty()) {
262 const auto *parent = sub->get_parent();
263 std::string parent_footer = (parent != nullptr) ? make_footer(sub->get_parent()) : std::string{};
264 if(footer_string == parent_footer) {
265 footer_string = "";
266 }
267 }
268 if(!footer_string.empty()) {
270 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
271 } else {
272 out << footer_string;
273 }
274 }
275 return out.str();
276}
277
278CLI11_INLINE std::string Formatter::make_option(const Option *opt, bool is_positional) const {
279 std::stringstream out;
280 if(is_positional) {
281 const std::string left = " " + make_option_name(opt, true) + make_option_opts(opt);
282 const std::string desc = make_option_desc(opt);
283 out << std::setw(static_cast<int>(column_width_)) << std::left << left;
284
285 if(!desc.empty()) {
286 bool skipFirstLinePrefix = true;
287 if(left.length() >= column_width_) {
288 out << '\n';
289 skipFirstLinePrefix = false;
290 }
291 detail::streamOutAsParagraph(
292 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
293 }
294 } else {
295 const std::string namesCombined = make_option_name(opt, false);
296 const std::string opts = make_option_opts(opt);
297 const std::string desc = make_option_desc(opt);
298
299 // Split all names at comma and sort them into short names and long names
300 const auto names = detail::split(namesCombined, ',');
301 std::vector<std::string> vshortNames;
302 std::vector<std::string> vlongNames;
303 std::for_each(names.begin(), names.end(), [&vshortNames, &vlongNames](const std::string &name) {
304 if(name.find("--", 0) != std::string::npos)
305 vlongNames.push_back(name);
306 else
307 vshortNames.push_back(name);
308 });
309
310 // Assemble short and long names
311 std::string shortNames = detail::join(vshortNames, ", ");
312 std::string longNames = detail::join(vlongNames, ", ");
313
314 // Calculate setw sizes
315 // Short names take enough width to align long names at the desired ratio
316 const auto shortNamesColumnWidth =
317 static_cast<int>(static_cast<float>(column_width_) * long_option_alignment_ratio_);
318 const auto longNamesColumnWidth = static_cast<int>(column_width_) - shortNamesColumnWidth;
319 int shortNamesOverSize = 0;
320
321 // Print short names
322 if(!shortNames.empty()) {
323 shortNames = " " + shortNames; // Indent
324 if(longNames.empty() && !opts.empty())
325 shortNames += opts; // Add opts if only short names and no long names
326 if(!longNames.empty())
327 shortNames += ",";
328 if(static_cast<int>(shortNames.length()) >= shortNamesColumnWidth) {
329 shortNames += " ";
330 shortNamesOverSize = static_cast<int>(shortNames.length()) - shortNamesColumnWidth;
331 }
332 out << std::setw(shortNamesColumnWidth) << std::left << shortNames;
333 } else {
334 out << std::setw(shortNamesColumnWidth) << std::left << "";
335 }
336
337 // Adjust long name column width in case of short names column reaching into long names column
338 shortNamesOverSize =
339 (std::min)(shortNamesOverSize, longNamesColumnWidth); // Prevent negative result with unsigned integers
340 const auto adjustedLongNamesColumnWidth = longNamesColumnWidth - shortNamesOverSize;
341
342 // Print long names
343 if(!longNames.empty()) {
344 if(!opts.empty())
345 longNames += opts;
346 if(static_cast<int>(longNames.length()) >= adjustedLongNamesColumnWidth)
347 longNames += " ";
348
349 out << std::setw(adjustedLongNamesColumnWidth) << std::left << longNames;
350 } else {
351 out << std::setw(adjustedLongNamesColumnWidth) << std::left << "";
352 }
353
354 if(!desc.empty()) {
355 bool skipFirstLinePrefix = true;
356 if(out.str().length() > column_width_) {
357 out << '\n';
358 skipFirstLinePrefix = false;
359 }
360 detail::streamOutAsParagraph(
361 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
362 }
363 }
364
365 out << '\n';
366 return out.str();
367}
368
369CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
370 if(is_positional)
371 return opt->get_name(true, false);
372
373 return opt->get_name(false, true, !enable_default_flag_values_);
374}
375
376CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
377 std::stringstream out;
378 // Help output should be stable across runs, so sort pointer-based sets by option name before printing.
379 const auto print_option_set = [&out](const std::set<Option *> &options) {
380 std::vector<const Option *> sorted(options.begin(), options.end());
381 std::sort(sorted.begin(), sorted.end(), [](const Option *lhs, const Option *rhs) {
382 return lhs->get_name() < rhs->get_name();
383 });
384 for(const Option *op : sorted)
385 out << " " << op->get_name();
386 };
387
388 if(!opt->get_option_text().empty()) {
389 out << " " << opt->get_option_text();
390 } else {
391 if(opt->get_type_size() != 0) {
392 if(enable_option_type_names_) {
393 if(!opt->get_type_name().empty())
394 out << " " << get_label(opt->get_type_name());
395 }
397 if(!opt->get_default_str().empty())
398 out << " [" << opt->get_default_str() << "] ";
399 }
400 if(opt->get_expected_max() == detail::expected_max_vector_size)
401 out << " ...";
402 else if(opt->get_expected_min() > 1)
403 out << " x " << opt->get_expected();
404
405 if(opt->get_required())
406 out << " " << get_label("REQUIRED");
407 }
408 if(!opt->get_envname().empty())
409 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
410 if(!opt->get_needs().empty()) {
411 out << " " << get_label("Needs") << ":";
412 print_option_set(opt->get_needs());
413 }
414 if(!opt->get_excludes().empty()) {
415 out << " " << get_label("Excludes") << ":";
416 print_option_set(opt->get_excludes());
417 }
418 }
419 return out.str();
420}
421
422CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
423
424CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
425 // Note that these are positionals usages
426 std::stringstream out;
427 out << make_option_name(opt, true);
428 if(opt->get_expected_max() >= detail::expected_max_vector_size)
429 out << "...";
430 else if(opt->get_expected_max() > 1)
431 out << "(" << opt->get_expected() << "x)";
432
433 return opt->get_required() ? out.str() : "[" + out.str() + "]";
434}
435// [CLI11:formatter_inl_hpp:end]
436} // namespace CLI
Creates a command line program, with very few defaults.
Definition App.hpp:115
CLI11_NODISCARD std::string get_usage() const
Generate and return the usage.
Definition App.hpp:1179
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition App.hpp:1192
Option * get_help_ptr()
Get a pointer to the help flag.
Definition App.hpp:1246
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition App.hpp:1184
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition App.hpp:1252
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition App.hpp:1267
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition App_inl.hpp:970
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition App.hpp:1198
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition App.hpp:1213
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition App_inl.hpp:1029
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition App.hpp:1276
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition App.hpp:1195
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition App.hpp:1176
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition App.hpp:977
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Get the list of options (user facing function, so returns raw pointers), has optional filter function...
Definition App_inl.hpp:832
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition App.hpp:1122
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition App.hpp:1189
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition App.hpp:1273
std::size_t column_width_
The width of the left column (options/flags/subcommands)
Definition FormatterFwd.hpp:48
std::size_t footer_paragraph_width_
The width of the footer paragraph.
Definition FormatterFwd.hpp:60
bool enable_option_defaults_
options controlling formatting of options
Definition FormatterFwd.hpp:67
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition FormatterFwd.hpp:135
CLI11_NODISCARD bool is_description_paragraph_formatting_enabled() const
Get the current status of description paragraph formatting.
Definition FormatterFwd.hpp:157
std::size_t right_column_width_
The width of the right column (description of options/flags/subcommands)
Definition FormatterFwd.hpp:54
float long_option_alignment_ratio_
The alignment ratio for long options within the left column.
Definition FormatterFwd.hpp:51
std::size_t description_paragraph_width_
The width of the description paragraph at the top of help.
Definition FormatterFwd.hpp:57
CLI11_NODISCARD bool is_footer_paragraph_formatting_enabled() const
Get the current status of whether footer paragraph formatting is enabled.
Definition FormatterFwd.hpp:160
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition Formatter_inl.hpp:46
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition Formatter_inl.hpp:96
virtual std::string make_option_name(const Option *, bool) const
This is the name part of an option, Default: left column.
Definition Formatter_inl.hpp:369
virtual std::string make_expanded(const App *sub, AppFormatMode mode) const
This prints out a subcommand in help-all.
Definition Formatter_inl.hpp:241
std::string make_help(const App *app, std::string, AppFormatMode mode) const override
This puts everything together.
Definition Formatter_inl.hpp:155
virtual CLI11_NODISCARD std::string make_group(std::string group, bool is_positional, std::vector< const Option * > opts) const
Definition Formatter_inl.hpp:25
virtual std::string make_option(const Option *, bool) const
This prints out an option help line, either positional or optional form.
Definition Formatter_inl.hpp:278
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition Formatter_inl.hpp:147
virtual std::string make_option_usage(const Option *opt) const
This is used to print the name on the USAGE line.
Definition Formatter_inl.hpp:424
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition Formatter_inl.hpp:230
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition Formatter_inl.hpp:36
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition Formatter_inl.hpp:188
virtual std::string make_description(const App *app) const
This displays the description line.
Definition Formatter_inl.hpp:71
virtual std::string make_option_desc(const Option *) const
This is the description. Default: Right column, on new line if left column too large.
Definition Formatter_inl.hpp:422
virtual std::string make_option_opts(const Option *) const
This is the options part of the name, Default: combined into left column.
Definition Formatter_inl.hpp:376
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition Option.hpp:137
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition Option.hpp:134
Definition Option.hpp:259
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition Option.hpp:628
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition Option.hpp:573
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition Option_inl.hpp:538
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false, bool disable_default_flag_values=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition Option_inl.hpp:258
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing)
Definition Option.hpp:582
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition Option.hpp:631
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition Option.hpp:579
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition Option.hpp:576
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition Option.hpp:637
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition Option.hpp:609
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition Option.hpp:612
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition Option.hpp:614
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition Option.hpp:562