fakevimplugin.cpp 56.9 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
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.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
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.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 51
#include <coreplugin/messagemanager.h>
#include <coreplugin/uniqueidmanager.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>
61 62
#include <texteditor/tabsettings.h>
#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>
hjk's avatar
hjk committed
77

78 79
#include <cppeditor/cppeditorconstants.h>

80 81
#include <cpptools/cpptoolsconstants.h>

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

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

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

namespace FakeVim {
namespace Constants {

con's avatar
con committed
107 108 109 110 111 112 113
const char * const INSTALL_HANDLER                = "TextEditor.FakeVimHandler";
const char * const MINI_BUFFER                    = "TextEditor.FakeVimMiniBuffer";
const char * const INSTALL_KEY                    = "Alt+V,Alt+V";
const char * const SETTINGS_CATEGORY              = "D.FakeVim";
const char * const SETTINGS_CATEGORY_FAKEVIM_ICON = ":/core/images/category_fakevim.png";
const char * const SETTINGS_ID                    = "A.General";
const char * const SETTINGS_EX_CMDS_ID            = "B.ExCommands";
114
const char * const SETTINGS_USER_CMDS_ID          = "C.UserCommands";
hjk's avatar
hjk committed
115 116 117 118 119

} // namespace Constants
} // namespace FakeVim


hjk's avatar
hjk committed
120 121 122
namespace FakeVim {
namespace Internal {

hjk's avatar
hjk committed
123 124 125 126 127 128
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

129 130
typedef QMap<QString, QRegExp> ExCommandMap;
typedef QMap<int, QString> UserCommandMap;
hjk's avatar
hjk committed
131
typedef QLatin1String _;
132

hjk's avatar
hjk committed
133 134 135 136 137 138 139 140
class FakeVimOptionPage : public Core::IOptionsPage
{
    Q_OBJECT

public:
    FakeVimOptionPage() {}

    // IOptionsPage
hjk's avatar
hjk committed
141
    QString id() const { return _(Constants::SETTINGS_ID); }
142
    QString displayName() const { return tr("General"); }
hjk's avatar
hjk committed
143
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
144
    QString displayCategory() const { return tr("FakeVim"); }
hjk's avatar
hjk committed
145 146
    QIcon categoryIcon() const
        { return QIcon(_(Constants::SETTINGS_CATEGORY_FAKEVIM_ICON)); }
hjk's avatar
hjk committed
147 148 149 150

    QWidget *createPage(QWidget *parent);
    void apply() { m_group.apply(ICore::instance()->settings()); }
    void finish() { m_group.finish(); }
151
    virtual bool matches(const QString &) const;
hjk's avatar
hjk committed
152 153 154 155 156 157 158 159 160

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

private:
    friend class DebuggerPlugin;
    Ui::FakeVimOptionPage m_ui;
161
    QString m_searchKeywords;
162
    Utils::SavedActionSet m_group;
hjk's avatar
hjk committed
163 164 165 166 167 168 169 170
};

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

    m_group.clear();
171
    m_group.insert(theFakeVimSetting(ConfigUseFakeVim),
172
        m_ui.checkBoxUseFakeVim);
173 174
    m_group.insert(theFakeVimSetting(ConfigReadVimRc),
        m_ui.checkBoxReadVimRc);
hjk's avatar
hjk committed
175

176
    m_group.insert(theFakeVimSetting(ConfigExpandTab),
hjk's avatar
hjk committed
177
        m_ui.checkBoxExpandTab);
178
    m_group.insert(theFakeVimSetting(ConfigHlSearch),
hjk's avatar
hjk committed
179
        m_ui.checkBoxHlSearch);
180
    m_group.insert(theFakeVimSetting(ConfigShiftWidth),
181
        m_ui.spinBoxShiftWidth);
182 183
    m_group.insert(theFakeVimSetting(ConfigShowMarks),
        m_ui.checkBoxShowMarks);
hjk's avatar
hjk committed
184

185
    m_group.insert(theFakeVimSetting(ConfigSmartTab),
hjk's avatar
hjk committed
186
        m_ui.checkBoxSmartTab);
187
    m_group.insert(theFakeVimSetting(ConfigStartOfLine),
hjk's avatar
hjk committed
188
        m_ui.checkBoxStartOfLine);
189
    m_group.insert(theFakeVimSetting(ConfigTabStop),
190
        m_ui.spinBoxTabStop);
191
    m_group.insert(theFakeVimSetting(ConfigBackspace),
hjk's avatar
hjk committed
192
        m_ui.lineEditBackspace);
193 194
    m_group.insert(theFakeVimSetting(ConfigIsKeyword),
        m_ui.lineEditIsKeyword);
hjk's avatar
hjk committed
195

196 197
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
198
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
199
        m_ui.checkBoxAutoIndent);
200
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
201
        m_ui.checkBoxSmartIndent);
