fakevimplugin.cpp 63.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
hjk's avatar
hjk committed
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
hjk's avatar
hjk committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
hjk's avatar
hjk committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
hjk's avatar
hjk committed
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29
30
31

#include "fakevimplugin.h"

32
#include "fakevimhandler.h"
hjk's avatar
hjk committed
33
34
#include "ui_fakevimoptions.h"

35
#include <coreplugin/actionmanager/actioncontainer.h>
36
#include <coreplugin/actionmanager/actionmanager.h>
37
38
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/command.h>
39
#include <coreplugin/actionmanager/commandmappings.h>
hjk's avatar
hjk committed
40
#include <coreplugin/coreconstants.h>
41
#include <coreplugin/dialogs/ioptionspage.h>
hjk's avatar
hjk committed
42
#include <coreplugin/editormanager/editormanager.h>
43
#include <coreplugin/editormanager/openeditorsmodel.h>
44
#include <coreplugin/documentmanager.h>
hjk's avatar
hjk committed
45
#include <coreplugin/icore.h>
46
#include <coreplugin/idocument.h>
hjk's avatar
hjk committed
47
#include <coreplugin/messagemanager.h>
48
#include <coreplugin/id.h>
49
50
#include <coreplugin/statusbarwidget.h>
#include <coreplugin/statusbarmanager.h>
hjk's avatar
hjk committed
51
52
53

#include <projectexplorer/projectexplorerconstants.h>

54
#include <texteditor/basetextdocumentlayout.h>
hjk's avatar
hjk committed
55
56
57
#include <texteditor/basetexteditor.h>
#include <texteditor/basetextmark.h>
#include <texteditor/texteditorconstants.h>
Jarek Kobus's avatar
Jarek Kobus committed
58
#include <texteditor/typingsettings.h>
59
#include <texteditor/tabsettings.h>
Jarek Kobus's avatar
Jarek Kobus committed
60
#include <texteditor/icodestylepreferences.h>
61
#include <texteditor/texteditorsettings.h>
62
#include <texteditor/indenter.h>
Leandro Melo's avatar
Leandro Melo committed
63
64
65
66
67
68
#include <texteditor/codeassist/basicproposalitem.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/completionassistprovider.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/codeassist/iassistinterface.h>
#include <texteditor/codeassist/genericproposal.h>
hjk's avatar
hjk committed
69

70
#include <find/findplugin.h>
71
#include <find/textfindconstants.h>
72
#include <find/ifindsupport.h>
73

hjk's avatar
hjk committed
74
#include <utils/qtcassert.h>
hjk's avatar
hjk committed
75
#include <utils/savedaction.h>
76
#include <utils/treewidgetcolumnstretcher.h>
77
#include <utils/stylehelper.h>
hjk's avatar
hjk committed
78

79
80
#include <cpptools/cpptoolsconstants.h>

Lukas Holecek's avatar
Lukas Holecek committed
81
82
#include <extensionsystem/pluginmanager.h>

83
84
85
86
87
88
#include <QAbstractTableModel>
#include <QDebug>
#include <QFile>
#include <QtPlugin>
#include <QObject>
#include <QSettings>
89
#include <QStackedWidget>
90
#include <QTextStream>
hjk's avatar
hjk committed
91

92
93
94
95
96
97
98
99
100
#include <QDesktopServices>
#include <QItemDelegate>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QShortcut>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextEdit>
#include <QTreeWidgetItem>
hjk's avatar
hjk committed
101
102
103
104
105

using namespace TextEditor;
using namespace Core;

