fakevimhandler.cpp 84.1 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
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
hjk's avatar
hjk committed
89
#   define UNDO_DEBUG(s) qDebug() << << m_tc.document()->revision() << s
90
91
92
93
#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
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
177
178
    foreach (QTextEdit::ExtraSelection sel, sels)
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
179
180
    return ts;
}
181

hjk's avatar
hjk committed
182
183
184
185
186
187
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

188
189
190
191
192
193
194
enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

hjk's avatar
hjk committed
195
196
197
class FakeVimHandler::Private
{
public:
198
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
199

200
201
    EventResult handleEvent(QKeyEvent *ev);
    bool wantsOverride(QKeyEvent *ev);
hjk's avatar
hjk committed
202
    void handleCommand(const QString &cmd); // sets m_tc + handleExCommand
203
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
204

205
    void installEventFilter();
206
207
208
    void setupWidget();
    void restoreWidget();

209
    friend class FakeVimHandler;
hjk's avatar
hjk committed
210
211
212
213
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
214
215
216
217
218
    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
219
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
220
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
221
    void highlightMatches(const QString &needle);
hjk's avatar
hjk committed
222

hjk's avatar
hjk committed
223
224
225
    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
226
227
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
228
229
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
230

hjk's avatar
hjk committed
231
    int lastPositionInDocument() const;
232
233
    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
234
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
235

hjk's avatar
hjk committed
236
237
238
239
240
241
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
242
    int linesInDocument() const;
hjk's avatar
hjk committed
243
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
244
245
    void scrollUp(int count);
    void scrollDown(int count) { scrollUp(-count); }
hjk's avatar
hjk committed
246

247
    // helper functions for indenting
hjk's avatar
hjk committed
248
    bool isElectricCharacter(QChar c) const
249
        { return c == '{' || c == '}' || c == '#'; }
hjk's avatar
hjk committed
250
251
252
    void indentRegion(QChar lastTyped = QChar());
    void shiftRegionLeft(int repeat = 1);
    void shiftRegionRight(int repeat = 1);
253

hjk's avatar
hjk committed
254
    void moveToFirstNonBlankOnLine();
255
256
    void moveToTargetColumn();
    void setTargetColumn() { m_targetColumn = leftDist(); }
hjk's avatar
hjk committed
257
    void moveToNextWord(bool simple);
258
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
259
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
260
261

    // to reduce line noise
hjk's avatar
hjk committed
262
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
263
    void moveToStartOfLine();
hjk's avatar
hjk committed
264
265
266
    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
267
268
    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
269
    void setAnchor() { m_anchor = m_tc.position(); }
270
271
    void setAnchor(int position) { m_anchor = position; }
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
272

hjk's avatar
hjk committed
273
    void handleFfTt(int key);
hjk's avatar
hjk committed
274

hjk's avatar
hjk committed
275
    // helper function for handleExCommand. return 1 based line index.
hjk's avatar
hjk committed
276
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
277
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
278

279
    void enterInsertMode();
280
    void enterCommandMode();
281
    void enterExMode();
hjk's avatar
hjk committed
282
283
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
284
    void notImplementedYet();
285
286
    void updateMiniBuffer();
    void updateSelection();
287
    QWidget *editor() const;
288
289
    QChar characterAtCursor() const
        { return m_tc.document()->characterAt(m_tc.position()); }
hjk's avatar
hjk committed
290
291
292
    void beginEditBlock() { UNDO_DEBUG("BEGIN EDIT BLOCK"); m_tc.beginEditBlock(); }
    void endEditBlock() { UNDO_DEBUG("END EDIT BLOCK"); m_tc.endEditBlock(); }
    void joinPreviousEditBlock() { UNDO_DEBUG("JOIN EDIT BLOCK"); m_tc.joinPreviousEditBlock(); }
293

294
295
296
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
297
    bool m_wasReadOnly; // saves read-only state of document
298

hjk's avatar
hjk committed
299
300
    FakeVimHandler *q;
    Mode m_mode;
301
    bool m_passing; // let the core see the next event
hjk's avatar
hjk committed
302
    SubMode m_submode;
hjk's avatar
hjk committed
303
304
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
305
306
    QString m_input;
    QTextCursor m_tc;
307
    QTextCursor m_oldTc; // copy from last event to check for external changes
308
    int m_anchor;
hjk's avatar
hjk committed
309
310
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
311
312
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
313
    MoveType m_moveType;
hjk's avatar
hjk committed
314
315
316

