fakevimhandler.cpp 67.7 KB
Newer Older
hjk's avatar
hjk committed
1
2
3
4
/***************************************************************************
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/

34
#include "fakevimhandler.h"
hjk's avatar
hjk committed
35

36
37
#include "fakevimconstants.h"

38
39
40
41
42
43
44
// 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.

//#include <indenter.h>

hjk's avatar
hjk committed
45
#include <QtCore/QDebug>
46
#include <QtCore/QFile>
hjk's avatar
hjk committed
47
#include <QtCore/QObject>
48
#include <QtCore/QPointer>
hjk's avatar
hjk committed
49
#include <QtCore/QProcess>
hjk's avatar
hjk committed
50
#include <QtCore/QRegExp>
51
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
52
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
53
54
#include <QtCore/QStack>

hjk's avatar
hjk committed
55
#include <QtGui/QApplication>
hjk's avatar
hjk committed
56
57
58
59
60
61
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
62
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
63
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
64
65
66


using namespace FakeVim::Internal;
67
using namespace FakeVim::Constants;
hjk's avatar
hjk committed
68

69
70
71
72
73
74
75
76
77
#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
78
79
80
81
82
83
84


///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
85

86
87
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
88
89
90
91
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

hjk's avatar
hjk committed
92
93
94
95
enum Mode
{
    InsertMode,
    CommandMode,
96
97
98
    ExMode,
    SearchForwardMode,
    SearchBackwardMode,
99
    PassingMode, // lets keyevents to be passed to the main application
hjk's avatar
hjk committed
100
};
hjk's avatar
hjk committed
101

hjk's avatar
hjk committed
102
103
104
105
106
107
enum SubMode
{
    NoSubMode,
    RegisterSubMode,
    ChangeSubMode,
    DeleteSubMode,
hjk's avatar
hjk committed
108
    FilterSubMode,
hjk's avatar
hjk committed
109
    ReplaceSubMode,    // used for R and r
110
    YankSubMode,
111
    IndentSubMode,
112
    ZSubMode,
hjk's avatar
hjk committed
113
};
hjk's avatar
hjk committed
114

hjk's avatar
hjk committed
115
116
enum SubSubMode
{
hjk's avatar
hjk committed
117
118
    // typically used for things that require one more data item
    // and are 'nested' behind a mode
hjk's avatar
hjk committed
119
    NoSubSubMode,
120
121
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
122
    BackTickSubSubMode, // used for `
hjk's avatar
hjk committed
123
    TickSubSubMode,     // used for '
hjk's avatar
hjk committed
124
125
};

126
127
128
129
130
131
132
133
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

hjk's avatar
hjk committed
134
135
136
137
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
hjk's avatar
hjk committed
138
    MoveLineWise,
hjk's avatar
hjk committed
139
140
};

141
142
struct EditOperation
{
hjk's avatar
hjk committed
143
144
145
146
147
    EditOperation() : position(-1), itemCount(0) {}
    int position;
    int itemCount; // used to combine several operations
    QString from;
    QString to;
148
149
};

hjk's avatar
hjk committed
150
QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
151
{
hjk's avatar
hjk committed
152
153
    if (op.itemCount > 0) {
        ts << "\n  EDIT BLOCK WITH " << op.itemCount << " ITEMS";
hjk's avatar
hjk committed
154
    } else {
hjk's avatar
hjk committed
155
156
        ts << "\n  EDIT AT " << op.position
           << "\n      FROM " << op.from << "\n      TO " << op.to;
hjk's avatar
hjk committed
157
158
159
160
    }
    return ts;
}

161
162
163
164
165
166
167
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
168
169
170
171
172
173
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

hjk's avatar
hjk committed
174
175
176
class FakeVimHandler::Private
{
public:
177
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
178

179
    bool handleEvent(QKeyEvent *ev);
180
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
181

182
183
184
    void setupWidget();
    void restoreWidget();

185
private:
186
    friend class FakeVimHandler;
hjk's avatar
hjk committed
187
188
189
190
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
191
192
193
194
195
    bool handleKey(int key, int unmodified, const QString &text);
    bool handleInsertMode(int key, int unmodified, const QString &text);
    bool handleCommandMode(int key, int unmodified, const QString &text);
    bool handleRegisterMode(int key, int unmodified, const QString &text);
    bool handleMiniBufferModes(int key, int unmodified, const QString &text);
hjk's avatar
hjk committed
196
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
197
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
198

hjk's avatar
hjk committed
199
200
201
    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
202
203
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
204
205
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
206

hjk's avatar
hjk committed
207
    int lastPositionInDocument() const;
hjk's avatar
hjk committed
208
209
    int positionForLine(int line) const; // 1 based line, 0 based pos
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
210

hjk's avatar
hjk committed
211
212
213
214
215
216
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
217
    int linesInDocument() const;
hjk's avatar
hjk committed
218
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
219

220
    // helper functions for indenting
hjk's avatar
hjk committed
221
    bool isElectricCharacter(QChar c) const
222
        { return c == '{' || c == '}' || c == '#'; }
223
224
225
226
    int indentDist() const;
    void indentRegion(QTextBlock first, QTextBlock last, QChar typedChar=0);
    void indentCurrentLine(QChar typedChar);

hjk's avatar
hjk committed
227
    void moveToFirstNonBlankOnLine();
228
    void moveToDesiredColumn();
hjk's avatar
hjk committed
229
    void moveToNextWord(bool simple);
230
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
231
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
232
233
234
235

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
236
237
238
239
240
241
242
    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
243
244
245
    void setAnchor() { m_anchor = m_tc.position(); }

    QString selectedText() const;
hjk's avatar
hjk committed
246

hjk's avatar
hjk committed
247
    void handleFfTt(int key);
hjk's avatar
hjk committed
248

hjk's avatar
hjk committed
249
250
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
251
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
252

253
    void enterInsertMode();
254
    void enterCommandMode();
255
    void enterExMode();
hjk's avatar
hjk committed
256
257
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
258
    void notImplementedYet();
259
260
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
261
    void quit();
262
    QWidget *editor() const;
263

264
265
266
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
267
    bool m_wasReadOnly; // saves read-only state of document
268

hjk's avatar
hjk committed
269
270
271
    FakeVimHandler *q;
    Mode m_mode;
    SubMode m_submode;
hjk's avatar
hjk committed
272
273
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
274
275
    QString m_input;
    QTextCursor m_tc;
hjk's avatar
hjk committed
276
    int m_anchor; 
hjk's avatar
hjk committed
277
278
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
279
280
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
281
    MoveType m_moveType;
hjk's avatar
hjk committed
282
283
284

    bool m_fakeEnd;

285
286
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
287
    int m_gflag;  // whether current command started with 'g'
288

hjk's avatar
hjk committed
289
    QString m_commandBuffer;
290
291
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
292

293
    bool m_lastSearchForward;
hjk's avatar
hjk committed
294
    QString m_lastInsertion;
hjk's avatar
hjk committed
295

296
    // undo handling
hjk's avatar
hjk committed
297
    void recordOperation(const EditOperation &op);
298
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
299
    void recordRemove(int position, const QString &data);
300
    void recordRemove(int position, int length);
hjk's avatar
hjk committed
301
302
303

    void recordRemoveNextChar();
    void recordInsertText(const QString &data);
hjk's avatar
hjk committed
304
    QString recordRemoveSelectedText();
305
    void recordMove();
hjk's avatar
hjk committed
306
307
    void recordBeginGroup();
    void recordEndGroup();
hjk's avatar
hjk committed
308
309
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
hjk's avatar
hjk committed
310

311
312
313
314
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;
hjk's avatar
hjk committed
315
    QStack<int> m_undoGroupStack;
316

hjk's avatar
hjk committed
317
318
319
    // extra data for '.'
    QString m_dotCommand;

hjk's avatar
hjk committed
320
321
322
323
324
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
325
    // history for '/'
hjk's avatar
hjk committed
326
327
328
329
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
330
    // history for ':'
hjk's avatar
hjk committed
331
332
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
333

hjk's avatar
hjk committed
334
    // visual line mode
335
336
337
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
338

339
340
341
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
342
343
    // vi style configuration
    QHash<QString, QString> m_config;
344
345

    // for restoring cursor position
hjk's avatar
hjk committed
346
    int m_savedYankPosition;
347
    int m_desiredColumn;
348
349

    QPointer<QObject> m_extraData;
350
    int m_cursorWidth;
hjk's avatar
hjk committed
351
352
};

353
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
354
355
{
    q = parent;
hjk's avatar
hjk committed
356

357
358
359
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);

hjk's avatar
hjk committed
360
    m_mode = CommandMode;
hjk's avatar
hjk committed
361
362
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
363
    m_fakeEnd = false;
364
    m_lastSearchForward = true;
hjk's avatar
hjk committed
365
    m_register = '"';
hjk's avatar
hjk committed
366
    m_gflag = false;
367
    m_visualMode = NoVisualMode;
368
    m_desiredColumn = 0;
hjk's avatar
hjk committed
369
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
370
371
    m_anchor = 0;
    m_savedYankPosition = 0;
372
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
373
374

    m_config[ConfigStartOfLine] = ConfigOn;
375
    m_config[ConfigTabStop]     = "8";
376
    m_config[ConfigSmartTab]    = ConfigOff;
377
    m_config[ConfigShiftWidth]  = "8";
378
    m_config[ConfigExpandTab]   = ConfigOff;
379
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
380
381
}

382
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
383
{
384
    int key = ev->key();
385
    const int um = key; // keep unmodified key around
386

387
    // FIXME
388
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
389
390
391
392
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
hjk's avatar
hjk committed
393
        m_mode = CommandMode;
394
395
396
        return false;
    }

hjk's avatar
hjk committed
397
398
399
400
401
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
        || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
        return false;

    // Fake "End of line"
402
    m_tc = EDITOR(textCursor());
403
    m_tc.setVisualNavigation(true);
404

hjk's avatar
hjk committed
405
    if (m_fakeEnd)
hjk's avatar
hjk committed
406
        moveRight();
hjk's avatar
hjk committed
407

408
    if ((ev->modifiers() & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
409
        key += 256;
410
411
412
413
414
        key += 32; // make it lower case
    } else if (key >= Key_A && key <= Key_Z
        && (ev->modifiers() & Qt::ShiftModifier) == 0) {
        key += 32;
    }
415
    bool handled = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
416
417

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

hjk's avatar
hjk committed
420
    if (m_fakeEnd)
hjk's avatar
hjk committed
421
        moveLeft();
hjk's avatar
hjk committed
422

423
424
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
425
    return handled;
hjk's avatar
hjk committed
426
427
}

428
429
430
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
431
432
    EDITOR(installEventFilter(q));
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
433
434
435
436
437
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
438
    m_wasReadOnly = EDITOR(isReadOnly());
439
440
441
442
443
444
445
446
    showBlackMessage("vi emulation mode.");
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
447
448
    EDITOR(removeEventFilter(q));
    EDITOR(setReadOnly(m_wasReadOnly));
449
450
}

451
bool FakeVimHandler::Private::handleKey(int key, int unmodified, const QString &text)
hjk's avatar
hjk committed
452
{
453
454
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
hjk's avatar
hjk committed
455
    if (m_mode == InsertMode)
456
        return handleInsertMode(key, unmodified, text);
457
    if (m_mode == CommandMode)
458
        return handleCommandMode(key, unmodified, text);
459
    if (m_mode == ExMode || m_mode == SearchForwardMode
460
            || m_mode == SearchBackwardMode)
461
        return handleMiniBufferModes(key, unmodified, text);
462
    return false;
hjk's avatar
hjk committed
463
464
}

hjk's avatar
hjk committed
465
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
466
{
467
    //qDebug() << "ANCHOR: " << m_anchor;
hjk's avatar
hjk committed
468
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
469
470
471
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
        m_tc.setPosition(qMin(anchor(), position()));
472
        enterExMode();
hjk's avatar
hjk committed
473
474
475
476
477
478
479
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

480
481
482
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
483
    if (m_submode == ChangeSubMode) {
hjk's avatar
hjk committed
484
485
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
486
        QString text = recordRemoveSelectedText();
hjk's avatar
hjk committed
487
        qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
488
        m_registers[m_register] = text;
hjk's avatar
hjk committed
489
490
491
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
492
493
        if (m_moveType == MoveInclusive)
            moveRight(); // correct 
hjk's avatar
hjk committed
494
495
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
496
497
        m_registers[m_register] = recordRemoveSelectedText();
        recordEndGroup();
hjk's avatar
hjk committed
498
        m_submode = NoSubMode;
499
        if (atEndOfLine())
hjk's avatar
hjk committed
500
            moveLeft();
501
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
502
503
        m_registers[m_register] = selectedText();
        m_tc.setPosition(m_savedYankPosition);
504
        m_submode = NoSubMode;
505
506
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
507
508
509
510
511
    } else if (m_submode == IndentSubMode) {
        QTextDocument *doc = EDITOR(document());
        int start = m_tc.selectionStart();
        int end = m_tc.selectionEnd();
        if (start > end)
hjk's avatar
hjk committed
512
            qSwap(start, end);
513
514
515
516
517
        QTextBlock startBlock = doc->findBlock(start);
        indentRegion(doc->findBlock(start), doc->findBlock(end).next());
        m_tc.setPosition(startBlock.position());
        moveToFirstNonBlankOnLine();
        m_submode = NoSubMode;
hjk's avatar
hjk committed
518
    }
hjk's avatar
hjk committed
519
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
520
521
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
522
    m_gflag = false;
hjk's avatar
hjk committed
523
524
    m_register = '"';
    m_tc.clearSelection();
525
526

    updateSelection();
hjk's avatar
hjk committed
527
    updateMiniBuffer();
528
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
529
530
}

531
532
533
534
535
536
537
void FakeVimHandler::Private::updateSelection()
{
    QList<QTextEdit::ExtraSelection> selections;
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
538
539
540
541
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
542
543
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
544
#endif
545
546
547
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
548
        if (m_visualMode == VisualCharMode) {
549
            sel.cursor.setPosition(anchorPos, KeepAnchor);
550
551
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
552
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
553
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
554
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
555
556
557
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
            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);
            }
579
580
        }
    }
581
    //qDebug() << "SELECTION: " << selections;
582
    emit q->selectionChanged(selections);
583
584
}

hjk's avatar
hjk committed
585
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
586
{
hjk's avatar
hjk committed
587
    QString msg;
588
589
590
    if (m_mode == PassingMode) {
        msg = "-- PASSING --";
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
591
592
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
593
594
595
596
597
598
599
600
    } 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 --";
        }
601
602
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
603
    } else {
604
        if (m_mode == SearchForwardMode)
605
            msg += '/';
606
        else if (m_mode == SearchBackwardMode)
607
            msg += '?';
608
        else if (m_mode == ExMode)
609
            msg += ':';
hjk's avatar
hjk committed
610
        foreach (QChar c, m_commandBuffer) {
611
612
613
614
615
616
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
617
        }
hjk's avatar
hjk committed
618
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
619
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
620
    }
hjk's avatar
hjk committed
621
622
623
624
625
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
626
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
627
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
628
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
629
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
630
631
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
632
    } else {
hjk's avatar
hjk committed
633
        status += "All";
hjk's avatar
hjk committed
634
    }
hjk's avatar
hjk committed
635
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
636
637
}

hjk's avatar
hjk committed
638
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
639
{
640
641
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
642
    updateMiniBuffer();
hjk's avatar
hjk committed
643
644
}

hjk's avatar
hjk committed
645
646
647
648
649
650
651
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

652
653
654
655
656
657
void FakeVimHandler::Private::notImplementedYet()
{
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

658
659
bool FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
660
{
661
    bool handled = true;
662

hjk's avatar
hjk committed
663
664
665
666
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
hjk's avatar
hjk committed
667
668
669
670
        moveToStartOfLine();
        setAnchor();
        moveDown(count());
        moveLeft();
hjk's avatar
hjk committed
671
        m_registers[m_register] = recordRemoveSelectedText();
hjk's avatar
hjk committed
672
673
        m_submode = NoSubMode;
        m_mode = InsertMode;
hjk's avatar
hjk committed
674
        finishMovement("c");
hjk's avatar
hjk committed
675
    } else if (m_submode == DeleteSubMode && key == 'd') {
hjk's avatar
hjk committed
676
        moveToStartOfLine();
hjk's avatar
hjk committed
677
        setAnchor();
hjk's avatar
hjk committed
678
679
        moveDown(count());
        m_registers[m_register] = recordRemoveSelectedText();
hjk's avatar
hjk committed
680
        finishMovement("d");
681
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
682
        moveToStartOfLine();
hjk's avatar
hjk committed
683
        setAnchor();
hjk's avatar
hjk committed
684
        moveDown(count());
hjk's avatar
hjk committed
685
686
        m_moveType = MoveLineWise;
        finishMovement("y");
687
688
    } else if (m_submode == IndentSubMode && key == '=') {
        indentRegion(m_tc.block(), m_tc.block().next());
689
        finishMovement();
hjk's avatar
hjk committed
690
691
    } else if (m_submode == ZSubMode) {
        if (key == Key_Return) {
hjk's avatar
hjk committed
692
            // cursor line to top of window, cursor on first non-blank
hjk's avatar
hjk committed
693
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
694
695
            moveToFirstNonBlankOnLine();
            finishMovement();
hjk's avatar
hjk committed
696
        } else {
hjk's avatar
hjk committed
697
            qDebug() << "IGNORED Z_MODE " << key << text;
hjk's avatar
hjk committed
698
699
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
700
    } else if (m_subsubmode == FtSubSubMode) {
hjk's avatar
hjk committed
701
702
        m_semicolonType = m_subsubdata;
        m_semicolonKey = key;
hjk's avatar
hjk committed
703
704
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
705
        finishMovement();
hjk's avatar
hjk committed
706
    } else if (m_submode == ReplaceSubMode) {
hjk's avatar
hjk committed
707
708
709
710
711
712
713
714
715
        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
716
            m_submode = NoSubMode;
hjk's avatar
hjk committed
717
718
719
            m_dotCommand = QString("%1r%2").arg(count()).arg(text);
            finishMovement();
        } else {
hjk's avatar
hjk committed
720
            m_submode = NoSubMode;
hjk's avatar
hjk committed
721
        }
722
723
724
725
726
727
    } 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)) {
hjk's avatar
hjk committed
728
            m_tc.setPosition(m_marks[key]);
729
730
731
732
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
733
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
734
735
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
736
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
737
        if (key == '0' && m_mvcount.isEmpty()) {
hjk's avatar
hjk committed
738
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
739
740
            finishMovement();
        } else {
hjk's avatar
hjk committed
741
            m_mvcount.append(QChar(key));
hjk's avatar
hjk committed
742
        }
hjk's avatar
hjk committed
743
744
745
746
747
748
749
750
751
752
753
754
755
756
    } else if (0 && key == ',') {
        // FIXME: fakevim uses ',' by itself, so it is incompatible
        m_subsubmode = FtSubSubMode;
        // HACK: toggle 'f' <-> 'F', 't' <-> 'T'
        m_subsubdata = m_semicolonType ^ 32;
        handleFfTt(m_semicolonKey);
        m_subsubmode = NoSubSubMode;
        finishMovement();
    } else if (key == ';') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = m_semicolonType;
        handleFfTt(m_semicolonKey);
        m_subsubmode = NoSubSubMode;
        finishMovement();
757
    } else if (key == ':') {
758
        enterExMode();
hjk's avatar
hjk committed
759
        m_commandBuffer.clear();
760
        if (m_visualMode != NoVisualMode)
761
762
763
764
765
766
767
768
769
            m_commandBuffer = "'<,'>";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
    } else if (key == '/' || key == '?') {
        m_mode = (key == '/') ? SearchForwardMode : SearchBackwardMode;
        m_commandBuffer.clear();
        m_searchHistory.append(QString());
        m_searchHistoryIndex = m_searchHistory.size() - 1;
hjk's avatar
hjk committed
770
        updateMiniBuffer();
771
772
    } else if (key == '`') {
        m_subsubmode = BackTickSubSubMode;
hjk's avatar
hjk committed
773
774
775
776
777
778
779
780
    } else if (key == '#' || key == '*') {
        // FIXME: That's not proper vim behaviour
        m_tc.select(QTextCursor::WordUnderCursor);
        QString needle = "\\<" + m_tc.selection().toPlainText() + "\\>";
        m_searchHistory.append(needle);
        m_lastSearchForward = (key == '*');
        updateMiniBuffer();
        search(needle, m_lastSearchForward);
781
782
    } else if (key == '\'') {
        m_subsubmode = TickSubSubMode;
hjk's avatar
hjk committed
783
    } else if (key == '|') {
hjk's avatar
hjk committed
784
785
786
        setAnchor();
        moveToStartOfLine();
        moveRight(qMin(count(), rightDist()) - 1);
hjk's avatar
hjk committed
787
        finishMovement();
hjk's avatar
hjk committed
788
789
790
    } else if (key == '!' && m_visualMode == NoVisualMode) {
        m_submode = FilterSubMode;
    } else if (key == '!' && m_visualMode == VisualLineMode) {
791
        enterExMode();
hjk's avatar
hjk committed
792
793
794
795
        m_commandBuffer = "'<,'>!";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
hjk's avatar
hjk committed
796
797
    } else if (key == '"') {
        m_submode = RegisterSubMode;
798
    } else if (unmodified == Key_Return) {
hjk's avatar
hjk committed
799
800
        moveToStartOfLine();
        moveDown();
801
        moveToFirstNonBlankOnLine();
802
        finishMovement();
hjk's avatar
hjk committed
803
    } else if (key == Key_Home) {
hjk's avatar
hjk committed
804
        moveToStartOfLine();
hjk's avatar
hjk committed
805
806
        finishMovement();
    } else if (key == '$' || key == Key_End) {
807
        int submode = m_submode;
hjk's avatar
hjk committed
808
        moveToEndOfLine();
hjk's avatar
hjk committed
809
        finishMovement();
810
811
        if (submode == NoSubMode)
            m_desiredColumn = -1;
812
813
814
815
    } else if (key == ',') {
        // FIXME: use some other mechanism
        m_mode = PassingMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
816
817
818
819
    } else if (key == '.') {
        qDebug() << "REPEATING" << m_dotCommand;
        for (int i = count(); --i >= 0; )
            foreach (QChar c, m_dotCommand)
820
                handleKey(c.unicode(), c.unicode(), QString(c));
821
822
    } else if (key == '=') {
        m_submode = IndentSubMode;
823
    } else if (key == '%') {
824
        moveToMatchingParanthesis();
825
        finishMovement();
hjk's avatar
hjk committed
826
    } else if (key == 'a') {
hjk's avatar
hjk committed
827
        m_mode = InsertMode;
hjk's avatar
hjk committed
828
        recordBeginGroup();
hjk's avatar
hjk committed
829
        m_lastInsertion.clear();
830
831
        if (!atEndOfLine())
            moveRight();
832
        updateMiniBuffer();
hjk's avatar
hjk committed
833
    } else if (key == 'A') {
hjk's avatar
hjk committed
834
        m_mode = InsertMode;
hjk's avatar
hjk committed
835
836
        moveToEndOfLine();
        recordBeginGroup();
hjk's avatar
hjk committed
837
        m_lastInsertion.clear();
hjk's avatar
hjk committed
838
    } else if (key == 'b') {
839
        m_moveType = MoveExclusive;
hjk's avatar
hjk committed
840
        moveToWordBoundary(false, false);
hjk's avatar
hjk committed
841
842
        finishMovement();
    } else if (key == 'B') {
843
        m_moveType = MoveExclusive;
hjk's avatar
hjk committed
844
        moveToWordBoundary(true, false);
hjk's avatar
hjk committed
845
        finishMovement();
hjk's avatar
hjk committed
846
    } else if (key == 'c') {
hjk's avatar
hjk committed
847
848
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
849
850
        m_submode = ChangeSubMode;
    } else if (key == 'C') {
hjk's avatar
hjk committed
851
852
853
854
855
        setAnchor();
        recordBeginGroup();
        moveToEndOfLine();
        m_registers[m_register] = recordRemoveSelectedText();
        m_mode = InsertMode;
hjk's avatar
hjk committed
856
        finishMovement();
857
    } else if (key == 'd' && m_visualMode == NoVisualMode) {
858
        if (atEndOfLine())
hjk's avatar
hjk committed
859
860
861
            moveLeft();
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
862
863
864
        m_opcount = m_mvcount;
        m_mvcount.clear();
        m_submode = DeleteSubMode;
865
    } else if (key == 'd') {
866
        //setAnchor();
867
868
869
        leaveVisualMode();
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
hjk's avatar
hjk committed
870
        selectRange(beginLine, endLine);
hjk's avatar
hjk committed
871
        recordRemoveSelectedText();
hjk's avatar
hjk committed
872
    } else if (key == 'D') {
hjk's avatar
hjk committed
873
874
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
875
        m_submode = DeleteSubMode;
hjk's avatar
hjk committed
876
877
        moveDown(qMax(count() - 1, 0));
        moveRight(rightDist());
hjk's avatar
hjk committed
878
        finishMovement();
hjk's avatar
hjk committed
879
    } else if (key == 'e') {
880
        m_moveType = MoveInclusive;
hjk's avatar
hjk committed
881
        moveToWordBoundary(false, true);
hjk's avatar
hjk committed
882
883
        finishMovement();
    } else if (key == 'E') {
884
        m_moveType = MoveInclusive;
hjk's avatar
hjk committed
885
        moveToWordBoundary(true, true);
hjk's avatar
hjk committed
886
        finishMovement();
hjk's avatar
hjk committed
887
888
889
    } else if (key == 'f' || key == 'F') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
890
891
    } else if (key == 'g') {
        m_gflag = true;
hjk's avatar
hjk committed
892
893
    } else if (key == 'G') {
        int n = m_mvcount.isEmpty() ? linesInDocument() : count();
Martin Aumueller's avatar
Martin Aumueller committed
894
        m_tc.setPosition(positionForLine(n), KeepAnchor);
hjk's avatar
hjk committed
895
        if (m_config[ConfigStartOfLine] == ConfigOn)
hjk's avatar