namespace FakeVim {
hjk's avatar
hjk committed
106
namespace Internal {
hjk's avatar
hjk committed
107

hjk's avatar
hjk committed
108
109
110
111
112
113
const char INSTALL_HANDLER[]                = "TextEditor.FakeVimHandler";
const char SETTINGS_CATEGORY[]              = "D.FakeVim";
const char SETTINGS_CATEGORY_FAKEVIM_ICON[] = ":/core/images/category_fakevim.png";
const char SETTINGS_ID[]                    = "A.General";
const char SETTINGS_EX_CMDS_ID[]            = "B.ExCommands";
const char SETTINGS_USER_CMDS_ID[]          = "C.UserCommands";
hjk's avatar
hjk committed
114

115
class MiniBuffer : public QStackedWidget
116
117
118
119
{
    Q_OBJECT

public:
120
    MiniBuffer() : m_label(new QLabel(this)), m_edit(new QLineEdit(this)), m_eventFilter(0)
121
    {
122
123
124
125
126
127
128
        m_edit->installEventFilter(this);
        connect(m_edit, SIGNAL(textEdited(QString)), SLOT(changed()));
        connect(m_edit, SIGNAL(cursorPositionChanged(int,int)), SLOT(changed()));
        m_label->setTextInteractionFlags(Qt::TextSelectableByMouse);

        addWidget(m_label);
        addWidget(m_edit);
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
    void setContents(const QString &contents, int cursorPos, int messageLevel, QObject *eventFilter)
    {
        if (cursorPos != -1) {
            m_edit->blockSignals(true);
            m_label->clear();
            m_edit->setText(contents);
            m_edit->setCursorPosition(cursorPos);
            m_edit->blockSignals(false);

            setCurrentWidget(m_edit);
            m_edit->setFocus();
        } else {
            m_label->setText(messageLevel == MessageMode ? "-- " + contents + " --" : contents);

            QString css;
            if (messageLevel == MessageError) {
                css = QString("border:1px solid rgba(255,255,255,150);"
                              "background-color:rgba(255,0,0,100);");
            } else if (messageLevel == MessageWarning) {
                css = QString("border:1px solid rgba(255,255,255,120);"
                              "background-color:rgba(255,255,0,20);");
            }
            m_label->setStyleSheet(QString(
                "*{border-radius:2px;padding-left:4px;padding-right:4px;%1}").arg(css));
155

156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
            if (m_edit->hasFocus())
                emit edited(QString(), -1);

            setCurrentWidget(m_label);
        }

        if (m_eventFilter != eventFilter) {
            if (m_eventFilter != 0) {
                m_edit->removeEventFilter(m_eventFilter);
                disconnect(SIGNAL(edited(QString,int)));
            }
            if (eventFilter != 0) {
                m_edit->installEventFilter(eventFilter);
                connect(this, SIGNAL(edited(QString,int)),
                        eventFilter, SLOT(miniBufferTextEdited(QString,int)));
            }
            m_eventFilter = eventFilter;
        }
    }

    QSize sizeHint() const
177
    {
178
179
180
        QSize size = QWidget::sizeHint();
        // reserve maximal width for line edit widget
        return currentWidget() == m_edit ? QSize(maximumWidth(), size.height()) : size;
181
    }
182
183
184
185
186
187

signals:
    void edited(const QString &text, int cursorPos);

private slots:
    void changed()
188
    {
189
        emit edited(m_edit->text(), m_edit->cursorPosition());
190
    }
191
192

    bool eventFilter(QObject *ob, QEvent *ev)
193
    {
194
195
196
197
198
199
200
201
        // cancel editing on escape
        if (m_eventFilter != 0 && ob == m_edit && ev->type() == QEvent::ShortcutOverride
            && static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Escape) {
            emit edited(QString(), -1);
            ev->accept();
            return true;
        }
        return false;
202
    }
203
204
205
206
207

private:
    QLabel *m_label;
    QLineEdit *m_edit;
    QObject *m_eventFilter;
208
209
};

hjk's avatar
hjk committed
210
211
212
213
214
215
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

216
217
typedef QMap<QString, QRegExp> ExCommandMap;
typedef QMap<int, QString> UserCommandMap;
hjk's avatar
hjk committed
218
typedef QLatin1String _;
219

hjk's avatar
hjk committed
220
class FakeVimOptionPage : public IOptionsPage
hjk's avatar
hjk committed
221
222
223
224
{
    Q_OBJECT

public:
225
226
    FakeVimOptionPage()
    {
hjk's avatar
hjk committed
227
        setId(_(SETTINGS_ID));
228
        setDisplayName(tr("General"));
hjk's avatar
hjk committed
229
        setCategory(_(SETTINGS_CATEGORY));
230
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
231
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
232
    }
hjk's avatar
hjk committed
233
234

    QWidget *createPage(QWidget *parent);
hjk's avatar
hjk committed
235
    void apply() { m_group.apply(ICore::settings()); }
hjk's avatar
hjk committed
236
    void finish() { m_group.finish(); }
237
    virtual bool matches(const QString &) const;
hjk's avatar
hjk committed
238
239
240
241
242
243
244
245
246

private slots:
    void copyTextEditorSettings();
    void setQtStyle();
    void setPlainStyle();

private:
    friend class DebuggerPlugin;
    Ui::FakeVimOptionPage m_ui;
247
    QString m_searchKeywords;
248
    Utils::SavedActionSet m_group;
hjk's avatar
hjk committed
249
250
251
252
253
254
255
256
};

QWidget *FakeVimOptionPage::createPage(QWidget *parent)
{
    QWidget *w = new QWidget(parent);
    m_ui.setupUi(w);

    m_group.clear();
257
    m_group.insert(theFakeVimSetting(ConfigUseFakeVim),
258
        m_ui.checkBoxUseFakeVim);
259
260
    m_group.insert(theFakeVimSetting(ConfigReadVimRc),
        m_ui.checkBoxReadVimRc);
hjk's avatar
hjk committed
261

262
    m_group.insert(theFakeVimSetting(ConfigExpandTab),
hjk's avatar
hjk committed
263
        m_ui.checkBoxExpandTab);
264
    m_group.insert(theFakeVimSetting(ConfigHlSearch),
hjk's avatar
hjk committed
265
        m_ui.checkBoxHlSearch);
266
    m_group.insert(theFakeVimSetting(ConfigShiftWidth),
267
        m_ui.spinBoxShiftWidth);
268
269
    m_group.insert(theFakeVimSetting(ConfigShowMarks),
        m_ui.checkBoxShowMarks);
hjk's avatar
hjk committed
270

271
    m_group.insert(theFakeVimSetting(ConfigSmartTab),
hjk's avatar
hjk committed
272
        m_ui.checkBoxSmartTab);
273
    m_group.insert(theFakeVimSetting(ConfigStartOfLine),
hjk's avatar
hjk committed
274
        m_ui.checkBoxStartOfLine);
275
    m_group.insert(theFakeVimSetting(ConfigTabStop),
276
        m_ui.spinBoxTabStop);
277
    m_group.insert(theFakeVimSetting(ConfigBackspace),
hjk's avatar
hjk committed
278
        m_ui.lineEditBackspace);
279
280
    m_group.insert(theFakeVimSetting(ConfigIsKeyword),
        m_ui.lineEditIsKeyword);
hjk's avatar
hjk committed
281

282
283
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
284
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
285
        m_ui.checkBoxAutoIndent);
286
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
287
        m_ui.checkBoxSmartIndent);
Lukas Holecek's avatar
Lukas Holecek committed
288

289
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
290
        m_ui.checkBoxIncSearch);
291
292
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
293
294
    m_group.insert(theFakeVimSetting(ConfigSmartCase),
        m_ui.checkBoxSmartCase);
Lukas Holecek's avatar
Lukas Holecek committed
295
296
    m_group.insert(theFakeVimSetting(ConfigWrapScan),
        m_ui.checkBoxWrapScan);
hjk's avatar
hjk committed
297
298

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
299
        SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
300
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
301
        SLOT(setQtStyle()));
