fakevimplugin.cpp 44.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) 2010 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
**
con's avatar
con committed
9
** No Commercial Usage
hjk's avatar
hjk committed
10
**
con's avatar
con committed
11 12 13 14
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
hjk's avatar
hjk committed
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
**
18 19 20 21 22 23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
con's avatar
con committed
25 26 27 28 29 30
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
hjk's avatar
hjk committed
31
**
32
**************************************************************************/
hjk's avatar
hjk committed
33 34 35

#include "fakevimplugin.h"

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

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

#include <projectexplorer/projectexplorerconstants.h>

58
#include <texteditor/basetextdocumentlayout.h>
hjk's avatar
hjk committed
59 60
#include <texteditor/basetexteditor.h>
#include <texteditor/basetextmark.h>
hjk's avatar
hjk committed
61
#include <texteditor/completionsupport.h>
hjk's avatar
hjk committed
62
#include <texteditor/texteditorconstants.h>
63 64
#include <texteditor/tabsettings.h>
#include <texteditor/texteditorsettings.h>
65
#include <texteditor/indenter.h>
hjk's avatar
hjk committed
66

67
#include <find/findplugin.h>
68 69
#include <find/textfindconstants.h>

hjk's avatar
hjk committed
70
#include <utils/qtcassert.h>
hjk's avatar
hjk committed
71
#include <utils/savedaction.h>
72
#include <utils/treewidgetcolumnstretcher.h>
hjk's avatar
hjk committed
73

74 75
#include <cppeditor/cppeditorconstants.h>

76 77
#include <cpptools/cpptoolsconstants.h>

hjk's avatar
hjk committed
78
#include <QtCore/QDebug>
79
#include <QtCore/QFile>
80
#include <QtCore/QtPlugin>
hjk's avatar
hjk committed
81 82
#include <QtCore/QObject>
#include <QtCore/QSettings>
83
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
84

85
#include <QtGui/QDesktopServices>
86
#include <QtGui/QMessageBox>
hjk's avatar
hjk committed
87
#include <QtGui/QPlainTextEdit>
88
#include <QtGui/QShortcut>
hjk's avatar
hjk committed
89 90
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
91
#include <QtGui/QTextEdit>
92
#include <QtGui/QTreeWidgetItem>
hjk's avatar
hjk committed
93 94 95 96 97 98 99 100

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

namespace FakeVim {
namespace Constants {

con's avatar
con committed
101 102 103 104 105 106 107
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";
hjk's avatar
hjk committed
108 109 110 111 112

} // namespace Constants
} // namespace FakeVim


hjk's avatar
hjk committed
113 114 115 116 117 118 119 120 121
///////////////////////////////////////////////////////////////////////
//
// FakeVimOptionPage
//
///////////////////////////////////////////////////////////////////////

namespace FakeVim {
namespace Internal {

122
typedef QMap<QString, QRegExp> CommandMap;
hjk's avatar
hjk committed
123
typedef QLatin1String _;
124

hjk's avatar
hjk committed
125 126 127 128 129 130 131 132
class FakeVimOptionPage : public Core::IOptionsPage
{
    Q_OBJECT

public:
    FakeVimOptionPage() {}

    // IOptionsPage
hjk's avatar
hjk committed
133
    QString id() const { return _(Constants::SETTINGS_ID); }
134
    QString displayName() const { return tr("General"); }
hjk's avatar
hjk committed
135
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
136
    QString displayCategory() const { return tr("FakeVim"); }
hjk's avatar
hjk committed
137 138
    QIcon categoryIcon() const
        { return QIcon(_(Constants::SETTINGS_CATEGORY_FAKEVIM_ICON)); }
hjk's avatar
hjk committed
139 140 141 142