    bool m_fakeEnd;

317
318
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
319
    int m_gflag;  // whether current command started with 'g'
320

hjk's avatar
hjk committed
321
    QString m_commandBuffer;
322
323
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
324

325
    bool m_lastSearchForward;
hjk's avatar
hjk committed
326
    QString m_lastInsertion;
hjk's avatar
hjk committed
327

328
    QString removeSelectedText();
hjk's avatar
hjk committed
329
330
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
331
332
    QString selectedText() const;

333
    // undo handling
334
335
    void undo();
    void redo();
336
    QMap<int, int> m_undoCursorPosition; // revision -> position
337

hjk's avatar
hjk committed
338
    // extra data for '.'
hjk's avatar
hjk committed
339
    void replay(const QString &text, int count);
340
341
    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
342
    QString m_dotCommand;
hjk's avatar
hjk committed
343
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
344

hjk's avatar
hjk committed
345
346
347
348
349
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
350
    // history for '/'
hjk's avatar
hjk committed
351
    QString lastSearchString() const;
352
    static QStringList m_searchHistory;
hjk's avatar
hjk committed
353
354
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
355
    // history for ':'
356
    static QStringList m_commandHistory;
hjk's avatar
hjk committed
357
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
358

hjk's avatar
hjk committed
359
    // visual line mode
360
361
362
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
363

364
365
    // marks as lines
    QHash<int, int> m_marks;
hjk's avatar
hjk committed
366
    QString m_oldNeedle;
367

hjk's avatar
hjk committed
368
    // vi style configuration
hjk's avatar
hjk committed
369
370
371
372
    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); }
373
374

    // for restoring cursor position
hjk's avatar
hjk committed
375
    int m_savedYankPosition;
376
    int m_targetColumn;
377

378
    int m_cursorWidth;
379

hjk's avatar
hjk committed
380
381
382
383
384
    // auto-indent
    void insertAutomaticIndentation(bool goingDown);
    bool removeAutomaticIndentation(); // true if something removed
    // number of autoindented characters
    int m_justAutoIndented;
385
    void handleStartOfLine();
hjk's avatar
hjk committed
386

387
    void recordJump();
388
    void recordNewUndo();
389
390
    QList<int> m_jumpListUndo;
    QList<int> m_jumpListRedo;
hjk's avatar
hjk committed
391
392

    QList<QTextEdit::ExtraSelection> m_searchSelections;
hjk's avatar
hjk committed
393
394
};

395
396
397
QStringList FakeVimHandler::Private::m_searchHistory;
QStringList FakeVimHandler::Private::m_commandHistory;

398
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
399
400
{
    q = parent;
401
402
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
hjk's avatar
hjk committed
403
404
    init();
}
405

hjk's avatar
hjk committed
406
407
void FakeVimHandler::Private::init()
{
hjk's avatar
hjk committed
408
    m_mode = CommandMode;
hjk's avatar
hjk committed
409
410
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
411
    m_passing = false;
hjk's avatar
hjk committed
412
    m_fakeEnd = false;
413
    m_lastSearchForward = true;
hjk's avatar
hjk committed
414
    m_register = '"';
hjk's avatar
hjk committed
415
    m_gflag = false;
416
    m_visualMode = NoVisualMode;
417
    m_targetColumn = 0;
hjk's avatar
hjk committed
418
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
419
420
    m_anchor = 0;
    m_savedYankPosition = 0;
421
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
422
    m_inReplay = false;
hjk's avatar
hjk committed
423
    m_justAutoIndented = 0;
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
            || 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
481
482

    // Fake "End of line"
483
484
    m_tc = EDITOR(textCursor());

485
486
487
488
489
    if (m_tc.position() != m_oldTc.position())
        setTargetColumn();

    m_tc.setVisualNavigation(true);
    
hjk's avatar
hjk committed
490
    if (m_fakeEnd)
hjk's avatar
hjk committed
491
        moveRight();
hjk's avatar
hjk committed
492

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

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

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

hjk's avatar
hjk committed
511
    if (m_fakeEnd)
hjk's avatar
hjk committed
512
        moveLeft();
hjk's avatar
hjk committed
513

514
    m_oldTc = m_tc;
515
    EDITOR(setTextCursor(m_tc));
516
    return result;
hjk's avatar
hjk committed
517
518
}

519
520
521
522
523
void FakeVimHandler::Private::installEventFilter()
{
    EDITOR(installEventFilter(q));
}

