fakevimhandler.cpp 76.8 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
#include "fakevimconstants.h"

34
35
36
37
// 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.
hjk's avatar
hjk committed
38
39


40
41
42
43
44
45
46
47
48
49
50
51
52
// Some conventions:
//
// 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.
//
// 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.

53

hjk's avatar
hjk committed
54
#include <QtCore/QDebug>
55
#include <QtCore/QFile>
hjk's avatar
hjk committed
56
#include <QtCore/QObject>
57
#include <QtCore/QPointer>
hjk's avatar
hjk committed
58
#include <QtCore/QProcess>
hjk's avatar
hjk committed
59
#include <QtCore/QRegExp>
60
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
61
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
62
63
#include <QtCore/QStack>

hjk's avatar
hjk committed
64
#include <QtGui/QApplication>
hjk's avatar
hjk committed
65
66
67
68
69
70
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
71
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
72
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
73
74


75
76
77
78
79
80
81
//#define DEBUG_KEY  1
#if DEBUG_KEY
#   define KEY_DEBUG(s) qDebug() << s
#else
#   define KEY_DEBUG(s)
#endif

82
83
84
85
86
87
88
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
#   define UNDO_DEBUG(s) qDebug() << s
#else
#   define UNDO_DEBUG(s)
#endif

hjk's avatar
hjk committed
89
using namespace FakeVim::Internal;
90
using namespace FakeVim::Constants;
hjk's avatar
hjk committed
91

hjk's avatar
hjk committed
92
93
94
95
96
97
98

///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////

99
100
101
102
103
104
105
106
107
#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
hjk's avatar
hjk committed
108

109
110
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
111
112
113
114
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

hjk's avatar
hjk committed
115
116
117
118
enum Mode
{
    InsertMode,
    CommandMode,
119
120
121
    ExMode,
    SearchForwardMode,
    SearchBackwardMode,
hjk's avatar
hjk committed
122
};
hjk's avatar
hjk committed
123

hjk's avatar
hjk committed
124
125
126
enum SubMode
{
    NoSubMode,
127
128
129
130
    RegisterSubMode,   // used for "
    ChangeSubMode,     // used for c
    DeleteSubMode,     // used for d
    FilterSubMode,     // used for !
hjk's avatar
hjk committed
131
    ReplaceSubMode,    // used for R and r
132
133
134
135
    YankSubMode,       // used for y
    ShiftLeftSubMode,  // used for <
    ShiftRightSubMode, // used for >
    IndentSubMode,     // used for =
136
    ZSubMode,
hjk's avatar
hjk committed
137
};
hjk's avatar
hjk committed
138

hjk's avatar
hjk committed
139
140
enum SubSubMode
{
hjk's avatar
hjk committed
141
142
    // typically used for things that require one more data item
    // and are 'nested' behind a mode
hjk's avatar
hjk committed
143
    NoSubSubMode,
144
145
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
146
    BackTickSubSubMode, // used for `
hjk's avatar
hjk committed
147
    TickSubSubMode,     // used for '
hjk's avatar
hjk committed
148
149
};

150
151
152
153
154
155
156
157
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

hjk's avatar
hjk committed
158
159
160
161
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
hjk's avatar
hjk committed
162
    MoveLineWise,
hjk's avatar
hjk committed
163
164
};

165
166
struct EditOperation
{
hjk's avatar
hjk committed
167
168
169
170
171
    EditOperation() : position(-1), itemCount(0) {}
    int position;
    int itemCount; // used to combine several operations
    QString from;
    QString to;
172
173
};

hjk's avatar
hjk committed
174
QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
175
{
hjk's avatar
hjk committed
176
177
    if (op.itemCount > 0) {
        ts << "\n  EDIT BLOCK WITH " << op.itemCount << " ITEMS";
hjk's avatar
hjk committed
178
    } else {
hjk's avatar
hjk committed
179
180
        ts << "\n  EDIT AT " << op.position
           << "\n      FROM " << op.from << "\n      TO " << op.to;
hjk's avatar
hjk committed
181
182
183
184
    }
    return ts;
}

185
186
187
188
189
190
191
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
    foreach (QTextEdit::ExtraSelection sel, sels) 
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position(); 
    return ts;
}
        
hjk's avatar
hjk committed
192
193
194
195
196
197
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

198
199
200
201
202
203
204
enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

