fakevimplugin.cpp 56.1 KB
Newer Older
1
/**************************************************************************
hjk's avatar
hjk committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
**
Eike Ziller's avatar
Eike Ziller committed
7
** Contact: http://www.qt-project.org/
hjk's avatar
hjk committed
8
9
**
**
10
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** 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.
hjk's avatar
hjk committed
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
hjk's avatar
hjk committed
28
**
29
**************************************************************************/
hjk's avatar
hjk committed
30
31
32

#include "fakevimplugin.h"

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

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

#include <projectexplorer/projectexplorerconstants.h>

55
#include <texteditor/basetextdocumentlayout.h>
hjk's avatar
hjk committed
56
57
58
#include <texteditor/basetexteditor.h>
#include <texteditor/basetextmark.h>
#include <texteditor/texteditorconstants.h>
Jarek Kobus's avatar
Jarek Kobus committed
59
#include <texteditor/typingsettings.h>
60
#include <texteditor/tabsettings.h>
Jarek Kobus's avatar
Jarek Kobus committed
61
#include <texteditor/icodestylepreferences.h>
62
#include <texteditor/texteditorsettings.h>
63
#include <texteditor/indenter.h>
Leandro Melo's avatar
Leandro Melo committed
64
65
66
67
68
69
#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
70

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

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>

81
82
83
84
85
86
87
#include <QAbstractTableModel>
#include <QDebug>
#include <QFile>
#include <QtPlugin>
#include <QObject>
#include <QSettings>
#include <QTextStream>
hjk's avatar
hjk committed
88

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

using namespace TextEditor;
using namespace Core;

namespace FakeVim {
hjk's avatar
hjk committed
103
namespace Internal {
hjk's avatar
hjk committed
104

hjk's avatar
hjk committed
105
106
107
108
109
110
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
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
class MiniBuffer : public QLabel
{
    Q_OBJECT

public:
    void setContents(const QString &contents, int cursorPos)
    {
        QString msg = contents;
        if (cursorPos != -1)
            msg = contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
        setText("  " + msg);
    }
};

class MiniBuffer1 : public QLineEdit
{
    Q_OBJECT

public:
    MiniBuffer1()
    {
        setFrame(false);
    }
    void showEvent(QShowEvent *ev)
    {
        QLineEdit::showEvent(ev);
        QColor color = Qt::black;
        QPalette pal = parentWidget()->palette();
        pal.setBrush(QPalette::All, QPalette::WindowText, color);
        pal.setBrush(QPalette::All, QPalette::ButtonText, color);
        pal.setBrush(QPalette::All, QPalette::Foreground, color);
        pal.setBrush(QPalette::All, QPalette::Background, color);
        //color.setAlpha(100);
        //pal.setBrush(QPalette::Disabled, QPalette::WindowText, color);
        //pal.setBrush(QPalette::Disabled, QPalette::ButtonText, color);
        //pal.setBrush(QPalette::Disabled, QPalette::Foreground, color);
        setPalette(pal);
    }
    void setContents(const QString &contents, int cursorPos)
    {
        setText(contents);
        setCursorPosition(cursorPos);
    }
};

hjk's avatar
hjk committed
157
158
159
160
161
162
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

163
164
typedef QMap<QString, QRegExp> ExCommandMap;
typedef QMap<int, QString> UserCommandMap;
hjk's avatar
hjk committed
165
typedef QLatin1String _;
166

hjk's avatar
hjk committed
167
class FakeVimOptionPage : public IOptionsPage
hjk's avatar
hjk committed
168
169
170
171
{
    Q_OBJECT

public:
172
173
    FakeVimOptionPage()
    {
hjk's avatar
hjk committed
174
        setId(_(SETTINGS_ID));
175
        setDisplayName(tr("General"));
hjk's avatar
hjk committed
176
        setCategory(_(SETTINGS_CATEGORY));
177
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
178
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
179
    }
hjk's avatar
hjk committed
180
181

    QWidget *createPage(QWidget *parent);
hjk's avatar
hjk committed
182
    void apply() { m_group.apply(ICore::settings()); }
hjk's avatar
hjk committed
183
    void finish() { m_group.finish(); }
184
    virtual bool matches(const QString &) const;
hjk's avatar
hjk committed
185
186
187
188
189
190
191
192
193

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

private:
    friend class DebuggerPlugin;
    Ui::FakeVimOptionPage m_ui;
194
    QString m_searchKeywords;
195
    Utils::SavedActionSet m_group;
hjk's avatar
hjk committed
196
197
198
199
200
201
202
203
};

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