    QWidget *createPage(QWidget *parent);
    void apply() { m_group.apply(ICore::instance()->settings()); }
    void finish() { m_group.finish(); }
143
    virtual bool matches(const QString &) const;
hjk's avatar
hjk committed
144 145 146 147 148 149 150 151 152

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

private:
    friend class DebuggerPlugin;
    Ui::FakeVimOptionPage m_ui;
153
    QString m_searchKeywords;
154
    Utils::SavedActionSet m_group;
hjk's avatar
hjk committed
155 156 157 158 159 160 161 162
};

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

    m_group.clear();
163
    m_group.insert(theFakeVimSetting(ConfigUseFakeVim),
164
        m_ui.checkBoxUseFakeVim);
165 166
    m_group.insert(theFakeVimSetting(ConfigReadVimRc),
        m_ui.checkBoxReadVimRc);
hjk's avatar
hjk committed
167

168
    m_group.insert(theFakeVimSetting(ConfigExpandTab),
hjk's avatar
hjk committed
169
        m_ui.checkBoxExpandTab);
170
    m_group.insert(theFakeVimSetting(ConfigHlSearch),
hjk's avatar
hjk committed
171
        m_ui.checkBoxHlSearch);
172
    m_group.insert(theFakeVimSetting(ConfigShiftWidth),
173
        m_ui.spinBoxShiftWidth);
174 175
    m_group.insert(theFakeVimSetting(ConfigShowMarks),
        m_ui.checkBoxShowMarks);
hjk's avatar
hjk committed
176

177
    m_group.insert(theFakeVimSetting(ConfigSmartTab),
hjk's avatar
hjk committed
178
        m_ui.checkBoxSmartTab);
179
    m_group.insert(theFakeVimSetting(ConfigStartOfLine),
hjk's avatar
hjk committed
180
        m_ui.checkBoxStartOfLine);
181
    m_group.insert(theFakeVimSetting(ConfigTabStop),
182
        m_ui.spinBoxTabStop);
183
    m_group.insert(theFakeVimSetting(ConfigBackspace),
hjk's avatar
hjk committed
184
        m_ui.lineEditBackspace);
185 186
    m_group.insert(theFakeVimSetting(ConfigIsKeyword),
        m_ui.lineEditIsKeyword);
hjk's avatar
hjk committed
187

188 189
    m_group.insert(theFakeVimSetting(ConfigPassControlKey),
        m_ui.checkBoxPassControlKey);
190
    m_group.insert(theFakeVimSetting(ConfigAutoIndent),
hjk's avatar
hjk committed
191
        m_ui.checkBoxAutoIndent);
192
    m_group.insert(theFakeVimSetting(ConfigSmartIndent),
193
        m_ui.checkBoxSmartIndent);
194
    m_group.insert(theFakeVimSetting(ConfigIncSearch),
195
        m_ui.checkBoxIncSearch);
196 197
    m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
        m_ui.checkBoxUseCoreSearch);
hjk's avatar
hjk committed
198 199

    connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
hjk's avatar
hjk committed
200
        this, SLOT(copyTextEditorSettings()));
hjk's avatar
hjk committed
201 202 203 204
    connect(m_ui.pushButtonSetQtStyle, SIGNAL(clicked()),
        this, SLOT(setQtStyle()));
    connect(m_ui.pushButtonSetPlainStyle, SIGNAL(clicked()),
        this, SLOT(setPlainStyle()));
205
    if (m_searchKeywords.isEmpty()) {
206
        QLatin1Char sep(' ');
207
        QTextStream(&m_searchKeywords)
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
                << 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();
224 225
        m_searchKeywords.remove(QLatin1Char('&'));
    }
hjk's avatar
hjk committed
226 227 228 229 230
    return w;
}

void FakeVimOptionPage::copyTextEditorSettings()
{
231
    TextEditor::TabSettings ts =
hjk's avatar
hjk committed
232
        TextEditor::TextEditorSettings::instance()->tabSettings();
233

hjk's avatar
hjk committed
234
    m_ui.checkBoxExpandTab->setChecked(ts.m_spacesForTabs);
235 236
    m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
    m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
hjk's avatar
hjk committed
237
    m_ui.checkBoxSmartTab->setChecked(ts.m_smartBackspace);
238 239
    m_ui.checkBoxAutoIndent->setChecked(true);
    m_ui.checkBoxSmartIndent->setChecked(ts.m_autoIndent);
240
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
241 242 243 244 245
}

