2 * UCW Library -- Formatting of command-line option help
4 * (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5 * (c) 2014 Martin Mares <mj@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
13 #include <ucw/opt-internal.h>
14 #include <ucw/mempool.h>
21 struct help_line *lines; // A growing array of lines
29 static void opt_help_scan_item(struct help *h, struct opt_precomputed *opt)
31 struct opt_item *item = opt->item;
33 if (opt->flags & OPT_NO_HELP)
36 if (item->cls == OPT_CL_HELP) {
37 struct help_line *l = GARY_PUSH(h->lines, 1);
38 l->extra = item->help ? : "";
42 if (item->letter >= OPT_POSITIONAL_TAIL)
45 struct help_line *first = GARY_PUSH(h->lines, 1);
47 char *text = mp_strdup(h->pool, item->help);
48 struct help_line *l = first;
50 char *eol = strchr(text, '\n');
54 int field = (l == first ? 1 : 0);
57 char *tab = strchr(f, '\t');
61 l->fields[field++] = f;
67 l = GARY_PUSH(h->lines, 1);
72 char *val = first->fields[1] ? : "";
73 if (opt->flags & OPT_REQUIRED_VALUE)
74 val = mp_printf(h->pool, "=%s", val);
75 else if (!(opt->flags & OPT_NO_VALUE))
76 val = mp_printf(h->pool, "[=%s]", val);
77 first->fields[1] = mp_printf(h->pool, "--%s%s", item->name, val);
82 first->fields[0] = mp_printf(h->pool, "-%c, ", item->letter);
84 char *val = first->fields[1] ? : "";
85 if (!(opt->flags & OPT_REQUIRED_VALUE) && !(opt->flags & OPT_NO_VALUE))
86 val = mp_printf(h->pool, "[%s]", val);
87 first->fields[0] = mp_printf(h->pool, "-%c%s", item->letter, val);
88 first->fields[1] = NULL;
93 static void opt_help_scan(struct help *h, const struct opt_section *sec)
95 for (struct opt_item * item = sec->opt; item->cls != OPT_CL_END; item++) {
96 if (item->cls == OPT_CL_SECTION)
97 opt_help_scan(h, item->u.section);
99 struct opt_precomputed opt;
100 opt_precompute(&opt, item);
101 opt_help_scan_item(h, &opt);
106 void opt_help(const struct opt_section * sec) {
109 h.pool = mp_new(4096);
110 GARY_INIT_ZERO(h.lines, 0);
111 opt_help_scan(&h, sec);
113 // Calculate natural width of each column
114 uns n = GARY_SIZE(h.lines);
115 uns widths[3] = { 0, 0, 0 };
116 for (uns i=0; i<n; i++) {
117 struct help_line *l = &h.lines[i];
118 for (uns f=0; f<3; f++) {
121 uns w = strlen(l->fields[f]);
122 widths[f] = MAX(widths[f], w);
127 * This is tricky: if there are short options, which have an argument,
128 * but no long variant, we are willing to let column 0 overflow to column 1.
130 widths[1] = MAX(widths[1], widths[0] - 4);
136 for (uns i=0; i<n; i++) {
137 struct help_line *l = &h.lines[i];
142 for (uns f=0; f<3; f++) {
144 t -= printf("%s", l->fields[f]);
159 void opt_handle_help(struct opt_item * opt UNUSED, const char * value UNUSED, void * data)