202
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
203
        m_ui.checkBoxIncSearch);
204 205
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
hjk's avatar
hjk committed
206 207

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
208
        SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
209
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
210
        SLOT(setQtStyle()));
hjk's avatar
hjk committed
211
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
212 213
        SLOT(setPlainStyle()));

214
    if (m_searchKeywords.isEmpty()) {
215
        QLatin1Char sep(' ');
216
        QTextStream(&m_searchKeywords)
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                << 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();
233 234
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
235 236 237 238 239
    return w;
}

void FakeVimOptionPage::copyTextEditorSettings()
{
hjk's avatar
hjk committed
240
    TabSettings ts = TextEditorSettings::instance()->tabSettings();
hjk's avatar
hjk committed
241
    m_ui.checkBoxExpandTab->setChecked(ts.m_spacesForTabs);
242 243
    m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
    m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
hjk's avatar
hjk committed
244
    m_ui.checkBoxSmartTab->setChecked(ts.m_smartBackspace);
245 246
    m_ui.checkBoxAutoIndent->setChecked(true);
    m_ui.checkBoxSmartIndent->setChecked(ts.m_autoIndent);
247
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
248 249 250 251 252
}

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
253 254
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
255 256
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
257
    m_ui.checkBoxSmartIndent->setChecked(true);
258
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
259
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
260 261 262 263 264
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
265 266
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
267 268
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
269
    m_ui.checkBoxSmartIndent->setChecked(false);
270
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
271
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
272 273
}

274 275 276 277 278
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

279
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
280

281 282 283 284 285 286
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

287
enum { CommandRole = Qt::UserRole };
288

289
class FakeVimExCommandsPage : public Core::CommandMappings
290 291 292 293
{
    Q_OBJECT

public:
294
    FakeVimExCommandsPage(FakeVimPluginPrivate *q) : m_q(q) {}
295
    ~FakeVimExCommandsPage() {}
296 297

    // IOptionsPage
hjk's avatar
hjk committed
298
    QString id() const { return _(Constants::SETTINGS_EX_CMDS_ID); }
299
    QString displayName() const { return tr("Ex Command Mapping"); }
hjk's avatar
hjk committed
300
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
301
    QString displayCategory() const { return tr("FakeVim"); }
302
    QIcon categoryIcon() const { return QIcon(); } // TODO: Icon for FakeVim
303 304 305

    QWidget *createPage(QWidget *parent);
    void initialize();
306 307
    ExCommandMap &exCommandMap();
    ExCommandMap &defaultExCommandMap();
308 309 310

public slots:
    void commandChanged(QTreeWidgetItem *current);
311 312 313
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
314 315 316
    void defaultAction();

private:
317
    FakeVimPluginPrivate *m_q;
318 319 320 321
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
322 323 324
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
325
    setTargetLabelText(tr("Regular expression:"));
326 327
    setTargetEditTitle(tr("Ex Command"));
    setImportExportEnabled(false);
328 329 330 331 332
    return w;
}