void FakeVimOptionPage::setQtStyle()
{
    m_ui.checkBoxExpandTab->setChecked(true);
246 247
    m_ui.spinBoxTabStop->setValue(4);
    m_ui.spinBoxShiftWidth->setValue(4);
hjk's avatar
hjk committed
248 249
    m_ui.checkBoxSmartTab->setChecked(true);
    m_ui.checkBoxAutoIndent->setChecked(true);
250
    m_ui.checkBoxSmartIndent->setChecked(true);
251
    m_ui.checkBoxIncSearch->setChecked(true);
hjk's avatar
hjk committed
252
    m_ui.lineEditBackspace->setText(_("indent,eol,start"));
hjk's avatar
hjk committed
253 254 255 256 257
}

void FakeVimOptionPage::setPlainStyle()
{
    m_ui.checkBoxExpandTab->setChecked(false);
258 259
    m_ui.spinBoxTabStop->setValue(8);
    m_ui.spinBoxShiftWidth->setValue(8);
hjk's avatar
hjk committed
260 261
    m_ui.checkBoxSmartTab->setChecked(false);
    m_ui.checkBoxAutoIndent->setChecked(false);
262
    m_ui.checkBoxSmartIndent->setChecked(false);
263
    m_ui.checkBoxIncSearch->setChecked(false);
hjk's avatar
hjk committed
264
    m_ui.lineEditBackspace->setText(QString());
hjk's avatar
hjk committed
265 266
}

267 268 269 270 271
bool FakeVimOptionPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

hjk's avatar
hjk committed
272 273 274
} // namespace Internal
} // namespace FakeVim

275
//const char *FAKEVIM_CONTEXT = "FakeVim";
hjk's avatar
hjk committed
276

277 278 279 280 281 282 283 284 285 286 287 288 289
///////////////////////////////////////////////////////////////////////
//
// FakeVimExCommandsPage
//
///////////////////////////////////////////////////////////////////////

struct CommandItem
{
    Command *m_cmd;
    QString m_regex;
    QTreeWidgetItem *m_item;
};

290
Q_DECLARE_METATYPE(CommandItem *)
291 292 293 294

