mirror of
https://github.com/NixOS/nix
synced 2025-06-27 08:31:16 +02:00
libutil: Add Pos::getSnippetUpTo(Pos)
This commit is contained in:
parent
63f520fd00
commit
e5af7cbeb9
3 changed files with 168 additions and 0 deletions
|
@ -110,4 +110,50 @@ void Pos::LinesIterator::bump(bool atFirst)
|
|||
input.remove_prefix(eol);
|
||||
}
|
||||
|
||||
std::string Pos::getSnippetUpTo(const Pos & end) const {
|
||||
assert(this->origin == end.origin);
|
||||
|
||||
if (end.line < this->line)
|
||||
return "";
|
||||
|
||||
if (auto source = getSource()) {
|
||||
|
||||
auto firstLine = LinesIterator(*source);
|
||||
for (auto i = 1; i < this->line; ++i) {
|
||||
++firstLine;
|
||||
}
|
||||
|
||||
auto lastLine = LinesIterator(*source);
|
||||
for (auto i = 1; i < end.line; ++i) {
|
||||
++lastLine;
|
||||
}
|
||||
|
||||
LinesIterator linesEnd;
|
||||
|
||||
std::string result;
|
||||
for (auto i = firstLine; i != linesEnd; ++i) {
|
||||
auto firstColumn = i == firstLine ? (this->column ? this->column - 1 : 0) : 0;
|
||||
if (firstColumn > i->size())
|
||||
firstColumn = i->size();
|
||||
|
||||
auto lastColumn = i == lastLine ? (end.column ? end.column - 1 : 0) : std::numeric_limits<int>::max();
|
||||
if (lastColumn < firstColumn)
|
||||
lastColumn = firstColumn;
|
||||
if (lastColumn > i->size())
|
||||
lastColumn = i->size();
|
||||
|
||||
result += i->substr(firstColumn, lastColumn - firstColumn);
|
||||
|
||||
if (i == lastLine) {
|
||||
break;
|
||||
} else {
|
||||
result += '\n';
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue