Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlrangeformatting.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <qqmlrangeformatting_p.h>
6#include <qqmlcodemodel_p.h>
7#include <qqmllsutils_p.h>
8
9#include <QtQmlDom/private/qqmldomitem_p.h>
10#include <QtQmlDom/private/qqmldomindentinglinewriter_p.h>
11#include <QtQmlDom/private/qqmldomcodeformatter_p.h>
12#include <QtQmlDom/private/qqmldomoutwriter_p.h>
13#include <QtQmlDom/private/qqmldomcompare_p.h>
14
16
17QQmlRangeFormatting::QQmlRangeFormatting(QmlLsp::QQmlCodeModelManager *codeModelManager)
18 : QQmlBaseModule(codeModelManager)
19{
20}
21
22void QQmlRangeFormatting::registerHandlers(QLanguageServer *, QLanguageServerProtocol *protocol)
23{
24 protocol->registerDocumentRangeFormattingRequestHandler(getRequestHandler());
25}
26
27void QQmlRangeFormatting::setupCapabilities(QLspSpecification::ServerCapabilities &caps)
28{
29 caps.documentRangeFormattingProvider = true;
30}
31
32void QQmlRangeFormatting::process(RequestPointerArgument request)
33{
34 using namespace QQmlJS::Dom;
35 QList<QLspSpecification::TextEdit> result{};
36
37 QmlLsp::OpenDocument doc = m_codeModelManager->openDocumentByUrl(
38 QQmlLSUtils::lspUriToQmlUrl(request->m_parameters.textDocument.uri));
39
40 DomItem file = doc.snapshot.doc.fileObject(GoTo::MostLikely);
41 if (!file) {
42 qWarning() << u"Could not find the file"_s << doc.snapshot.doc.toString();
43 return;
44 }
45
46 if (auto envPtr = file.environment().ownerAs<DomEnvironment>())
47 envPtr->clearReferenceCache();
48
49 auto qmlFile = file.ownerAs<QmlFile>();
50 auto code = qmlFile->code();
51
52 // Range requested to be formatted
53 const auto selectedRange = request->m_parameters.range;
54 const auto selectedRangeStartLine = selectedRange.start.line;
55 const auto selectedRangeEndLine = selectedRange.end.line;
56
57 LineWriterOptions options;
58 options.attributesSequence = LineWriterOptions::AttributesSequence::Preserve;
59
60 QTextStream in(&code);
61 FormatTextStatus status = FormatTextStatus::initialStatus();
62 FormatPartialStatus partialStatus({}, options.formatOptions, status);
63
64 // Get the token status of the previous line without performing write operation
65 unsigned lineNumber = 0;
66 while (!in.atEnd()) {
67 const auto line = in.readLine();
68 partialStatus = formatCodeLine(line, options.formatOptions, partialStatus.currentStatus);
69 if (++lineNumber >= selectedRangeStartLine)
70 break;
71 }
72
73 QString resultText;
74 QTextStream out(&resultText);
75 IndentingLineWriter lw([&out](QStringView writtenText) { out << writtenText.toUtf8(); },
76 QString(), options, partialStatus.currentStatus);
77 OutWriter ow(qmlFile, lw);
78 ow.indentNextlines = true;
79
80 // TODO: This is a workaround and will/should be handled by the actual formatter
81 // once we improve the range-formatter design in QTBUG-116139
82 const auto removeSpaces = [](const QString &line) {
83 QString result;
84 QTextStream out(&result);
85 bool previousIsSpace = false;
86
87 int newLineCount = 0;
88 for (int i = 0; i < line.length(); ++i) {
89 QChar c = line.at(i);
90 if (c.isSpace()) {
91 if (c == '\n'_L1 && newLineCount < 2) {
92 out << '\n'_L1;
93 ++newLineCount;
94 } else if (c == '\r'_L1 && (i + 1) < line.length() && line.at(i + 1) == '\n'_L1
95 && newLineCount < 2) {
96 out << "\r\n";
97 ++newLineCount;
98 ++i;
99 } else {
100 if (!previousIsSpace)
101 out << ' '_L1;
102 }
103 previousIsSpace = true;
104 } else {
105 out << c;
106 previousIsSpace = false;
107 newLineCount = 0;
108 }
109 }
110
111 out.flush();
112 return result;
113 };
114
115 const auto startOffset = QQmlLSUtils::textOffsetFrom(code, selectedRangeStartLine, 0);
116 auto endOffset = QQmlLSUtils::textOffsetFrom(code, selectedRangeEndLine + 1, 0);
117
118 // note: the character at endOffset (usually a \n) is ignored. Therefore avoid
119 // formatting \r\n that will ignore \n and format \r as a space (' ').
120 if (endOffset < code.size() && code[endOffset - 1] == u'\r' && code[endOffset] == u'\n')
121 --endOffset;
122
123 const auto &toFormat = code.mid(startOffset, endOffset - startOffset);
124 ow.write(removeSpaces(toFormat));
125 ow.flush();
126 ow.eof();
127
128 const auto documentLineCount = QQmlLSUtils::textRowAndColumnFrom(code, code.length()).line;
129 code.replace(startOffset, toFormat.length(), resultText);
130
131 QLspSpecification::TextEdit add;
132 add.newText = code.toUtf8();
133 add.range = { { 0, 0 }, { documentLineCount + 1u } };
134 result.append(add);
135
136 request->m_response.sendResponse(result);
137}
138
139QT_END_NAMESPACE
void setupCapabilities(QLspSpecification::ServerCapabilities &caps) override
void process(RequestPointerArgument req) override
void registerHandlers(QLanguageServer *server, QLanguageServerProtocol *protocol) override
Combined button and popup list for selecting options.