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(positionals.size());
125 std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [this](const Option *opt) {
126 return make_option_usage(opt);
127 });
128
129 out << " " << detail::join(positional_names, " ");
130 }
131
132 // Add a marker if subcommands are expected or optional
133 if(!app->get_subcommands(
134 [](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
135 .empty()) {
136 out << ' ' << (app->get_require_subcommand_min() == 0 ? "[" : "")
137 << get_label(app->get_require_subcommand_max() == 1 ? "SUBCOMMAND" : "SUBCOMMANDS")
138 << (app->get_require_subcommand_min() == 0 ? "]" : "");
139 }
140
141 out << "\n\n";
142
143 return out.str();
144}
145
146CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
147 std::string footer = app->get_footer();
148 if(footer.empty()) {
149 return std::string{};
150 }
151 return '\n' + footer + '\n';
152}
153
154CLI11_INLINE std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
155 // This immediately forwards to the make_expanded method. This is done this way so that subcommands can
156 // have overridden formatters
157 if(mode == AppFormatMode::Sub)
158 return make_expanded(app, mode);
159
160 std::stringstream out;
161 if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
162 if(app->get_group() != "SUBCOMMANDS") {
163 out << app->get_group() << ':';
164 }
165 }
167 detail::streamOutAsParagraph(
168 out, make_description(app), description_paragraph_width_, ""); // Format description as paragraph
169 } else {
170 out << make_description(app) << '\n';
171 }
172 out << make_usage(app, name);
173 out << make_positionals(app);
174 out << make_groups(app, mode);
175 out << make_subcommands(app, mode);
176 std::string footer_string = make_footer(app);
177
179 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
180 } else {
181 out << footer_string;
182 }
183
184 return out.str();
185}
186
187CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
188 std::stringstream out;
189
190 std::vector<const App *> subcommands = app->get_subcommands({});
191
192 // Make a list in definition order of the groups seen
193 std::vector<std::string> subcmd_groups_seen;
194 for(const App *com : subcommands) {
195 if(com->get_name().empty()) {
196 if(!com->get_group().empty() && com->get_group().front() != '+') {
197 out << make_expanded(com, mode);
198 }
199 continue;
200 }
201 std::string group_key = com->get_group();
202 if(!group_key.empty() &&
203 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
204 return detail::to_lower(a) == detail::to_lower(group_key);
205 }) == subcmd_groups_seen.end())
206 subcmd_groups_seen.push_back(group_key);
207 }
208
209 // For each group, filter out and print subcommands
210 for(const std::string &group : subcmd_groups_seen) {
211 out << '\n' << group << ":\n";
212 std::vector<const App *> subcommands_group = app->get_subcommands(
213 [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
214 for(const App *new_com : subcommands_group) {
215 if(new_com->get_name().empty())
216 continue;
217 if(mode != AppFormatMode::All) {
218 out << make_subcommand(new_com);
219 } else {
220 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
221 out << '\n';
222 }
223 }
224 }
225
226 return out.str();
227}
228
229CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
230 std::stringstream out;
231 std::string name = " " + sub->get_display_name(true) + (sub->get_required() ? " " + get_label("REQUIRED") : "");
232
233 out << std::setw(static_cast<int>(column_width_)) << std::left << name;
234 detail::streamOutAsParagraph(
235 out, sub->get_description(), right_column_width_, std::string(column_width_, ' '), true);
236 out << '\n';
237 return out.str();
238}
239
240CLI11_INLINE std::string Formatter::make_expanded(const App *sub, AppFormatMode mode) const {
241 std::stringstream out;
242 out << sub->get_display_name(true) << '\n';
243
245 detail::streamOutAsParagraph(
246 out, make_description(sub), description_paragraph_width_, " "); // Format description as paragraph
247 } else {
248 out << make_description(sub) << '\n';
249 }
250
251 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
252 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
253 }
254
255 out << make_positionals(sub);
256 out << make_groups(sub, mode);
257 out << make_subcommands(sub, mode);
258 std::string footer_string = make_footer(sub);
259
260 if(mode == AppFormatMode::Sub && !footer_string.empty()) {
261 const auto *parent = sub->get_parent();
262 std::string parent_footer = (parent != nullptr) ? make_footer(sub->get_parent()) : std::string{};
263 if(footer_string == parent_footer) {
264 footer_string = "";
265 }
266 }
267 if(!footer_string.empty()) {
269 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
270 } else {
271 out << footer_string;
272 }
273 }
274 return out.str();
275}
276
277CLI11_INLINE std::string Formatter::make_option(const Option *opt, bool is_positional) const {
278 std::stringstream out;
279 if(is_positional) {
280 const std::string left = " " + make_option_name(opt, true) + make_option_opts(opt);
281 const std::string desc = make_option_desc(opt);
282 out << std::setw(static_cast<int>(column_width_)) << std::left << left;
283
284 if(!desc.empty()) {
285 bool skipFirstLinePrefix = true;
286 if(left.length() >= column_width_) {
287 out << '\n';
288 skipFirstLinePrefix = false;
289 }
290 detail::streamOutAsParagraph(
291 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
292 }
293 } else {
294 const std::string namesCombined = make_option_name(opt, false);
295 const std::string opts = make_option_opts(opt);
296 const std::string desc = make_option_desc(opt);
297
298 // Split all names at comma and sort them into short names and long names
299 const auto names = detail::split(namesCombined, ',');
300 std::vector<std::string> vshortNames;
301 std::vector<std::string> vlongNames;
302 std::for_each(names.begin(), names.end(), [&vshortNames, &vlongNames](const std::string &name) {
303 if(name.find("--", 0) != std::string::npos)
304 vlongNames.push_back(name);
305 else
306 vshortNames.push_back(name);
307 });
308
309 // Assemble short and long names
310 std::string shortNames = detail::join(vshortNames, ", ");
311 std::string longNames = detail::join(vlongNames, ", ");
312
313 // Calculate setw sizes
314 // Short names take enough width to align long names at the desired ratio
315 const auto shortNamesColumnWidth =
316 static_cast<int>(static_cast<float>(column_width_) * long_option_alignment_ratio_);
317 const auto longNamesColumnWidth = static_cast<int>(column_width_) - shortNamesColumnWidth;
318 int shortNamesOverSize = 0;
319
320 // Print short names
321 if(!shortNames.empty()) {
322 shortNames = " " + shortNames; // Indent
323 if(longNames.empty() && !opts.empty())
324 shortNames += opts; // Add opts if only short names and no long names
325 if(!longNames.empty())
326 shortNames += ",";
327 if(static_cast<int>(shortNames.length()) >= shortNamesColumnWidth) {
328 shortNames += " ";
329 shortNamesOverSize = static_cast<int>(shortNames.length()) - shortNamesColumnWidth;
330 }
331 out << std::setw(shortNamesColumnWidth) << std::left << shortNames;
332 } else {
333 out << std::setw(shortNamesColumnWidth) << std::left << "";
334 }
335
336 // Adjust long name column width in case of short names column reaching into long names column
337 shortNamesOverSize =
338 (std::min)(shortNamesOverSize, longNamesColumnWidth); // Prevent negative result with unsigned integers
339 const auto adjustedLongNamesColumnWidth = longNamesColumnWidth - shortNamesOverSize;
340
341 // Print long names
342 if(!longNames.empty()) {
343 if(!opts.empty())
344 longNames += opts;
345 if(static_cast<int>(longNames.length()) >= adjustedLongNamesColumnWidth)
346 longNames += " ";
347
348 out << std::setw(adjustedLongNamesColumnWidth) << std::left << longNames;
349 } else {
350 out << std::setw(adjustedLongNamesColumnWidth) << std::left << "";
351 }
352
353 if(!desc.empty()) {
354 bool skipFirstLinePrefix = true;
355 if(out.str().length() > column_width_) {
356 out << '\n';
357 skipFirstLinePrefix = false;
358 }
359 detail::streamOutAsParagraph(
360 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
361 }
362 }
363
364 out << '\n';
365 return out.str();
366}
367
368CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
369 if(is_positional)
370 return opt->get_name(true, false);
371
372 return opt->get_name(false, true, !enable_default_flag_values_);
373}
374
375CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
376 std::stringstream out;
377 // Help output should be stable across runs, so sort pointer-based sets by option name before printing.
378 const auto print_option_set = [&out](const std::set<Option *> &options) {
379 std::vector<const Option *> sorted(options.begin(), options.end());
380 std::sort(sorted.begin(), sorted.end(), [](const Option *lhs, const Option *rhs) {
381 return lhs->get_name() < rhs->get_name();
382 });
383 for(const Option *op : sorted)
384 out << " " << op->get_name();
385 };
386
387 if(!opt->get_option_text().empty()) {
388 out << " " << opt->get_option_text();
389 } else {
390 if(opt->get_type_size() != 0) {
391 if(enable_option_type_names_) {
392 if(!opt->get_type_name().empty())
393 out << " " << get_label(opt->get_type_name());
394 }
396 if(!opt->get_default_str().empty())
397 out << " [" << opt->get_default_str() << "] ";
398 }
399 if(opt->get_expected_max() == detail::expected_max_vector_size)
400 out << " ...";
401 else if(opt->get_expected_min() > 1)
402 out << " x " << opt->get_expected();
403
404 if(opt->get_required())
405 out << " " << get_label("REQUIRED");
406 }
407 if(!opt->get_envname().empty())
408 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
409 if(!opt->get_needs().empty()) {
410 out << " " << get_label("Needs") << ":";
411 print_option_set(opt->get_needs());
412 }
413 if(!opt->get_excludes().empty()) {
414 out << " " << get_label("Excludes") << ":";
415 print_option_set(opt->get_excludes());
416 }
417 }
418 return out.str();
419}
420
421CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
422
423CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
424 // Note that these are positionals usages
425 std::stringstream out;
426 out << make_option_name(opt, true);
427 if(opt->get_expected_max() >= detail::expected_max_vector_size)
428 out << "...";
429 else if(opt->get_expected_max() > 1)
430 out << "(" << opt->get_expected() << "x)";
431
432 return opt->get_required() ? out.str() : "[" + out.str() + "]";
433}
434// [CLI11:formatter_inl_hpp:end]
435} // 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:368
virtual std::string make_expanded(const App *sub, AppFormatMode mode) const
This prints out a subcommand in help-all.
Definition Formatter_inl.hpp:240
std::string make_help(const App *app, std::string, AppFormatMode mode) const override
This puts everything together.
Definition Formatter_inl.hpp:154
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:277
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition Formatter_inl.hpp:146
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:423
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition Formatter_inl.hpp:229
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:187
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:421
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:375
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