aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/beautifier/clangformat/clangformat.cpp
blob: 8a7d1d8c9ec9cff989fae388a1afd860c810641d (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// Copyright (C) 2016 Lorenz Haas
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

// Tested with version 3.3, 3.4 and 3.4.1

#include "clangformat.h"

#include "../beautifierconstants.h"
#include "../beautifiertool.h"
#include "../beautifiertr.h"
#include "../configurationpanel.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>

#include <texteditor/formattexteditor.h>
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>

#include <utils/algorithm.h>
#include <utils/aspects.h>
#include <utils/fileutils.h>
#include <utils/layoutbuilder.h>
#include <utils/pathchooser.h>

#include <QAction>
#include <QButtonGroup>
#include <QComboBox>
#include <QDateTime>
#include <QGroupBox>
#include <QMenu>
#include <QRadioButton>
#include <QTextBlock>
#include <QXmlStreamWriter>

using namespace TextEditor;
using namespace Utils;

namespace Beautifier::Internal {

const char SETTINGS_NAME[]               = "clangformat";

class ClangFormatSettings : public AbstractSettings
{
public:
    ClangFormatSettings()
        : AbstractSettings(SETTINGS_NAME, ".clang-format")
    {
        command.setDefaultValue("clang-format");
        command.setPromptDialogTitle(BeautifierTool::msgCommandPromptDialogTitle("ClangFormat"));
        command.setLabelText(Tr::tr("ClangFormat command:"));

        usePredefinedStyle.setSettingsKey("usePredefinedStyle");
        usePredefinedStyle.setDefaultValue(true);
        usePredefinedStyle.setLabelPlacement(BoolAspect::LabelPlacement::Compact);
        usePredefinedStyle.setLabelText(Tr::tr("Use predefined style:"));

        predefinedStyle.setSettingsKey("predefinedStyle");
        predefinedStyle.setDisplayStyle(SelectionAspect::DisplayStyle::ComboBox);
        predefinedStyle.addOption("LLVM");
        predefinedStyle.addOption("Google");
        predefinedStyle.addOption("Chromium");
        predefinedStyle.addOption("Mozilla");
        predefinedStyle.addOption("WebKit");
        predefinedStyle.addOption("File");
        predefinedStyle.setDefaultValue("LLVM");

        fallbackStyle.setSettingsKey("fallbackStyle");
        fallbackStyle.setDisplayStyle(SelectionAspect::DisplayStyle::ComboBox);
        fallbackStyle.addOption("Default");
        fallbackStyle.addOption("None");
        fallbackStyle.addOption("LLVM");
        fallbackStyle.addOption("Google");
        fallbackStyle.addOption("Chromium");
        fallbackStyle.addOption("Mozilla");
        fallbackStyle.addOption("WebKit");
        fallbackStyle.setDefaultValue("Default");

        customStyle.setSettingsKey("customStyle");

        documentationFilePath = Core::ICore::userResourcePath(Constants::SETTINGS_DIRNAME)
                                    .pathAppended(Constants::DOCUMENTATION_DIRNAME)
                                    .pathAppended(SETTINGS_NAME).stringAppended(".xml");

        read();
    }

    void createDocumentationFile() const final;

    QStringList completerWords() final;

    BoolAspect usePredefinedStyle{this};
    SelectionAspect predefinedStyle{this};
    SelectionAspect fallbackStyle{this};
    StringAspect customStyle{this};

    Utils::FilePath styleFileName(const QString &key) const final;

private:
    void readStyles() final;
};

void ClangFormatSettings::createDocumentationFile() const
{
    QFile file(documentationFilePath.toFSPathString());
    const QFileInfo fi(file);
    if (!fi.exists())
        fi.dir().mkpath(fi.absolutePath());
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
        return;

    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument("1.0", true);
    stream.writeComment("Created " + QDateTime::currentDateTime().toString(Qt::ISODate));
    stream.writeStartElement(Constants::DOCUMENTATION_XMLROOT);

    const QStringList lines = {
        "BasedOnStyle {string: LLVM, Google, Chromium, Mozilla, WebKit}",
        "AccessModifierOffset {int}",
        "AlignEscapedNewlinesLeft {bool}",
        "AlignTrailingComments {bool}",
        "AllowAllParametersOfDeclarationOnNextLine {bool}",
        "AllowShortFunctionsOnASingleLine {bool}",
        "AllowShortIfStatementsOnASingleLine {bool}",
        "AllowShortLoopsOnASingleLine {bool}",
        "AlwaysBreakBeforeMultilineStrings {bool}",
        "AlwaysBreakTemplateDeclarations {bool}",
        "BinPackParameters {bool}",
        "BreakBeforeBinaryOperators {bool}",
        "BreakBeforeBraces {BraceBreakingStyle: BS_Attach, BS_Linux, BS_Stroustrup, BS_Allman, BS_GNU}",
        "BreakBeforeTernaryOperators {bool}",
        "BreakConstructorInitializersBeforeComma {bool}",
        "ColumnLimit {unsigned}",
        "CommentPragmas {string}",
        "ConstructorInitializerAllOnOneLineOrOnePerLine {bool}",
        "ConstructorInitializerIndentWidth {unsigned}",
        "ContinuationIndentWidth {unsigned}",
        "Cpp11BracedListStyle {bool}",
        "IndentCaseLabels {bool}",
        "IndentFunctionDeclarationAfterType {bool}",
        "IndentWidth {unsigned}",
        "Language {LanguageKind: LK_None, LK_Cpp, LK_JavaScript, LK_Proto}",
        "MaxEmptyLinesToKeep {unsigned}",
        "NamespaceIndentation {NamespaceIndentationKind: NI_None, NI_Inner, NI_All}",
        "ObjCSpaceAfterProperty {bool}",
        "ObjCSpaceBeforeProtocolList {bool}",
        "PenaltyBreakBeforeFirstCallParameter {unsigned}",
        "PenaltyBreakComment {unsigned}",
        "PenaltyBreakFirstLessLess {unsigned}",
        "PenaltyBreakString {unsigned}",
        "PenaltyExcessCharacter {unsigned}",
        "PenaltyReturnTypeOnItsOwnLine {unsigned}",
        "PointerBindsToType {bool}",
        "SpaceBeforeAssignmentOperators {bool}",
        "SpaceBeforeParens {SpaceBeforeParensOptions: SBPO_Never, SBPO_ControlStatements, SBPO_Always}",
        "SpaceInEmptyParentheses {bool}",
        "SpacesBeforeTrailingComments {unsigned}",
        "SpacesInAngles {bool}",
        "SpacesInCStyleCastParentheses {bool}",
        "SpacesInContainerLiterals {bool}",
        "SpacesInParentheses {bool}",
        "Standard {LanguageStandard: LS_Cpp03, LS_Cpp11, LS_Auto}",
        "TabWidth {unsigned}",
        "UseTab {UseTabStyle: UT_Never, UT_ForIndentation, UT_Always}"
    };

    for (const QString& line : lines) {
        const int firstSpace = line.indexOf(' ');
        const QString keyword = line.left(firstSpace);
        const QString options = line.right(line.size() - firstSpace).trimmed();
        const QString text = "<p><span class=\"option\">" + keyword
                + "</span> <span class=\"param\">" + options
                + "</span></p><p>" + Tr::tr("No description available.") + "</p>";
        stream.writeStartElement(Constants::DOCUMENTATION_XMLENTRY);
        stream.writeTextElement(Constants::DOCUMENTATION_XMLKEY, keyword);
        stream.writeTextElement(Constants::DOCUMENTATION_XMLDOC, text);
        stream.writeEndElement();
    }

    stream.writeEndElement();
    stream.writeEndDocument();
}

QStringList ClangFormatSettings::completerWords()
{
    return {
        "LLVM",
        "Google",
        "Chromium",
        "Mozilla",
        "WebKit",
        "BS_Attach",
        "BS_Linux",
        "BS_Stroustrup",
        "BS_Allman",
        "NI_None",
        "NI_Inner",
        "NI_All",
        "LS_Cpp03",
        "LS_Cpp11",
        "LS_Auto",
        "UT_Never",
        "UT_ForIndentation",
        "UT_Always"
    };
}

FilePath ClangFormatSettings::styleFileName(const QString &key) const
{
    return m_styleDir / key / m_ending;
}

void ClangFormatSettings::readStyles()
{
    const FilePaths dirs = m_styleDir.dirEntries(QDir::AllDirs | QDir::NoDotAndDotDot);
    for (const FilePath &dir : dirs) {
        if (auto contents = dir.pathAppended(m_ending).fileContents())
            m_styles.insert(dir.fileName(), QString::fromLocal8Bit(*contents));
    }
}

static ClangFormatSettings &settings()
{
    static ClangFormatSettings theSettings;
    return theSettings;
}

class ClangFormatSettingsPageWidget : public Core::IOptionsPageWidget
{
public:
    ClangFormatSettingsPageWidget()
    {
        ClangFormatSettings &s = settings();
        QGroupBox *options = nullptr;

        auto predefinedStyleButton = new QRadioButton;
        auto customizedStyleButton = new QRadioButton(Tr::tr("Use customized style:"));

        auto styleButtonGroup = new QButtonGroup;
        styleButtonGroup->addButton(predefinedStyleButton);
        styleButtonGroup->addButton(customizedStyleButton);

        auto configurations = new ConfigurationPanel(this);
        configurations->setSettings(&s);
        configurations->setCurrentConfiguration(s.customStyle());

        using namespace Layouting;

        auto fallbackBlob = Row { noMargin, Tr::tr("Fallback style:"), s.fallbackStyle }.emerge();

        auto predefinedBlob = Column { noMargin, s.predefinedStyle, fallbackBlob }.emerge();
        // clang-format off
        Column {
            Group {
                title(Tr::tr("Configuration")),
                Form {
                    s.command, br,
                    s.supportedMimeTypes
                }
            },
            Group {
                title(Tr::tr("Options")),
                bindTo(&options),
                Form {
                    s.usePredefinedStyle.adoptButton(predefinedStyleButton),
                    predefinedBlob, br,
                    customizedStyleButton, configurations,
                },
            },
            st
        }.attachTo(this);
        // clang-format on

        if (s.usePredefinedStyle.value())
            predefinedStyleButton->click();
        else
            customizedStyleButton->click();

        const auto updateEnabled = [&s, styleButtonGroup, predefinedBlob, fallbackBlob,
                                    configurations, predefinedStyleButton] {
            const bool predefSelected = styleButtonGroup->checkedButton() == predefinedStyleButton;
            predefinedBlob->setEnabled(predefSelected);
            fallbackBlob->setEnabled(predefSelected && s.predefinedStyle.volatileValue() == 5); // File
            configurations->setEnabled(!predefSelected);
        };
        updateEnabled();
        connect(styleButtonGroup, &QButtonGroup::buttonClicked, this, updateEnabled);
        connect(&s.predefinedStyle, &SelectionAspect::volatileValueChanged, this, updateEnabled);

        setOnApply([configurations, customizedStyleButton] {
            settings().usePredefinedStyle.setValue(!customizedStyleButton->isChecked());
            settings().customStyle.setValue(configurations->currentConfiguration());
            settings().apply();
            settings().save();
        });
        setOnCancel([] { settings().cancel(); });

        s.read();

        connect(s.command.pathChooser(), &PathChooser::validChanged, options, &QWidget::setEnabled);
        options->setEnabled(s.command.pathChooser()->isValid());
    }
};

// ClangFormat

class ClangFormat final : public BeautifierTool
{
public:
    ClangFormat()
    {
        const Id menuId = "ClangFormat.Menu";
        Core::MenuBuilder(menuId)
            .setTitle(Tr::tr("&ClangFormat"))
            .addToContainer(Constants::MENU_ID);

        Core::ActionBuilder(this, "ClangFormat.FormatFile")
            .setText(msgFormatCurrentFile())
            .bindContextAction(&m_formatFile)
            .addToContainer(menuId)
            .addOnTriggered(this, &ClangFormat::formatFile);

        Core::ActionBuilder(this, "ClangFormat.FormatLines")
            .setText(msgFormatLines())
            .bindContextAction(&m_formatLines)
            .addToContainer(menuId)
            .addOnTriggered(this, &ClangFormat::formatLines);

        Core::ActionBuilder(this, "ClangFormat.FormatAtCursor")
            .setText(msgFormatAtCursor())
            .bindContextAction(&m_formatRange)
            .addToContainer(menuId)
            .addOnTriggered(this, &ClangFormat::formatAtCursor);

        Core::ActionBuilder(this, "ClangFormat.DisableFormattingSelectedText")
            .setText(msgDisableFormattingSelectedText())
            .bindContextAction(&m_disableFormattingSelectedText)
            .addToContainer(menuId)
            .addOnTriggered(this, &ClangFormat::disableFormattingSelectedText);

        settings().supportedMimeTypes.addOnChanged(this, [this] {
            updateActions(Core::EditorManager::currentEditor());
        });
    }

    QString id() const final
    {
        return "ClangFormat";
    }

    void updateActions(Core::IEditor *editor) final
    {
        const bool enabled = editor && settings().isApplicable(editor->document());
        m_formatFile->setEnabled(enabled);
        m_formatRange->setEnabled(enabled);
    }

    TextEditor::Command textCommand() const final;

    bool isApplicable(const Core::IDocument *document) const final
    {
        return settings().isApplicable(document);
    }

private:
    void formatFile();
    void formatAtPosition(const int pos, const int length);
    void formatAtCursor();
    void formatLines();
    void disableFormattingSelectedText();
    TextEditor::Command textCommand(int offset, int length) const;

    QAction *m_formatFile = nullptr;
    QAction *m_formatLines = nullptr;
    QAction *m_formatRange = nullptr;
    QAction *m_disableFormattingSelectedText = nullptr;
};

void ClangFormat::formatFile()
{
    formatCurrentFile(textCommand());
}

void ClangFormat::formatAtPosition(const int pos, const int length)
{
    const TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
    if (!widget)
        return;

    const TextEncoding encoding = widget->textDocument()->encoding();
    if (!encoding.isValid()) {
        formatCurrentFile(textCommand(pos, length));
        return;
    }

    const QString &text = widget->textAt(0, pos + length);
    const QStringView buffer(text);
    QStringEncoder encoder(encoding.name());
    const int encodedOffset = QByteArray(encoder.encode(buffer.left(pos))).size();
    const int encodedLength = QByteArray(encoder.encode(buffer.mid(pos, length))).size();
    formatCurrentFile(textCommand(encodedOffset, encodedLength));
}

void ClangFormat::formatAtCursor()
{
    const TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
    if (!widget)
        return;

    const QTextCursor tc = widget->textCursor();

    if (tc.hasSelection()) {
        const int selectionStart = tc.selectionStart();
        formatAtPosition(selectionStart, tc.selectionEnd() - selectionStart);
    } else {
        // Pretend that the current line was selected.
        // Note that clang-format will extend the range to the next bigger
        // syntactic construct if needed.
        const QTextBlock block = tc.block();
        formatAtPosition(block.position(), block.length());
    }
}

void ClangFormat::formatLines()
{
    const TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
    if (!widget)
        return;

    const QTextCursor tc = widget->textCursor();
    // Current line by default
    int lineStart = tc.blockNumber() + 1;
    int lineEnd = lineStart;

    // Note that clang-format will extend the range to the next bigger
    // syntactic construct if needed.
    if (tc.hasSelection()) {
        const QTextBlock start = tc.document()->findBlock(tc.selectionStart());
        const QTextBlock end = tc.document()->findBlock(tc.selectionEnd());
        lineStart = start.blockNumber() + 1;
        lineEnd = end.blockNumber() + 1;
    }

    auto cmd = textCommand();
    cmd.addOption(QString("-lines=%1:%2").arg(QString::number(lineStart)).arg(QString::number(lineEnd)));
    formatCurrentFile(cmd);
}

void ClangFormat::disableFormattingSelectedText()
{
    TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
    if (!widget)
        return;

    const QTextCursor tc = widget->textCursor();
    if (!tc.hasSelection())
        return;

    // Insert start marker
    const QTextBlock selectionStartBlock = tc.document()->findBlock(tc.selectionStart());
    QTextCursor insertCursor(tc.document());
    insertCursor.beginEditBlock();
    insertCursor.setPosition(selectionStartBlock.position());
    insertCursor.insertText("// clang-format off\n");
    const int positionToRestore = tc.position();

    // Insert end marker
    QTextBlock selectionEndBlock = tc.document()->findBlock(tc.selectionEnd());
    insertCursor.setPosition(selectionEndBlock.position() + selectionEndBlock.length() - 1);
    insertCursor.insertText("\n// clang-format on");
    insertCursor.endEditBlock();

    // Reset the cursor position in order to clear the selection.
    QTextCursor restoreCursor(tc.document());
    restoreCursor.setPosition(positionToRestore);
    widget->setTextCursor(restoreCursor);

    // The indentation of these markers might be undesired, so reformat.
    // This is not optimal because two undo steps will be needed to remove the markers.
    const int reformatTextLength = insertCursor.position() - selectionStartBlock.position();
    formatAtPosition(selectionStartBlock.position(), reformatTextLength);
}

Command ClangFormat::textCommand() const
{
    Command cmd;
    cmd.setExecutable(settings().command());
    cmd.setProcessing(Command::PipeProcessing);

    if (settings().usePredefinedStyle()) {
        const QString predefinedStyle = settings().predefinedStyle.stringValue();
        cmd.addOption("-style=" + predefinedStyle);
        if (predefinedStyle == "File") {
            const QString fallbackStyle = settings().fallbackStyle.stringValue();
            if (fallbackStyle != "Default")
                cmd.addOption("-fallback-style=" + fallbackStyle);
        }

        cmd.addOption("-assume-filename=%file");
    } else {
        cmd.addOption("-style=file");
        const FilePath path = settings().styleFileName(settings().customStyle())
            .absolutePath().pathAppended("%filename");
        cmd.addOption("-assume-filename=" + path.nativePath());
    }

    return cmd;
}

Command ClangFormat::textCommand(int offset, int length) const
{
    Command cmd = textCommand();
    cmd.addOption("-offset=" + QString::number(offset));
    cmd.addOption("-length=" + QString::number(length));
    return cmd;
}

// ClangFormatSettingsPage

class ClangFormatSettingsPage final : public Core::IOptionsPage
{
public:
    ClangFormatSettingsPage()
    {
        setId("ClangFormat");
        setDisplayName(Tr::tr("ClangFormat"));
        setCategory(Constants::OPTION_CATEGORY);
        setWidgetCreator([] { return new ClangFormatSettingsPageWidget; });
    }
};

const ClangFormatSettingsPage settingsPage;

void setupClangFormat()
{
    static ClangFormat theClangFormat;
}

} // Beautifier::Internal