CLI11
C++11 Command Line Interface Parser
Loading...
Searching...
No Matches
Formatter_inl.hpp
1// Copyright (c) 2017-2025, 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 <string>
17#include <utility>
18#include <vector>
19// [CLI11:public_includes:end]
20
21namespace CLI {
22// [CLI11:formatter_inl_hpp:verbatim]
23CLI11_INLINE std::string
24Formatter::make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const {
25 std::stringstream out;
26
27 out << "\n" << group << ":\n";
28 for(const Option *opt : opts) {
29 out << make_option(opt, is_positional);
30 }
31
32 return out.str();
33}
34
35CLI11_INLINE std::string Formatter::make_positionals(const App *app) const {
36 std::vector<const Option *> opts =
37 app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
38
39 if(opts.empty())
40 return {};
41
42 return make_group(get_label("POSITIONALS"), true, opts);
43}
44
45CLI11_INLINE std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
46 std::stringstream out;
47 std::vector<std::string> groups = app->get_groups();
48
49 // Options
50 for(const std::string &group : groups) {
51 std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
52 return opt->get_group() == group // Must be in the right group
53 && opt->nonpositional() // Must not be a positional
54 && (mode != AppFormatMode::Sub // If mode is Sub, then
55 || (app->get_help_ptr() != opt // Ignore help pointer
56 && app->get_help_all_ptr() != opt)); // Ignore help all pointer
57 });
58 if(!group.empty() && !opts.empty()) {
59 out << make_group(group, false, opts);
60
61 // Removed double newline between groups for consistency of help text
62 // if(group != groups.back())
63 // out << "\n";
64 }
65 }
66
67 return out.str();
68}
69
70CLI11_INLINE std::string Formatter::make_description(const App *app) const {
71 std::string desc = app->get_description();
72 auto min_options = app->get_require_option_min();
73 auto max_options = app->get_require_option_max();
74
75 if(app->get_required()) {
76 desc += " " + get_label("REQUIRED") + " ";
77 }
78
79 if(min_options > 0) {
80 if(max_options == min_options) {
81 desc += " \n[Exactly " + std::to_string(min_options) + " of the following options are required]";
82 } else if(max_options > 0) {
83 desc += " \n[Between " + std::to_string(min_options) + " and " + std::to_string(max_options) +
84 " of the following options are required]";
85 } else {
86 desc += " \n[At least " + std::to_string(min_options) + " of the following options are required]";
87 }
88 } else if(max_options > 0) {
89 desc += " \n[At most " + std::to_string(max_options) + " of the following options are allowed]";
90 }
91
92 return (!desc.empty()) ? desc + "\n\n" : std::string{};
93}
94
95CLI11_INLINE std::string Formatter::make_usage(const App *app, std::string name) const {
96 std::string usage = app->get_usage();
97 if(!usage.empty()) {
98 return usage + "\n\n";
99 }
100
101 std::stringstream out;
102 out << '\n';
103
104 if(name.empty())
105 out << get_label("Usage") << ':';
106 else
107 out << name;
108
109 std::vector<std::string> groups = app->get_groups();
110
111 // Print an Options badge if any options exist
112 std::vector<const Option *> non_pos_options =
113 app->get_options([](const Option *opt) { return opt->nonpositional(); });
114 if(!non_pos_options.empty())
115 out << " [" << get_label("OPTIONS") << "]";
116
117 // Positionals need to be listed here
118 std::vector<const Option *> positionals = app->get_options([](const Option *opt) { return opt->get_positional(); });
119
120 // Print out positionals if any are left
121 if(!positionals.empty()) {
122 // Convert to help names
123 std::vector<std::string> positional_names(positionals.size());
124 std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [this](const Option *opt) {
125 return make_option_usage(opt);
126 });
127
128 out << " " << detail::join(positional_names, " ");
129 }
130
131 // Add a marker if subcommands are expected or optional
132 if(!app->get_subcommands(
133 [](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
134 .empty()) {
135 out << ' ' << (app->get_require_subcommand_min() == 0 ? "[" : "")
136 << get_label(app->get_require_subcommand_max() < 2 || app->get_require_subcommand_min() > 1 ? "SUBCOMMAND"
137 : "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\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);
177 detail::streamOutAsParagraph(out, make_footer(app), footer_paragraph_width_); // Format footer as paragraph
178 } else {
179 out << make_footer(app) << '\n';
180 }
181
182 return out.str();
183}
184
185CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
186 std::stringstream out;
187
188 std::vector<const App *> subcommands = app->get_subcommands({});
189
190 // Make a list in definition order of the groups seen
191 std::vector<std::string> subcmd_groups_seen;
192 for(const App *com : subcommands) {
193 if(com->get_name().empty()) {
194 if(!com->get_group().empty() && com->get_group().front() != '+') {
195 out << make_expanded(com, mode);
196 }
197 continue;
198 }
199 std::string group_key = com->get_group();
200 if(!group_key.empty() &&
201 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
202 return detail::to_lower(a) == detail::to_lower(group_key);
203 }) == subcmd_groups_seen.end())
204 subcmd_groups_seen.push_back(group_key);
205 }
206
207 // For each group, filter out and print subcommands
208 for(const std::string &group : subcmd_groups_seen) {
209 out << '\n' << group << ":\n";
210 std::vector<const App *> subcommands_group = app->get_subcommands(
211 [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
212 for(const App *new_com : subcommands_group) {
213 if(new_com->get_name().empty())
214 continue;
215 if(mode != AppFormatMode::All) {
216 out << make_subcommand(new_com);
217 } else {
218 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
219 out << '\n';
220 }
221 }
222 }
223
224 return out.str();
225}
226
227CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
228 std::stringstream out;
229 std::string name = " " + sub->get_display_name(true) + (sub->get_required() ? " " + get_label("REQUIRED") : "");
230
231 out << std::setw(static_cast<int>(column_width_)) << std::left << name;
232 detail::streamOutAsParagraph(
233 out, sub->get_description(), right_column_width_, std::string(column_width_, ' '), true);
234 out << '\n';
235 return out.str();
236}
237
238CLI11_INLINE std::string Formatter::make_expanded(const App *sub, AppFormatMode mode) const {
239 std::stringstream out;
240 out << sub->get_display_name(true) << '\n';
241
243 detail::streamOutAsParagraph(
244 out, make_description(sub), description_paragraph_width_, " "); // Format description as paragraph
245 } else {
246 out << make_description(sub) << '\n';
247 }
248
249 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
250 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
251 }
252
253 out << make_positionals(sub);
254 out << make_groups(sub, mode);
255 out << make_subcommands(sub, mode);
257 detail::streamOutAsParagraph(out, make_footer(sub), footer_paragraph_width_); // Format footer as paragraph
258 } else {
259 out << make_footer(sub) << '\n';
260 }
261 out << '\n';
262 return out.str();
263}
264
265CLI11_INLINE std::string Formatter::make_option(const Option *opt, bool is_positional) const {
266 std::stringstream out;
267 if(is_positional) {
268 const std::string left = " " + make_option_name(opt, true) + make_option_opts(opt);
269 const std::string desc = make_option_desc(opt);
270 out << std::setw(static_cast<int>(column_width_)) << std::left << left;
271
272 if(!desc.empty()) {
273 bool skipFirstLinePrefix = true;
274 if(left.length() >= column_width_) {
275 out << '\n';
276 skipFirstLinePrefix = false;
277 }
278 detail::streamOutAsParagraph(
279 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
280 }
281 } else {
282 const std::string namesCombined = make_option_name(opt, false);
283 const std::string opts = make_option_opts(opt);
284 const std::string desc = make_option_desc(opt);
285
286 // Split all names at comma and sort them into short names and long names
287 const auto names = detail::split(namesCombined, ',');
288 std::vector<std::string> vshortNames;
289 std::vector<std::string> vlongNames;
290 std::for_each(names.begin(), names.end(), [&vshortNames, &vlongNames](const std::string &name) {
291 if(name.find("--", 0) != std::string::npos)
292 vlongNames.push_back(name);
293 else
294 vshortNames.push_back(name);
295 });
296
297 // Assemble short and long names
298 std::string shortNames = detail::join(vshortNames, ", ");
299 std::string longNames = detail::join(vlongNames, ", ");
300
301 // Calculate setw sizes
302 const auto shortNamesColumnWidth = static_cast<int>(column_width_ / 3); // 33% left for short names
303 const auto longNamesColumnWidth = static_cast<int>(std::ceil(
304 static_cast<float>(column_width_) / 3.0f * 2.0f)); // 66% right for long names and options, ceil result
305 int shortNamesOverSize = 0;
306
307 // Print short names
308 if(!shortNames.empty()) {
309 shortNames = " " + shortNames; // Indent
310 if(longNames.empty() && !opts.empty())
311 shortNames += opts; // Add opts if only short names and no long names
312 if(!longNames.empty())
313 shortNames += ",";
314 if(static_cast<int>(shortNames.length()) >= shortNamesColumnWidth) {
315 shortNames += " ";
316 shortNamesOverSize = static_cast<int>(shortNames.length()) - shortNamesColumnWidth;
317 }
318 out << std::setw(shortNamesColumnWidth) << std::left << shortNames;
319 } else {
320 out << std::setw(shortNamesColumnWidth) << std::left << "";
321 }
322
323 // Adjust long name column width in case of short names column reaching into long names column
324 shortNamesOverSize =
325 (std::min)(shortNamesOverSize, longNamesColumnWidth); // Prevent negative result with unsigned integers
326 const auto adjustedLongNamesColumnWidth = longNamesColumnWidth - shortNamesOverSize;
327
328 // Print long names
329 if(!longNames.empty()) {
330 if(!opts.empty())
331 longNames += opts;
332 if(static_cast<int>(longNames.length()) >= adjustedLongNamesColumnWidth)
333 longNames += " ";
334
335 out << std::setw(adjustedLongNamesColumnWidth) << std::left << longNames;
336 } else {
337 out << std::setw(adjustedLongNamesColumnWidth) << std::left << "";
338 }
339
340 if(!desc.empty()) {
341 bool skipFirstLinePrefix = true;
342 if(out.str().length() > column_width_) {
343 out << '\n';
344 skipFirstLinePrefix = false;
345 }
346 detail::streamOutAsParagraph(
347 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
348 }
349 }
350
351 out << '\n';
352 return out.str();
353}
354
355CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
356 if(is_positional)
357 return opt->get_name(true, false);
358
359 return opt->get_name(false, true);
360}
361
362CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
363 std::stringstream out;
364
365 if(!opt->get_option_text().empty()) {
366 out << " " << opt->get_option_text();
367 } else {
368 if(opt->get_type_size() != 0) {
369 if(!opt->get_type_name().empty())
370 out << " " << get_label(opt->get_type_name());
371 if(!opt->get_default_str().empty())
372 out << " [" << opt->get_default_str() << "] ";
373 if(opt->get_expected_max() == detail::expected_max_vector_size)
374 out << " ...";
375 else if(opt->get_expected_min() > 1)
376 out << " x " << opt->get_expected();
377
378 if(opt->get_required())
379 out << " " << get_label("REQUIRED");
380 }
381 if(!opt->get_envname().empty())
382 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
383 if(!opt->get_needs().empty()) {
384 out << " " << get_label("Needs") << ":";
385 for(const Option *op : opt->get_needs())
386 out << " " << op->get_name();
387 }
388 if(!opt->get_excludes().empty()) {
389 out << " " << get_label("Excludes") << ":";
390 for(const Option *op : opt->get_excludes())
391 out << " " << op->get_name();
392 }
393 }
394 return out.str();
395}
396
397CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
398
399CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
400 // Note that these are positionals usages
401 std::stringstream out;
402 out << make_option_name(opt, true);
403 if(opt->get_expected_max() >= detail::expected_max_vector_size)
404 out << "...";
405 else if(opt->get_expected_max() > 1)
406 out << "(" << opt->get_expected() << "x)";
407
408 return opt->get_required() ? out.str() : "[" + out.str() + "]";
409}
410// [CLI11:formatter_inl_hpp:end]
411} // namespace CLI
Creates a command line program, with very few defaults.
Definition App.hpp:98
CLI11_NODISCARD std::string get_usage() const
Generate and return the usage.
Definition App.hpp:1141
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition App.hpp:1154
Option * get_help_ptr()
Get a pointer to the help flag.
Definition App.hpp:1200
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition App.hpp:1146
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition App.hpp:1206
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition App.hpp:1221
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition App_inl.hpp:889
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition App.hpp:1160
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition App.hpp:1169
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition App_inl.hpp:948
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition App.hpp:1230
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition App.hpp:1157
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition App.hpp:1138
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition App.hpp:938
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:811
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition App.hpp:1072
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition App.hpp:1151
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition App.hpp:1227
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:57
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition FormatterFwd.hpp:111
CLI11_NODISCARD bool is_description_paragraph_formatting_enabled() const
Get the current status of description paragraph formatting.
Definition FormatterFwd.hpp:130
std::size_t right_column_width_
The width of the right column (description of options/flags/subcommands)
Definition FormatterFwd.hpp:51
std::size_t description_paragraph_width_
The width of the description paragraph at the top of help.
Definition FormatterFwd.hpp:54
CLI11_NODISCARD bool is_footer_paragraph_formatting_enabled() const
Get the current status of whether footer paragraph formatting is enabled.
Definition FormatterFwd.hpp:133
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition Formatter_inl.hpp:45
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition Formatter_inl.hpp:95
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:355
virtual std::string make_expanded(const App *sub, AppFormatMode mode) const
This prints out a subcommand in help-all.
Definition Formatter_inl.hpp:238
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:24
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:265
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:399
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition Formatter_inl.hpp:227
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition Formatter_inl.hpp:35
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition Formatter_inl.hpp:185
virtual std::string make_description(const App *app) const
This displays the description line.
Definition Formatter_inl.hpp:70
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:397
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:362
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition Option.hpp:118
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition Option.hpp:115
Definition Option.hpp:231
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition Option.hpp:587
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition Option.hpp:532
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition Option_inl.hpp:510
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition Option_inl.hpp:233
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing)
Definition Option.hpp:541
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition Option.hpp:590
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition Option.hpp:538
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition Option.hpp:535
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition Option.hpp:596
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition Option.hpp:568
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition Option.hpp:571
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition Option.hpp:573
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition Option.hpp:521