MiscUtils: teach word_wrap() to optionally preserve whitespace

develop
Tim Siegel 2022-04-21 16:58:53 -04:00
parent e95d8c7296
commit 55e4008925
No known key found for this signature in database
GPG Key ID: 856AC2B87AB8474E
2 changed files with 44 additions and 17 deletions

@ -168,32 +168,58 @@ std::string to_search_normalized(const std::string &str)
return result; return result;
} }
bool word_wrap(std::vector<std::string> *out, const std::string &str, size_t line_length)
bool word_wrap(std::vector<std::string> *out, const std::string &str,
size_t line_length, bool collapse_whitespace)
{ {
out->clear(); if (line_length == 0)
std::istringstream input(str); line_length = SIZE_MAX;
std::string out_line;
std::string word; std::string line;
if (input >> word) size_t break_pos = 0;
for (auto &c : str)
{ {
out_line += word; if (c == '\n')
// size_t remaining = line_length - std::min(line_length, word.length()); {
while (input >> word) out->push_back(line);
line.clear();
break_pos = 0;
continue;
}
if (isspace(c))
{ {
if (out_line.length() + word.length() + 1 <= line_length) if (break_pos == line.length() && collapse_whitespace)
continue;
line.push_back(collapse_whitespace ? ' ' : c);
break_pos = line.length();
}
else {
line.push_back(c);
}
if (line.length() > line_length)
{
if (break_pos > 0)
{ {
out_line += ' '; // Break before last space, and skip that space
out_line += word; out->push_back(line.substr(0, break_pos - 1));
} }
else else
{ {
out->push_back(out_line); // Single word is too long, just break it
out_line = word; out->push_back(line.substr(0, line_length));
break_pos = line_length;
} }
line = line.substr(break_pos);
break_pos = 0;
} }
if (out_line.length())
out->push_back(out_line);
} }
if (line.length())
out->push_back(line);
return true; return true;
} }

@ -391,7 +391,8 @@ DFHACK_EXPORT std::string to_search_normalized(const std::string &str);
DFHACK_EXPORT bool word_wrap(std::vector<std::string> *out, DFHACK_EXPORT bool word_wrap(std::vector<std::string> *out,
const std::string &str, const std::string &str,
size_t line_length = 80); size_t line_length = 80,
bool collapse_whitespace = false);
inline bool bits_match(unsigned required, unsigned ok, unsigned mask) inline bool bits_match(unsigned required, unsigned ok, unsigned mask)
{ {