    m_group.clear();
204
    m_group.insert(theFakeVimSetting(ConfigUseFakeVim),
205
        m_ui.checkBoxUseFakeVim);
206
207
    m_group.insert(theFakeVimSetting(ConfigReadVimRc),
        m_ui.checkBoxReadVimRc);
hjk's avatar
hjk committed
208

209
    m_group.insert(theFakeVimSetting(ConfigExpandTab),
hjk's avatar
hjk committed
210
        m_ui.checkBoxExpandTab);
211
    m_group.insert(theFakeVimSetting(ConfigHlSearch),
hjk's avatar
hjk committed
212
        m_ui.checkBoxHlSearch);
213
    m_group.insert(theFakeVimSetting(ConfigShiftWidth),
214
        m_ui.spinBoxShiftWidth);
215
216
    m_group.insert(theFakeVimSetting(ConfigShowMarks),
        m_ui.checkBoxShowMarks);
hjk's avatar
hjk committed
217

218
    m_group.insert(theFakeVimSetting(ConfigSmartTab),
hjk's avatar
hjk committed
219
        m_ui.checkBoxSmartTab);
220
    m_group.insert(theFakeVimSetting(ConfigStartOfLine),
hjk's avatar
hjk committed
221
        m_ui.checkBoxStartOfLine);
222
    m_group.insert(theFakeVimSetting(ConfigTabStop),
223
        m_ui.spinBoxTabStop);
224
    m_group.insert(theFakeVimSetting(ConfigBackspace),
hjk's avatar
hjk committed
225
        m_ui.lineEditBackspace);
226
227
    m_group.insert(theFakeVimSetting(ConfigIsKeyword),
        m_ui.lineEditIsKeyword);
hjk's avatar
hjk committed
228

229
230
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
231
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
232
        m_ui.checkBoxAutoIndent);
233
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
234
        m_ui.checkBoxSmartIndent);
235
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
236
        m_ui.checkBoxIncSearch);
237
238
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
hjk's avatar
hjk committed
239
240

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
241
        SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
242
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
243
        SLOT(setQtStyle()));
hjk's avatar
hjk committed
244
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
245
246
        SLOT(setPlainStyle()));

247
    if (m_searchKeywords.isEmpty()) {
248
        QLatin1Char sep(' ');
249
        QTextStream(&m_searchKeywords)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                << 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()
                << 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();
266
267
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
268
269
270
271
272
    return w;
}

void FakeVimOptionPage::copyTextEditorSettings()
{
Jarek Kobus's avatar
Jarek Kobus committed
273
274
275
    TabSettings ts = TextEditorSettings::instance()->codeStyle()->tabSettings();
    TypingSettings tps = TextEditorSettings::instance()->typingSettings();
    m_ui.checkBoxExpandTab->setChecked(ts.m_tabPolicy != TabSettings::TabsOnlyTabPolicy);
276
277
    m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
    m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
278
    m_ui.checkBoxSmartTab->setChecked(
Jarek Kobus's avatar
Jarek Kobus committed
279
        tps.m_smartBackspaceBehavior == TypingSettings::BackspaceFollowsPreviousIndents);
280
    m_ui.checkBoxAutoIndent->setChecked(true);
Jarek Kobus's avatar
Jarek Kobus committed
281
    m_ui.checkBoxSmartIndent->setChecked(tps.m_autoIndent);
282
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
283
284
285
286
287
}

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
288
289
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
290
291
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
292
    m_ui.checkBoxSmartIndent->setChecked(true);