hjk's avatar
hjk committed
205
206
207
class FakeVimHandler::Private
{
public:
208
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
209

210
211
    EventResult handleEvent(QKeyEvent *ev);
    bool wantsOverride(QKeyEvent *ev);
212
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
213

214
215
216
    void setupWidget();
    void restoreWidget();

217
private:
218
    friend class FakeVimHandler;
hjk's avatar
hjk committed
219
220
221
222
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
223
224
225
226
227
    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
228
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
229
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
230

hjk's avatar
hjk committed
231
232
233
    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
234
235
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
236
237
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
238

hjk's avatar
hjk committed
239
    int lastPositionInDocument() const;
240
241
    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
242
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
243

hjk's avatar
hjk committed
244
245
246
247
248
249
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
250
    int linesInDocument() const;
hjk's avatar
hjk committed
251
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
252

253
    // helper functions for indenting
hjk's avatar
hjk committed
254
    bool isElectricCharacter(QChar c) const
255
        { return c == '{' || c == '}' || c == '#'; }
256
    int indentDist() const;
hjk's avatar
hjk committed
257
258
259
    void indentRegion(QChar lastTyped = QChar());
    void shiftRegionLeft(int repeat = 1);
    void shiftRegionRight(int repeat = 1);
260

hjk's avatar
hjk committed
261
    void moveToFirstNonBlankOnLine();
262
    void moveToDesiredColumn();
hjk's avatar
hjk committed
263
    void moveToNextWord(bool simple);
264
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
265
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
266
267
268
269

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
270
271
272
273
274
275
276
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
    void moveToStartOfLine() { m_tc.movePosition(StartOfLine, MoveAnchor); }
    void moveToEndOfLine() { m_tc.movePosition(EndOfLine, MoveAnchor); }
    void moveUp(int n = 1) { m_tc.movePosition(Up, MoveAnchor, n); }
    void moveDown(int n = 1) { m_tc.movePosition(Down, MoveAnchor, n); }
    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
277
    void setAnchor() { m_anchor = m_tc.position(); }
278
279
    void setAnchor(int position) { m_anchor = position; }
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
280

hjk's avatar
hjk committed
281
    void handleFfTt(int key);
hjk's avatar
hjk committed
282

hjk's avatar
hjk committed
283
284
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
285
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
286

287
    void enterInsertMode();
288
    void enterCommandMode();
289
    void enterExMode();
hjk's avatar
hjk committed
290
291
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
292
    void notImplementedYet();
293
294
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
295
    void quit();
296
    QWidget *editor() const;
297
298
    QChar characterAtCursor() const
        { return m_tc.document()->characterAt(m_tc.position()); }
299

300
301
302
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
303
    bool m_wasReadOnly; // saves read-only state of document
304

hjk's avatar
hjk committed
305
306
    FakeVimHandler *q;
    Mode m_mode;
307
    bool m_passing; // let the core see the next event
hjk's avatar
hjk committed
308
    SubMode m_submode;
hjk's avatar
hjk committed
309
310
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
311
312
    QString m_input;
    QTextCursor m_tc;
hjk's avatar
hjk committed
313
    int m_anchor; 
hjk's avatar
hjk committed
314
315
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
316
317
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
318
    MoveType m_moveType;
hjk's avatar
hjk committed
319
320
321

    bool m_fakeEnd;

322
323
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
324
    int m_gflag;  // whether current command started with 'g'
325

hjk's avatar
hjk committed
326
    QString m_commandBuffer;
327
328
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
329

330
    bool m_lastSearchForward;
hjk's avatar
hjk committed
331
    QString m_lastInsertion;
hjk's avatar
hjk committed
332

333
    // undo handling
hjk's avatar
hjk committed
334
    void recordOperation(const EditOperation &op);
335
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
336
    void recordRemove(int position, const QString &data);
337
    void recordRemove(int position, int length);
hjk's avatar
hjk committed
338
339
340

    void recordRemoveNextChar();
    void recordInsertText(const QString &data);
hjk's avatar
hjk committed
341
    QString recordRemoveSelectedText();
342
    void recordPosition();
hjk's avatar
hjk committed
343
344
    void recordBeginGroup();
    void recordEndGroup();
hjk's avatar
hjk committed
345
346
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
347
348
    QString selectedText() const;

349
350
351
352
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;
hjk's avatar
hjk committed
353
    QStack<int> m_undoGroupStack;
354
    QMap<int, int> m_undoCursorPosition;
355

hjk's avatar
hjk committed
356
357
358
    // extra data for '.'
    QString m_dotCommand;

hjk's avatar
hjk committed
359
360
361
362
363
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
364
    // history for '/'
hjk's avatar
hjk committed
365
366
367
368
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
369
    // history for ':'
hjk's avatar
hjk committed
370
371
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
372

hjk's avatar
hjk committed
373
    // visual line mode
374
375
376
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
377

378
379
380
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
381
382
    // vi style configuration
    QHash<QString, QString> m_config;
383
384