void FakeVimExCommandsPage::initialize()
{
hjk's avatar
hjk committed
333
    ActionManager *am = ICore::instance()->actionManager();
334 335 336 337
    QTC_ASSERT(am, return);
    UniqueIDManager *uidm = UniqueIDManager::instance();
    QTC_ASSERT(uidm, return);

338 339
    QMap<QString, QTreeWidgetItem *> sections;

340 341 342 343
    foreach (Command *c, am->commands()) {
        if (c->action() && c->action()->isSeparator())
            continue;

344
        QTreeWidgetItem *item = new QTreeWidgetItem;
345
        item->setData(0, CommandRole, int(c->id()));
346 347

        const QString name = uidm->stringForUniqueIdentifier(c->id());
348 349
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
350
        const QString subId = name.mid(pos + 1);
351 352

        if (!sections.contains(section)) {
353 354
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
355 356 357 358
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
359
            commandList()->expandItem(categoryItem);
360 361 362 363
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
364 365

        if (c->action()) {
366 367 368
            QString text = c->hasAttribute(Command::CA_UpdateText)
                    && !c->defaultText().isNull()
                ? c->defaultText() : c->action()->text();
369 370 371 372 373 374
            text.remove(QRegExp("&(?!&)"));
            item->setText(1, text);
        } else {
            item->setText(1, c->shortcut()->whatsThis());
        }

375 376 377 378
        QString regex;
        if (exCommandMap().contains(name))
            regex = exCommandMap()[name].pattern();
        item->setText(2, regex);
379

380
        if (regex != defaultExCommandMap()[name].pattern())
381
            setModified(item, true);
382 383 384 385 386 387 388
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
389
    CommandMappings::commandChanged(current);
390 391
    if (current)
        targetEdit()->setText(current->text(2));
392 393
}

394
void FakeVimExCommandsPage::targetIdentifierChanged()
395
{
396
    QTreeWidgetItem *current = commandList()->currentItem();
397 398 399 400
    if (!current)
        return;

    UniqueIDManager *uidm = UniqueIDManager::instance();
401 402 403
    int id = current->data(0, CommandRole).toInt();
    const QString name = uidm->stringForUniqueIdentifier(id);
    const QString regex = targetEdit()->text();
404 405

    if (current->data(0, Qt::UserRole).isValid()) {
406 407
        current->setText(2, regex);
        exCommandMap()[name] = QRegExp(regex);
408
    }
409

410
    setModified(current, regex != defaultExCommandMap()[name].pattern());
411 412
}

413
void FakeVimExCommandsPage::resetTargetIdentifier()
414
{
415
    QTreeWidgetItem *current = commandList()->currentItem();
416 417 418 419 420 421 422 423 424
    if (!current)
        return;
    UniqueIDManager *uidm = UniqueIDManager::instance();
    int id = current->data(0, CommandRole).toInt();
    const QString name = uidm->stringForUniqueIdentifier(id);
    QString regex;
    if (defaultExCommandMap().contains(name))
        regex = defaultExCommandMap()[name].pattern();
    targetEdit()->setText(regex);
425 426
}

427
void FakeVimExCommandsPage::removeTargetIdentifier()
428
{
429
    targetEdit()->clear();
430 431 432 433 434
}

void FakeVimExCommandsPage::defaultAction()
{
    UniqueIDManager *uidm = UniqueIDManager::instance();
hjk's avatar
hjk committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    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);
            const int id = item->data(0, CommandRole).toInt();
            const QString name = uidm->stringForUniqueIdentifier(id);
            QString regex;
            if (defaultExCommandMap().contains(name))
                regex = defaultExCommandMap()[name].pattern();
            setModified(item, false);
            item->setText(2, regex);
            if (item == commandList()->currentItem())
                commandChanged(item);
        }
451 452 453
    }
}

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 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
///////////////////////////////////////////////////////////////////////
//
// FakeVimUserCommandsPage
//
///////////////////////////////////////////////////////////////////////