524
525
526
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
527
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
528
529
530
531
532
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
533
    m_wasReadOnly = EDITOR(isReadOnly());
534
    //EDITOR(setReadOnly(true));
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549

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

550
    //showBlackMessage("vi emulation mode. Type :q to leave. Use , Ctrl-R to trigger run.");
551
552
553
554
555
556
557
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
558
    //EDITOR(removeEventFilter(q));
559
    EDITOR(setReadOnly(m_wasReadOnly));
560
561
    EDITOR(setCursorWidth(m_cursorWidth));
    EDITOR(setOverwriteMode(false));
562

563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
    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();
579
580
}

581
582
EventResult FakeVimHandler::Private::handleKey(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
583
{
584
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
hjk's avatar
hjk committed
585
    if (m_mode == InsertMode)
586
        return handleInsertMode(key, unmodified, text);
587
    if (m_mode == CommandMode)
588
        return handleCommandMode(key, unmodified, text);
589
    if (m_mode == ExMode || m_mode == SearchForwardMode
590
            || m_mode == SearchBackwardMode)
591
        return handleMiniBufferModes(key, unmodified, text);
592
    return EventUnhandled;
hjk's avatar
hjk committed
593
594
}

hjk's avatar
hjk committed
595
596
void FakeVimHandler::Private::moveDown(int n)
{
hjk's avatar
hjk committed
597
598
599
600
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(Down, MoveAnchor, n);
#else
hjk's avatar
hjk committed
601
    const int col = m_tc.position() - m_tc.block().position();
602
603
604
    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
605
606
607
    const int pos = block.position();
    setPosition(pos + qMin(block.length() - 1, col));
    moveToTargetColumn();
hjk's avatar
hjk committed
608
#endif
hjk's avatar
hjk committed
609
610
611
612
}

void FakeVimHandler::Private::moveToEndOfLine()
{
hjk's avatar
hjk committed
613
614
615
616
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(EndOfLine, MoveAnchor);
#else
hjk's avatar
hjk committed
617
618
    const QTextBlock &block = m_tc.block();
    setPosition(block.position() + block.length() - 1);
hjk's avatar
hjk committed
619
#endif
hjk's avatar
hjk committed
620
621
}

622
623
624
625
626
627
628
629
630
631
632
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
633
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
634
{
635
    //qDebug() << "ANCHOR: " << position() << anchor();
hjk's avatar
hjk committed
636
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
637
638
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
639
        setPosition(qMin(anchor(), position()));
640
        enterExMode();
hjk's avatar
hjk committed
641
        m_currentMessage.clear();
hjk's avatar
hjk committed
642
643
644
645
646
647
648
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

649
650
651
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
652
    if (m_submode == ChangeSubMode) {
653
654
        if (m_moveType == MoveInclusive)
            moveRight(); // correction
655
656
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
657
        if (!dotCommand.isEmpty())
658
            setDotCommand("c" + dotCommand);
659
        QString text = removeSelectedText();
660
        //qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
661
        m_registers[m_register] = text;
662
        enterInsertMode();
hjk's avatar
hjk committed
663
664
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
665
        if (m_moveType == MoveInclusive)
666
            moveRight(); // correction
667
668
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
669
        if (!dotCommand.isEmpty())
670
            setDotCommand("d" + dotCommand);
671
        m_registers[m_register] = removeSelectedText();
hjk's avatar
hjk committed
672
        m_submode = NoSubMode;
673
        if (atEndOfLine())
hjk's avatar
hjk committed
674
            moveLeft();
675
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
676
        m_registers[m_register] = selectedText();
677
        setPosition(m_savedYankPosition);
678
        m_submode = NoSubMode;
679
680
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
681
    } else if (m_submode == IndentSubMode) {
682
        recordJump();
hjk's avatar
hjk committed
683
        indentRegion();
684
        m_submode = NoSubMode;
685
        updateMiniBuffer();
686
    } else if (m_submode == ShiftRightSubMode) {
687
        recordJump();
688
        shiftRegionRight(1);
689
690
691
        m_submode = NoSubMode;
        updateMiniBuffer();
    } else if (m_submode == ShiftLeftSubMode) {
692
        recordJump();
693
        shiftRegionLeft(1);
694
695
        m_submode = NoSubMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
696
    }
697

hjk's avatar
hjk committed
698
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
699
700
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
701
    m_gflag = false;
hjk's avatar
hjk committed
702
703
    m_register = '"';
    m_tc.clearSelection();
704
705

    updateSelection();
hjk's avatar
hjk committed
706
    updateMiniBuffer();
hjk's avatar
hjk committed
707
708
}

709
710
void FakeVimHandler::Private::updateSelection()
{
hjk's avatar
hjk committed
711
    QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
712
713
714
715
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
716
717
718
719
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
720
721
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
722
#endif
723
724
725
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
726
        if (m_visualMode == VisualCharMode) {
727
            sel.cursor.setPosition(anchorPos, KeepAnchor);
728
729
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
730
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
731
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
732
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
733
734
735
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
            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);
            }
757
758
        }
    }