293
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
294
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
295
296
297
298
299
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
300
301
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
302
303
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
304
    m_ui.checkBoxSmartIndent->setChecked(false);
305
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
306
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
307
308
}

309
310
311
312
313
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

314
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
315

316
317
318
319
320
321
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

322
enum { CommandRole = Qt::UserRole };
323

hjk's avatar
hjk committed
324
class FakeVimExCommandsPage : public CommandMappings
325
326
327
328
{
    Q_OBJECT

public:
329
330
331
    FakeVimExCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
332
        setId(_(SETTINGS_EX_CMDS_ID));
333
        setDisplayName(tr("Ex Command Mapping"));
hjk's avatar
hjk committed
334
        setCategory(_(SETTINGS_CATEGORY));
335
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
336
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
337
    }
338
339
340

    QWidget *createPage(QWidget *parent);
    void initialize();
341
342
    ExCommandMap &exCommandMap();
    ExCommandMap &defaultExCommandMap();
343
344
345

public slots:
    void commandChanged(QTreeWidgetItem *current);
346
347
348
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
349
350
351
    void defaultAction();

private:
352
    FakeVimPluginPrivate *m_q;
353
354
355
356
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
357
358
359
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
360
    setTargetLabelText(tr("Regular expression:"));
361
362
    setTargetEditTitle(tr("Ex Command"));
    setImportExportEnabled(false);
363
364
365
366
367
    return w;
}

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

hjk's avatar
hjk committed
370
    foreach (Command *c, ActionManager::commands()) {
371
372
373
        if (c->action() && c->action()->isSeparator())
            continue;

374
        QTreeWidgetItem *item = new QTreeWidgetItem;
375
        const QString name = c->id().toString();
376
377
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
378
        const QString subId = name.mid(pos + 1);
379
        item->setData(0, CommandRole, name);
380
381

        if (!sections.contains(section)) {
382
383
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
384
385
386
387
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
388
            commandList()->expandItem(categoryItem);
389
390
391
392
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
393
        item->setText(1, c->description());
394

395
396
397
398
        QString regex;
        if (exCommandMap().contains(name))
            regex = exCommandMap()[name].pattern();
        item->setText(2, regex);
399

400
        if (regex != defaultExCommandMap()[name].pattern())
401
            setModified(item, true);
402
403
404
405
406
407
408
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
409
    CommandMappings::commandChanged(current);
410
411
    if (current)
        targetEdit()->setText(current->text(2));
412
413
}

414
void FakeVimExCommandsPage::targetIdentifierChanged()
415
{
416
    QTreeWidgetItem *current = commandList()->currentItem();
417
418
419
    if (!current)
        return;

420
    const QString name =  current->data(0, CommandRole).toString();
421
    const QString regex = targetEdit()->text();
422
423

    if (current->data(0, Qt::UserRole).isValid()) {
424
425
        current->setText(2, regex);
        exCommandMap()[name] = QRegExp(regex);
426
    }
427

428
    setModified(current, regex != defaultExCommandMap()[name].pattern());
429
430
}

431
void FakeVimExCommandsPage::resetTargetIdentifier()
432
{
433
    QTreeWidgetItem *current = commandList()->currentItem();
434
435
    if (!current)
        return;
436
    const QString name = current->data(0, CommandRole).toString();
437
438
439
440
    QString regex;
    if (defaultExCommandMap().contains(name))
        regex = defaultExCommandMap()[name].pattern();
    targetEdit()->setText(regex);
441
442
}

443
void FakeVimExCommandsPage::removeTargetIdentifier()
444
{
445
    targetEdit()->clear();
446
447
448
449
}

void FakeVimExCommandsPage::defaultAction()
{
hjk's avatar
hjk committed
450
451
452
453
454
455
    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);
456
            const QString name = item->data(0, CommandRole).toString();
hjk's avatar
hjk committed
457
458
459
460
461
462
463
464
            QString regex;
            if (defaultExCommandMap().contains(name))
                regex = defaultExCommandMap()[name].pattern();
            setModified(item, false);
            item->setText(2, regex);
            if (item == commandList()->currentItem())
                commandChanged(item);
        }
