ClangFormat: Format multiple text ranges at once

'reformat' function in LibFormat accepts mutilple ranges.
Let's provide the ranges for the same file together when
formatting on save and formatting after fix-its.

Change-Id: I27789da83a1efc27beb57acf238508a191562bb9
Reviewed-by: Marco Bubke <marco.bubke@qt.io>
This commit is contained in:
Ivan Donchevskii
2019-02-13 14:17:21 +01:00
parent 660cd8da19
commit 9bcc871ece
7 changed files with 129 additions and 117 deletions

View File

@@ -446,46 +446,39 @@ TextEditor::TabSettings CppEditorDocument::tabSettings() const
return indenter()->tabSettings().value_or(TextEditor::TextDocument::tabSettings());
}
static int formatRange(QTextDocument *doc,
TextEditor::Indenter *indenter,
std::pair<int, int> editedRange,
const TextEditor::TabSettings &tabSettings)
{
QTextCursor cursor(doc);
cursor.setPosition(editedRange.first);
cursor.setPosition(editedRange.second, QTextCursor::KeepAnchor);
const int oldBlockCount = doc->blockCount();
indenter->format(cursor, tabSettings);
return doc->blockCount() - oldBlockCount;
}
bool CppEditorDocument::save(QString *errorString, const QString &fileName, bool autoSave)
{
if (indenter()->formatOnSave() && !autoSave) {
QTextCursor cursor(document());
cursor.joinPreviousEditBlock();
auto *layout = qobject_cast<TextEditor::TextDocumentLayout *>(document()->documentLayout());
const int documentRevision = layout->lastSaveRevision;
std::pair<int, int> editedRange;
TextEditor::RangesInLines editedRanges;
TextEditor::RangeInLines lastRange{-1, -1};
for (int i = 0; i < document()->blockCount(); ++i) {
const QTextBlock block = document()->findBlockByNumber(i);
if (block.revision() == documentRevision) {
if (editedRange.first != -1)
i += formatRange(document(), indenter(), editedRange, tabSettings());
if (lastRange.startLine != -1)
editedRanges.push_back(lastRange);
editedRange = std::make_pair(-1, -1);
lastRange.startLine = lastRange.endLine = -1;
continue;
}
// block.revision() != documentRevision
if (editedRange.first == -1)
editedRange.first = block.position();
editedRange.second = block.position() + block.length();
if (lastRange.startLine == -1)
lastRange.startLine = block.blockNumber() + 1;
lastRange.endLine = block.blockNumber() + 1;
}
if (lastRange.startLine != -1)
editedRanges.push_back(lastRange);
if (!editedRanges.empty()) {
QTextCursor cursor(document());
cursor.joinPreviousEditBlock();
indenter()->format(editedRanges);
cursor.endEditBlock();
}
if (editedRange.first != -1)
formatRange(document(), indenter(), editedRange, tabSettings());
cursor.endEditBlock();
}
return TextEditor::TextDocument::save(errorString, fileName, autoSave);