fakevimhandler.cpp 83.9 KB
Newer Older
1
/**************************************************************************
hjk's avatar
hjk committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
** Commercial Usage
hjk's avatar
hjk committed
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
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
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
hjk's avatar
hjk committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

30
#include "fakevimhandler.h"
hjk's avatar
hjk committed
31

32
//
33
34
35
36
37
38
39
40
41
42
43
// ATTENTION:
//
// 1 Please do not add any direct dependencies to other Qt Creator code here.
//   Instead emit signals and let the FakeVimPlugin channel the information to
//   Qt Creator. The idea is to keep this file here in a "clean" state that
//   allows easy reuse with any QTextEdit or QPlainTextEdit derived class.
//
// 2 There are a few auto tests located in ../../../tests/auto/fakevim.
//   Commands that are covered there are marked as "// tested" below.
//
// 3 Some conventions:
44
//
45
46
47
//   Use 1 based line numbers and 0 based column numbers. Even though
//   the 1 based line are not nice it matches vim's and QTextEdit's 'line'
//   concepts.
48
//
49
50
51
52
53
54
55
//   Do not pass QTextCursor etc around unless really needed. Convert
//   early to  line/column.
//
//   There is always a "current" cursor (m_tc). A current "region of interest"
//   spans between m_anchor (== anchor()) and  m_tc.position() (== position())
//   The value of m_tc.anchor() is not used.
// 
56

hjk's avatar
hjk committed
57
#include <utils/qtcassert.h>
58

hjk's avatar
hjk committed
59
#include <QtCore/QDebug>
60
#include <QtCore/QFile>
hjk's avatar
hjk committed
61
#include <QtCore/QObject>
62
#include <QtCore/QPointer>
hjk's avatar
hjk committed
63
#include <QtCore/QProcess>
hjk's avatar
hjk committed
64
#include <QtCore/QRegExp>
65
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
66
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
67
68
#include <QtCore/QStack>

hjk's avatar
hjk committed
69
#include <QtGui/QApplication>
hjk's avatar
hjk committed
70
71
72
73
74
75
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
76
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
77
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
78
79


80
81
82
83
84
85
86
//#define DEBUG_KEY  1
#if DEBUG_KEY
#   define KEY_DEBUG(s) qDebug() << s
#else
#   define KEY_DEBUG(s)
#endif

87
88
89
90
91
92
93
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
#   define UNDO_DEBUG(s) qDebug() << s
#else
#   define UNDO_DEBUG(s)
#endif

hjk's avatar
hjk committed
94
95
96
97
98
using namespace Core::Utils;

namespace FakeVim {
namespace Internal {

hjk's avatar
hjk committed
99
100
101
102
103
104
///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
105
106
107
108
109
110
111
112
113
114
#define StartOfLine     QTextCursor::StartOfLine
#define EndOfLine       QTextCursor::EndOfLine
#define MoveAnchor      QTextCursor::MoveAnchor
#define KeepAnchor      QTextCursor::KeepAnchor
#define Up              QTextCursor::Up
#define Down            QTextCursor::Down
#define Right           QTextCursor::Right
#define Left            QTextCursor::Left
#define EndOfDocument   QTextCursor::End
#define StartOfDocument QTextCursor::Start
hjk's avatar
hjk committed
115

116
117
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
118
119
120
121
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

122

hjk's avatar
hjk committed
123
124
125
126
enum Mode
{
    InsertMode,
    CommandMode,
127
128
129
    ExMode,
    SearchForwardMode,
    SearchBackwardMode,
hjk's avatar
hjk committed
130
};
hjk's avatar
hjk committed
131

hjk's avatar
hjk committed
132
133
134
enum SubMode
{
    NoSubMode,
135
136
137
    ChangeSubMode,     // used for c
    DeleteSubMode,     // used for d
    FilterSubMode,     // used for !
hjk's avatar
hjk committed
138
139
    IndentSubMode,     // used for =
    RegisterSubMode,   // used for "
hjk's avatar
hjk committed
140
    ReplaceSubMode,    // used for R and r
141
142
    ShiftLeftSubMode,  // used for <
    ShiftRightSubMode, // used for >
hjk's avatar
hjk committed
143
144
    WindowSubMode,     // used for Ctrl-w
    YankSubMode,       // used for y
145
146
    ZSubMode,          // used for z
    CapitalZSubMode    // used for Z
hjk's avatar
hjk committed
147
};
hjk's avatar
hjk committed
148

hjk's avatar
hjk committed
149
150
enum SubSubMode
{
hjk's avatar
hjk committed
151
152
    // typically used for things that require one more data item
    // and are 'nested' behind a mode
hjk's avatar
hjk committed
153
    NoSubSubMode,
154
155
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
156
    BackTickSubSubMode, // used for `
hjk's avatar
hjk committed
157
    TickSubSubMode,     // used for '
hjk's avatar
hjk committed
158
159
};

160
161
162
163
164
165
166
167
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

hjk's avatar
hjk committed
168
169
170
171
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
hjk's avatar
hjk committed
172
    MoveLineWise,
hjk's avatar
hjk committed
173
174
};

175
176
struct EditOperation
{
hjk's avatar
hjk committed
177
178
179
180
181
    EditOperation() : position(-1), itemCount(0) {}
    int position;
    int itemCount; // used to combine several operations
    QString from;
    QString to;
182
183
};

hjk's avatar
hjk committed
184
QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
185
{
hjk's avatar
hjk committed
186
187
    if (op.itemCount > 0) {
        ts << "\n  EDIT BLOCK WITH " << op.itemCount << " ITEMS";
hjk's avatar
hjk committed
188
    } else {
hjk's avatar
hjk committed
189
        ts << "\n  EDIT AT " << op.position
hjk's avatar
hjk committed
190
           << "  FROM   " << op.from << "   TO    " << op.to;
hjk's avatar
hjk committed
191
192
193
194
    }
    return ts;
}

195
196
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
197
198
    foreach (QTextEdit::ExtraSelection sel, sels)
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
199
200
    return ts;
}
201

hjk's avatar
hjk committed
202
203
204
205
206
207
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

208
209
210
211
212
213
214
enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

215
216
class UndoBreaker;

hjk's avatar
hjk committed
217
218
219
class FakeVimHandler::Private
{
public:
220
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
221

222
223
    EventResult handleEvent(QKeyEvent *ev);
    bool wantsOverride(QKeyEvent *ev);
hjk's avatar
hjk committed
224
    void handleCommand(const QString &cmd); // sets m_tc + handleExCommand
225
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
226

227
    void installEventFilter();
228
229
230
    void setupWidget();
    void restoreWidget();

231
    friend class FakeVimHandler;
232
    friend class UndoBreaker;
hjk's avatar
hjk committed
233
234
235
236
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
237
238
239
240
241
    EventResult handleKey(int key, int unmodified, const QString &text);
    EventResult handleInsertMode(int key, int unmodified, const QString &text);
    EventResult handleCommandMode(int key, int unmodified, const QString &text);
    EventResult handleRegisterMode(int key, int unmodified, const QString &text);
    EventResult handleMiniBufferModes(int key, int unmodified, const QString &text);
hjk's avatar
hjk committed
242
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
243
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
244
    void highlightMatches(const QString &needle);
hjk's avatar
hjk committed
245

hjk's avatar
hjk committed
246
247
248
    int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
    int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
    int count() const { return mvCount() * opCount(); }
hjk's avatar
hjk committed
249
250
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
251
252
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
253

hjk's avatar
hjk committed
254
    int lastPositionInDocument() const;
255
256
    int firstPositionInLine(int line) const; // 1 based line, 0 based pos
    int lastPositionInLine(int line) const; // 1 based line, 0 based pos
hjk's avatar
hjk committed
257
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
258

hjk's avatar
hjk committed
259
260
261
262
263
264
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
265
    int linesInDocument() const;
hjk's avatar
hjk committed
266
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
267
268
    void scrollUp(int count);
    void scrollDown(int count) { scrollUp(-count); }
hjk's avatar
hjk committed
269

270
    // helper functions for indenting
hjk's avatar
hjk committed
271
    bool isElectricCharacter(QChar c) const
272
        { return c == '{' || c == '}' || c == '#'; }
hjk's avatar
hjk committed
273
274
275
    void indentRegion(QChar lastTyped = QChar());
    void shiftRegionLeft(int repeat = 1);
    void shiftRegionRight(int repeat = 1);
276

hjk's avatar
hjk committed
277
    void moveToFirstNonBlankOnLine();
278
279
    void moveToTargetColumn();
    void setTargetColumn() { m_targetColumn = leftDist(); }
hjk's avatar
hjk committed
280
    void moveToNextWord(bool simple);
281
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
282
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
283
284

    // to reduce line noise
hjk's avatar
hjk committed
285
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
286
    void moveToStartOfLine();
hjk's avatar
hjk committed
287
288
289
    void moveToEndOfLine();
    void moveUp(int n = 1) { moveDown(-n); }
    void moveDown(int n = 1); // { m_tc.movePosition(Down, MoveAnchor, n); }
hjk's avatar
hjk committed
290
291
    void moveRight(int n = 1) { m_tc.movePosition(Right, MoveAnchor, n); }
    void moveLeft(int n = 1) { m_tc.movePosition(Left, MoveAnchor, n); }
hjk's avatar
hjk committed
292
    void setAnchor() { m_anchor = m_tc.position(); }
293
294
    void setAnchor(int position) { m_anchor = position; }
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
295

hjk's avatar
hjk committed
296
    void handleFfTt(int key);
hjk's avatar
hjk committed
297

hjk's avatar
hjk committed
298
    // helper function for handleExCommand. return 1 based line index.
hjk's avatar
hjk committed
299
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
300
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
301

302
    void enterInsertMode();
303
    void enterCommandMode();
304
    void enterExMode();
hjk's avatar
hjk committed
305
306
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
307
    void notImplementedYet();
308
309
    void updateMiniBuffer();
    void updateSelection();
310
    QWidget *editor() const;
311
312
    QChar characterAtCursor() const
        { return m_tc.document()->characterAt(m_tc.position()); }
313

314
315
316
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
317
    bool m_wasReadOnly; // saves read-only state of document
318

hjk's avatar
hjk committed
319
320
    FakeVimHandler *q;
    Mode m_mode;
321
    bool m_passing; // let the core see the next event
hjk's avatar
hjk committed
322
    SubMode m_submode;
hjk's avatar
hjk committed
323
324
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
325
326
    QString m_input;
    QTextCursor m_tc;
327
    QTextCursor m_oldTc; // copy from last event to check for external changes
328
    int m_anchor;
hjk's avatar
hjk committed
329
330
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
331
332
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
333
    MoveType m_moveType;
hjk's avatar
hjk committed
334
335
336

    bool m_fakeEnd;

337
338
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
339
    int m_gflag;  // whether current command started with 'g'
340

hjk's avatar
hjk committed
341
    QString m_commandBuffer;
342
343
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
344

345
    bool m_lastSearchForward;
hjk's avatar
hjk committed
346
    QString m_lastInsertion;
hjk's avatar
hjk committed
347

348
    QString removeSelectedText();
hjk's avatar
hjk committed
349
350
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
351
352
    QString selectedText() const;

353
    // undo handling
354
355
    void undo();
    void redo();
356
357
    QMap<int, int> m_undoCursorPosition; // revision -> position
    bool m_needMoreUndo;
358

hjk's avatar
hjk committed
359
    // extra data for '.'
hjk's avatar
hjk committed
360
    void replay(const QString &text, int count);
361
362
    void setDotCommand(const QString &cmd) { m_dotCommand = cmd; }
    void setDotCommand(const QString &cmd, int n) { m_dotCommand = cmd.arg(n); }
hjk's avatar
hjk committed
363
    QString m_dotCommand;
hjk's avatar
hjk committed
364
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
365

hjk's avatar
hjk committed
366
367
368
369
370
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
371
    // history for '/'
hjk's avatar
hjk committed
372
    QString lastSearchString() const;
373
    static QStringList m_searchHistory;
hjk's avatar
hjk committed
374
375
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
376
    // history for ':'
377
    static QStringList m_commandHistory;
hjk's avatar
hjk committed
378
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
379

hjk's avatar
hjk committed
380
    // visual line mode
381
382
383
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
384

385
386
    // marks as lines
    QHash<int, int> m_marks;
hjk's avatar
hjk committed
387
    QString m_oldNeedle;
388

hjk's avatar
hjk committed
389
    // vi style configuration
hjk's avatar
hjk committed
390
391
392
393
    QVariant config(int code) const { return theFakeVimSetting(code)->value(); }
    bool hasConfig(int code) const { return config(code).toBool(); }
    bool hasConfig(int code, const char *value) const // FIXME
        { return config(code).toString().contains(value); }
394
395

    // for restoring cursor position
hjk's avatar
hjk committed
396
    int m_savedYankPosition;
397
    int m_targetColumn;
398

399
    int m_cursorWidth;
400

hjk's avatar
hjk committed
401
402
403
404
405
    // auto-indent
    void insertAutomaticIndentation(bool goingDown);
    bool removeAutomaticIndentation(); // true if something removed
    // number of autoindented characters
    int m_justAutoIndented;
406
    void handleStartOfLine();
hjk's avatar
hjk committed
407

408
    void recordJump();
409
    void recordNewUndo();
410
411
    QList<int> m_jumpListUndo;
    QList<int> m_jumpListRedo;
hjk's avatar
hjk committed
412
413

    QList<QTextEdit::ExtraSelection> m_searchSelections;
hjk's avatar
hjk committed
414
415
};

416
417
418
QStringList FakeVimHandler::Private::m_searchHistory;
QStringList FakeVimHandler::Private::m_commandHistory;

419
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
420
421
{
    q = parent;
422
423
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
hjk's avatar
hjk committed
424
425
    init();
}
426

hjk's avatar
hjk committed
427
428
void FakeVimHandler::Private::init()
{
hjk's avatar
hjk committed
429
    m_mode = CommandMode;
hjk's avatar
hjk committed
430
431
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
432
    m_passing = false;
hjk's avatar
hjk committed
433
    m_fakeEnd = false;
434
    m_lastSearchForward = true;
hjk's avatar
hjk committed
435
    m_register = '"';
hjk's avatar
hjk committed
436
    m_gflag = false;
437
    m_visualMode = NoVisualMode;
438
    m_targetColumn = 0;
hjk's avatar
hjk committed
439
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
440
441
    m_anchor = 0;
    m_savedYankPosition = 0;
442
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
443
    m_inReplay = false;
hjk's avatar
hjk committed
444
    m_justAutoIndented = 0;
hjk's avatar
hjk committed
445
446
}

447
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
hjk's avatar
hjk committed
448
{
449
450
451
    const int key = ev->key();
    const int mods = ev->modifiers();
    KEY_DEBUG("SHORTCUT OVERRIDE" << key << "  PASSING: " << m_passing);
452

453
    if (key == Key_Escape) {
hjk's avatar
hjk committed
454
        // Not sure this feels good. People often hit Esc several times
455
456
457
458
459
460
461
462
463
464
465
466
467
        if (m_visualMode == NoVisualMode && m_mode == CommandMode)
            return false;
        return true;
    }

    // We are interested in overriding  most Ctrl key combinations
    if (mods == Qt::ControlModifier && key >= Key_A && key <= Key_Z && key != Key_K) {
        // Ctrl-K is special as it is the Core's default notion of QuickOpen
        if (m_passing) {
            KEY_DEBUG(" PASSING CTRL KEY");
            // We get called twice on the same key
            //m_passing = false;
            return false;
468
        }
469
470
471
        KEY_DEBUG(" NOT PASSING CTRL KEY");
        //updateMiniBuffer();
        return true;
472
473
    }

474
475
476
477
478
479
480
481
482
483
    // Let other shortcuts trigger
    return false;
}

EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
{
    int key = ev->key();
    const int um = key; // keep unmodified key around
    const int mods = ev->modifiers();

hjk's avatar
hjk committed
484
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
            || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
    {
        KEY_DEBUG("PLAIN MODIFIER");
        return EventUnhandled;
    }

    if (m_passing) {
        KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
        //if (key == ',') { // use ',,' to leave, too.
        //    qDebug() << "FINISHED...";
        //    return EventHandled;
        //}
        m_passing = false;
        updateMiniBuffer();
        KEY_DEBUG("   PASS TO CORE");
        return EventPassedToCore;
    }
hjk's avatar
hjk committed
502
503

    // Fake "End of line"
504
505
    m_tc = EDITOR(textCursor());

506
507
508
509
510
    if (m_tc.position() != m_oldTc.position())
        setTargetColumn();

    m_tc.setVisualNavigation(true);
    
hjk's avatar
hjk committed
511
    if (m_fakeEnd)
hjk's avatar
hjk committed
512
        moveRight();
hjk's avatar
hjk committed
513

514
    if ((mods & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
515
        key += 256;
516
        key += 32; // make it lower case
517
    } else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
518
519
        key += 32;
    }
520

hjk's avatar
hjk committed
521
    m_undoCursorPosition[m_tc.document()->revision()] = m_tc.position();
522
523
524
525
    if (m_mode == InsertMode)
        m_tc.joinPreviousEditBlock();
    else
        m_tc.beginEditBlock();
526
    EventResult result = handleKey(key, um, ev->text());
527
    m_tc.endEditBlock();
hjk's avatar
hjk committed
528
529

    // We fake vi-style end-of-line behaviour
530
    m_fakeEnd = (atEndOfLine() && m_mode == CommandMode);
hjk's avatar
hjk committed
531

hjk's avatar
hjk committed
532
    if (m_fakeEnd)
hjk's avatar
hjk committed
533
        moveLeft();
hjk's avatar
hjk committed
534

535
    m_oldTc = m_tc;
536
    EDITOR(setTextCursor(m_tc));
537
    return result;
hjk's avatar
hjk committed
538
539
}

540
541
542
543
544
void FakeVimHandler::Private::installEventFilter()
{
    EDITOR(installEventFilter(q));
}

545
546
547
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
548
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
549
550
551
552
553
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
554
    m_wasReadOnly = EDITOR(isReadOnly());
555
    //EDITOR(setReadOnly(true));
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

    QTextCursor tc = EDITOR(textCursor());
    if (tc.hasSelection()) {
        int pos = tc.position();
        int anc = tc.anchor();
        m_marks['<'] = anc;
        m_marks['>'] = pos;
        m_anchor = anc;
        m_visualMode = VisualCharMode;
        tc.clearSelection();
        EDITOR(setTextCursor(tc));
        m_tc = tc; // needed in updateSelection
        updateSelection();
    }

571
    //showBlackMessage("vi emulation mode. Type :q to leave. Use , Ctrl-R to trigger run.");
572
573
574
575
576
577
578
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
579
    //EDITOR(removeEventFilter(q));
580
    EDITOR(setReadOnly(m_wasReadOnly));
581
582
    EDITOR(setCursorWidth(m_cursorWidth));
    EDITOR(setOverwriteMode(false));
583

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
    if (m_visualMode == VisualLineMode) {
        m_tc = EDITOR(textCursor());
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
        m_tc.setPosition(firstPositionInLine(beginLine), MoveAnchor);
        m_tc.setPosition(lastPositionInLine(endLine), KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    } else if (m_visualMode == VisualCharMode) {
        m_tc = EDITOR(textCursor());
        m_tc.setPosition(m_marks['<'], MoveAnchor);
        m_tc.setPosition(m_marks['>'], KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    }

    m_visualMode = NoVisualMode;
    updateSelection();
600
601
}

602
603
EventResult FakeVimHandler::Private::handleKey(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
604
{
605
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
hjk's avatar
hjk committed
606
    if (m_mode == InsertMode)
607
        return handleInsertMode(key, unmodified, text);
608
    if (m_mode == CommandMode)
609
        return handleCommandMode(key, unmodified, text);
610
    if (m_mode == ExMode || m_mode == SearchForwardMode
611
            || m_mode == SearchBackwardMode)
612
        return handleMiniBufferModes(key, unmodified, text);
613
    return EventUnhandled;
hjk's avatar
hjk committed
614
615
}

hjk's avatar
hjk committed
616
617
void FakeVimHandler::Private::moveDown(int n)
{
hjk's avatar
hjk committed
618
619
620
621
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(Down, MoveAnchor, n);
#else
hjk's avatar
hjk committed
622
    const int col = m_tc.position() - m_tc.block().position();
623
624
625
    const int lastLine = m_tc.document()->lastBlock().blockNumber();
    const int targetLine = qMax(0, qMin(lastLine, m_tc.block().blockNumber() + n));
    const QTextBlock &block = m_tc.document()->findBlockByNumber(targetLine);
hjk's avatar
hjk committed
626
627
628
    const int pos = block.position();
    setPosition(pos + qMin(block.length() - 1, col));
    moveToTargetColumn();
hjk's avatar
hjk committed
629
#endif
hjk's avatar
hjk committed
630
631
632
633
}

void FakeVimHandler::Private::moveToEndOfLine()
{
hjk's avatar
hjk committed
634
635
636
637
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(EndOfLine, MoveAnchor);
#else
hjk's avatar
hjk committed
638
639
    const QTextBlock &block = m_tc.block();
    setPosition(block.position() + block.length() - 1);
hjk's avatar
hjk committed
640
#endif
hjk's avatar
hjk committed
641
642
}

643
644
645
646
647
648
649
650
651
652
653
void FakeVimHandler::Private::moveToStartOfLine()
{
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(StartOfLine, MoveAnchor);
#else
    const QTextBlock &block = m_tc.block();
    setPosition(block.position());
#endif
}

hjk's avatar
hjk committed
654
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
655
{
656
    //qDebug() << "ANCHOR: " << position() << anchor();
hjk's avatar
hjk committed
657
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
658
659
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
660
        setPosition(qMin(anchor(), position()));
661
        enterExMode();
hjk's avatar
hjk committed
662
663
664
665
666
667
668
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

669
670
671
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
672
    if (m_submode == ChangeSubMode) {
673
674
        if (m_moveType == MoveInclusive)
            moveRight(); // correction
675
676
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
677
        if (!dotCommand.isEmpty())
678
            setDotCommand("c" + dotCommand);
679
        QString text = removeSelectedText();
680
        //qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
681
        m_registers[m_register] = text;
hjk's avatar
hjk committed
682
683
684
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
685
        if (m_moveType == MoveInclusive)
686
            moveRight(); // correction
687
688
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
689
        if (!dotCommand.isEmpty())
690
            setDotCommand("d" + dotCommand);
691
        m_registers[m_register] = removeSelectedText();
hjk's avatar
hjk committed
692
        m_submode = NoSubMode;
693
        if (atEndOfLine())
hjk's avatar
hjk committed
694
            moveLeft();
695
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
696
        m_registers[m_register] = selectedText();
697
        setPosition(m_savedYankPosition);
698
        m_submode = NoSubMode;
699
700
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
701
    } else if (m_submode == IndentSubMode) {
702
        recordJump();
hjk's avatar
hjk committed
703
        indentRegion();
704
        m_submode = NoSubMode;
705
        updateMiniBuffer();
706
    } else if (m_submode == ShiftRightSubMode) {
707
        recordJump();
708
        shiftRegionRight(1);
709
710
711
        m_submode = NoSubMode;
        updateMiniBuffer();
    } else if (m_submode == ShiftLeftSubMode) {
712
        recordJump();
713
        shiftRegionLeft(1);
714
715
        m_submode = NoSubMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
716
    }
717

hjk's avatar
hjk committed
718
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
719
720
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
721
    m_gflag = false;
hjk's avatar
hjk committed
722
723
    m_register = '"';
    m_tc.clearSelection();
724
725

    updateSelection();
hjk's avatar
hjk committed
726
    updateMiniBuffer();
hjk's avatar
hjk committed
727
728
}

729
730
void FakeVimHandler::Private::updateSelection()
{
hjk's avatar
hjk committed
731
    QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
732
733
734
735
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
736
737
738
739
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
740
741
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
742
#endif
743
744
745
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
746
        if (m_visualMode == VisualCharMode) {
747
            sel.cursor.setPosition(anchorPos, KeepAnchor);
748
749
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
750
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
751
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
752
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
753
754
755
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
            QTextCursor tc = m_tc;
            tc.setPosition(anchorPos);
            tc.movePosition(StartOfLine, MoveAnchor);
            QTextBlock anchorBlock = tc.block();
            QTextBlock cursorBlock = m_tc.block();
            int anchorColumn = anchorPos - anchorBlock.position();
            int cursorColumn = cursorPos - cursorBlock.position();
            int startColumn = qMin(anchorColumn, cursorColumn);
            int endColumn = qMax(anchorColumn, cursorColumn);
            int endPos = cursorBlock.position();
            while (tc.position() <= endPos) {
                if (startColumn < tc.block().length() - 1) {
                    int last = qMin(tc.block().length() - 1, endColumn);
                    int len = last - startColumn + 1;
                    sel.cursor = tc;
                    sel.cursor.movePosition(Right, MoveAnchor, startColumn);
                    sel.cursor.movePosition(Right, KeepAnchor, len);
                    selections.append(sel);
                }
                tc.movePosition(Down, MoveAnchor, 1);
            }
777
778
        }
    }
779
    //qDebug() << "SELECTION: " << selections;
780
    emit q->selectionChanged(selections);
781
782
}

hjk's avatar
hjk committed
783
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
784
{
hjk's avatar
hjk committed
785
    QString msg;
786
787
    if (m_passing) {
        msg = "-- PASSING --  ";
788
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
789
790
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
791
792
793
794
795
796
797
798
    } else if (m_mode == CommandMode && m_visualMode != NoVisualMode) {
        if (m_visualMode == VisualCharMode) {
            msg = "-- VISUAL --";
        } else if (m_visualMode == VisualLineMode) {
            msg = "-- VISUAL LINE --";
        } else if (m_visualMode == VisualBlockMode) {
            msg = "-- VISUAL BLOCK --";
        }
799
    } else if (m_mode == InsertMode) {
hjk's avatar
hjk committed
800
801
802
803
        if (m_submode == ReplaceSubMode)
            msg = "-- REPLACE --";
        else
            msg = "-- INSERT --";
hjk's avatar
hjk committed
804
    } else {
805
        if (m_mode == SearchForwardMode)
806
            msg += '/';
807
        else if (m_mode == SearchBackwardMode)
808
            msg += '?';
809
        else if (m_mode == ExMode)
810
            msg += ':';
hjk's avatar
hjk committed
811
        foreach (QChar c, m_commandBuffer) {
812
813
814
815
816
817
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
818
        }
hjk's avatar
hjk committed
819
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
820
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
821
    }
822

hjk's avatar
hjk committed
823
824
825
826
827
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
828
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
829
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
830
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
831
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
832
833
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
834
    } else {
hjk's avatar
hjk committed
835
        status += "All";
hjk's avatar
hjk committed
836
    }
hjk's avatar
hjk committed
837
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
838
839
}

hjk's avatar
hjk committed
840
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
841
{
842
843
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
844
    updateMiniBuffer();
hjk's avatar
hjk committed
845
846
}

hjk's avatar
hjk committed
847
848
849
850
851
852
853
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

854
855
void FakeVimHandler::Private::notImplementedYet()
{
hjk's avatar
hjk committed
856
    qDebug() << "Not implemented in FakeVim";
857
    showRedMessage(tr("Not implemented in FakeVim"));
858
859
860
    updateMiniBuffer();
}

861
EventResult FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
862
    const QString &text)
hjk's avatar
hjk committed
863
{
864
    EventResult handled = EventHandled;
865

hjk's avatar
hjk committed
866
867
868
869
    if (m_submode == WindowSubMode) {
        emit q->windowCommandRequested(key);
        m_submode = NoSubMode;
    } else if (m_submode == RegisterSubMode) {
hjk's avatar
hjk committed
870
871
        m_register = key;
        m_submode = NoSubMode;
872
873
874
875
    } else if (m_submode == ChangeSubMode && key == 'c') { // tested
        moveDown(count() - 1);
        moveToEndOfLine();
        moveLeft();
hjk's avatar
hjk committed
876
        setAnchor();
877
878
879
        moveToStartOfLine();
        setTargetColumn();
        moveUp(count() - 1);
880
        m_moveType = MoveLineWise;
881
882
883
884
        m_lastInsertion.clear();
        setDotCommand("%1cc", count());
        finishMovement();
    } else if (m_submode == DeleteSubMode && key == 'd') { // tested
hjk's avatar
hjk committed
885
        moveToStartOfLine();
886
        setTargetColumn(); 
hjk's avatar
hjk committed
887
        setAnchor();
hjk's avatar
hjk committed