fakevimplugin.cpp 58.1 KB
Newer Older
1
/**************************************************************************
hjk's avatar
hjk committed
2 3 4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
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.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
hjk's avatar
hjk committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32 33 34

#include "fakevimplugin.h"

35
#include "fakevimhandler.h"
hjk's avatar
hjk committed
36 37
#include "ui_fakevimoptions.h"

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

#include <projectexplorer/projectexplorerconstants.h>

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

73
#include <find/findplugin.h>
74 75
#include <find/textfindconstants.h>

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

81 82
#include <cppeditor/cppeditorconstants.h>

83 84
#include <cpptools/cpptoolsconstants.h>

85
#include <QtCore/QAbstractTableModel>
hjk's avatar
hjk committed
86
#include <QtCore/QDebug>
87
#include <QtCore/QFile>
88
#include <QtCore/QtPlugin>
hjk's avatar
hjk committed
89 90
#include <QtCore/QObject>
#include <QtCore/QSettings>
91
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
92

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

using namespace FakeVim::Internal;
using namespace TextEditor;
using namespace Core;

namespace FakeVim {
namespace Constants {

hjk's avatar
hjk committed
110 111 112 113 114 115 116 117
const char INSTALL_HANDLER[]                = "TextEditor.FakeVimHandler";
const char MINI_BUFFER[]                    = "TextEditor.FakeVimMiniBuffer";
const char INSTALL_KEY[]                    = "Alt+V,Alt+V";
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
118 119 120 121 122

} // namespace Constants
} // namespace FakeVim


hjk's avatar
hjk committed
123 124 125
namespace FakeVim {
namespace Internal {

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
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
171 172 173 174 175 176
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

177 178
typedef QMap<QString, QRegExp> ExCommandMap;
typedef QMap<int, QString> UserCommandMap;
hjk's avatar
hjk committed
179
typedef QLatin1String _;
180

hjk's avatar
hjk committed
181 182 183 184 185 186 187 188
class FakeVimOptionPage : public Core::IOptionsPage
{
    Q_OBJECT

public:
    FakeVimOptionPage() {}

    // IOptionsPage
hjk's avatar
hjk committed
189
    QString id() const { return _(Constants::SETTINGS_ID); }
190
    QString displayName() const { return tr("General"); }
hjk's avatar
hjk committed
191
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
192
    QString displayCategory() const { return tr("FakeVim"); }
hjk's avatar
hjk committed
193 194
    QIcon categoryIcon() const
        { return QIcon(_(Constants::SETTINGS_CATEGORY_FAKEVIM_ICON)); }
hjk's avatar
hjk committed
195 196 197 198

    QWidget *createPage(QWidget *parent);
    void apply() { m_group.apply(ICore::instance()->settings()); }
    void finish() { m_group.finish(); }
199
    virtual bool matches(const QString &) const;
hjk's avatar
hjk committed
200 201 202 203 204 205 206 207 208

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

private:
    friend class DebuggerPlugin;
    Ui::FakeVimOptionPage m_ui;
209
    QString m_searchKeywords;
210
    Utils::SavedActionSet m_group;
hjk's avatar
hjk committed
211 212 213 214 215 216 217 218
};

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

    m_group.clear();
219
    m_group.insert(theFakeVimSetting(ConfigUseFakeVim),
220
        m_ui.checkBoxUseFakeVim);
221 222
    m_group.insert(theFakeVimSetting(ConfigReadVimRc),
        m_ui.checkBoxReadVimRc);
hjk's avatar
hjk committed
223

224
    m_group.insert(theFakeVimSetting(ConfigExpandTab),
hjk's avatar
hjk committed
225
        m_ui.checkBoxExpandTab);
226
    m_group.insert(theFakeVimSetting(ConfigHlSearch),
hjk's avatar
hjk committed
227
        m_ui.checkBoxHlSearch);
228
    m_group.insert(theFakeVimSetting(ConfigShiftWidth),
229
        m_ui.spinBoxShiftWidth);
230 231
    m_group.insert(theFakeVimSetting(ConfigShowMarks),
        m_ui.checkBoxShowMarks);
hjk's avatar
hjk committed
232

233
    m_group.insert(theFakeVimSetting(ConfigSmartTab),
hjk's avatar
hjk committed
234
        m_ui.checkBoxSmartTab);
235
    m_group.insert(theFakeVimSetting(ConfigStartOfLine),
hjk's avatar
hjk committed
236
        m_ui.checkBoxStartOfLine);
237
    m_group.insert(theFakeVimSetting(ConfigTabStop),
238
        m_ui.spinBoxTabStop);
239
    m_group.insert(theFakeVimSetting(ConfigBackspace),
hjk's avatar
hjk committed
240
        m_ui.lineEditBackspace);
241 242
    m_group.insert(theFakeVimSetting(ConfigIsKeyword),
        m_ui.lineEditIsKeyword);
hjk's avatar
hjk committed
243

244 245
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
246
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
247
        m_ui.checkBoxAutoIndent);
248
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
249
        m_ui.checkBoxSmartIndent);
250
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
251
        m_ui.checkBoxIncSearch);
252 253
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
hjk's avatar
hjk committed
254 255

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
256
        SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
257
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
258
        SLOT(setQtStyle()));
hjk's avatar
hjk committed
259
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
260 261
        SLOT(setPlainStyle()));

262
    if (m_searchKeywords.isEmpty()) {
263
        QLatin1Char sep(' ');
264
        QTextStream(&m_searchKeywords)
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                << 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();
281 282
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
283 284 285 286 287
    return w;
}

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

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
303 304
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
305 306
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
307
    m_ui.checkBoxSmartIndent->setChecked(true);
308
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
309
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
310 311 312 313 314
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
315 316
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
317 318
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
319
    m_ui.checkBoxSmartIndent->setChecked(false);
320
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
321
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
322 323
}

324 325 326 327 328
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

329
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
330

331 332 333 334 335 336
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

337
enum { CommandRole = Qt::UserRole };
338

339
class FakeVimExCommandsPage : public Core::CommandMappings
340 341 342 343
{
    Q_OBJECT

public:
344
    FakeVimExCommandsPage(FakeVimPluginPrivate *q) : m_q(q) {}
345
    ~FakeVimExCommandsPage() {}
346 347

    // IOptionsPage
hjk's avatar
hjk committed
348
    QString id() const { return _(Constants::SETTINGS_EX_CMDS_ID); }
349
    QString displayName() const { return tr("Ex Command Mapping"); }
hjk's avatar
hjk committed
350
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
351
    QString displayCategory() const { return tr("FakeVim"); }
352
    QIcon categoryIcon() const { return QIcon(); } // TODO: Icon for FakeVim
353 354 355

    QWidget *createPage(QWidget *parent);
    void initialize();
356 357
    ExCommandMap &exCommandMap();
    ExCommandMap &defaultExCommandMap();
358 359 360

public slots:
    void commandChanged(QTreeWidgetItem *current);
361 362 363
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
364 365 366
    void defaultAction();

private:
367
    FakeVimPluginPrivate *m_q;
368 369 370 371
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
372 373 374
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
375
    setTargetLabelText(tr("Regular expression:"));
376 377
    setTargetEditTitle(tr("Ex Command"));
    setImportExportEnabled(false);
378 379 380 381 382
    return w;
}

void FakeVimExCommandsPage::initialize()
{
hjk's avatar
hjk committed
383
    ActionManager *am = ICore::instance()->actionManager();
384 385
    QTC_ASSERT(am, return);

386 387
    QMap<QString, QTreeWidgetItem *> sections;

388 389 390 391
    foreach (Command *c, am->commands()) {
        if (c->action() && c->action()->isSeparator())
            continue;

392
        QTreeWidgetItem *item = new QTreeWidgetItem;
393
        const QString name = Id::fromUniqueIdentifier(c->id()).toString();
394 395
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
396
        const QString subId = name.mid(pos + 1);
397
        item->setData(0, CommandRole, name);
398 399

        if (!sections.contains(section)) {
400 401
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
402 403 404 405
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
406
            commandList()->expandItem(categoryItem);
407 408 409 410
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
411 412

        if (c->action()) {
413 414 415
            QString text = c->hasAttribute(Command::CA_UpdateText)
                    && !c->defaultText().isNull()
                ? c->defaultText() : c->action()->text();
416 417 418 419 420 421
            text.remove(QRegExp("&(?!&)"));
            item->setText(1, text);
        } else {
            item->setText(1, c->shortcut()->whatsThis());
        }

422 423 424 425
        QString regex;
        if (exCommandMap().contains(name))
            regex = exCommandMap()[name].pattern();
        item->setText(2, regex);
426

427
        if (regex != defaultExCommandMap()[name].pattern())
428
            setModified(item, true);
429 430 431 432 433 434 435
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
436
    CommandMappings::commandChanged(current);
437 438
    if (current)
        targetEdit()->setText(current->text(2));
439 440
}

441
void FakeVimExCommandsPage::targetIdentifierChanged()
442
{
443
    QTreeWidgetItem *current = commandList()->currentItem();
444 445 446
    if (!current)
        return;

447
    const QString name =  current->data(0, CommandRole).toString();
448
    const QString regex = targetEdit()->text();
449 450

    if (current->data(0, Qt::UserRole).isValid()) {
451 452
        current->setText(2, regex);
        exCommandMap()[name] = QRegExp(regex);
453
    }
454

455
    setModified(current, regex != defaultExCommandMap()[name].pattern());
456 457
}

458
void FakeVimExCommandsPage::resetTargetIdentifier()
459
{
460
    QTreeWidgetItem *current = commandList()->currentItem();
461 462
    if (!current)
        return;
463
    const QString name = current->data(0, CommandRole).toString();
464 465 466 467
    QString regex;
    if (defaultExCommandMap().contains(name))
        regex = defaultExCommandMap()[name].pattern();
    targetEdit()->setText(regex);
468 469
}

470
void FakeVimExCommandsPage::removeTargetIdentifier()
471
{
472
    targetEdit()->clear();
473 474 475 476
}

void FakeVimExCommandsPage::defaultAction()
{
hjk's avatar
hjk committed
477 478 479 480 481 482
    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);
483
            const QString name = item->data(0, CommandRole).toString();
hjk's avatar
hjk committed
484 485 486 487 488 489 490 491
            QString regex;
            if (defaultExCommandMap().contains(name))
                regex = defaultExCommandMap()[name].pattern();
            setModified(item, false);
            item->setText(2, regex);
            if (item == commandList()->currentItem())
                commandChanged(item);
        }
492 493 494
    }
}

495 496 497 498 499 500 501 502
///////////////////////////////////////////////////////////////////////
//
// FakeVimUserCommandsPage
//
///////////////////////////////////////////////////////////////////////

class FakeVimUserCommandsModel : public QAbstractTableModel
{
Friedemann Kleint's avatar
Friedemann Kleint committed
503
    Q_OBJECT
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 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 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
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);
    }
};

class FakeVimUserCommandsPage : public Core::IOptionsPage
{
    Q_OBJECT

public:
    FakeVimUserCommandsPage(FakeVimPluginPrivate *q) : m_q(q) {}
    ~FakeVimUserCommandsPage() {}

    // IOptionsPage
    QString id() const { return _(Constants::SETTINGS_USER_CMDS_ID); }
    QString displayName() const { return tr("User Command Mapping"); }
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
    QString displayCategory() const { return tr("FakeVim"); }
    QIcon categoryIcon() const { return QIcon(); }
    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
623 624 625 626 627 628 629

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

Leandro Melo's avatar
Leandro Melo committed
630
class FakeVimCompletionAssistProvider : public TextEditor::CompletionAssistProvider
hjk's avatar
hjk committed
631 632
{
public:
hjk's avatar
hjk committed
633
    bool supportsEditor(const Core::Id &) const
hjk's avatar
hjk committed
634
    {
Leandro Melo's avatar
Leandro Melo committed
635
        return false;
hjk's avatar
hjk committed
636 637
    }

hjk's avatar
hjk committed
638
    TextEditor::IAssistProcessor *createProcessor() const;
Leandro Melo's avatar
Leandro Melo committed
639 640

    void setActive(const QString &needle, bool forward, FakeVimHandler *handler)
hjk's avatar
hjk committed
641
    {
Leandro Melo's avatar
Leandro Melo committed
642 643 644 645 646 647 648 649 650 651 652 653
        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
654 655
    }

Leandro Melo's avatar
Leandro Melo committed
656
    void setInactive()
hjk's avatar
hjk committed
657
    {
Leandro Melo's avatar
Leandro Melo committed
658 659
        m_needle.clear();
        m_handler = 0;
hjk's avatar
hjk committed
660 661
    }

Leandro Melo's avatar
Leandro Melo committed
662
    const QString &needle() const
663
    {
Leandro Melo's avatar
Leandro Melo committed
664
        return m_needle;
665
    }
hjk's avatar
hjk committed
666

Leandro Melo's avatar
Leandro Melo committed
667
    void appendNeedle(const QChar &c)
668
    {
Leandro Melo's avatar
Leandro Melo committed
669
        m_needle.append(c);
670 671
    }

Leandro Melo's avatar
Leandro Melo committed
672
    FakeVimHandler *handler() const
673
    {
Leandro Melo's avatar
Leandro Melo committed
674
        return m_handler;
675
    }
hjk's avatar
hjk committed
676

Leandro Melo's avatar
Leandro Melo committed
677 678 679 680 681 682 683 684 685 686 687 688 689
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
690
    {
Leandro Melo's avatar
Leandro Melo committed
691
        return false;
hjk's avatar
hjk committed
692 693
    }

Leandro Melo's avatar
Leandro Melo committed
694
    virtual bool prematurelyApplies(const QChar &c) const
hjk's avatar
hjk committed
695
    {
Leandro Melo's avatar
Leandro Melo committed
696 697
        m_provider->appendNeedle(c);
        return text() == m_provider->needle();
hjk's avatar
hjk committed
698 699
    }

Leandro Melo's avatar
Leandro Melo committed
700
    virtual void applyContextualContent(BaseTextEditor *, int) const
hjk's avatar
hjk committed
701
    {
Leandro Melo's avatar
Leandro Melo committed
702 703 704
        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
705 706
    }

Leandro Melo's avatar
Leandro Melo committed
707 708 709 710 711 712 713 714 715 716 717 718 719
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
720
    {
Leandro Melo's avatar
Leandro Melo committed
721
        return false;
hjk's avatar
hjk committed
722
    }
Leandro Melo's avatar
Leandro Melo committed
723
};
hjk's avatar
hjk committed
724

Leandro Melo's avatar
Leandro Melo committed
725 726 727 728 729 730 731 732
class FakeVimCompletionAssistProcessor : public IAssistProcessor
{
public:
    FakeVimCompletionAssistProcessor(const TextEditor::IAssistProvider *provider)
        : m_provider(static_cast<const FakeVimCompletionAssistProvider *>(provider))
    {}

    virtual TextEditor::IAssistProposal *perform(const IAssistInterface *interface)
hjk's avatar
hjk committed
733
    {
Leandro Melo's avatar
Leandro Melo committed
734 735 736 737 738 739
        const QString &needle = m_provider->needle();

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

        QTextCursor tc(interface->document());
        tc.setPosition(interface->position());
hjk's avatar
hjk committed
740 741
        tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

Leandro Melo's avatar
Leandro Melo committed
742
        QList<BasicProposalItem *> items;
hjk's avatar
hjk committed
743 744 745
        QSet<QString> seen;
        QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
        while (1) {
Leandro Melo's avatar
Leandro Melo committed
746
            tc = tc.document()->find(needle, tc.position(), flags);
hjk's avatar
hjk committed
747 748 749 750 751 752
            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
753
            if (found.startsWith(needle)
hjk's avatar
hjk committed
754
                    && !seen.contains(found)
Leandro Melo's avatar
Leandro Melo committed
755
                    && sel.anchor() != basePosition) {
hjk's avatar
hjk committed
756
                seen.insert(found);
Leandro Melo's avatar
Leandro Melo committed
757 758 759
                BasicProposalItem *item = new FakeVimAssistProposalItem(m_provider);
                item->setText(found);
                items.append(item);
hjk's avatar
hjk committed
760 761 762 763 764
            }
            tc.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
        }
        //qDebug() << "COMPLETIONS" << completions->size();

Leandro Melo's avatar
Leandro Melo committed
765 766
        delete interface;
        return new GenericProposal(basePosition, new FakeVimAssistProposalModel(items));
hjk's avatar
hjk committed
767 768 769
    }

private:
Leandro Melo's avatar
Leandro Melo committed
770
    const FakeVimCompletionAssistProvider *m_provider;
hjk's avatar
hjk committed
771
};
772

Leandro Melo's avatar
Leandro Melo committed
773 774 775 776 777
IAssistProcessor *FakeVimCompletionAssistProvider::createProcessor() const
{
    return new FakeVimCompletionAssistProcessor(this);
}

778

hjk's avatar
hjk committed
779 780
///////////////////////////////////////////////////////////////////////
//
781
// FakeVimPluginPrivate
hjk's avatar
hjk committed
782 783 784
//
///////////////////////////////////////////////////////////////////////

785
class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
786
{
787 788 789 790 791 792
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
793
    friend class FakeVimExCommandsPage;
794 795
    friend class FakeVimUserCommandsPage;
    friend class FakeVimUserCommandsModel;
796

797
    bool initialize();
798
    void aboutToShutdown();
799 800

private slots:
801
    void onCoreAboutToClose();
802 803
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
804

805
    void setUseFakeVim(const QVariant &value);
806
    void setUseFakeVimInternal(bool on);
807
    void quitFakeVim();
808
    void triggerCompletions();
809
    void triggerSimpleCompletions(const QString &needle, bool forward);
hjk's avatar
hjk committed
810
    void windowCommand(int key);
811
    void find(bool reverse);
812
    void findNext(bool reverse);
hjk's avatar
hjk committed
813
    void showSettingsDialog();
814
    void maybeReadVimRc();
hjk's avatar
hjk committed
815 816
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
817

818
    void showCommandBuffer(const QString &contents, int cursorPos);
819 820
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
821
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
822
    void checkForElectricCharacter(bool *result, QChar c);
823
    void indentRegion(int beginLine, int endLine, QChar typedChar);
824
    void handleExCommand(bool *handled, const ExCommand &cmd);
825

826 827 828
    void writeSettings();
    void readSettings();

829 830
    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);
831
    void userActionTriggered();
832

833 834
    void switchToFile(int n);
    int currentFile() const;
835

836 837 838
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
839 840 841

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
842
    FakeVimOptionPage *m_fakeVimOptionsPage;
843
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
844
    FakeVimUserCommandsPage *m_fakeVimUserCommandsPage;
845
    QHash<Core::IEditor *, FakeVimHandler *> m_editorToHandler;
846

hjk's avatar
hjk committed
847 848
    void triggerAction(const Core::Id &id);
    void setActionChecked(const Core::Id &id, bool check);
849

850 851 852
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

853 854 855 856 857 858 859 860 861 862
    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;

863
    Core::StatusBarWidget *m_statusBar;
Leandro Melo's avatar
Leandro Melo committed
864 865 866
    // @TODO: Delete
    //WordCompletion *m_wordCompletion;
    FakeVimCompletionAssistProvider *m_wordProvider;
867 868
};

869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
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;
}

895
FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
896
{
897
    q = plugin;
hjk's avatar
hjk committed
898
    m_fakeVimOptionsPage = 0;
899
    m_fakeVimExCommandsPage = 0;
900
    m_fakeVimUserCommandsPage = 0;
901
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
902
        QRegExp("^A$");
903
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
904
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");