fakevimplugin.cpp 56.5 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>

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

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

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

using namespace TextEditor;
using namespace Core;

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

hjk's avatar
hjk committed
107 108 109 110 111 112
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
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
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
159 160 161 162 163 164
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

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

hjk's avatar
hjk committed
169
class FakeVimOptionPage : public IOptionsPage
hjk's avatar
hjk committed
170 171 172 173
{
    Q_OBJECT

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

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

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

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

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

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

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

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

231 232
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
233
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
234
        m_ui.checkBoxAutoIndent);
235
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
236
        m_ui.checkBoxSmartIndent);
Lukas Holecek's avatar
Lukas Holecek committed
237

238
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
239
        m_ui.checkBoxIncSearch);
240 241
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
242 243
    m_group.insert(theFakeVimSetting(ConfigSmartCase),
        m_ui.checkBoxSmartCase);
Lukas Holecek's avatar
Lukas Holecek committed
244 245
    m_group.insert(theFakeVimSetting(ConfigWrapScan),
        m_ui.checkBoxWrapScan);
hjk's avatar
hjk committed
246 247

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
248
        SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
249
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
250
        SLOT(setQtStyle()));
hjk's avatar
hjk committed
251
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
252 253
        SLOT(setPlainStyle()));

254
    if (m_searchKeywords.isEmpty()) {
255
        QLatin1Char sep(' ');
256
        QTextStream(&m_searchKeywords)
257 258 259 260 261 262 263 264 265 266
                << 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()
267
                << sep << m_ui.checkBoxSmartCase->text()
268 269 270 271 272 273
                << 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();
274 275
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
276 277 278 279 280
    return w;
}

void FakeVimOptionPage::copyTextEditorSettings()
{
Jarek Kobus's avatar
Jarek Kobus committed
281 282 283
    TabSettings ts = TextEditorSettings::instance()->codeStyle()->tabSettings();
    TypingSettings tps = TextEditorSettings::instance()->typingSettings();
    m_ui.checkBoxExpandTab->setChecked(ts.m_tabPolicy != TabSettings::TabsOnlyTabPolicy);
284 285
    m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
    m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
286
    m_ui.checkBoxSmartTab->setChecked(
Jarek Kobus's avatar
Jarek Kobus committed
287
        tps.m_smartBackspaceBehavior == TypingSettings::BackspaceFollowsPreviousIndents);
288
    m_ui.checkBoxAutoIndent->setChecked(true);
Jarek Kobus's avatar
Jarek Kobus committed
289
    m_ui.checkBoxSmartIndent->setChecked(tps.m_autoIndent);
290
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
291 292 293 294 295
}

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
296 297
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
298 299
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
300
    m_ui.checkBoxSmartIndent->setChecked(true);
301
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
302
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
303 304 305 306 307
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
308 309
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
310 311
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
312
    m_ui.checkBoxSmartIndent->setChecked(false);
313
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
314
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
315 316
}

317 318 319 320 321
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

322
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
323

324 325 326 327 328 329
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

330
enum { CommandRole = Qt::UserRole };
331

hjk's avatar
hjk committed
332
class FakeVimExCommandsPage : public CommandMappings
333 334 335 336
{
    Q_OBJECT

public:
337 338 339
    FakeVimExCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
340
        setId(_(SETTINGS_EX_CMDS_ID));
341
        setDisplayName(tr("Ex Command Mapping"));
hjk's avatar
hjk committed
342
        setCategory(_(SETTINGS_CATEGORY));
343
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
344
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
345
    }
346 347 348

    QWidget *createPage(QWidget *parent);
    void initialize();
349 350
    ExCommandMap &exCommandMap();
    ExCommandMap &defaultExCommandMap();
351 352 353

public slots:
    void commandChanged(QTreeWidgetItem *current);
354 355 356
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
357 358 359
    void defaultAction();

private:
360
    FakeVimPluginPrivate *m_q;
361 362 363 364
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
365 366 367
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
368
    setTargetLabelText(tr("Regular expression:"));
369 370
    setTargetEditTitle(tr("Ex Command"));
    setImportExportEnabled(false);
371 372 373 374 375
    return w;
}

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