hjk's avatar
hjk committed
302
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
303
304
        SLOT(setPlainStyle()));

305
    if (m_searchKeywords.isEmpty()) {
306
        QLatin1Char sep(' ');
307
        QTextStream(&m_searchKeywords)
308
309
310
311
312
313
314
315
316
317
                << sep << m_ui.checkBoxUseFakeVim->text()
                << sep << m_ui.checkBoxReadVimRc->text()
                << sep << m_ui.checkBoxAutoIndent->text()
                << sep << m_ui.checkBoxSmartIndent->text()
                << sep << m_ui.checkBoxExpandTab->text()
                << sep << m_ui.checkBoxSmartTab->text()
                << sep << m_ui.checkBoxHlSearch->text()
                << sep << m_ui.checkBoxIncSearch->text()
                << sep << m_ui.checkBoxStartOfLine->text()
                << sep << m_ui.checkBoxUseCoreSearch->text()
318
                << sep << m_ui.checkBoxSmartCase->text()
319
320
321
322
323
324
                << sep << m_ui.checkBoxShowMarks->text()
                << sep << m_ui.checkBoxPassControlKey->text()
                << sep << m_ui.labelShiftWidth->text()
                << sep << m_ui.labelTabulator->text()
                << sep << m_ui.labelBackspace->text()
                << sep << m_ui.labelIsKeyword->text();
325
326
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
327
328
329
330
331
    return w;
}

void FakeVimOptionPage::copyTextEditorSettings()
{
Jarek Kobus's avatar
Jarek Kobus committed
332
333
334
    TabSettings ts = TextEditorSettings::instance()->codeStyle()->tabSettings();
    TypingSettings tps = TextEditorSettings::instance()->typingSettings();
    m_ui.checkBoxExpandTab->setChecked(ts.m_tabPolicy != TabSettings::TabsOnlyTabPolicy);
335
336
    m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
    m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
337
    m_ui.checkBoxSmartTab->setChecked(
Jarek Kobus's avatar
Jarek Kobus committed
338
        tps.m_smartBackspaceBehavior == TypingSettings::BackspaceFollowsPreviousIndents);
339
    m_ui.checkBoxAutoIndent->setChecked(true);
Jarek Kobus's avatar
Jarek Kobus committed
340
    m_ui.checkBoxSmartIndent->setChecked(tps.m_autoIndent);
341
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
342
343
344
345
346
}

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
347
348
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
349
350
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
351
    m_ui.checkBoxSmartIndent->setChecked(true);