465
466
467
    }
}

468
469
470
471
472
473
474
475
///////////////////////////////////////////////////////////////////////
//
// FakeVimUserCommandsPage
//
///////////////////////////////////////////////////////////////////////

class FakeVimUserCommandsModel : public QAbstractTableModel
{
Friedemann Kleint's avatar
Friedemann Kleint committed
476
    Q_OBJECT
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
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
546
class FakeVimUserCommandsPage : public IOptionsPage
547
548
549
550
{
    Q_OBJECT

public:
551
552
553
    FakeVimUserCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
554
        setId(_(SETTINGS_USER_CMDS_ID));
555
        setDisplayName(tr("User Command Mapping"));
hjk's avatar
hjk committed
556
        setCategory(_(SETTINGS_CATEGORY));
557
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
558
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
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
    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
597
598
599
600
601
602
603

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

hjk's avatar
hjk committed
604
class FakeVimCompletionAssistProvider : public CompletionAssistProvider
hjk's avatar
hjk committed
605
606
{
public:
hjk's avatar
hjk committed
607
    bool supportsEditor(const Id &) const
hjk's avatar
hjk committed
608
    {
Leandro Melo's avatar
Leandro Melo committed
609
        return false;
hjk's avatar
hjk committed
610
611
    }

hjk's avatar
hjk committed
612
    IAssistProcessor *createProcessor() const;
Leandro Melo's avatar
Leandro Melo committed
613
614

    void setActive(const QString &needle, bool forward, FakeVimHandler *handler)
hjk's avatar
hjk committed
615
    {
Leandro Melo's avatar
Leandro Melo committed
616
617
618
619
620
621
622
623
624
625
626
627
        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
628
629
    }

Leandro Melo's avatar
Leandro Melo committed
630
    void setInactive()
hjk's avatar
hjk committed
631
    {
Leandro Melo's avatar
Leandro Melo committed
632
633
        m_needle.clear();
        m_handler = 0;
hjk's avatar
hjk committed
634
635
    }

Leandro Melo's avatar
Leandro Melo committed
636
    const QString &needle() const
637
    {
Leandro Melo's avatar
Leandro Melo committed
638
        return m_needle;
639
    }
hjk's avatar
hjk committed
640

Leandro Melo's avatar
Leandro Melo committed
641
    void appendNeedle(const QChar &c)
642
    {
Leandro Melo's avatar
Leandro Melo committed
643
        m_needle.append(c);
644
645
    }

Leandro Melo's avatar
Leandro Melo committed
646
    FakeVimHandler *handler() const
647
    {
Leandro Melo's avatar
Leandro Melo committed
648
        return m_handler;
649
    }
hjk's avatar
hjk committed
650

Leandro Melo's avatar
Leandro Melo committed
651
652
653
654
655
656
657
658
659
660
661
662
663
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
664
    {
Leandro Melo's avatar
Leandro Melo committed
665
        return false;
hjk's avatar
hjk committed
666
667
    }

Leandro Melo's avatar
Leandro Melo committed
668
    virtual bool prematurelyApplies(const QChar &c) const
hjk's avatar
hjk committed
669
    {
Leandro Melo's avatar
Leandro Melo committed
670
671
        m_provider->appendNeedle(c);
        return text() == m_provider->needle();
hjk's avatar
hjk committed
672
673
    }

Leandro Melo's avatar
Leandro Melo committed
674
    virtual void applyContextualContent(BaseTextEditor *, int) const
hjk's avatar
hjk committed
675
    {
Leandro Melo's avatar
Leandro Melo committed
676
677
678
        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
679
680
    }

Leandro Melo's avatar
Leandro Melo committed
681
682
683
684
685
686
687
688
689
690
691
692
693
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
694
    {
Leandro Melo's avatar
Leandro Melo committed
695
        return false;
hjk's avatar
hjk committed
696
    }
Leandro Melo's avatar
Leandro Melo committed
697
};
hjk's avatar
hjk committed
698

Leandro Melo's avatar
Leandro Melo committed
699
700
701
class FakeVimCompletionAssistProcessor : public IAssistProcessor
{
public:
hjk's avatar
hjk committed
702
    FakeVimCompletionAssistProcessor(const IAssistProvider *provider)
Leandro Melo's avatar
Leandro Melo committed
703
704
705
        : m_provider(static_cast<const FakeVimCompletionAssistProvider *>(provider))
    {}

hjk's avatar
hjk committed
706
    IAssistProposal *perform(const IAssistInterface *interface)
hjk's avatar
hjk committed
707
    {
Leandro Melo's avatar
Leandro Melo committed
708
709
710
711
        const QString &needle = m_provider->needle();

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

712
        QTextCursor tc(interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
713
        tc.setPosition(interface->position());
hjk's avatar
hjk committed
714
715
        tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

Leandro Melo's avatar
Leandro Melo committed
716
        QList<BasicProposalItem *> items;
hjk's avatar
hjk committed
717
718
719
        QSet<QString> seen;
        QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
        while (1) {
Leandro Melo's avatar
Leandro Melo committed
720
            tc = tc.document()->find(needle, tc.position(), flags);
hjk's avatar
hjk committed
721
722
723
724
725
726
            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
727
            if (found.startsWith(needle)
hjk's avatar
hjk committed
728
                    && !seen.contains(found)
Leandro Melo's avatar
Leandro Melo committed
729
                    && sel.anchor() != basePosition) {
hjk's avatar
hjk committed
730
                seen.insert(found);
Leandro Melo's avatar
Leandro Melo committed
731
732
733
                BasicProposalItem *item = new FakeVimAssistProposalItem(m_provider);
                item->setText(found);
                items.append(item);
hjk's avatar
hjk committed
734
735
736
737
738
            }
            tc.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
        }
        //qDebug() << "COMPLETIONS" << completions->size();

Leandro Melo's avatar
Leandro Melo committed
739
740
        delete interface;
        return new GenericProposal(basePosition, new FakeVimAssistProposalModel(items));
hjk's avatar
hjk committed
741
742
743
    }

private:
Leandro Melo's avatar
Leandro Melo committed
744
    const FakeVimCompletionAssistProvider *m_provider;
hjk's avatar
hjk committed
745
};
746

Leandro Melo's avatar
Leandro Melo committed
747
748
749
750
751
IAssistProcessor *FakeVimCompletionAssistProvider::createProcessor() const
{
    return new FakeVimCompletionAssistProcessor(this);
}

752

hjk's avatar
hjk committed
753
754
///////////////////////////////////////////////////////////////////////
//
755
// FakeVimPluginPrivate
hjk's avatar
hjk committed
756
757
758
//
///////////////////////////////////////////////////////////////////////

759
class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
760
{
761
762
763
764
765
766
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
767
    friend class FakeVimExCommandsPage;
768
769
    friend class FakeVimUserCommandsPage;
    friend class FakeVimUserCommandsModel;
770

771
    bool initialize();
772
    void aboutToShutdown();
773
774

private slots:
775
    void onCoreAboutToClose();
776
777
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
778

779
    void setUseFakeVim(const QVariant &value);
780
    void setUseFakeVimInternal(bool on);
781
    void quitFakeVim();
782
    void triggerCompletions();
783
    void triggerSimpleCompletions(const QString &needle, bool forward);
hjk's avatar
hjk committed
784
    void windowCommand(int key);
785
    void find(bool reverse);
786
    void findNext(bool reverse);
hjk's avatar
hjk committed
787
    void showSettingsDialog();
788
    void maybeReadVimRc();
hjk's avatar
hjk committed
789
790
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
791

792
    void showCommandBuffer(const QString &contents, int cursorPos);
793
794
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
795
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
796
    void checkForElectricCharacter(bool *result, QChar c);
797
    void indentRegion(int beginLine, int endLine, QChar typedChar);
798
    void handleExCommand(bool *handled, const ExCommand &cmd);
799

800
801
802
    void writeSettings();
    void readSettings();

803
804
    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);
805
    void userActionTriggered();
806

807
808
    void switchToFile(int n);
    int currentFile() const;
809

810
811
812
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
813
814
815

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
816
    FakeVimOptionPage *m_fakeVimOptionsPage;
817
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
818
    FakeVimUserCommandsPage *m_fakeVimUserCommandsPage;
hjk's avatar
hjk committed
819
    QHash<IEditor *, FakeVimHandler *> m_editorToHandler;
820

hjk's avatar
hjk committed
821
822
    void triggerAction(const Id &id);
    void setActionChecked(const Id &id, bool check);
823

824
825
826
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

827
828
829
830
831
832
833
834
835
836
    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
837
    StatusBarWidget *m_statusBar;
Leandro Melo's avatar
Leandro Melo committed
838
839
840
    // @TODO: Delete
    //WordCompletion *m_wordCompletion;
    FakeVimCompletionAssistProvider *m_wordProvider;
841
842
};

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
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;
}

869
FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
870
{
871
    q = plugin;
hjk's avatar
hjk committed
872
    m_fakeVimOptionsPage = 0;
873
    m_fakeVimExCommandsPage = 0;
874
    m_fakeVimUserCommandsPage = 0;
875
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
876
        QRegExp("^A$");
877
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
878
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
879
    defaultExCommandMap()["Coreplugin.OutputPane.nextitem"] =
880
        QRegExp("^cn(ext)?!?( (.*))?$");
881
    defaultExCommandMap()[TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR] =
882
        QRegExp("^tag?$");
883
    defaultExCommandMap()[Core::Constants::GO_BACK] =
884
        QRegExp("^pop?$");
hjk's avatar
hjk committed
885
    defaultExCommandMap()[_("QtCreator.Locate")] =
886
        QRegExp("^e$");
887
888
889
890
891
892

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

893
    m_statusBar = 0;
hjk's avatar
hjk committed
894
895
}

896
FakeVimPluginPrivate::~FakeVimPluginPrivate()
hjk's avatar
hjk committed
897
{
hjk's avatar
hjk committed
898
899
900
    q->removeObject(m_fakeVimOptionsPage);
    delete m_fakeVimOptionsPage;
    m_fakeVimOptionsPage = 0;
dt's avatar
dt committed
901
    delete theFakeVimSettings();
902
903
904
905

    q->removeObject(m_fakeVimExCommandsPage);
    delete m_fakeVimExCommandsPage;
    m_fakeVimExCommandsPage = 0;
906
907
908
909

    q->removeObject(m_fakeVimUserCommandsPage);
    delete m_fakeVimUserCommandsPage;
    m_fakeVimUserCommandsPage = 0;
910
911
}

912
913
void FakeVimPluginPrivate::onCoreAboutToClose()
{
914
    // Don't attach to editors anymore.
hjk's avatar
hjk committed
915
    disconnect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
916
917
918
        this, SLOT(editorOpened(Core::IEditor*)));
}