namespace FakeVim {
namespace Internal {

295
class FakeVimExCommandsPage : public Core::CommandMappings
296 297 298 299
{
    Q_OBJECT

public:
300
    FakeVimExCommandsPage(FakeVimPluginPrivate *q) : m_q(q) {}
301 302

    // IOptionsPage
hjk's avatar
hjk committed
303
    QString id() const { return _(Constants::SETTINGS_EX_CMDS_ID); }
304
    QString displayName() const { return tr("Ex Command Mapping"); }
hjk's avatar
hjk committed
305
    QString category() const { return _(Constants::SETTINGS_CATEGORY); }
306
    QString displayCategory() const { return tr("FakeVim"); }
307
    QIcon categoryIcon() const { return QIcon(); } // TODO: Icon for FakeVim
308 309 310

    QWidget *createPage(QWidget *parent);
    void initialize();
311 312
    CommandMap &exCommandMap();
    CommandMap &defaultExCommandMap();
313 314 315

public slots:
    void commandChanged(QTreeWidgetItem *current);
316 317 318
    void targetIdentifierChanged();
    void resetTargetIdentifier();
    void removeTargetIdentifier();
319 320 321 322 323
    void defaultAction();

private:
    void setRegex(const QString &regex);
    QList<CommandItem *> m_citems;
324
    FakeVimPluginPrivate *m_q;
325 326 327 328
};

QWidget *FakeVimExCommandsPage::createPage(QWidget *parent)
{
329 330 331
    QWidget *w = CommandMappings::createPage(parent);
    setPageTitle(tr("Ex Command Mapping"));
    setTargetHeader(tr("Ex Trigger Expression"));
332
    setTargetLabelText(tr("Regular expression:"));
333
    setTargetEditTitle(tr("Ex Command"));
334

335
    setImportExportEnabled(false);
336 337 338 339 340 341

    return w;
}

void FakeVimExCommandsPage::initialize()
{
hjk's avatar
hjk committed
342
    ActionManager *am = ICore::instance()->actionManager();
343 344 345 346
    QTC_ASSERT(am, return);
    UniqueIDManager *uidm = UniqueIDManager::instance();
    QTC_ASSERT(uidm, return);

347 348
    QMap<QString, QTreeWidgetItem *> sections;

349 350 351 352 353
    foreach (Command *c, am->commands()) {
        if (c->action() && c->action()->isSeparator())
            continue;

        CommandItem *ci = new CommandItem;
354
        QTreeWidgetItem *item = new QTreeWidgetItem;
355 356
        ci->m_cmd = c;
        ci->m_item = item;
357
        m_citems.append(ci);
358 359

        const QString name = uidm->stringForUniqueIdentifier(c->id());
360 361
        const int pos = name.indexOf(QLatin1Char('.'));
        const QString section = name.left(pos);
362
        const QString subId = name.mid(pos + 1);
363 364

        if (!sections.contains(section)) {
365 366
            QTreeWidgetItem *categoryItem =
                new QTreeWidgetItem(commandList(), QStringList() << section);
367 368 369 370
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
371
            commandList()->expandItem(categoryItem);
372 373 374 375
        }
        sections[section]->addChild(item);

        item->setText(0, subId);
376 377

        if (c->action()) {
378 379 380
            QString text = c->hasAttribute(Command::CA_UpdateText)
                    && !c->defaultText().isNull()
                ? c->defaultText() : c->action()->text();
381 382 383 384 385
            text.remove(QRegExp("&(?!&)"));
            item->setText(1, text);
        } else {
            item->setText(1, c->shortcut()->whatsThis());
        }
386 387
        if (exCommandMap().contains(name)) {
            ci->m_regex = exCommandMap()[name].pattern();
388
        } else {
hjk's avatar
hjk committed
389
            ci->m_regex.clear();
390 391 392 393
        }

        item->setText(2, ci->m_regex);
        item->setData(0, Qt::UserRole, qVariantFromValue(ci));
394

395
        if (ci->m_regex != defaultExCommandMap()[name].pattern())
396
            setModified(item, true);
397 398 399 400 401 402 403
    }

    commandChanged(0);
}

void FakeVimExCommandsPage::commandChanged(QTreeWidgetItem *current)
{
404 405 406
    CommandMappings::commandChanged(current);

    if (!current || !current->data(0, Qt::UserRole).isValid())
407
        return;
408

409
    CommandItem *citem = qVariantValue<CommandItem *>(current->data(0, Qt::UserRole));
410
    targetEdit()->setText(citem->m_regex);
411 412
}

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

