Fix bugs in search::context().

- Don't add context if words == 0
- Handle beginning / end of text correctly.
This commit is contained in:
tastytea 2021-05-24 19:57:15 +02:00
parent 1f25daed26
commit 09090a1c13
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
1 changed files with 31 additions and 4 deletions

View File

@ -153,27 +153,54 @@ match_context
context(const boost::match_results<std::string::const_iterator> &match,
std::uint64_t words)
{
if (words == 0)
{
return {};
}
const auto &prefix{match.prefix().str()};
const auto &suffix{match.suffix().str()};
size_t pos_before{prefix.length()};
size_t pos_after{};
++words;
while (words != 0)
{
if (pos_before != std::string::npos)
if (pos_before != 0)
{
pos_before = prefix.rfind(' ', pos_before) - 1;
pos_before = prefix.rfind(' ', pos_before);
if (pos_before != std::string::npos)
{
--pos_before;
}
else
{
pos_before = 0;
}
}
if (pos_after != std::string::npos)
{
pos_after = suffix.find(' ', pos_after) + 1;
pos_after = suffix.find(' ', pos_after);
if (pos_after != std::string::npos)
{
++pos_after;
}
}
words -= 1;
}
return {prefix.substr(pos_before + 2), suffix.substr(0, pos_after - 1)};
if (pos_before != 0)
{
pos_before += 2;
}
if (pos_after != std::string::npos)
{
pos_after -= 1;
}
return {prefix.substr(pos_before), suffix.substr(0, pos_after)};
}
std::string headline(const std::string_view prefix)