919
920
void FakeVimPluginPrivate::aboutToShutdown()
{
hjk's avatar
hjk committed
921
922
}

923
bool FakeVimPluginPrivate::initialize()
hjk's avatar
hjk committed
924
{
hjk's avatar
hjk committed
925
    EditorManager *editorManager = ICore::editorManager();
hjk's avatar
hjk committed
926

Leandro Melo's avatar
Leandro Melo committed
927
928
929
930
    //m_wordCompletion = new WordCompletion;
    //q->addAutoReleasedObject(m_wordCompletion);
    m_wordProvider = new FakeVimCompletionAssistProvider;

hjk's avatar
hjk committed
931
932
933
934
935
936
937
938
939
940
/*
    // 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
941
    Context globalcontext(Core::Constants::C_GLOBAL);
hjk's avatar
hjk committed
942

hjk's avatar
hjk committed
943
944
    m_fakeVimOptionsPage = new FakeVimOptionPage;
    q->addObject(m_fakeVimOptionsPage);
945

946
    m_fakeVimExCommandsPage = new FakeVimExCommandsPage(this);
947
    q->addObject(m_fakeVimExCommandsPage);
948
949
950
951

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

952
    readSettings();
953

hjk's avatar
hjk committed
954
955
956
957
    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
958

959
    ActionContainer *advancedMenu =
hjk's avatar
hjk committed
960
        ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED);
961
962
    advancedMenu->addAction(cmd, Core::Constants::G_EDIT_EDITOR);

963
964
    for (int i = 1; i < 10; ++i) {
        QAction *act = new QAction(this);
Robert Loehning's avatar
Robert Loehning committed
965
        act->setText(tr("Execute User Action #%1").arg(i));
966
967
        act->setData(i);
        QString id = QString("FakeVim.UserAction%1").arg(i);
hjk's avatar
hjk committed
968
969
        cmd = ActionManager::registerAction(act, Id(id), globalcontext);
        cmd->setDefaultKeySequence(QKeySequence((UseMacShortcuts ? tr("Meta+V,%1") : tr("Alt+V,%1")).arg(i)));
970
971
972
        connect(act, SIGNAL(triggered()), SLOT(userActionTriggered()));
    }

hjk's avatar
hjk committed
973
    connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(onCoreAboutToClose()));
974

975
    // EditorManager
976
    connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
977
        this, SLOT(editorAboutToClose(Core::IEditor*)));
978
    connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
979
980
        this, SLOT(editorOpened(Core::IEditor*)));

981
982
    connect(theFakeVimSetting(ConfigUseFakeVim), SIGNAL(valueChanged(QVariant)),
        this, SLOT(setUseFakeVim(QVariant)));
983
984
    connect(theFakeVimSetting(ConfigReadVimRc), SIGNAL(valueChanged(QVariant)),
        this, SLOT(maybeReadVimRc()));
hjk's avatar
hjk committed
985

986
    // Delayed operations.
987
988
989
990
    connect(this, SIGNAL(delayedQuitRequested(bool,Core::IEditor*)),
        this, SLOT(handleDelayedQuit(bool,Core::IEditor*)), Qt::QueuedConnection);
    connect(this, SIGNAL(delayedQuitAllRequested(bool)),
        this, SLOT(handleDelayedQuitAll(bool)), Qt::QueuedConnection);
991
992
    maybeReadVimRc();
    //    << "MODE: " << theFakeVimSetting(ConfigUseFakeVim)->value();
993

hjk's avatar
hjk committed
994
995
996
    return true;
}

997
998
999
1000
1001
1002
1003
1004
1005
void FakeVimPluginPrivate::userActionTriggered()
{
    QAction *act = qobject_cast<QAction *>(sender());
    if (!act)
        return;
    const int key = act->data().toInt();
    if (!key)
        return;
    QString cmd = userCommandMap().value(key);
hjk's avatar
hjk committed
1006
    IEditor *editor = EditorManager::currentEditor();
1007
1008
1009
1010
1011
    FakeVimHandler *handler = m_editorToHandler[editor];
    if (handler)
        handler->handleInput(cmd);
}

hjk's avatar
hjk committed
1012
1013
1014
1015
1016
1017

const char exCommandMapGroup[] = "FakeVimExCommand";
const char userCommandMapGroup[] = "FakeVimUserCommand";
const char reKey[] = "RegEx";
const char cmdKey[] = "Cmd";
const char idKey[] = "Command";
1018