Skip to content

Commit 9c01cc0

Browse files
[crispy] CLI: Handle newlines in help descriptions when printed, preserving indentation.
1 parent af81fdf commit 9c01cc0

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/crispy/CLI.cpp

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -565,15 +565,28 @@ namespace // {{{ helpers
565565
return stylizer(style);
566566
}
567567

568-
string_view wordWrapped(string_view _text, unsigned _margin, unsigned _cursor)
568+
string_view wordWrapped(string_view _text, int _margin, int _cursor, bool* _trimLeadingWhitespaces)
569569
{
570-
auto const unwrappedLength = _cursor + _text.size();
570+
auto const linefeed = _text.find('\n');
571+
if (linefeed != string_view::npos)
572+
{
573+
auto i = linefeed - 1; // Position before the found LF and trim off right whitespaces.
574+
while (i > 0 && _text[i] == ' ')
575+
--i;
576+
*_trimLeadingWhitespaces = false;
577+
return _text.substr(0, i + 1);
578+
}
579+
580+
*_trimLeadingWhitespaces = true;
581+
582+
auto const unwrappedLength = _cursor + int(_text.size());
571583
if (unwrappedLength <= _margin)
572584
return _text;
573585

574586
// Cut string at right margin, then shift left until we've hit a whitespace character.
575-
auto i = _margin - _cursor + 1;
576-
while (i > 0 && _text[i] != ' ')
587+
auto const rightMargin = _margin - _cursor + 1;
588+
auto i = rightMargin;
589+
while (i > 0 && (_text[i] != ' ' && _text[i] != '\n'))
577590
--i;
578591

579592
return _text.substr(0, i);
@@ -583,12 +596,14 @@ namespace // {{{ helpers
583596
{
584597
string output;
585598
size_t i = 0;
599+
bool trimLeadingWhitespaces = true;
586600
for (;;)
587601
{
588-
while (i < _text.size() && _text[i] == ' ')
602+
auto const trimChar = trimLeadingWhitespaces ? ' ' : '\n';
603+
while (i < _text.size() && _text[i] == trimChar)
589604
++i; // skip leading whitespaces
590605

591-
auto const chunk = wordWrapped(_text.substr(i), _margin, *_cursor);
606+
auto const chunk = wordWrapped(_text.substr(i), _margin, *_cursor, &trimLeadingWhitespaces);
592607

593608
output += chunk;
594609
*_cursor += static_cast<unsigned>(chunk.size());

0 commit comments

Comments
 (0)