    UniqueIDManager *uidm = UniqueIDManager::instance();
    CommandItem *citem = qVariantValue<CommandItem *>(current->data(0, Qt::UserRole));
    const QString name = uidm->stringForUniqueIdentifier(citem->m_cmd->id());

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

429
    if (citem->m_regex != defaultExCommandMap()[name].pattern())
430 431 432
        setModified(current, true);
    else
        setModified(current, false);
433

434 435 436 437
}

void FakeVimExCommandsPage::setRegex(const QString &regex)
{
438
    targetEdit()->setText(regex);
439 440
}

441
void FakeVimExCommandsPage::resetTargetIdentifier()
442 443
{
    UniqueIDManager *uidm = UniqueIDManager::instance();
444
    QTreeWidgetItem *current = commandList()->currentItem();
445 446 447
    if (current && current->data(0, Qt::UserRole).isValid()) {
        CommandItem *citem = qVariantValue<CommandItem *>(current->data(0, Qt::UserRole));
        const QString &name = uidm->stringForUniqueIdentifier(citem->m_cmd->id());
448 449
        if (defaultExCommandMap().contains(name))
            setRegex(defaultExCommandMap()[name].pattern());
450
        else
hjk's avatar
hjk committed
451
            setRegex(QString());
452 453 454
    }
}

455
void FakeVimExCommandsPage::removeTargetIdentifier()
456
{
457
    targetEdit()->clear();
458 459 460 461 462 463 464
}

void FakeVimExCommandsPage::defaultAction()
{
    UniqueIDManager *uidm = UniqueIDManager::instance();
    foreach (CommandItem *item, m_citems) {
        const QString &name = uidm->stringForUniqueIdentifier(item->m_cmd->id());
465 466
        if (defaultExCommandMap().contains(name)) {
            item->m_regex = defaultExCommandMap()[name].pattern();
467
        } else {
hjk's avatar
hjk committed
468
            item->m_regex.clear();
469
        }
470
        setModified(item->m_item, false);
471
        item->m_item->setText(2, item->m_regex);
472
        if (item->m_item == commandList()->currentItem())
473 474 475 476 477 478 479 480
            commandChanged(item->m_item);
    }
}

} // namespace Internal
} // namespace FakeVim


hjk's avatar
hjk committed
481 482
///////////////////////////////////////////////////////////////////////
//
483
// FakeVimPluginPrivate
hjk's avatar
hjk committed
484 485 486
//
///////////////////////////////////////////////////////////////////////

487 488 489 490
namespace FakeVim {
namespace Internal {

class FakeVimPluginPrivate : public QObject
hjk's avatar
hjk committed
491
{
492 493 494 495 496 497
    Q_OBJECT

public:
    FakeVimPluginPrivate(FakeVimPlugin *);
    ~FakeVimPluginPrivate();
    friend class FakeVimPlugin;
498
    friend class FakeVimExCommandsPage;
499

500
    bool initialize();
501
    void aboutToShutdown();
502 503

private slots:
504
    void onCoreAboutToClose();
505 506
    void editorOpened(Core::IEditor *);
    void editorAboutToClose(Core::IEditor *);
507

508
    void setUseFakeVim(const QVariant &value);
509
    void quitFakeVim();
510
    void triggerCompletions();
hjk's avatar
hjk committed
511
    void windowCommand(int key);
512
    void find(bool reverse);
513
    void findNext(bool reverse);
hjk's avatar
hjk committed
514
    void showSettingsDialog();
515
    void maybeReadVimRc();
hjk's avatar
hjk committed
516 517
    void setBlockSelection(bool);
    void hasBlockSelection(bool*);
518 519 520 521

    void showCommandBuffer(const QString &contents);
    void showExtraInformation(const QString &msg);
    void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
522
    void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
523
    void checkForElectricCharacter(bool *result, QChar c);
524
    void indentRegion(int beginLine, int endLine, QChar typedChar);
525
    void handleExCommand(bool *handled, const ExCommand &cmd);
526 527 528 529

    void handleDelayedQuitAll(bool forced);
    void handleDelayedQuit(bool forced, Core::IEditor *editor);

530 531
    void switchToFile(int n);
    int currentFile() const;
532

533 534 535
signals:
    void delayedQuitRequested(bool forced, Core::IEditor *editor);
    void delayedQuitAllRequested(bool forced);
536 537 538

private:
    FakeVimPlugin *q;
hjk's avatar
hjk committed
539
    FakeVimOptionPage *m_fakeVimOptionsPage;
540
    FakeVimExCommandsPage *m_fakeVimExCommandsPage;
541
    QHash<Core::IEditor *, FakeVimHandler *> m_editorToHandler;
hjk's avatar
hjk committed
542 543 544 545
    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
546
    EditorManager *editorManager() const { return m_editorManager; }
hjk's avatar
hjk committed
547
    ActionManager *actionManager() const { return m_actionManager; }
548

549 550
    void triggerAction(const QString &code);
    void setActionChecked(const QString &code, bool check);
551 552 553

    void readSettings(QSettings *settings);
    void writeSettings(QSettings *settings);
554

555 556 557
    typedef int (*DistFunction)(const QRect &cursor, const QRect &other);
    void moveSomewhere(DistFunction f);

558 559 560 561
    CommandMap &exCommandMap() { return m_exCommandMap; }
    CommandMap &defaultExCommandMap() { return m_exCommandMap; }
    CommandMap m_exCommandMap;
    CommandMap m_defaultExCommandMap;
562
    Core::StatusBarWidget *m_statusBar;
563 564 565 566 567 568
};

} // namespace Internal
} // namespace FakeVim

FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
569
{
570
    q = plugin;
hjk's avatar
hjk committed
571
    m_fakeVimOptionsPage = 0;
572
    m_fakeVimExCommandsPage = 0;
573
    defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
574
        QRegExp("^A$");
575
    defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
576
        QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
577
    defaultExCommandMap()["Coreplugin.OutputPane.nextitem"] =
578
        QRegExp("^cn(ext)?!?( (.*))?$");
579
    defaultExCommandMap()[CppEditor::Constants::JUMP_TO_DEFINITION] =
580
        QRegExp("^tag?$");
581
    defaultExCommandMap()[Core::Constants::GO_BACK] =
582
        QRegExp("^pop?$");
hjk's avatar
hjk committed
583
    defaultExCommandMap()[_("QtCreator.Locate")] =
584
        QRegExp("^e$");
585
    m_statusBar = 0;
hjk's avatar
hjk committed
586 587
}

588
FakeVimPluginPrivate::~FakeVimPluginPrivate()
hjk's avatar
hjk committed
589
{
hjk's avatar
hjk committed
590 591 592
    q->removeObject(m_fakeVimOptionsPage);
    delete m_fakeVimOptionsPage;
    m_fakeVimOptionsPage = 0;
dt's avatar
dt committed
593
    delete theFakeVimSettings();
594 595 596 597

    q->removeObject(m_fakeVimExCommandsPage);
    delete m_fakeVimExCommandsPage;
    m_fakeVimExCommandsPage = 0;
598 599
}

600 601 602 603 604 605 606
void FakeVimPluginPrivate::onCoreAboutToClose()
{
    // don't attach to editors any more
    disconnect(editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
        this, SLOT(editorOpened(Core::IEditor*)));
}

607 608
void FakeVimPluginPrivate::aboutToShutdown()
{
hjk's avatar
hjk committed
609 610
    theFakeVimSettings()->writeSettings(ICore::instance()->settings());
    writeSettings(ICore::instance()->settings());
hjk's avatar
hjk committed
611 612
}

