Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qqmlformatting.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
4#include <qqmlformatting_p.h>
5#include <qqmlcodemodel_p.h>
6#include <qqmllsutils_p.h>
7
8#include <QtQmlDom/private/qqmldomitem_p.h>
9#include <QtQmlDom/private/qqmldomindentinglinewriter_p.h>
10#include <QtQmlDom/private/qqmldomoutwriter_p.h>
11
13
14Q_LOGGING_CATEGORY(formatLog, "qt.languageserver.formatting")
15
17 : QQmlBaseModule(codeModel)
18{
19}
20
22{
23 return u"QQmlDocumentFormatting"_s;
24}
25
26void QQmlDocumentFormatting::registerHandlers(QLanguageServer *, QLanguageServerProtocol *protocol)
27{
28 protocol->registerDocumentFormattingRequestHandler(getRequestHandler());
29}
30
32 const QLspSpecification::InitializeParams &,
33 QLspSpecification::InitializeResult &serverCapabilities)
34{
35 // TODO: Allow customized formatting in future
36 serverCapabilities.capabilities.documentFormattingProvider = true;
37}
38
39void QQmlDocumentFormatting::process(RequestPointerArgument request)
40{
41 QList<QLspSpecification::TextEdit> result;
42 ResponseScopeGuard guard(result, request->m_response);
43
44 using namespace QQmlJS::Dom;
46 QQmlLSUtils::lspUriToQmlUrl(request->m_parameters.textDocument.uri));
47
48 DomItem file = doc.snapshot.doc.fileObject(GoTo::MostLikely);
49 if (!file) {
51 0, u"Could not find the file %1"_s.arg(doc.snapshot.doc.canonicalFilePath()) });
52 return;
53 }
54 if (!file.field(Fields::isValid).value().toBool(false)) {
55 guard.setError(QQmlLSUtilsErrorMessage{ 0, u"Cannot format invalid documents!"_s });
56 return;
57 }
58 if (auto envPtr = file.environment().ownerAs<DomEnvironment>())
59 envPtr->clearReferenceCache();
60
61 auto qmlFile = file.ownerAs<QmlFile>();
62 if (!qmlFile || !qmlFile->isValid()) {
63 file.iterateErrors(
64 [](const DomItem &, const ErrorMessage &msg) {
65 errorToQDebug(msg);
66 return true;
67 },
68 true);
70 0, u"Failed to parse %1"_s.arg(file.canonicalFilePath()) });
71 return;
72 }
73
74 // TODO: implement formatting options
75 // For now, qmlformat's default options.
76 LineWriterOptions options;
77 options.updateOptions = LineWriterOptions::Update::None;
78 options.attributesSequence = LineWriterOptions::AttributesSequence::Preserve;
79
80 QLspSpecification::TextEdit formattedText;
81 LineWriter lw([&formattedText](QStringView s) {formattedText.newText += s.toUtf8(); }, QString(), options);
82 OutWriter ow(lw);
83 file.writeOutForFile(ow, WriteOutCheck::None);
84 ow.flush();
85 const auto &code = qmlFile->code();
86 const auto [endLine, endColumn] = QQmlLSUtils::textRowAndColumnFrom(code, code.length());
87
88 Q_UNUSED(endColumn);
89 formattedText.range = QLspSpecification::Range{ QLspSpecification::Position{ 0, 0 },
90 QLspSpecification::Position{ endLine + 1, 0 } };
91
92 result.append(formattedText);
93}
94
bool flush()
Flushes any buffered data to the file.
Implements a server for the language server protocol.
void setupCapabilities(const QLspSpecification::InitializeParams &clientInfo, QLspSpecification::InitializeResult &) override
void process(RequestPointerArgument req) override
void registerHandlers(QLanguageServer *server, QLanguageServerProtocol *protocol) override
QString name() const override
Represents a consistent set of types organized in modules, it is the top level of the DOM.
DomItem fileObject(GoTo option=GoTo::Strict) const
QString canonicalFilePath() const
Represents an error message connected to the dom.
A QmlFile, when loaded in a DomEnvironment that has the DomCreationOption::WithSemanticAnalysis,...
static QByteArray lspUriToQmlUrl(const QByteArray &uri)
static QQmlLSUtilsTextPosition textRowAndColumnFrom(const QString &code, qsizetype offset)
Convert a text position from an offset into (line, column).
\inmodule QtCore
Definition qstringview.h:78
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
qsizetype length() const noexcept
Returns the number of characters in this string.
Definition qstring.h:191
OpenDocumentSnapshot snapshot
OpenDocument openDocumentByUrl(const QByteArray &url)
Combined button and popup list for selecting options.
#define Q_LOGGING_CATEGORY(name,...)
GLdouble s
[6]
Definition qopenglext.h:235
GLuint64EXT * result
[6]
#define Q_UNUSED(x)
QFile file
[0]
QNetworkRequest request(url)
This class sends a result or an error when going out of scope.
void setError(const QQmlLSUtilsErrorMessage &error)