hjk's avatar
hjk committed
378
    foreach (Command *c, ActionManager::commands()) {
379 380 381
        if (c->action() && c->action()->isSeparator())
            continue;

382
        QTreeWidgetItem *item = new QTreeWidgetItem;
383
        const QString name = c->id().toString();
384 385
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
386
        const QString subId = name.mid(pos + 1);
387
        item->setData(0, CommandRole, name);
388 389

        if (!sections.contains(section)) {
390 391
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
392 393 394 395
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
396
            commandList()->expandItem(categoryItem);
397 398 399 400
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
401
        item->setText(1, c->description());
402

403 404 405 406
        QString regex;
        if (exCommandMap().contains(name))
            regex = exCommandMap()[name].pattern();
        item->setText(2, regex);
407

408
        if (regex != defaultExCommandMap()[name].pattern())
409
            setModified(item, true);
410 411 412 413 414 415 416
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
417
    CommandMappings::commandChanged(current);
418 419
    if (current)
        targetEdit()->setText(current->text(2));
420 421
}

422
void FakeVimExCommandsPage::targetIdentifierChanged()
423
{
424
    QTreeWidgetItem *current = commandList()->currentItem();
425 426 427
    if (!current)
        return;

428
    const QString name =  current->data(0, CommandRole).toString();
429
    const QString regex = targetEdit()->text();
430 431

    if (current->data(0, Qt::UserRole).isValid()) {
432 433
        current->setText(2, regex);
        exCommandMap()[name] = QRegExp(regex);
434
    }
435

436
    setModified(current, regex != defaultExCommandMap()[name].pattern());
437 438
}

439
void FakeVimExCommandsPage::resetTargetIdentifier()
440
{
441
    QTreeWidgetItem *current = commandList()->currentItem();
442 443
    if (!current)
        return;
444
    const QString name = current->data(0, CommandRole).toString();
445 446 447 448
    QString regex;
    if (defaultExCommandMap().contains(name))
        regex = defaultExCommandMap()[name].pattern();
    targetEdit()->setText(regex);
449 450
}

451
void FakeVimExCommandsPage::removeTargetIdentifier()
452
{
453
    targetEdit()->clear();
454 455 456 457
}

void FakeVimExCommandsPage::defaultAction()
{
hjk's avatar
hjk committed
458 459 460 461 462 463
    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);
464
            const QString name = item->data(0, CommandRole).toString();
hjk's avatar
hjk committed
465 466 467 468 469 470 471 472
            QString regex;
            if (defaultExCommandMap().contains(name))
                regex = defaultExCommandMap()[name].pattern();
            setModified(item, false);
            item->setText(2, regex);
            if (item == commandList()->currentItem())
                commandChanged(item);
        }
473 474 475
    }
}

476 477 478 479 480 481 482 483
///////////////////////////////////////////////////////////////////////
//
// FakeVimUserCommandsPage
//
///////////////////////////////////////////////////////////////////////

