aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/texteditor/jsoneditor.cpp
blob: 7081394f9be9fd6f1dac28392b3a5c084ed38a09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "jsoneditor.h"

#include "autocompleter.h"
#include "textdocument.h"
#include "texteditor.h"
#include "texteditortr.h"
#include "textindenter.h"

#include <utils/mimeconstants.h>

namespace TextEditor::Internal {

const char JSON_EDITOR_ID[] = "Editors.Json";

static int startsWith(const QString &line, const QString &closingChars)
{
    int count = 0;
    for (const QChar &lineChar : line) {
        if (closingChars.contains(lineChar))
            ++count;
        else if (!lineChar.isSpace())
            break;
    }
    return count;
}

class JsonAutoCompleter : public AutoCompleter
{
    bool contextAllowsElectricCharacters(const QTextCursor &cursor) const override
    {
        return !isInString(cursor);
    }

    bool contextAllowsAutoBrackets(const QTextCursor &cursor, const QString &) const override
    {
        return !isInString(cursor);
    }
    QString insertMatchingBrace(const QTextCursor &cursor,
                                const QString &text,
                                QChar lookAhead,
                                bool skipChars,
                                int *skippedChars) const override
    {
        Q_UNUSED(cursor)
        if (text.isEmpty())
            return QString();
        const QChar current = text.at(0);
        switch (current.unicode()) {
        case '{':
            return QStringLiteral("}");
        case '[':
            return QStringLiteral("]");
        case ']':
        case '}':
            if (current == lookAhead && skipChars)
                ++*skippedChars;
            break;
        default:
            break;
        }

        return QString();
    }

    bool contextAllowsAutoQuotes(const QTextCursor &cursor, const QString &) const override
    {
        return !isInString(cursor);
    }
    QString insertMatchingQuote(const QTextCursor &cursor,
                                const QString &text,
                                QChar lookAhead,
                                bool skipChars,
                                int *skippedChars) const override
    {
        Q_UNUSED(cursor)
        static const QChar quote('"');
        if (text.isEmpty() || text != quote)
            return QString();
        if (lookAhead == quote && skipChars) {
            ++*skippedChars;
            return QString();
        }
        return quote;
    }

    bool isInString(const QTextCursor &cursor) const override
    {
        bool result = false;
        const QString text = cursor.block().text();
        const int position = qMin(cursor.positionInBlock(), text.size());

        for (int i = 0; i < position; ++i) {
            if (text.at(i) == '"') {
                if (!result || text[i - 1] != '\\')
                    result = !result;
            }
        }
        return result;
    }
};

class JsonIndenter : public TextIndenter
{
public:
    JsonIndenter(QTextDocument *doc) : TextIndenter(doc) {}

    bool isElectricCharacter(const QChar &c) const override
    {
        static QString echars("{}[]");
        return echars.contains(c);
    }

    int indentFor(const QTextBlock &block,
                  const TabSettings &tabSettings,
                  int /*cursorPositionInEditor*/) override
    {
        QTextBlock previous = block.previous();
        if (!previous.isValid())
            return 0;

        QString previousText = previous.text();
        while (previousText.trimmed().isEmpty()) {
            previous = previous.previous();
            if (!previous.isValid())
                return 0;
            previousText = previous.text();
        }

        int indent = tabSettings.indentationColumn(previousText);

        int adjust = previousText.count('{') + previousText.count('[');
        adjust -= previousText.count('}') + previousText.count(']');
        adjust += startsWith(previousText, "}]") - startsWith(block.text(), "}]");
        adjust *= tabSettings.m_indentSize;

        return qMax(0, indent + adjust);
    }

    void indentBlock(const QTextBlock &block,
                     const QChar &typedChar,
                     const TabSettings &tabSettings,
                     int cursorPositionInEditor) override
    {
        Q_UNUSED(typedChar)
        tabSettings.indentLine(block, indentFor(block, tabSettings, cursorPositionInEditor));
    }
};

class JsonEditorFactory final : public TextEditorFactory
{
public:
    JsonEditorFactory()
    {
        setId(JSON_EDITOR_ID);
        setDisplayName(Tr::tr("JSON Editor"));
        addMimeType(Utils::Constants::JSON_MIMETYPE);

        setEditorCreator([] { return new BaseTextEditor; });
        setEditorWidgetCreator([] { return new TextEditorWidget; });
        setDocumentCreator([] { return new TextDocument(JSON_EDITOR_ID); });
        setAutoCompleterCreator([] { return new JsonAutoCompleter; });
        setIndenterCreator([](QTextDocument *doc) { return new JsonIndenter(doc); });
        setOptionalActionMask(OptionalActions::Format);
        setUseGenericHighlighter(true);
    }
};

void setupJsonEditor()
{
    static JsonEditorFactory theJsonEditorFactory;
}

} // TextEditor::Internal