34 using namespace QQmlJS::Dom;
35 QList<QLspSpecification::TextEdit> result{};
38 QQmlLSUtils::lspUriToQmlUrl(request->m_parameters.textDocument.uri));
40 DomItem file = doc.snapshot.doc.fileObject(GoTo::MostLikely);
42 qWarning() << u"Could not find the file"_s << doc.snapshot.doc.toString();
46 if (
auto envPtr = file.environment().ownerAs<DomEnvironment>())
47 envPtr->clearReferenceCache();
49 auto qmlFile = file.ownerAs<QmlFile>();
50 auto code = qmlFile->code();
53 const auto selectedRange = request->m_parameters.range;
54 const auto selectedRangeStartLine = selectedRange.start.line;
55 const auto selectedRangeEndLine = selectedRange.end.line;
57 LineWriterOptions options;
58 options.attributesSequence = LineWriterOptions::AttributesSequence::Preserve;
60 QTextStream in(&code);
61 FormatTextStatus status = FormatTextStatus::initialStatus();
62 FormatPartialStatus partialStatus({}, options.formatOptions, status);
65 unsigned lineNumber = 0;
67 const auto line = in.readLine();
68 partialStatus = formatCodeLine(line, options.formatOptions, partialStatus.currentStatus);
69 if (++lineNumber >= selectedRangeStartLine)
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;
82 const auto removeSpaces = [](
const QString &line) {
84 QTextStream out(&result);
85 bool previousIsSpace =
false;
88 for (
int i = 0; i < line.length(); ++i) {
91 if (c ==
'\n'_L1 && newLineCount < 2) {
94 }
else if (c ==
'\r'_L1 && (i + 1) < line.length() && line.at(i + 1) ==
'\n'_L1
95 && newLineCount < 2) {
100 if (!previousIsSpace)
103 previousIsSpace =
true;
106 previousIsSpace =
false;
115 const auto startOffset = QQmlLSUtils::textOffsetFrom(code, selectedRangeStartLine, 0);
116 auto endOffset = QQmlLSUtils::textOffsetFrom(code, selectedRangeEndLine + 1, 0);
120 if (endOffset < code.size() && code[endOffset - 1] == u'\r' && code[endOffset] == u'\n')
123 const auto &toFormat = code.mid(startOffset, endOffset - startOffset);
124 ow.write(removeSpaces(toFormat));
128 const auto documentLineCount = QQmlLSUtils::textRowAndColumnFrom(code, code.length()).line;
129 code.replace(startOffset, toFormat.length(), resultText);
131 QLspSpecification::TextEdit add;
132 add.newText = code.toUtf8();
133 add.range = { { 0, 0 }, { documentLineCount + 1u } };
136 request->m_response.sendResponse(result);