352
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
353
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
354
355
356
357
358
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
359
360
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
361
362
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
363
    m_ui.checkBoxSmartIndent->setChecked(false);
364
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
365
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
366
367
}

368
369
370
371
372
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

373
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
374

375
376
377
378
379
380
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

381
enum { CommandRole = Qt::UserRole };
382

hjk's avatar
hjk committed
383
class FakeVimExCommandsPage : public CommandMappings
384
385
386
387
{
    Q_OBJECT

public:
388
389
390
    FakeVimExCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
391
        setId(_(SETTINGS_EX_CMDS_ID));
392
        setDisplayName(tr("Ex Command Mapping"));
hjk's avatar
hjk committed
393
        setCategory(_(SETTINGS_CATEGORY));
394
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
395
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
396
    }
397
398
399

    QWidget *createPage(QWidget *parent);
    void initialize();
400
401
    ExCommandMap &exCommandMap();
    ExCommandMap &defaultExCommandMap();
402
403
404

public slots:
    void commandChanged(QTreeWidgetItem *current);
405
406
407
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
408
409
410
    void defaultAction();

private:
411
    FakeVimPluginPrivate *m_q;
412
413
414
415
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
416
417
418
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
419
    setTargetLabelText(tr("Regular expression:"));
420
421
    setTargetEditTitle(tr("Ex Command"));
    setImportExportEnabled(false);
422
423
424
425
426
    return w;
}

void FakeVimExCommandsPage::initialize()
{
427
428
    QMap<QString, QTreeWidgetItem *> sections;

hjk's avatar
hjk committed
429
    foreach (Command *c, ActionManager::commands()) {
430
431
432
        if (c->action() && c->action()->isSeparator())
            continue;

433
        QTreeWidgetItem *item = new QTreeWidgetItem;
434
        const QString name = c->id().toString();
435
436
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
437
        const QString subId = name.mid(pos + 1);
438
        item->setData(0, CommandRole, name);
439
440

        if (!sections.contains(section)) {
441
442
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
443
444
445
446
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
447
            commandList()->expandItem(categoryItem);
448
449
450
451
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
452
        item->setText(1, c->description());
453

454
455
456
457
        QString regex;
        if (exCommandMap().contains(name))
            regex = exCommandMap()[name].pattern();
        item->setText(2, regex);
458

459
        if (regex != defaultExCommandMap()[name].pattern())
460
            setModified(item, true);
461
462
463
464
465
466
467
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
468
    CommandMappings::commandChanged(current);
469
470
    if (current)
        targetEdit()->setText(current->text(2));
471
472
}

473
void FakeVimExCommandsPage::targetIdentifierChanged()
474
{
475
    QTreeWidgetItem *current = commandList()->currentItem();
476
477
478
    if (!current)
        return;

479
    const QString name =  current->data(0, CommandRole).toString();
480
    const QString regex = targetEdit()->text();
481
482

    if (current->data(0, Qt::UserRole).isValid()) {
483
484
        current->setText(2, regex);
        exCommandMap()[name] = QRegExp(regex);
485
    }
486

487
    setModified(current, regex != defaultExCommandMap()[name].pattern());
488
489
}

490
void FakeVimExCommandsPage::resetTargetIdentifier()
491
{
492
    QTreeWidgetItem *current = commandList()->currentItem();
493
494
    if (!current)
        return;
495
    const QString name = current->data(0, CommandRole).toString();
496
497
498
499
    QString regex;
    if (defaultExCommandMap().contains(name))
        regex = defaultExCommandMap()[name].pattern();
    targetEdit()->setText(regex);
500
501
}

502
void FakeVimExCommandsPage::removeTargetIdentifier()
503
{
504
    targetEdit()->clear();
505
506
507
508
}

void FakeVimExCommandsPage::defaultAction()
{
hjk's avatar
hjk committed
509
510
511
512
513
514
    int n = commandList()->topLevelItemCount();
    for (int i = 0; i != n; ++i) {
        QTreeWidgetItem *section = commandList()->topLevelItem(i);
        int m = section->childCount();
        for (int j = 0; j != m; ++j) {
            QTreeWidgetItem *item = section->child(j);
515
            const QString name = item->data(0, CommandRole).toString();
hjk's avatar
hjk committed
516
517
518
519
520
521
522
523
            QString regex;
            if (defaultExCommandMap().contains(name))
                regex = defaultExCommandMap()[name].pattern();
            setModified(item, false);
            item->setText(2, regex);
            if (item == commandList()->currentItem())
                commandChanged(item);
        }
524
525
526
    }
}

527
528
529
530
531
532
533
534
///////////////////////////////////////////////////////////////////////
//
// FakeVimUserCommandsPage
//
///////////////////////////////////////////////////////////////////////

class FakeVimUserCommandsModel : public QAbstractTableModel
{
Friedemann Kleint's avatar
Friedemann Kleint committed
535
    Q_OBJECT
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
public:
    FakeVimUserCommandsModel(FakeVimPluginPrivate *q) : m_q(q) {}
    ~FakeVimUserCommandsModel() {}

    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index, int role) const;
    bool setData(const QModelIndex &index, const QVariant &data, int role);
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;
    Qt::ItemFlags flags(const QModelIndex &index) const;

private:
    FakeVimPluginPrivate *m_q;
};

int FakeVimUserCommandsModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : 9;
}

int FakeVimUserCommandsModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : 2;
}


QVariant FakeVimUserCommandsModel::headerData(int section,
    Qt::Orientation orient, int role) const
{
    if (orient == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
            case 0: return tr("Action");
            case 1: return tr("Command");
        };
    }
    return QVariant();
}

Qt::ItemFlags FakeVimUserCommandsModel::flags(const QModelIndex &index) const
{
    if (index.column() == 1)
        return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
    return QAbstractTableModel::flags(index);
}

class FakeVimUserCommandsDelegate : public QItemDelegate
{
public:
    explicit FakeVimUserCommandsDelegate(QObject *parent)
        : QItemDelegate(parent)
    {}

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &,
        const QModelIndex &) const
    {
        QLineEdit *lineEdit = new QLineEdit(parent);
        lineEdit->setFrame(false);
        return lineEdit;
    }

    void setModelData(QWidget *editor, QAbstractItemModel *model,
                      const QModelIndex &index) const
    {
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        QTC_ASSERT(lineEdit, return);
        model->setData(index, lineEdit->text(), Qt::EditRole);
    }
};

hjk's avatar
hjk committed
605
class FakeVimUserCommandsPage : public IOptionsPage
606
607
608
609
{
    Q_OBJECT

public:
610
611
612
    FakeVimUserCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
613
        setId(_(SETTINGS_USER_CMDS_ID));
614
        setDisplayName(tr("User Command Mapping"));
hjk's avatar
hjk committed
615
        setCategory(_(SETTINGS_CATEGORY));
616
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
617
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
618
619
    }

620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    void apply();
    void finish() {}

    QWidget *createPage(QWidget *parent);
    void initialize() {}
    UserCommandMap &userCommandMap();
    UserCommandMap &defaultUserCommandMap();

private:
    FakeVimPluginPrivate *m_q;
};

QWidget *FakeVimUserCommandsPage::createPage(QWidget *parent)
{
    QGroupBox *box = new QGroupBox(parent);

    FakeVimUserCommandsModel *model = new FakeVimUserCommandsModel(m_q);
    QTreeView *widget = new QTreeView;
    widget->setModel(model);
    widget->resizeColumnToContents(0);

    FakeVimUserCommandsDelegate *delegate = new FakeVimUserCommandsDelegate(widget);
    widget->setItemDelegateForColumn(1, delegate);

    QGridLayout *layout = new QGridLayout(box);
    layout->addWidget(widget, 0, 0);
    box->setLayout(layout);

    return box;
}

void FakeVimUserCommandsPage::apply()
{
    //m_q->writeSettings();
}

hjk's avatar
hjk committed
656
657
658
659
660
661
662

///////////////////////////////////////////////////////////////////////
//
// WordCompletion
//
///////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
663
class FakeVimCompletionAssistProvider : public CompletionAssistProvider
hjk's avatar
hjk committed
664
665
{
public:
hjk's avatar
hjk committed
666
    bool supportsEditor(const Id &) const
hjk's avatar
hjk committed
667
    {
Leandro Melo's avatar
Leandro Melo committed
668
        return false;
hjk's avatar
hjk committed
669
670
    }

hjk's avatar
hjk committed
671
    IAssistProcessor *createProcessor() const;
Leandro Melo's avatar
Leandro Melo committed
672
673

    void setActive(const QString &needle, bool forward, FakeVimHandler *handler)
hjk's avatar
hjk committed
674
    {
Leandro Melo's avatar
Leandro Melo committed
675
676
677
678
679
680
681
682
683
684
685
686
        Q_UNUSED(forward);
        m_handler = handler;
        if (!m_handler)
            return;

        BaseTextEditorWidget *editor = qobject_cast<BaseTextEditorWidget *>(handler->widget());
        if (!editor)
            return;

        //qDebug() << "ACTIVATE: " << needle << forward;
        m_needle = needle;
        editor->invokeAssist(Completion, this);
hjk's avatar
hjk committed
687
688
    }

Leandro Melo's avatar
Leandro Melo committed
689
    void setInactive()
hjk's avatar
hjk committed
690
    {
Leandro Melo's avatar
Leandro Melo committed
691
692
        m_needle.clear();
        m_handler = 0;
hjk's avatar
hjk committed
693
694
    }

Leandro Melo's avatar
Leandro Melo committed
695
    const QString &needle() const
696
    {
Leandro Melo's avatar
Leandro Melo committed
697
        return m_needle;
698
    }
hjk's avatar
hjk committed
699

Leandro Melo's avatar
Leandro Melo committed
700
    void appendNeedle(const QChar &c)
701
    {
Leandro Melo's avatar
Leandro Melo committed
702
        m_needle.append(c);
703
704
    }

Leandro Melo's avatar
Leandro Melo committed
705
    FakeVimHandler *handler() const
706
    {
Leandro Melo's avatar
Leandro Melo committed
707
        return m_handler;
708
    }
hjk's avatar
hjk committed
709

Leandro Melo's avatar
Leandro Melo committed
710
711
712
713
714
715
716
717
718
719
720
721
722
private:
    FakeVimHandler *m_handler;
    QString m_needle;
};