class FakeVimUserCommandsModel : public QAbstractTableModel
{
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
581 582 583 584 585 586 587

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

Leandro Melo's avatar
Leandro Melo committed
588
class FakeVimCompletionAssistProvider : public TextEditor::CompletionAssistProvider
hjk's avatar
hjk committed
589 590
{
public:
Leandro Melo's avatar
Leandro Melo committed
591
    virtual bool supportsEditor(const QString &) const
hjk's avatar
hjk committed
592
    {
Leandro Melo's avatar
Leandro Melo committed
593
        return false;
hjk's avatar
hjk committed
594 595
    }

Leandro Melo's avatar
Leandro Melo committed
596 597 598
    virtual TextEditor::IAssistProcessor *createProcessor() const;

    void setActive(const QString &needle, bool forward, FakeVimHandler *handler)
hjk's avatar
hjk committed
599
    {
Leandro Melo's avatar
Leandro Melo committed
600 601 602 603 604 605 606 607 608 609 610 611
        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
612 613
    }

Leandro Melo's avatar
Leandro Melo committed
614
    void setInactive()
hjk's avatar
hjk committed
615
    {
Leandro Melo's avatar
Leandro Melo committed
616 617
        m_needle.clear();
        m_handler = 0;
hjk's avatar
hjk committed
618 619
    }

Leandro Melo's avatar
Leandro Melo committed
620
    const QString &needle() const
621
    {
Leandro Melo's avatar
Leandro Melo committed
622
        return m_needle;
623
    }
hjk's avatar
hjk committed
624

Leandro Melo's avatar
Leandro Melo committed
625
    void appendNeedle(const QChar &c)
626
    {
Leandro Melo's avatar
Leandro Melo committed
627
        m_needle.append(c);
628 629
    }

Leandro Melo's avatar
Leandro Melo committed
630
    FakeVimHandler *handler() const
631
    {
Leandro Melo's avatar
Leandro Melo committed
632
        return m_handler;
633
    }
hjk's avatar
hjk committed
634

Leandro Melo's avatar
Leandro Melo committed
635 636 637 638 639 640 641 642 643 644 645 646 647
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
648
    {
Leandro Melo's avatar
Leandro Melo committed
649
        return false;
hjk's avatar
hjk committed
650 651
    }

Leandro Melo's avatar
Leandro Melo committed
652
    virtual bool prematurelyApplies(const QChar &c) const
hjk's avatar
hjk committed
653
    {
Leandro Melo's avatar
Leandro Melo committed
654 655
        m_provider->appendNeedle(c);
        return text() == m_provider->needle();
hjk's avatar
hjk committed
656 657
    }

Leandro Melo's avatar
Leandro Melo committed
658
    virtual void applyContextualContent(BaseTextEditor *, int) const
hjk's avatar
hjk committed
659
    {
Leandro Melo's avatar
Leandro Melo committed
660 661 662
        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
663 664
    }

Leandro Melo's avatar
Leandro Melo committed
665 666 667 668 669 670 671 672 673 674 675 676 677
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
678
    {
Leandro Melo's avatar
Leandro Melo committed
679
        return false;
hjk's avatar
hjk committed
680
    }
Leandro Melo's avatar
Leandro Melo committed
681
};
hjk's avatar
hjk committed
682

Leandro Melo's avatar
Leandro Melo committed
683 684 685 686 687 688 689 690
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
691
    {
Leandro Melo's avatar
Leandro Melo committed
692 693 694 695 696 697
        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
698 699
        tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

Leandro Melo's avatar
Leandro Melo committed
700
        QList<BasicProposalItem *> items;
hjk's avatar
hjk committed
701 702 703
        QSet<QString> seen;
        QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
        while (1) {
Leandro Melo's avatar
Leandro Melo committed
704
            tc = tc.document()->find(needle, tc.position(), flags);
hjk's avatar
hjk committed
705 706 707 708 709 710
            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
711
            if (found.startsWith(needle)
hjk's avatar
hjk committed
712
                    && !seen.contains(found)
Leandro Melo's avatar
Leandro Melo committed
713
                    && sel.anchor() != basePosition) {
hjk's avatar
hjk committed
714
                seen.insert(found);
Leandro Melo's avatar
Leandro Melo committed
715 716 717
                BasicProposalItem *item = new FakeVimAssistProposalItem(m_provider);
                item->setText(found);
                items.append(item);
hjk's avatar
hjk committed
718 719 720 721 722
            }
            tc.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
        }
        //qDebug() << "COMPLETIONS" << completions->size();

Leandro Melo's avatar
Leandro Melo committed
723 724
        delete interface;
        return new GenericProposal(basePosition, new FakeVimAssistProposalModel(items));
hjk's avatar
hjk committed
725 726 727
    }

private:
Leandro Melo's avatar
Leandro Melo committed
728
    const FakeVimCompletionAssistProvider *m_provider;
hjk's avatar
hjk committed
729
};
730

Leandro Melo's avatar
Leandro Melo committed
731 732 733 734 735
IAssistProcessor *FakeVimCompletionAssistProvider::createProcessor() const
{
    return new FakeVimCompletionAssistProcessor(this);
}

736