    // for restoring cursor position
hjk's avatar
hjk committed
385
    int m_savedYankPosition;
386
    int m_desiredColumn;
387
388

    QPointer<QObject> m_extraData;
389
    int m_cursorWidth;
390
391
392
393

    void recordJump();
    QList<int> m_jumpListUndo;
    QList<int> m_jumpListRedo;
hjk's avatar
hjk committed
394
395
};

396
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
397
398
{
    q = parent;
hjk's avatar
hjk committed
399

400
401
402
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);

hjk's avatar
hjk committed
403
    m_mode = CommandMode;
hjk's avatar
hjk committed
404
405
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
406
    m_passing = false;
hjk's avatar
hjk committed
407
    m_fakeEnd = false;
408
    m_lastSearchForward = true;
hjk's avatar
hjk committed
409
    m_register = '"';
hjk's avatar
hjk committed
410
    m_gflag = false;
411
    m_visualMode = NoVisualMode;
412
    m_desiredColumn = 0;
hjk's avatar
hjk committed
413
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
414
415
    m_anchor = 0;
    m_savedYankPosition = 0;
416
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
417
418

    m_config[ConfigStartOfLine] = ConfigOn;
419
    m_config[ConfigTabStop]     = "8";
420
    m_config[ConfigSmartTab]    = ConfigOff;
421
    m_config[ConfigShiftWidth]  = "8";
422
    m_config[ConfigExpandTab]   = ConfigOff;
423
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
424
425
}

426
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
hjk's avatar
hjk committed
427
{
428
429
430
    const int key = ev->key();
    const int mods = ev->modifiers();
    KEY_DEBUG("SHORTCUT OVERRIDE" << key << "  PASSING: " << m_passing);
431

432
    if (key == Key_Escape) {
hjk's avatar
hjk committed
433
        // Not sure this feels good. People often hit Esc several times
434
435
436
437
438
439
440
441
442
443
444
445
446
        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;
447
        }
448
449
450
        KEY_DEBUG(" NOT PASSING CTRL KEY");
        //updateMiniBuffer();
        return true;
451
452
    }

453
454
455
456
457
458
459
460
461
462
    // 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
463
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
            || 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...";
        //    quit();
        //    return EventHandled;
        //}
        m_passing = false;
        updateMiniBuffer();
        KEY_DEBUG("   PASS TO CORE");
        return EventPassedToCore;
    }
hjk's avatar
hjk committed
482
483

    // Fake "End of line"
484
    m_tc = EDITOR(textCursor());
485
    m_tc.setVisualNavigation(true);
486

hjk's avatar
hjk committed
487
    if (m_fakeEnd)
hjk's avatar
hjk committed
488
        moveRight();
hjk's avatar
hjk committed
489

490
    if ((mods & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
491
        key += 256;
492
        key += 32; // make it lower case
493
    } else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
494
495
        key += 32;
    }
496
497
498
499
500
501

    m_undoCursorPosition[EDITOR(document())->revision()] = m_tc.position();
    if (m_mode == InsertMode)
        m_tc.joinPreviousEditBlock();
    else
        m_tc.beginEditBlock();
502
    EventResult result = handleKey(key, um, ev->text());
503
    m_tc.endEditBlock();
hjk's avatar
hjk committed
504
505

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

hjk's avatar
hjk committed
508
    if (m_fakeEnd)
hjk's avatar
hjk committed
509
        moveLeft();
hjk's avatar
hjk committed
510

511
512
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
513
    return result;
hjk's avatar
hjk committed
514
515
}

516
517
518
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
519
520
    EDITOR(installEventFilter(q));
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
521
522
523
524
525
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
526
    m_wasReadOnly = EDITOR(isReadOnly());
527
    //EDITOR(setReadOnly(true)); 
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

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

543
544
545
546
547
548
549
550
    showBlackMessage("vi emulation mode.");
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
551
552
    EDITOR(removeEventFilter(q));
    EDITOR(setReadOnly(m_wasReadOnly));
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    
    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();
570
571
}