class FakeVimAssistProposalItem : public BasicProposalItem
{
public:
    FakeVimAssistProposalItem(const FakeVimCompletionAssistProvider *provider)
        : m_provider(const_cast<FakeVimCompletionAssistProvider *>(provider))
    {}

    virtual bool implicitlyApplies() const
hjk's avatar
hjk committed
723
    {
Leandro Melo's avatar
Leandro Melo committed
724
        return false;
hjk's avatar
hjk committed
725
726
    }

Leandro Melo's avatar
Leandro Melo committed
727
    virtual bool prematurelyApplies(const QChar &c) const
hjk's avatar
hjk committed
728
    {
Leandro Melo's avatar
Leandro Melo committed
729
730
        m_provider->appendNeedle(c);
        return text() == m_provider->needle();
hjk's avatar
hjk committed
731
732
    }

Leandro Melo's avatar
Leandro Melo committed
733
    virtual void applyContextualContent(BaseTextEditor *, int) const
hjk's avatar
hjk committed
734
    {
Leandro Melo's avatar
Leandro Melo committed
735
736
737
        QTC_ASSERT(m_provider->handler(), return);
        m_provider->handler()->handleReplay(text().mid(m_provider->needle().size()));
        const_cast<FakeVimCompletionAssistProvider *>(m_provider)->setInactive();
hjk's avatar
hjk committed
738
739
    }

Leandro Melo's avatar
Leandro Melo committed
740
741
742
743
744
745
746
747
748
749
750
751
752
private:
    FakeVimCompletionAssistProvider *m_provider;
};


class FakeVimAssistProposalModel : public BasicProposalItemListModel
{
public:
    FakeVimAssistProposalModel(const QList<BasicProposalItem *> &items)
        : BasicProposalItemListModel(items)
    {}

    virtual bool supportsPrefixExpansion() const
hjk's avatar
hjk committed
753
    {
Leandro Melo's avatar
Leandro Melo committed
754
        return false;
hjk's avatar
hjk committed
755
    }
Leandro Melo's avatar
Leandro Melo committed
756
};
hjk's avatar
hjk committed
757

