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() == 1 ? "SUBCOMMAND" : "SUBCOMMANDS")
137 << (app->get_require_subcommand_min() == 0 ? "]" : "");
138 }
139
140 out << "\n\n";
141
142 return out.str();
143}
144
145CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
146 std::string footer = app->get_footer();
147 if(footer.empty()) {
148 return std::string{};
149 }
150 return '\n' + footer + "\n\n";
151}
152
153CLI11_INLINE std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
154 // This immediately forwards to the make_expanded method. This is done this way so that subcommands can
155 // have overridden formatters
156 if(mode == AppFormatMode::Sub)
157 return make_expanded(app, mode);
158
159 std::stringstream out;
160 if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
161 if(app->get_group() != "SUBCOMMANDS") {
162 out << app->get_group() << ':';
163 }
164 }
166 detail::streamOutAsParagraph(
167 out, make_description(app), description_paragraph_width_, ""); // Format description as paragraph
168 } else {
169 out << make_description(app) << '\n';
170 }
171 out << make_usage(app, name);
172 out << make_positionals(app);
173 out << make_groups(app, mode);
174 out << make_subcommands(app, mode);
175 std::string footer_string = make_footer(app);
176
178 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
179 } else {
180 out << footer_string << '\n';
181 }
182
183 return out.str();
184}
185
186CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
187 std::stringstream out;
188
189 std::vector<const App *> subcommands = app->get_subcommands({});
190
191 // Make a list in definition order of the groups seen
192 std::vector<std::string> subcmd_groups_seen;
193 for(const App *com : subcommands) {
194 if(com->get_name().empty()) {
195 if(!com->get_group().empty() && com->get_group().front() != '+') {
196 out << make_expanded(com, mode);
197 }
198 continue;
199 }
200 std::string group_key = com->get_group();
201 if(!group_key.empty() &&
202 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
203 return detail::to_lower(a) == detail::to_lower(group_key);
204 }) == subcmd_groups_seen.end())
205 subcmd_groups_seen.push_back(group_key);
206 }
207
208 // For each group, filter out and print subcommands
209 for(const std::string &group : subcmd_groups_seen) {
210 out << '\n' << group << ":\n";
211 std::vector<const App *> subcommands_group = app->get_subcommands(
212 [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
213 for(const App *new_com : subcommands_group) {
214 if(new_com->get_name().empty())
215 continue;
216 if(mode != AppFormatMode::All) {
217 out << make_subcommand(new_com);
218 } else {
219 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
220 out << '\n';
221 }
222 }
223 }
224
225 return out.str();
226}
227
228CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
229 std::stringstream out;
230 std::string name = " " + sub->get_display_name(true) + (sub->get_required() ? " " + get_label("REQUIRED") : "");
231
232 out << std::setw(static_cast<int>(column_width_)) << std::left << name;
233 detail::streamOutAsParagraph(
234 out, sub->get_description(), right_column_width_, std::string(column_width_, ' '), true);
235 out << '\n';
236 return out.str();
237}
238
239CLI11_INLINE std::string Formatter::make_expanded(const App *sub, AppFormatMode mode) const {
240 std::stringstream out;
241 out << sub->get_display_name(true) << '\n';
242
244 detail::streamOutAsParagraph(
245 out, make_description(sub), description_paragraph_width_, " "); // Format description as paragraph
246 } else {
247 out << make_description(sub) << '\n';
248 }
249
250 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
251 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
252 }
253
254 out << make_positionals(sub);
255 out << make_groups(sub, mode);
256 out << make_subcommands(sub, mode);
257 std::string footer_string = make_footer(sub);
258
259 if(mode == AppFormatMode::Sub && !footer_string.empty()) {
260 const auto *parent = sub->get_parent();
261 std::string parent_footer = (parent != nullptr) ? make_footer(sub->get_parent()) : std::string{};
262 if(footer_string == parent_footer) {
263 footer_string = "";
264 }
265 }
267 detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
268 } else {
269 out << footer_string << '\n';
270 }
271 out << '\n';
272 return out.str();
273}
274
275CLI11_INLINE std::string Formatter::make_option(const Option *opt, bool is_positional) const {
276 std::stringstream out;
277 if(is_positional) {
278 const std::string left = " " + make_option_name(opt, true) + make_option_opts(opt);
279 const std::string desc = make_option_desc(opt);
280 out << std::setw(static_cast<int>(column_width_)) << std::left << left;
281
282 if(!desc.empty()) {
283 bool skipFirstLinePrefix = true;
284 if(left.length() >= column_width_) {
285 out << '\n';
286 skipFirstLinePrefix = false;
287 }
288 detail::streamOutAsParagraph(
289 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
290 }
291 } else {
292 const std::string namesCombined = make_option_name(opt, false);
293 const std::string opts = make_option_opts(opt);
294 const std::string desc = make_option_desc(opt);
295
296 // Split all names at comma and sort them into short names and long names
297 const auto names = detail::split(namesCombined, ',');
298 std::vector<std::string> vshortNames;
299 std::vector<std::string> vlongNames;
300 std::for_each(names.begin(), names.end(), [&vshortNames, &vlongNames](const std::string &name) {
301 if(name.find("--", 0) != std::string::npos)
302 vlongNames.push_back(name);
303 else
304 vshortNames.push_back(name);
305 });
306
307 // Assemble short and long names
308 std::string shortNames = detail::join(vshortNames, ", ");
309 std::string longNames = detail::join(vlongNames, ", ");
310
311 // Calculate setw sizes
312 // Short names take enough width to align long names at the desired ratio
313 const auto shortNamesColumnWidth =
314 static_cast<int>(static_cast<float>(column_width_) * long_option_alignment_ratio_);
315 const auto longNamesColumnWidth = static_cast<int>(column_width_) - shortNamesColumnWidth;
316 int shortNamesOverSize = 0;
317
318 // Print short names
319 if(!shortNames.empty()) {
320 shortNames = " " + shortNames; // Indent
321 if(longNames.empty() && !opts.empty())
322 shortNames += opts; // Add opts if only short names and no long names
323 if(!longNames.empty())
324 shortNames += ",";
325 if(static_cast<int>(shortNames.length()) >= shortNamesColumnWidth) {
326 shortNames += " ";
327 shortNamesOverSize = static_cast<int>(shortNames.length()) - shortNamesColumnWidth;
328 }
329 out << std::setw(shortNamesColumnWidth) << std::left << shortNames;
330 } else {
331 out << std::setw(shortNamesColumnWidth) << std::left << "";
332 }
333
334 // Adjust long name column width in case of short names column reaching into long names column
335 shortNamesOverSize =
336 (std::min)(shortNamesOverSize, longNamesColumnWidth); // Prevent negative result with unsigned integers
337 const auto adjustedLongNamesColumnWidth = longNamesColumnWidth - shortNamesOverSize;
338
339 // Print long names
340 if(!longNames.empty()) {
341 if(!opts.empty())
342 longNames += opts;
343 if(static_cast<int>(longNames.length()) >= adjustedLongNamesColumnWidth)
344 longNames += " ";
345
346 out << std::setw(adjustedLongNamesColumnWidth) << std::left << longNames;
347 } else {
348 out << std::setw(adjustedLongNamesColumnWidth) << std::left << "";
349 }
350
351 if(!desc.empty()) {
352 bool skipFirstLinePrefix = true;
353 if(out.str().length() > column_width_) {
354 out << '\n';
355 skipFirstLinePrefix = false;
356 }
357 detail::streamOutAsParagraph(
358 out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
359 }
360 }
361
362 out << '\n';
363 return out.str();
364}
365
366CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
367 if(is_positional)
368 return opt->get_name(true, false);
369
370 return opt->get_name(false, true);
371}
372
373CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
374 std::stringstream out;
375
376 if(!opt->get_option_text().empty()) {
377 out << " " << opt->get_option_text();
378 } else {
379 if(opt->get_type_size() != 0) {
380 if(!opt->get_type_name().empty())
381 out << " " << get_label(opt->get_type_name());
382 if(!opt->get_default_str().empty())
383 out << " [" << opt->get_default_str() << "] ";
384 if(opt->get_expected_max() == detail::expected_max_vector_size)
385 out << " ...";
386 else if(opt->get_expected_min() > 1)
387 out << " x " << opt->get_expected();
388
389 if(opt->get_required())
390 out << " " << get_label("REQUIRED");
391 }
392 if(!opt->get_envname().empty())
393 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
394 if(!opt->get_needs().empty()) {
395 out << " " << get_label("Needs") << ":";
396 for(const Option *op : opt->get_needs())
397 out << " " << op->get_name();
398 }
399 if(!opt->get_excludes().empty()) {
400 out << " " << get_label("Excludes") << ":";
401 for(const Option *op : opt->get_excludes())
402 out << " " << op->get_name();
403 }
404 }
405 return out.str();
406}
407
408CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
409
410CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
411 // Note that these are positionals usages
412 std::stringstream out;
413 out << make_option_name(opt, true);
414 if(opt->get_expected_max() >= detail::expected_max_vector_size)
415 out << "...";
416 else if(opt->get_expected_max() > 1)
417 out << "(" << opt->get_expected() << "x)";
418
419 return opt->get_required() ? out.str() : "[" + out.str() + "]";
420}
421// [CLI11:formatter_inl_hpp:end]
422} // 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:1143
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition App.hpp:1156
Option * get_help_ptr()
Get a pointer to the help flag.
Definition App.hpp:1202
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition App.hpp:1148
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition App.hpp:1208
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition App.hpp:1223
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition App_inl.hpp:909
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition App.hpp:1162
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition App.hpp:1171
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition App_inl.hpp:968
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition App.hpp:1232
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition App.hpp:1159
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition App.hpp:1140
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition App.hpp:940
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:831
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition App.hpp:1074
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition App.hpp:1153
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition App.hpp:1229
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
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition FormatterFwd.hpp:118
CLI11_NODISCARD bool is_description_paragraph_formatting_enabled() const
Get the current status of description paragraph formatting.
Definition FormatterFwd.hpp:137
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:140
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:366
virtual std::string make_expanded(const App *sub, AppFormatMode mode) const
This prints out a subcommand in help-all.
Definition Formatter_inl.hpp:239
std::string make_help(const App *app, std::string, AppFormatMode mode) const override
This puts everything together.
Definition Formatter_inl.hpp:153
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:275
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition Formatter_inl.hpp:145
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:410
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition Formatter_inl.hpp:228
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:186
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:408
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:373
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition Option.hpp:122
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition Option.hpp:119
Definition Option.hpp:235
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition Option.hpp:598
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition Option.hpp:543
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition Option_inl.hpp:533
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:256
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing)
Definition Option.hpp:552
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition Option.hpp:601
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition Option.hpp:549
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition Option.hpp:546
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition Option.hpp:607
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition Option.hpp:579
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition Option.hpp:582
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition Option.hpp:584
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition Option.hpp:532