572
573
EventResult FakeVimHandler::Private::handleKey(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
574
{
575
576
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
hjk's avatar
hjk committed
577
    if (m_mode == InsertMode)
578
        return handleInsertMode(key, unmodified, text);
579
    if (m_mode == CommandMode)
580
        return handleCommandMode(key, unmodified, text);
581
    if (m_mode == ExMode || m_mode == SearchForwardMode
582
            || m_mode == SearchBackwardMode)
583
        return handleMiniBufferModes(key, unmodified, text);
584
    return EventUnhandled;
hjk's avatar
hjk committed
585
586
}

hjk's avatar
hjk committed
587
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
588
{
589
    //qDebug() << "ANCHOR: " << m_anchor;
hjk's avatar
hjk committed
590
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
591
592
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
593
        setPosition(qMin(anchor(), position()));
594
        enterExMode();
hjk's avatar
hjk committed
595
596
597
598
599
600
601
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

602
603
604
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
605
    if (m_submode == ChangeSubMode) {
606
607
        if (m_moveType == MoveInclusive)
            moveRight(); // correction
608
609
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
610
611
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
612
        QString text = recordRemoveSelectedText();
613
        //qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
614
        m_registers[m_register] = text;
hjk's avatar
hjk committed
615
616
617
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
618
        if (m_moveType == MoveInclusive)
619
            moveRight(); // correction
620
621
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
622
623
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
624
625
        m_registers[m_register] = recordRemoveSelectedText();
        recordEndGroup();
hjk's avatar
hjk committed
626
        m_submode = NoSubMode;
627
        if (atEndOfLine())
hjk's avatar
hjk committed
628
            moveLeft();
629
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
630
        m_registers[m_register] = selectedText();
631
        setPosition(m_savedYankPosition);
632
        m_submode = NoSubMode;
633
634
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
635
    } else if (m_submode == IndentSubMode) {
hjk's avatar
hjk committed
636
        indentRegion();
637
        m_submode = NoSubMode;
638
    } else if (m_submode == ShiftRightSubMode) {
639
        shiftRegionRight(1);
640
641
642
        m_submode = NoSubMode;
        updateMiniBuffer();
    } else if (m_submode == ShiftLeftSubMode) {
643
        shiftRegionLeft(1);
644
645
        m_submode = NoSubMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
646
    }
647

hjk's avatar
hjk committed
648
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
649
650
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
651
    m_gflag = false;
hjk's avatar
hjk committed
652
653
    m_register = '"';
    m_tc.clearSelection();
654
655

    updateSelection();
hjk's avatar
hjk committed
656
    updateMiniBuffer();
657
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
658
659
}

660
661
662
663
664
665
666
void FakeVimHandler::Private::updateSelection()
{
    QList<QTextEdit::ExtraSelection> selections;
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
667
668
669
670
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
671
672
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
673
#endif
674
675
676
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
677
        if (m_visualMode == VisualCharMode) {
678
            sel.cursor.setPosition(anchorPos, KeepAnchor);
679
680
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
681
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
682
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
683
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
684
685
686
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
            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);
            }
708
709
        }
    }
710
    //qDebug() << "SELECTION: " << selections;
711
    emit q->selectionChanged(selections);
712
713
}

hjk's avatar
hjk committed
714
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
715
{
hjk's avatar
hjk committed
716
    QString msg;
717
718
    if (m_passing) {
        msg = "-- PASSING --  ";
719
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
720
721
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
722
723
724
725
726
727
728
729
    } 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 --";
        }
730
731
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
732
    } else {
733
        if (m_mode == SearchForwardMode)
734
            msg += '/';
735
        else if (m_mode == SearchBackwardMode)
736
            msg += '?';
737
        else if (m_mode == ExMode)
738
            msg += ':';
hjk's avatar
hjk committed
739
        foreach (QChar c, m_commandBuffer) {
740
741
742
743
744
745
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
746
        }
hjk's avatar
hjk committed
747
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
748
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
749
    }
750

hjk's avatar
hjk committed
751
752
753
754
755
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
756
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
757
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
758
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
759
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
760
761
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
762
    } else {
hjk's avatar
hjk committed
763
        status += "All";
hjk's avatar
hjk committed
764
    }
hjk's avatar
hjk committed
765
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
766
767
}

hjk's avatar
hjk committed
768
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
769
{
770
771
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
772
    updateMiniBuffer();
hjk's avatar
hjk committed
773
774
}

hjk's avatar
hjk committed
775
776
777
778
779
780
781
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

782
783
784
785
786
787
void FakeVimHandler::Private::notImplementedYet()
{
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

788
EventResult FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
789
    const QString &text)