613
bool FakeVimPluginPrivate::initialize()
hjk's avatar
hjk committed
614
{
hjk's avatar
hjk committed
615 616 617 618
    m_core = Core::ICore::instance();
    m_editorManager = core()->editorManager();
    m_actionManager = core()->actionManager();
    QTC_ASSERT(actionManager(), return false);
hjk's avatar
hjk committed
619

hjk's avatar
hjk committed
620
    Context globalcontext(Core::Constants::C_GLOBAL);
hjk's avatar
hjk committed
621

hjk's avatar
hjk committed
622 623
    m_fakeVimOptionsPage = new FakeVimOptionPage;
    q->addObject(m_fakeVimOptionsPage);
hjk's avatar
hjk committed
624
    theFakeVimSettings()->readSettings(ICore::instance()->settings());
625

626
    m_fakeVimExCommandsPage = new FakeVimExCommandsPage(this);
627
    q->addObject(m_fakeVimExCommandsPage);
hjk's avatar
hjk committed
628
    readSettings(core()->settings());
629

con's avatar
con committed
630
    Core::Command *cmd = 0;
hjk's avatar
hjk committed
631
    cmd = actionManager()->registerAction(theFakeVimSetting(ConfigUseFakeVim),
hjk's avatar
hjk committed
632 633 634
        Constants::INSTALL_HANDLER, globalcontext);
    cmd->setDefaultKeySequence(QKeySequence(Constants::INSTALL_KEY));

635
    ActionContainer *advancedMenu =
hjk's avatar
hjk committed
636
        actionManager()->actionContainer(Core::Constants::M_EDIT_ADVANCED);
637
    advancedMenu->addAction(cmd, Core::Constants::G_EDIT_EDITOR);
hjk's avatar
hjk committed
638

639 640
    connect(m_core, SIGNAL(coreAboutToClose()), this, SLOT(onCoreAboutToClose()));

641
    // EditorManager
hjk's avatar
hjk committed
642
    connect(editorManager(), SIGNAL(editorAboutToClose(Core::IEditor*)),
643
        this, SLOT(editorAboutToClose(Core::IEditor*)));
hjk's avatar
hjk committed
644
    connect(editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
645 646
        this, SLOT(editorOpened(Core::IEditor*)));

647 648
    connect(theFakeVimSetting(ConfigUseFakeVim), SIGNAL(valueChanged(QVariant)),
        this, SLOT(setUseFakeVim(QVariant)));
649 650
    connect(theFakeVimSetting(ConfigReadVimRc), SIGNAL(valueChanged(QVariant)),
        this, SLOT(maybeReadVimRc()));
hjk's avatar
hjk committed
651

652
    // Delayed operations.
653 654 655 656
    connect(this, SIGNAL(delayedQuitRequested(bool,Core::IEditor*)),
        this, SLOT(handleDelayedQuit(bool,Core::IEditor*)), Qt::QueuedConnection);
    connect(this, SIGNAL(delayedQuitAllRequested(bool)),
        this, SLOT(handleDelayedQuitAll(bool)), Qt::QueuedConnection);
657 658
    maybeReadVimRc();
    //    << "MODE: " << theFakeVimSetting(ConfigUseFakeVim)->value();
659

hjk's avatar
hjk committed
660 661 662
    return true;
}

663 664 665 666 667 668
static const char *exCommandMapGroup = "FakeVimExCommand";
static const char *reKey = "RegEx";
static const char *idKey = "Command";

void FakeVimPluginPrivate::writeSettings(QSettings *settings)
{
hjk's avatar
hjk committed
669
    settings->beginWriteArray(_(exCommandMapGroup));
670 671

    int count = 0;
672 673 674
    typedef CommandMap::const_iterator Iterator;
    const Iterator end = exCommandMap().constEnd();
    for (Iterator it = exCommandMap().constBegin(); it != end; ++it) {
675 676 677
        const QString &id = it.key();
        const QRegExp &re = it.value();

678 679
        if ((defaultExCommandMap().contains(id) && defaultExCommandMap()[id] != re)
            || (!defaultExCommandMap().contains(id) && !re.pattern().isEmpty())) {
680
            settings->setArrayIndex(count);
hjk's avatar
hjk committed
681 682
            settings->setValue(_(idKey), id);
            settings->setValue(_(reKey), re.pattern());
683 684 685 686 687 688 689 690 691
            ++count;
        }
    }

    settings->endArray();
}

void FakeVimPluginPrivate::readSettings(QSettings *settings)
{
692
    exCommandMap() = defaultExCommandMap();
693

hjk's avatar
hjk committed
694
    int size = settings->beginReadArray(_(exCommandMapGroup));
695
    for (int i = 0; i < size; ++i) {
696
        settings->setArrayIndex(i);
hjk's avatar
hjk committed
697 698
        const QString id = settings->value(_(idKey)).toString();
        const QString re = settings->value(_(reKey)).toString();
699
        exCommandMap()[id] = QRegExp(re);
700 701 702 703
    }
    settings->endArray();
}