hjk's avatar
hjk committed
737 738
///////////////////////////////////////////////////////////////////////
//
739
// FakeVimPluginPrivate
hjk's avatar
hjk committed
740 741 742
//
///////////////////////////////////////////////////////////////////////

743
class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
744
{
745 746 747 748 749 750
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
751
    friend class FakeVimExCommandsPage;
752 753
    friend class FakeVimUserCommandsPage;
    friend class FakeVimUserCommandsModel;
754

755
    bool initialize();
756
    void aboutToShutdown();
757 758

private slots:
759
    void onCoreAboutToClose();
760 761
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
762

763
    void setUseFakeVim(const QVariant &value);
764
    void setUseFakeVimInternal(bool on);
765
    void quitFakeVim();
766
    void triggerCompletions();
767
    void triggerSimpleCompletions(const QString &needle, bool forward);
hjk's avatar
hjk committed
768
    void windowCommand(int key);
769
    void find(bool reverse);
770
    void findNext(bool reverse);
hjk's avatar
hjk committed
771
    void showSettingsDialog();
772
    void maybeReadVimRc();
hjk's avatar
hjk committed
773 774
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
775 776 777 778

    void showCommandBuffer(const QString &contents);
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
779
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
780
    void checkForElectricCharacter(bool *result, QChar c);
781
    void indentRegion(int beginLine, int endLine, QChar typedChar);
782
    void handleExCommand(bool *handled, const ExCommand &cmd);
783

784 785 786
    void writeSettings();
    void readSettings();

787 788
    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);
789
    void userActionTriggered();
790

791 792
    void switchToFile(int n);
    int currentFile() const;
793

794 795 796
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
797 798 799

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
800
    FakeVimOptionPage *m_fakeVimOptionsPage;
801
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
802
    FakeVimUserCommandsPage *m_fakeVimUserCommandsPage;
803
    QHash<Core::IEditor *, FakeVimHandler *> m_editorToHandler;
hjk's avatar
hjk committed
804 805 806 807
    QPointer<Core::ICore> m_core;
    QPointer<Core::EditorManager> m_editorManager;
    QPointer<Core::ActionManager> m_actionManager;
    ICore *core() const { return m_core; }
hjk's avatar
hjk committed
808
    EditorManager *editorManager() const { return m_editorManager; }
hjk's avatar
hjk committed
809
    ActionManager *actionManager() const { return m_actionManager; }
810

811 812
    void triggerAction(const QString &code);
    void setActionChecked(const QString &code, bool check);
813

814 815 816
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

817 818 819 820 821 822 823 824 825 826
    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;

827
    Core::StatusBarWidget *m_statusBar;
Leandro Melo's avatar
Leandro Melo committed
828 829 830
    // @TODO: Delete
    //WordCompletion *m_wordCompletion;
    FakeVimCompletionAssistProvider *m_wordProvider;
831 832
};

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
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;
}

859
FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
860
{
861
    q = plugin;
hjk's avatar
hjk committed
862
    m_fakeVimOptionsPage = 0;
863
    m_fakeVimExCommandsPage = 0;
864
    m_fakeVimUserCommandsPage = 0;
865
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
866
        QRegExp("^A$");
867
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
868
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
869
    defaultExCommandMap()["Coreplugin.OutputPane.nextitem"] =
870
        QRegExp("^cn(ext)?!?( (.*))?$");
871
    defaultExCommandMap()[CppEditor::Constants::JUMP_TO_DEFINITION] =
872
        QRegExp("^tag?$");
873
    defaultExCommandMap()[Core::Constants::GO_BACK] =
874
        QRegExp("^pop?$");
hjk's avatar
hjk committed
875
    defaultExCommandMap()[_("QtCreator.Locate")] =
876
        QRegExp("^e$");
877 878 879 880 881 882

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

883
    m_statusBar = 0;
hjk's avatar
hjk committed
884 885
}

886
FakeVimPluginPrivate::~FakeVimPluginPrivate()
hjk's avatar
hjk committed
887
{
hjk's avatar
hjk committed
888 889 890
    q->removeObject(m_fakeVimOptionsPage);
    delete m_fakeVimOptionsPage;
    m_fakeVimOptionsPage = 0;
dt's avatar
dt committed
891
    delete theFakeVimSettings();
892 893 894 895