hjk's avatar
hjk committed
790
{
791
    EventResult handled = EventHandled;
792

hjk's avatar
hjk committed
793
794
795
796
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
hjk's avatar
hjk committed
797
798
799
        moveToStartOfLine();
        setAnchor();
        moveDown(count());
800
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
801
        finishMovement("c");
hjk's avatar
hjk committed
802
    } else if (m_submode == DeleteSubMode && key == 'd') {
hjk's avatar
hjk committed
803
        moveToStartOfLine();
hjk's avatar
hjk committed
804
        setAnchor();
hjk's avatar
hjk committed
805
        moveDown(count());
806
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
807
        finishMovement("d");
808
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
809
        moveToStartOfLine();
hjk's avatar
hjk committed
810
        setAnchor();
hjk's avatar
hjk committed
811
        moveDown(count());
hjk's avatar
hjk committed
812
813
        m_moveType = MoveLineWise;
        finishMovement("y");
814
815
816
817
818
819
820
821
822
823
824
825
    } else if (m_submode == ShiftLeftSubMode && key == '<') {
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1<<").arg(count());
        finishMovement();
    } else if (m_submode == ShiftRightSubMode && key == '>') {
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1>>").arg(count());
        finishMovement();
826
    } else if (m_submode == IndentSubMode && key == '=') {
hjk's avatar
hjk committed
827
828
829
830
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1>>").arg(count());
831
        finishMovement();
hjk's avatar
hjk committed
832
    } else if (m_submode == ZSubMode) {
hjk's avatar
hjk committed
833
834
835
        //qDebug() << "Z_MODE " << cursorLineInDocument() << linesOnScreen();
        if (key == Key_Return || key == 't') { // cursor line to top of window
            if (!m_mvcount.isEmpty())
836
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
837
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
838
839
            if (key == Key_Return)
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
840
            finishMovement();
hjk's avatar
hjk committed
841
842
        } else if (key == '.' || key == 'z') { // cursor line to center of window
            if (!m_mvcount.isEmpty())
843
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
844
            scrollToLineInDocument(cursorLineInDocument() - linesOnScreen() / 2);
hjk's avatar
hjk committed
845
846
            if (key == '.')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
847
            finishMovement();
hjk's avatar
hjk committed
848
849
        } else if (key == '-' || key == 'b') { // cursor line to bottom of window
            if (!m_mvcount.isEmpty())
850
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
851
852
853
            scrollToLineInDocument(cursorLineInDocument() - linesOnScreen() - 1);
            if (key == '-')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
854
            finishMovement();
hjk's avatar
hjk committed
855
        } else {
hjk's avatar
hjk committed
856
            qDebug() << "IGNORED Z_MODE " << key << text;
hjk's avatar
hjk committed
857
858
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
859
    } else if (m_subsubmode == FtSubSubMode) {
hjk's avatar
hjk committed
860
861
        m_semicolonType = m_subsubdata;
        m_semicolonKey = key;
hjk's avatar
hjk committed
862
863
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
864
865
866
867
        finishMovement(QString("%1%2%3")
            .arg(count())
            .arg(QChar(m_semicolonType))
            .arg(QChar(m_semicolonKey)));
hjk's avatar
hjk committed
868
    } else if (m_submode == ReplaceSubMode) {
hjk's avatar
hjk committed
869
870
871
872
873
874
875
876
877
        if (count() < rightDist() && text.size() == 1
                && (text.at(0).isPrint() || text.at(0).isSpace())) {
            recordBeginGroup();
            setAnchor();
            moveRight(count());
            recordRemoveSelectedText();
            recordInsertText(QString(count(), text.at(0)));
            recordEndGroup();
            m_moveType = MoveExclusive;
hjk's avatar
hjk committed
878
            m_submode = NoSubMode;
hjk's avatar
hjk committed
879
880
881
            m_dotCommand = QString("%1r%2").arg(count()).arg(text);
            finishMovement();
        } else {
hjk's avatar
hjk committed
882
            m_submode = NoSubMode;
hjk's avatar
hjk committed
883
        }
884
885
886
887
888
889
    } else if (m_subsubmode == MarkSubSubMode) {
        m_marks[key] = m_tc.position();
        m_subsubmode = NoSubSubMode;
    } else if (m_subsubmode == BackTickSubSubMode
            || m_subsubmode == TickSubSubMode) {
        if (m_marks.contains(key)) {
890
            setPosition(m_marks[key]);
891
892
893
894
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
895
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
896
897
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
898
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
899
        if (key == '0' && m_mvcount.isEmpty()) {
900
            moveToStartOfLine();