704 705
void FakeVimPluginPrivate::maybeReadVimRc()
{
hjk's avatar
hjk committed
706 707 708
    //qDebug() << theFakeVimSetting(ConfigReadVimRc)
    //    << theFakeVimSetting(ConfigReadVimRc)->value();
    //qDebug() << theFakeVimSetting(ConfigShiftWidth)->value();
709 710 711 712 713 714 715 716 717 718
    if (!theFakeVimSetting(ConfigReadVimRc)->value().toBool())
        return;
    QString fileName =
        QDesktopServices::storageLocation(QDesktopServices::HomeLocation)
            + "/.vimrc";
    //qDebug() << "READING VIMRC: " << fileName;
    // Read it into a temporary handler for effects modifying global state.
    QPlainTextEdit editor;
    FakeVimHandler handler(&editor);
    handler.handleCommand("source " + fileName);
hjk's avatar
hjk committed
719
    theFakeVimSettings()->writeSettings(core()->settings());
hjk's avatar
hjk committed
720
    //qDebug() << theFakeVimSetting(ConfigShiftWidth)->value();
721 722
}

hjk's avatar
hjk committed
723 724
void FakeVimPluginPrivate::showSettingsDialog()
{
hjk's avatar
hjk committed
725
    core()->showOptionsDialog(
hjk's avatar
hjk committed
726 727
        _(Constants::SETTINGS_CATEGORY),
        _(Constants::SETTINGS_ID));
hjk's avatar
hjk committed
728 729
}

730
void FakeVimPluginPrivate::triggerAction(const QString &code)
731
{
hjk's avatar
hjk committed
732
    Core::ActionManager *am = actionManager();
733 734
    QTC_ASSERT(am, return);
    Core::Command *cmd = am->command(code);
735
    QTC_ASSERT(cmd, qDebug() << "UNKNOWN CODE: " << code; return);
736 737 738 739 740
    QAction *action = cmd->action();
    QTC_ASSERT(action, return);
    action->trigger();
}

741
void FakeVimPluginPrivate::setActionChecked(const QString &code, bool check)
742
{
hjk's avatar
hjk committed
743
    Core::ActionManager *am = actionManager();
744 745 746 747 748 749
    QTC_ASSERT(am, return);
    Core::Command *cmd = am->command(code);
    QTC_ASSERT(cmd, return);
    QAction *action = cmd->action();
    QTC_ASSERT(action, return);
    QTC_ASSERT(action->isCheckable(), return);
750
    action->setChecked(!check); // trigger negates the action's state
751 752 753
    action->trigger();
}

754 755 756 757 758 759
static int moveRightWeight(const QRect &cursor, const QRect &other)
{
    int dx = other.left() - cursor.right();
    if (dx < 0)
        return -1;
    int w = 10000 * dx;
760 761
    int dy1 = cursor.top() - other.bottom();
    int dy2 = cursor.bottom() - other.top();
762 763 764 765 766 767 768 769 770 771 772 773
    w += dy1 * (dy1 > 0);
    w += dy2 * (dy2 > 0);
    qDebug() << "      DX: " << dx << dy1 << dy2 << w;
    return w;
}

static int moveLeftWeight(const QRect &cursor, const QRect &other)
{
    int dx = other.right() - cursor.left();
    if (dx < 0)
        return -1;
    int w = 10000 * dx;
774 775
    int dy1 = cursor.top() - other.bottom();
    int dy2 = cursor.bottom() - other.top();
776 777 778 779 780 781 782 783 784 785 786
    w += dy1 * (dy1 > 0);
    w += dy2 * (dy2 > 0);
    return w;
}

static int moveUpWeight(const QRect &cursor, const QRect &other)
{
    int dy = other.bottom() - cursor.top();
    if (dy < 0)
        return -1;
    int w = 10000 * dy;
787 788
    int dx1 = cursor.left() - other.right();
    int dx2 = cursor.right() - other.left();
789 790 791 792 793 794 795 796 797 798 799
    w += dx1 * (dx1 > 0);
    w += dx2 * (dx2 > 0);
    return w;
}

static int moveDownWeight(const QRect &cursor, const QRect &other)
{
    int dy = other.top() - cursor.bottom();
    if (dy < 0)
        return -1;
    int w = 10000 * dy;