759
    //qDebug() << "SELECTION: " << selections;
760
    emit q->selectionChanged(selections);
761
762
}

hjk's avatar
hjk committed
763
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
764
{
hjk's avatar
hjk committed
765
    QString msg;
766
767
    if (m_passing) {
        msg = "-- PASSING --  ";
768
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
769
        msg = m_currentMessage;
hjk's avatar
hjk committed
770
771
772
773
774
775
776
777
    } 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 --";
        }
778
    } else if (m_mode == InsertMode) {
hjk's avatar
hjk committed
779
780
781
782
        if (m_submode == ReplaceSubMode)
            msg = "-- REPLACE --";
        else
            msg = "-- INSERT --";
hjk's avatar
hjk committed
783
    } else {
784
        if (m_mode == SearchForwardMode)
785
            msg += '/';
786
        else if (m_mode == SearchBackwardMode)
787
            msg += '?';
788
        else if (m_mode == ExMode)
789
            msg += ':';
hjk's avatar
hjk committed
790
        foreach (QChar c, m_commandBuffer) {
791
792
793
794
795
796
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
797
        }
hjk's avatar
hjk committed
798
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
799
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
800
    }
801

hjk's avatar
hjk committed
802
803
804
805
806
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
807
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
808
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
809
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
810
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
811
812
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
813
    } else {
hjk's avatar
hjk committed
814
        status += "All";
hjk's avatar
hjk committed
815
    }
hjk's avatar
hjk committed
816
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
817
818
}

hjk's avatar
hjk committed
819
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
820
{
821
822
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
823
    updateMiniBuffer();
hjk's avatar
hjk committed
824
825
}

hjk's avatar
hjk committed
826
827
828
829
830
831
832
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

833
834
void FakeVimHandler::Private::notImplementedYet()
{
hjk's avatar
hjk committed
835
    qDebug() << "Not implemented in FakeVim";
836
    showRedMessage(tr("Not implemented in FakeVim"));
837
838
839
    updateMiniBuffer();
}

840
EventResult FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
841
    const QString &text)
hjk's avatar
hjk committed
842
{
843
    EventResult handled = EventHandled;
844

hjk's avatar
hjk committed
845
846
847
848
    if (m_submode == WindowSubMode) {
        emit q->windowCommandRequested(key);
        m_submode = NoSubMode;
    } else if (m_submode == RegisterSubMode) {
hjk's avatar
hjk committed
849
850
        m_register = key;
        m_submode = NoSubMode;
851
852
853
854
    } else if (m_submode == ChangeSubMode && key == 'c') { // tested
        moveDown(count() - 1);
        moveToEndOfLine();
        moveLeft();
hjk's avatar
hjk committed
855
        setAnchor();
856
857
858
        moveToStartOfLine();
        setTargetColumn();
        moveUp(count() - 1);
859
        m_moveType = MoveLineWise;
860
861
862
863
        m_lastInsertion.clear();
        setDotCommand("%1cc", count());
        finishMovement();
    } else if (m_submode == DeleteSubMode && key == 'd') { // tested
hjk's avatar
hjk committed
864
        moveToStartOfLine();
865
        setTargetColumn(); 
hjk's avatar
hjk committed
866
        setAnchor();
hjk's avatar
hjk committed
867
        moveDown(count());
868
        m_moveType = MoveLineWise;
869
870
        setDotCommand("%1dd", count());
        finishMovement();
871
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
872
        moveToStartOfLine();
hjk's avatar
hjk committed
873
        setAnchor();
hjk's avatar
hjk committed
874
        moveDown(count());
hjk's avatar
hjk committed
875
876
        m_moveType = MoveLineWise;
        finishMovement("y");
877
878
879
880
    } else if (m_submode == ShiftLeftSubMode && key == '<') {
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;