Leandro Melo's avatar
Leandro Melo committed
758
759
760
class FakeVimCompletionAssistProcessor : public IAssistProcessor
{
public:
hjk's avatar
hjk committed
761
    FakeVimCompletionAssistProcessor(const IAssistProvider *provider)
Leandro Melo's avatar
Leandro Melo committed
762
763
764
        : m_provider(static_cast<const FakeVimCompletionAssistProvider *>(provider))
    {}

hjk's avatar
hjk committed
765
    IAssistProposal *perform(const IAssistInterface *interface)
hjk's avatar
hjk committed
766
    {
Leandro Melo's avatar
Leandro Melo committed
767
768
769
770
        const QString &needle = m_provider->needle();

        const int basePosition = interface->position() - needle.size();

771
        QTextCursor tc(interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
772
        tc.setPosition(interface->position());
hjk's avatar
hjk committed
773
774
        tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

Leandro Melo's avatar
Leandro Melo committed
775
        QList<BasicProposalItem *> items;
hjk's avatar
hjk committed
776
777
778
        QSet<QString> seen;
        QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
        while (1) {
Leandro Melo's avatar
Leandro Melo committed
779
            tc = tc.document()->find(needle, tc.position(), flags);
hjk's avatar
hjk committed
780
781
782
783
784
785
            if (tc.isNull())
                break;
            QTextCursor sel = tc;
            sel.select(QTextCursor::WordUnderCursor);
            QString found = sel.selectedText();
            // Only add "real" completions.
Leandro Melo's avatar
Leandro Melo committed
786
            if (found.startsWith(needle)
hjk's avatar
hjk committed
787
                    && !seen.contains(found)
Leandro Melo's avatar
Leandro Melo committed
788
                    && sel.anchor() != basePosition) {
hjk's avatar
hjk committed
789
                seen.insert(found);
Leandro Melo's avatar
Leandro Melo committed
790
791
792
                BasicProposalItem *item = new FakeVimAssistProposalItem(m_provider);
                item->setText(found);
                items.append(item);
hjk's avatar
hjk committed
793
794
795
796
797
            }
            tc.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
        }
        //qDebug() << "COMPLETIONS" << completions->size();

Leandro Melo's avatar
Leandro Melo committed
798
799
        delete interface;
        return new GenericProposal(basePosition, new FakeVimAssistProposalModel(items));
hjk's avatar
hjk committed
800
801
802
    }

private:
Leandro Melo's avatar
Leandro Melo committed
803
    const FakeVimCompletionAssistProvider *m_provider;
hjk's avatar
hjk committed
804
};
805

Leandro Melo's avatar
Leandro Melo committed
806
807
808
809
810
IAssistProcessor *FakeVimCompletionAssistProvider::createProcessor() const
{
    return new FakeVimCompletionAssistProcessor(this);
}

811

hjk's avatar
hjk committed
812
813
///////////////////////////////////////////////////////////////////////
//
814
// FakeVimPluginPrivate
hjk's avatar
hjk committed
815
816
817
//
///////////////////////////////////////////////////////////////////////

818
class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
819
{
820
821
822
823
824
825
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
826
    friend class FakeVimExCommandsPage;
827
828
    friend class FakeVimUserCommandsPage;
    friend class FakeVimUserCommandsModel;
829

830
    bool initialize();
831
    void aboutToShutdown();
832
833

private slots:
834
    void onCoreAboutToClose();
835
836
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
837

838
    void setUseFakeVim(const QVariant &value);
839
    void setUseFakeVimInternal(bool on);
840
    void quitFakeVim();
841
    void triggerCompletions();
842
    void triggerSimpleCompletions(const QString &needle, bool forward);
hjk's avatar
hjk committed
843
    void windowCommand(int key);
844
    void find(bool reverse);
845
    void findNext(bool reverse);
846
847
848
    void foldToggle(int depth);
    void foldAll(bool fold);
    void fold(int depth, bool fold);
hjk's avatar
hjk committed
849
    void showSettingsDialog();
850
    void maybeReadVimRc();
hjk's avatar
hjk committed
851
852
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
853

854
855
856
    void resetCommandBuffer();
    void showCommandBuffer(const QString &contents, int cursorPos, int messageLevel,
                           QObject *eventFilter);
857
858
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
859
    void highlightMatches(const QString &needle);
860
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
861
    void checkForElectricCharacter(bool *result, QChar c);
Lukas Holecek's avatar
Lukas Holecek committed
862
    void indentRegion(int beginBlock, int endBlock, QChar typedChar);
863
    void handleExCommand(bool *handled, const ExCommand &cmd);
864

865
866
867
    void writeSettings();
    void readSettings();

868
869
    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);
870
    void userActionTriggered();
871

872
873
    void switchToFile(int n);
    int currentFile() const;
874

875
876
877
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
878
879
880

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
881
    FakeVimOptionPage *m_fakeVimOptionsPage;
882
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
883
    FakeVimUserCommandsPage *m_fakeVimUserCommandsPage;
hjk's avatar
hjk committed
884
    QHash<IEditor *, FakeVimHandler *> m_editorToHandler;
885

hjk's avatar
hjk committed
886
887
    void triggerAction(const Id &id);
    void setActionChecked(const Id &id, bool check);
888

889
890
891
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

892
893
894
895
896
897
898
899
900
901
    ExCommandMap &exCommandMap() { return m_exCommandMap; }
    ExCommandMap &defaultExCommandMap() { return m_defaultExCommandMap; }
    ExCommandMap m_exCommandMap;
    ExCommandMap m_defaultExCommandMap;

    UserCommandMap &userCommandMap() { return m_userCommandMap; }
    UserCommandMap &defaultUserCommandMap() { return m_defaultUserCommandMap; }
    UserCommandMap m_userCommandMap;
    UserCommandMap m_defaultUserCommandMap;

hjk's avatar
hjk committed
902
    StatusBarWidget *m_statusBar;
Leandro Melo's avatar
Leandro Melo committed
903
904
905
    // @TODO: Delete
    //WordCompletion *m_wordCompletion;
    FakeVimCompletionAssistProvider *m_wordProvider;
906
907
};

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
QVariant FakeVimUserCommandsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        switch (index.column()) {
        case 0: // Action
            return tr("User command #%1").arg(index.row() + 1);
        case 1: // Command
            return m_q->userCommandMap().value(index.row() + 1);
        }
    }

    return QVariant();
}

