clang-format: Make moving of the Cursor work properly when sorting #includes.
llvm-svn: 253860
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2a7b9ac..0b6c9f5 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1706,7 +1706,7 @@
static void sortIncludes(const FormatStyle &Style,
const SmallVectorImpl<IncludeDirective> &Includes,
ArrayRef<tooling::Range> Ranges, StringRef FileName,
- tooling::Replacements &Replaces) {
+ tooling::Replacements &Replaces, unsigned *Cursor) {
if (!affectsRange(Ranges, Includes.front().Offset,
Includes.back().Offset + Includes.back().Text.size()))
return;
@@ -1730,10 +1730,21 @@
if (!OutOfOrder)
return;
- std::string result = Includes[Indices[0]].Text;
- for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
- result += "\n";
- result += Includes[Indices[i]].Text;
+ std::string result;
+ bool CursorMoved = false;
+ for (unsigned Index : Indices) {
+ if (!result.empty())
+ result += "\n";
+ result += Includes[Index].Text;
+
+ if (Cursor && !CursorMoved) {
+ unsigned Start = Includes[Index].Offset;
+ unsigned End = Start + Includes[Index].Text.size();
+ if (*Cursor >= Start && *Cursor < End) {
+ *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
+ CursorMoved = true;
+ }
+ }
}
// Sorting #includes shouldn't change their total number of characters.
@@ -1748,7 +1759,7 @@
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
ArrayRef<tooling::Range> Ranges,
- StringRef FileName) {
+ StringRef FileName, unsigned *Cursor) {
tooling::Replacements Replaces;
if (!Style.SortIncludes)
return Replaces;
@@ -1811,7 +1822,8 @@
LookForMainHeader = false;
IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
} else if (!IncludesInBlock.empty()) {
- sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
+ sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
+ Cursor);
IncludesInBlock.clear();
}
Prev = Pos + 1;
@@ -1821,7 +1833,7 @@
SearchFrom = Pos + 1;
}
if (!IncludesInBlock.empty())
- sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces);
+ sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
return Replaces;
}