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;
}
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();
std::istringstream input(str);
std::string out_line;
std::string word;
if (input >> word)
if (line_length == 0)
line_length = SIZE_MAX;
std::string line;
size_t break_pos = 0;
for (auto &c : str)
{
out_line += word;
// size_t remaining = line_length - std::min(line_length, word.length());
while (input >> word)
if (c == '\n')
{
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 += ' ';
out_line += word;
// Break before last space, and skip that space
out->push_back(line.substr(0, break_pos - 1));
}
else
{
out->push_back(out_line);
out_line = word;
// Single word is too long, just break it
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;
}

@ -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,
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)
{