class FakeVimUserCommandsModel : public QAbstractTableModel
{
Friedemann Kleint's avatar
Friedemann Kleint committed
484
    Q_OBJECT
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 547 548 549 550 551 552 553
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
554
class FakeVimUserCommandsPage : public IOptionsPage
555 556 557 558
{
    Q_OBJECT

public:
559 560 561
    FakeVimUserCommandsPage(FakeVimPluginPrivate *q)
        : m_q(q)
    {
hjk's avatar
hjk committed
562
        setId(_(SETTINGS_USER_CMDS_ID));
563
        setDisplayName(tr("User Command Mapping"));
hjk's avatar
hjk committed
564
        setCategory(_(SETTINGS_CATEGORY));
565
        setDisplayCategory(tr("FakeVim"));
hjk's avatar
hjk committed
566
        setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
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
    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
605 606 607 608 609 610 611

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

hjk's avatar
hjk committed
612
class FakeVimCompletionAssistProvider : public CompletionAssistProvider
hjk's avatar
hjk committed
613 614
{
public:
hjk's avatar
hjk committed
615
    bool supportsEditor(const Id &) const
hjk's avatar
hjk committed
616
    {
Leandro Melo's avatar
Leandro Melo committed
617
        return false;
hjk's avatar
hjk committed
618 619
    }

hjk's avatar
hjk committed
620
    IAssistProcessor *createProcessor() const;
Leandro Melo's avatar
Leandro Melo committed
621 622

    void setActive(const QString &needle, bool forward, FakeVimHandler *handler)
hjk's avatar
hjk committed
623
    {
Leandro Melo's avatar
Leandro Melo committed
624 625 626 627 628 629 630 631 632 633 634 635
        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
636 637
    }

Leandro Melo's avatar
Leandro Melo committed
638
    void setInactive()
hjk's avatar
hjk committed
639
    {
Leandro Melo's avatar
Leandro Melo committed
640 641
        m_needle.clear();
        m_handler = 0;
hjk's avatar
hjk committed
642 643
    }

Leandro Melo's avatar
Leandro Melo committed
644
    const QString &needle() const
645
    {
Leandro Melo's avatar
Leandro Melo committed
646
        return m_needle;
647
    }
hjk's avatar
hjk committed
648

Leandro Melo's avatar
Leandro Melo committed
649
    void appendNeedle(const QChar &c)
650
    {
Leandro Melo's avatar
Leandro Melo committed
651
        m_needle.append(c);
652 653
    }

Leandro Melo's avatar
Leandro Melo committed
654
    FakeVimHandler *handler() const
655
    {
Leandro Melo's avatar
Leandro Melo committed
656
        return m_handler;
657
    }
hjk's avatar
hjk committed
658

Leandro Melo's avatar
Leandro Melo committed
659 660 661 662 663 664 665 666 667 668 669 670 671
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
672
    {
Leandro Melo's avatar
Leandro Melo committed
673
        return false;
hjk's avatar
hjk committed
674 675
    }

Leandro Melo's avatar
Leandro Melo committed
676
    virtual bool prematurelyApplies(const QChar &c) const
hjk's avatar
hjk committed
677
    {
Leandro Melo's avatar
Leandro Melo committed
678 679
        m_provider->appendNeedle(c);
        return text() == m_provider->needle();
hjk's avatar
hjk committed
680 681
    }

Leandro Melo's avatar
Leandro Melo committed
682
    virtual void applyContextualContent(BaseTextEditor *, int) const
hjk's avatar
hjk committed
683
    {
Leandro Melo's avatar
Leandro Melo committed
684 685 686
        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
687 688
    }

Leandro Melo's avatar
Leandro Melo committed
689 690 691 692 693 694 695 696 697 698 699 700 701
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
702
    {
Leandro Melo's avatar
Leandro Melo committed
703
        return false;
hjk's avatar
hjk committed
704
    }
Leandro Melo's avatar
Leandro Melo committed
705
};
hjk's avatar
hjk committed
706

Leandro Melo's avatar
Leandro Melo committed
707 708 709
class FakeVimCompletionAssistProcessor : public IAssistProcessor
{
public:
hjk's avatar
hjk committed
710
    FakeVimCompletionAssistProcessor(const IAssistProvider *provider)
Leandro Melo's avatar
Leandro Melo committed
711 712 713
        : m_provider(static_cast<const FakeVimCompletionAssistProvider *>(provider))
    {}

hjk's avatar
hjk committed
714
    IAssistProposal *perform(const IAssistInterface *interface)
hjk's avatar
hjk committed
715
    {
Leandro Melo's avatar
Leandro Melo committed
716 717 718 719
        const QString &needle = m_provider->needle();

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

720
        QTextCursor tc(interface->textDocument());
Leandro Melo's avatar
Leandro Melo committed
721
        tc.setPosition(interface->position());
hjk's avatar
hjk committed
722 723
        tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

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

Leandro Melo's avatar
Leandro Melo committed
747 748
        delete interface;
        return new GenericProposal(basePosition, new FakeVimAssistProposalModel(items));
hjk's avatar
hjk committed
749 750 751
    }

private:
Leandro Melo's avatar
Leandro Melo committed
752
    const FakeVimCompletionAssistProvider *m_provider;
hjk's avatar
hjk committed
753
};
754

Leandro Melo's avatar
Leandro Melo committed
755 756 757 758 759
IAssistProcessor *FakeVimCompletionAssistProvider::createProcessor() const
{
    return new FakeVimCompletionAssistProcessor(this);
}

760

hjk's avatar
hjk committed
761 762
///////////////////////////////////////////////////////////////////////
//
763
// FakeVimPluginPrivate
hjk's avatar
hjk committed
764 765 766
//
///////////////////////////////////////////////////////////////////////

767
class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
768
{
769 770 771 772 773 774
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
775
    friend class FakeVimExCommandsPage;
776 777
    friend class FakeVimUserCommandsPage;
    friend class FakeVimUserCommandsModel;
778

779
    bool initialize();
780
    void aboutToShutdown();
781 782

private slots:
783
    void onCoreAboutToClose();
784 785
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
786

787
    void setUseFakeVim(const QVariant &value);
788
    void setUseFakeVimInternal(bool on);
789
    void quitFakeVim();
790
    void triggerCompletions();
791
    void triggerSimpleCompletions(const QString &needle, bool forward);
hjk's avatar
hjk committed
792
    void windowCommand(int key);
793
    void find(bool reverse);
794
    void findNext(bool reverse);
hjk's avatar
hjk committed
795
    void showSettingsDialog();
796
    void maybeReadVimRc();
hjk's avatar
hjk committed
797 798
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
799

800
    void showCommandBuffer(const QString &contents, int cursorPos);
801 802
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
803
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
804
    void checkForElectricCharacter(bool *result, QChar c);
805
    void indentRegion(int beginLine, int endLine, QChar typedChar);
806
    void handleExCommand(bool *handled, const ExCommand &cmd);
807

808 809 810
    void writeSettings();
    void readSettings();

811 812
    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);
813
    void userActionTriggered();
814

815 816
    void switchToFile(int n);
    int currentFile() const;
817

818 819 820
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
821 822 823

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
824
    FakeVimOptionPage *m_fakeVimOptionsPage;
825
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
826
    FakeVimUserCommandsPage *m_fakeVimUserCommandsPage;
hjk's avatar
hjk committed
827
    QHash<IEditor *, FakeVimHandler *> m_editorToHandler;
828

hjk's avatar
hjk committed
829 830
    void triggerAction(const Id &id);
    void setActionChecked(const Id &id, bool check);
831

832 833 834
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

835 836 837 838 839 840 841 842 843 844
    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
845
    StatusBarWidget *m_statusBar;
Leandro Melo's avatar
Leandro Melo committed
846 847 848
    // @TODO: Delete
    //WordCompletion *m_wordCompletion;
    FakeVimCompletionAssistProvider *m_wordProvider;
849 850
};

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
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;
}

877
FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
878
{
879
    q = plugin;
hjk's avatar
hjk committed
880
    m_fakeVimOptionsPage = 0;
881
    m_fakeVimExCommandsPage = 0;
882
    m_fakeVimUserCommandsPage = 0;
883
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
884
        QRegExp("^A$");
885
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
886
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
887