fakevimhandler.cpp 82.7 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
    ZSubMode,
hjk's avatar
hjk committed
146
};
hjk's avatar
hjk committed
147

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

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

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

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

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

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

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

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

214
215
class UndoBreaker;

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

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

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

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

    void init();
236
237
238
239
240
    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
241
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
242
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
243
    void highlightMatches(const QString &needle);
hjk's avatar
hjk committed
244

hjk's avatar
hjk committed
245
246
247
    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
248
249
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
250
251
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
252

hjk's avatar
hjk committed
253
    int lastPositionInDocument() const;
254
255
    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
256
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
257

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

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

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

    // to reduce line noise
hjk's avatar
hjk committed
284
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
285
    void moveToStartOfLine();
hjk's avatar
hjk committed
286
287
288
    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
289
290
    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
291
    void setAnchor() { m_anchor = m_tc.position(); }
292
293
    void setAnchor(int position) { m_anchor = position; }
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
294

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

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

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

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

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

    bool m_fakeEnd;

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

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

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

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

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

hjk's avatar
hjk committed
358
    // extra data for '.'
hjk's avatar
hjk committed
359
    void replay(const QString &text, int count);
360
361
    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
362
    QString m_dotCommand;
hjk's avatar
hjk committed
363
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
364

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

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

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

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

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

hjk's avatar
hjk committed
388
    // vi style configuration
hjk's avatar
hjk committed
389
390
391
392
    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); }
393
394

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

398
    int m_cursorWidth;
399

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

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

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

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

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

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

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

452
    if (key == Key_Escape) {
hjk's avatar
hjk committed
453
        // Not sure this feels good. People often hit Esc several times
454
455
456
457
458
459
460
461
462
463
464
465
466
        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;
467
        }
468
469
470
        KEY_DEBUG(" NOT PASSING CTRL KEY");
        //updateMiniBuffer();
        return true;
471
472
    }

473
474
475
476
477
478
479
480
481
482
    // 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
483
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
            || 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
501
502

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

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

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

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

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

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

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

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

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

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

    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();
    }

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

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

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    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();
599
600
}

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

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

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

642
643
644
645
646
647
648
649
650
651
652
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
653
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
654
{
655
    //qDebug() << "ANCHOR: " << position() << anchor();
hjk's avatar
hjk committed
656
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
657
658
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
659
        setPosition(qMin(anchor(), position()));
660
        enterExMode();
hjk's avatar
hjk committed
661
662
663
664
665
666
667
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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