From: Nick Bowler Date: Tue, 5 Dec 2023 01:55:43 +0000 (-0500) Subject: help_print_desc: Simplify implementation. X-Git-Url: https://git.draconx.ca/gitweb/dxcommon.git/commitdiff_plain/f7845ef1698291a23975052a100c12bf38a0664d help_print_desc: Simplify implementation. Simplify the way this function works by basing the loop around strcspn. There is a slight change of behaviour when called with i==0 and an empty description. Previously, no newline was printed. Now, a newline is printed. I think the original behaviour was a mistake as it does not make much sense (and this function serves no real purpose unless i is nonzero). The tests are updated to expect this behaviour change. As a bonus, we no longer tickle a problem with some ancient systems (e.g., ULTRIX 4.5) which have a printf that doesn't support a negative precision argument to mean "default precision". This problem actually has no coverage in the test suite, so fix that up too. --- diff --git a/src/help.c b/src/help.c index 4b77b2c..3aa0830 100644 --- a/src/help.c +++ b/src/help.c @@ -202,17 +202,11 @@ void help_print_desc(const struct option *opt, const char *s, int i, int w) if (opt) s = pgettext_expr(opt->name, s); - if (i && s[0] == '\0') - putchar('\n'); - - for (; *s; w = 0) { - const char *nl = strchr(s, '\n'); - int n = (nl ? nl-s : -1); + do { + size_t n = strcspn(s, "\n"); - printf("%*s%.*s\n", i-w, "", n, s); - if (!nl) - break; - - s = nl+1; - } + printf("%*s%.*s\n", n ? i-w : 0, "", (int)n, s); + s += n + (s[n] != '\0'); + w = 0; + } while (*s); } diff --git a/src/help.h b/src/help.h index a78bc59..7dbb65d 100644 --- a/src/help.h +++ b/src/help.h @@ -1,5 +1,5 @@ /* - * Copyright © 2021 Nick Bowler + * Copyright © 2021, 2023 Nick Bowler * * Helper functions for formatting --help program output. * @@ -28,6 +28,9 @@ int help_print_optstring(const struct option *opt, const char *argname, int l); * with the context set to opt->name. The first line will be indented by * i-w spaces (to account for the cursor being in some other column), all * other lines are indented by i spaces. + * + * The output always ends with a newline, regardless of whether or not the + * input string ends with a newline. */ void help_print_desc(const struct option *opt, const char *desc, int i, int w); diff --git a/tests/functions.at b/tests/functions.at index e1d556b..71a282d 100644 --- a/tests/functions.at +++ b/tests/functions.at @@ -33,6 +33,11 @@ sed -e '5,$s/^/ /' -e '6,$s/^/ /' \ AT_CHECK(["$builddir/t/helpdesc" 0 0 10 5 30 20 40 40