bool FakeVimUserCommandsModel::setData(const QModelIndex &index,
    const QVariant &data, int role)
{
    if (role == Qt::DisplayRole || role == Qt::EditRole)
        if (index.column() == 1)
            m_q->userCommandMap()[index.row() + 1] = data.toString();
    return true;
}

934
FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
935
{
936
    q = plugin;
hjk's avatar
hjk committed
937
    m_fakeVimOptionsPage = 0;
938
    m_fakeVimExCommandsPage = 0;
939
    m_fakeVimUserCommandsPage = 0;
940
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
941
        QRegExp("^A$");
942
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
943
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
944
    defaultExCommandMap()["Coreplugin.OutputPane.nextitem"] =
945
        QRegExp("^cn(ext)?!?( (.*))?$");
946
    defaultExCommandMap()[TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR] =
947
        QRegExp("^tag?$");
948
    defaultExCommandMap()[Core::Constants::GO_BACK] =
949
        QRegExp("^pop?$");
hjk's avatar
hjk committed
950
    defaultExCommandMap()[_("QtCreator.Locate")] =
951
        QRegExp("^e$");
952
953
954
955
956
957

    for (int i = 1; i < 10; ++i) {
        QString cmd = QString::fromLatin1(":echo User command %1 executed.<CR>");
        defaultUserCommandMap().insert(i, cmd.arg(i));
    }

958
    m_statusBar = 0;
hjk's avatar
hjk committed
959
960
}

961
FakeVimPluginPrivate::~FakeVimPluginPrivate()
hjk's avatar
hjk committed
962
{
hjk's avatar
hjk committed
963
964
965
    q->removeObject(m_fakeVimOptionsPage);
    delete m_fakeVimOptionsPage;
    m_fakeVimOptionsPage = 0;
dt's avatar
dt committed
966
    delete theFakeVimSettings();
967
968
969
970

    q->removeObject(m_fakeVimExCommandsPage);
    delete m_fakeVimExCommandsPage;
    m_fakeVimExCommandsPage = 0;
971
972
973
974

    q->removeObject(m_fakeVimUserCommandsPage);
    delete m_fakeVimUserCommandsPage;
    m_fakeVimUserCommandsPage = 0;
975
976
}

977
978
void FakeVimPluginPrivate::onCoreAboutToClose()
{
979
    // Don't attach to editors anymore.
hjk's avatar
hjk committed
980
    disconnect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
981
982
983
        this, SLOT(editorOpened(Core::IEditor*)));
}

984
985
void FakeVimPluginPrivate::aboutToShutdown()
{
hjk's avatar
hjk committed
986
987
}

988
bool FakeVimPluginPrivate::initialize()
hjk's avatar
hjk committed
989
{
hjk's avatar
hjk committed
990
    EditorManager *editorManager = ICore::editorManager();
hjk's avatar
hjk committed
991

Leandro Melo's avatar
Leandro Melo committed
992
993
994
995
    //m_wordCompletion = new WordCompletion;
    //q->addAutoReleasedObject(m_wordCompletion);
    m_wordProvider = new FakeVimCompletionAssistProvider;

hjk's avatar
hjk committed
996
997
998
999
1000
1001
1002
1003
1004
1005
/*
    // Set completion settings and keep them up to date.
    TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
    completion->setCompletionSettings(textEditorSettings->completionSettings());
    connect(textEditorSettings,
        SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)),
        completion,
        SLOT(setCompletionSettings(TextEditor::CompletionSettings)));
*/

hjk's avatar
hjk committed
1006
    Context globalcontext(Core::Constants::C_GLOBAL);
hjk's avatar
hjk committed
1007

hjk's avatar
hjk committed
1008
1009
    m_fakeVimOptionsPage = new FakeVimOptionPage;
    q->addObject(m_fakeVimOptionsPage);
1010

1011
    m_fakeVimExCommandsPage = new FakeVimExCommandsPage(this);
1012
    q->addObject(m_fakeVimExCommandsPage);
1013
1014
1015
1016

    m_fakeVimUserCommandsPage = new FakeVimUserCommandsPage(this);
    q->addObject(m_fakeVimUserCommandsPage);

1017
    readSettings();
1018

hjk's avatar
hjk committed
1019
1020
1021
1022
    Command *cmd = 0;
    cmd = ActionManager::registerAction(theFakeVimSetting(ConfigUseFakeVim),
        INSTALL_HANDLER, globalcontext, true);
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+V,Meta+V") : tr("Alt+V,Alt+V")));
hjk's avatar
hjk committed