fakevimhandler.cpp 62.6 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>
hjk's avatar
hjk committed
48
#include <QtCore/QProcess>
hjk's avatar
hjk committed
49
#include <QtCore/QRegExp>
50
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
51
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
52
53
#include <QtCore/QStack>

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


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

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


///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
84

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

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

using namespace Qt;

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

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

hjk's avatar
hjk committed
114
115
116
enum SubSubMode
{
    NoSubSubMode,
117
118
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
119
    BackTickSubSubMode, // used for `
120
    TickSubSubMode      // used for '
hjk's avatar
hjk committed
121
122
};

123
124
125
126
127
128
129
130
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

131
132
struct EditOperation
{
hjk's avatar
hjk committed
133
    EditOperation() : m_position(-1), m_itemCount(0) {}
134
    int m_position;
hjk's avatar
hjk committed
135
136
137
    int m_itemCount; // used to combine several operations
    QString m_from;
    QString m_to;
138
139
};

hjk's avatar
hjk committed
140
static QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
141
142
{
    if (op.m_itemCount > 0) {
hjk's avatar
hjk committed
143
        ts << "\n  EDIT BLOCK WITH " << op.m_itemCount << " ITEMS";
hjk's avatar
hjk committed
144
    } else {
hjk's avatar
hjk committed
145
146
        ts << "\n  EDIT AT " << op.m_position
           << "\n      FROM " << op.m_from << "\n      TO " << op.m_to;
hjk's avatar
hjk committed
147
148
149
150
    }
    return ts;
}

hjk's avatar
hjk committed
151
152
153
154
155
156
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

hjk's avatar
hjk committed
157
158
159
160
161
class FakeVimHandler::Private
{
public:
    Private(FakeVimHandler *parent);

162
    bool handleEvent(QKeyEvent *ev);
163
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
164

165
private:
166
    friend class FakeVimHandler;
hjk's avatar
hjk committed
167
168
169
170
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
171
172
173
174
175
    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
176
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
177
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
178

hjk's avatar
hjk committed
179
180
181
    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
182
183
184
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
    bool atEol() const { return m_tc.atBlockEnd() && m_tc.block().length()>1; }
hjk's avatar
hjk committed
185

hjk's avatar
hjk committed
186
    int lastPositionInDocument() const;
hjk's avatar
hjk committed
187
188
    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
189

hjk's avatar
hjk committed
190
191
192
193
194
195
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
196
    int linesInDocument() const;
hjk's avatar
hjk committed
197
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
198

199
    // helper functions for indenting
hjk's avatar
hjk committed
200
201
    bool isElectricCharacter(QChar c) const
        { return (c == '{' || c == '}' || c == '#'); }
202
203
204
205
    int indentDist() const;
    void indentRegion(QTextBlock first, QTextBlock last, QChar typedChar=0);
    void indentCurrentLine(QChar typedChar);

hjk's avatar
hjk committed
206
    void moveToFirstNonBlankOnLine();
207
    void moveToDesiredColumn();
hjk's avatar
hjk committed
208
    void moveToNextWord(bool simple);
209
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
210
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
211
212
213
214

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    void moveToEndOfDocument()
        { m_tc.movePosition(QTextCursor::End, MoveAnchor); }
    void moveToStartOfLine()
        { m_tc.movePosition(QTextCursor::StartOfLine, MoveAnchor); }
    void moveToEndOfLine()
        { m_tc.movePosition(QTextCursor::EndOfLine, MoveAnchor); }
    void moveUp(int n = 1)
        { m_tc.movePosition(QTextCursor::Up, MoveAnchor, n); }
    void moveDown(int n = 1)
        { m_tc.movePosition(QTextCursor::Down, MoveAnchor, n); }
    void moveRight(int n = 1)
        { m_tc.movePosition(QTextCursor::Right, MoveAnchor, n); }
    void moveLeft(int n = 1)
        { m_tc.movePosition(QTextCursor::Left, MoveAnchor, n); }
    void setAnchor() { m_anchor = m_tc.position(); }

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

hjk's avatar
hjk committed
233
    void handleFfTt(int key);
hjk's avatar
hjk committed
234

hjk's avatar
hjk committed
235
236
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
237
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
238

239
    void setWidget(QWidget *ob);
240
    void enterInsertMode();
241
    void enterCommandMode();
hjk's avatar
hjk committed
242
243
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
244
    void notImplementedYet();
245
246
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
247
    void quit();
248
    QWidget *editor() const;
249

250
251
252
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
253
    bool m_wasReadOnly; // saves read-only state of document
254

hjk's avatar
hjk committed
255
256
257
    FakeVimHandler *q;
    Mode m_mode;
    SubMode m_submode;
hjk's avatar
hjk committed
258
259
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
260
261
    QString m_input;
    QTextCursor m_tc;
hjk's avatar
hjk committed
262
    int m_anchor; 
hjk's avatar
hjk committed
263
264
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
265
266
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
267
268
269

    bool m_fakeEnd;

270
271
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
272
    int m_gflag;  // whether current command started with 'g'
273

hjk's avatar
hjk committed
274
    QString m_commandBuffer;
275
276
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
277

278
    bool m_lastSearchForward;
hjk's avatar
hjk committed
279
    QString m_lastInsertion;
hjk's avatar
hjk committed
280

281
    // undo handling
hjk's avatar
hjk committed
282
    void recordOperation(const EditOperation &op);
283
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
284
    void recordRemove(int position, const QString &data);
285
    void recordRemove(int position, int length);
286
    void recordMove(int position, int nestedCount);
hjk's avatar
hjk committed
287
288
289

    void recordRemoveNextChar();
    void recordInsertText(const QString &data);
hjk's avatar
hjk committed
290
    QString recordRemoveSelectedText();
hjk's avatar
hjk committed
291
292
    void recordBeginGroup();
    void recordEndGroup();
hjk's avatar
hjk committed
293
294
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
hjk's avatar
hjk committed
295

296
297
298
299
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;
hjk's avatar
hjk committed
300
    QStack<int> m_undoGroupStack;
301

hjk's avatar
hjk committed
302
303
304
305
    // extra data for '.'
    QString m_dotCount;
    QString m_dotCommand;

hjk's avatar
hjk committed
306
    // history for '/'
hjk's avatar
hjk committed
307
308
309
310
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
311
    // history for ':'
hjk's avatar
hjk committed
312
313
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
314

hjk's avatar
hjk committed
315
    // visual line mode
316
317
318
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
319

320
321
322
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
323
324
    // vi style configuration
    QHash<QString, QString> m_config;
325
326
327

    // for restoring cursor position
    int m_savedPosition;
328
    int m_desiredColumn;
hjk's avatar
hjk committed
329
330
331
332
333
};

FakeVimHandler::Private::Private(FakeVimHandler *parent)
{
    q = parent;
hjk's avatar
hjk committed
334

hjk's avatar
hjk committed
335
    m_mode = CommandMode;
hjk's avatar
hjk committed
336
337
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
338
    m_fakeEnd = false;
339
    m_lastSearchForward = true;
hjk's avatar
hjk committed
340
    m_register = '"';
hjk's avatar
hjk committed
341
    m_gflag = false;
342
343
    m_textedit = 0;
    m_plaintextedit = 0;
344
    m_visualMode = NoVisualMode;
345
    m_desiredColumn = 0;
hjk's avatar
hjk committed
346
347

    m_config[ConfigStartOfLine] = ConfigOn;
348
    m_config[ConfigTabStop]     = "8";
349
    m_config[ConfigSmartTab]    = ConfigOff;
350
    m_config[ConfigShiftWidth]  = "8";
351
    m_config[ConfigExpandTab]   = ConfigOff;
352
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
353
354
}

355
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
356
{
357
    int key = ev->key();
358
    const int um = key; // keep unmodified key around
359

360
    // FIXME
361
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
362
363
364
365
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
366
367
368
        return false;
    }

hjk's avatar
hjk committed
369
370
371
372
373
    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"
374
    m_tc = EDITOR(textCursor());
375
    m_tc.setVisualNavigation(true);
376

hjk's avatar
hjk committed
377
    if (m_fakeEnd)
hjk's avatar
hjk committed
378
        moveRight(MoveAnchor);
hjk's avatar
hjk committed
379

380
    if ((ev->modifiers() & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
381
        key += 256;
382
383
384
385
386
        key += 32; // make it lower case
    } else if (key >= Key_A && key <= Key_Z
        && (ev->modifiers() & Qt::ShiftModifier) == 0) {
        key += 32;
    }
387
    bool handled = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
388
389

    // We fake vi-style end-of-line behaviour
hjk's avatar
hjk committed
390
    m_fakeEnd = (atEol() && m_mode == CommandMode);
hjk's avatar
hjk committed
391

hjk's avatar
hjk committed
392
    if (m_fakeEnd)
hjk's avatar
hjk committed
393
        moveLeft(MoveAnchor);
hjk's avatar
hjk committed
394

395
396
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
397
    return handled;
hjk's avatar
hjk committed
398
399
}

400
bool FakeVimHandler::Private::handleKey(int key, int unmodified, const QString &text)
hjk's avatar
hjk committed
401
{
402
403
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
404
    m_savedPosition = m_tc.position();
hjk's avatar
hjk committed
405
    if (m_mode == InsertMode)
406
        return handleInsertMode(key, unmodified, text);
407
    if (m_mode == CommandMode)
408
        return handleCommandMode(key, unmodified, text);
409
    if (m_mode == ExMode || m_mode == SearchForwardMode
410
            || m_mode == SearchBackwardMode)
411
        return handleMiniBufferModes(key, unmodified, text);
412
    return false;
hjk's avatar
hjk committed
413
414
}

hjk's avatar
hjk committed
415
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
416
{
hjk's avatar
hjk committed
417
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
418
419
420
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
        m_tc.setPosition(qMin(anchor(), position()));
hjk's avatar
hjk committed
421
422
423
424
425
426
427
428
        m_mode = ExMode;
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

429
430
431
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
432
    if (m_submode == ChangeSubMode) {
hjk's avatar
hjk committed
433
434
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
435
        QString text = recordRemoveSelectedText();
hjk's avatar
hjk committed
436
        qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
437
        m_registers[m_register] = text;
hjk's avatar
hjk committed
438
439
440
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
hjk's avatar
hjk committed
441
442
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
443
444
        m_registers[m_register] = recordRemoveSelectedText();
        recordEndGroup();
hjk's avatar
hjk committed
445
446
        m_submode = NoSubMode;
        if (atEol())
hjk's avatar
hjk committed
447
            moveLeft(MoveAnchor);
448
449
450
451
    } else if (m_submode == YankSubMode) {
        m_registers[m_register] = m_tc.selectedText();
        m_tc.setPosition(m_savedPosition);
        m_submode = NoSubMode;
452
453
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
454
455
456
457
458
    } 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
459
            qSwap(start, end);
460
461
462
463
464
        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
465
    }
hjk's avatar
hjk committed
466
467
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
468
    m_gflag = false;
hjk's avatar
hjk committed
469
470
    m_register = '"';
    m_tc.clearSelection();
471
472

    updateSelection();
hjk's avatar
hjk committed
473
    updateMiniBuffer();
474
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
475
476
}

477
478
479
480
481
482
483
void FakeVimHandler::Private::updateSelection()
{
    QList<QTextEdit::ExtraSelection> selections;
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
hjk's avatar
hjk committed
484
485
486
487
        //sel.format.setFontWeight(QFont::Bold);
        //sel.format.setFontUnderline(true);
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
488
489
490
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
491
        if (m_visualMode == VisualCharMode) {
492
            sel.cursor.setPosition(anchorPos, KeepAnchor);
493
494
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
495
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
496
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
497
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
498
499
500
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
            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);
            }
522
523
        }
    }
524
    emit q->selectionChanged(editor(), selections);
525
526
}

hjk's avatar
hjk committed
527
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
528
{
hjk's avatar
hjk committed
529
    QString msg;
530
531
532
    if (m_mode == PassingMode) {
        msg = "-- PASSING --";
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
533
534
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
535
536
537
538
539
540
541
542
    } 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 --";
        }
543
544
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
545
    } else {
546
        if (m_mode == SearchForwardMode)
547
            msg += '/';
548
        else if (m_mode == SearchBackwardMode)
549
            msg += '?';
550
        else if (m_mode == ExMode)
551
            msg += ':';
hjk's avatar
hjk committed
552
        foreach (QChar c, m_commandBuffer) {
553
554
555
556
557
558
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
559
        }
hjk's avatar
hjk committed
560
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
561
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
562
    }
hjk's avatar
hjk committed
563
564
565
566
567
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
568
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
569
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
570
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
571
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
572
573
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
574
    } else {
hjk's avatar
hjk committed
575
        status += "All";
hjk's avatar
hjk committed
576
    }
hjk's avatar
hjk committed
577
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
578
579
}

hjk's avatar
hjk committed
580
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
581
{
582
583
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
584
    updateMiniBuffer();
hjk's avatar
hjk committed
585
586
}

hjk's avatar
hjk committed
587
588
589
590
591
592
593
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

594
595
596
597
598
599
void FakeVimHandler::Private::notImplementedYet()
{
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

600
601
bool FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
602
{
603
    bool handled = true;
604

hjk's avatar
hjk committed
605
606
607
608
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
hjk's avatar
hjk committed
609
610
611
612
613
614
615
616
        moveToStartOfLine();
        setAnchor();
        moveDown(count());
        moveLeft();
        QString text = recordRemoveSelectedText();
        m_registers[m_register] = text;
        m_submode = NoSubMode;
        m_mode = InsertMode;
hjk's avatar
hjk committed
617
        finishMovement("c");
hjk's avatar
hjk committed
618
    } else if (m_submode == DeleteSubMode && key == 'd') {
hjk's avatar
hjk committed
619
620
621
        moveToStartOfLine();
        moveDown(count());
        m_registers[m_register] = recordRemoveSelectedText();
hjk's avatar
hjk committed
622
        finishMovement("d");
623
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
624
625
626
        moveToStartOfLine();
        moveDown(count());
        m_registers[m_register] = selectedText();
627
        finishMovement();
628
629
    } else if (m_submode == ReplaceSubMode) {
        if (atEol())
hjk's avatar
hjk committed
630
            moveLeft(KeepAnchor);
631
632
        else
            m_tc.deleteChar();
hjk's avatar
hjk committed
633
        recordInsertText(text);
634
635
    } else if (m_submode == IndentSubMode && key == '=') {
        indentRegion(m_tc.block(), m_tc.block().next());
636
        finishMovement();
hjk's avatar
hjk committed
637
638
    } else if (m_submode == ZSubMode) {
        if (key == Key_Return) {
hjk's avatar
hjk committed
639
            // cursor line to top of window, cursor on first non-blank
hjk's avatar
hjk committed
640
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
641
642
            moveToFirstNonBlankOnLine();
            finishMovement();
hjk's avatar
hjk committed
643
        } else {
hjk's avatar
hjk committed
644
            qDebug() << "IGNORED Z_MODE " << key << text;
hjk's avatar
hjk committed
645
646
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
647
648
649
    } else if (m_subsubmode == FtSubSubMode) {
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
650
        finishMovement(QString(QChar(m_subsubdata)) + QChar(key));
651
652
653
654
655
656
    } 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
657
            m_tc.setPosition(m_marks[key], MoveAnchor);
658
659
660
661
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
662
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
663
664
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
665
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
666
        if (key == '0' && m_mvcount.isEmpty()) {
hjk's avatar
hjk committed
667
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
668
669
            finishMovement();
        } else {
hjk's avatar
hjk committed
670
            m_mvcount.append(QChar(key));
hjk's avatar
hjk committed
671
        }
672
    } else if (key == ':') {
hjk's avatar
hjk committed
673
        m_mode = ExMode;
hjk's avatar
hjk committed
674
        m_commandBuffer.clear();
675
        if (m_visualMode != NoVisualMode)
676
677
678
679
680
681
682
683
684
            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
685
        updateMiniBuffer();
686
687
    } else if (key == '`') {
        m_subsubmode = BackTickSubSubMode;
hjk's avatar
hjk committed
688
689
690
691
692
693
694
695
    } 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);
696
697
    } else if (key == '\'') {
        m_subsubmode = TickSubSubMode;
hjk's avatar
hjk committed
698
    } else if (key == '|') {
hjk's avatar
hjk committed
699
700
701
        setAnchor();
        moveToStartOfLine();
        moveRight(qMin(count(), rightDist()) - 1);
hjk's avatar
hjk committed
702
        finishMovement();
hjk's avatar
hjk committed
703
704
705
706
707
708
709
710
    } else if (key == '!' && m_visualMode == NoVisualMode) {
        m_submode = FilterSubMode;
    } else if (key == '!' && m_visualMode == VisualLineMode) {
        m_mode = ExMode;
        m_commandBuffer = "'<,'>!";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
hjk's avatar
hjk committed
711
712
    } else if (key == '"') {
        m_submode = RegisterSubMode;
713
    } else if (unmodified == Key_Return) {
hjk's avatar
hjk committed
714
715
        moveToStartOfLine();
        moveDown();
716
        moveToFirstNonBlankOnLine();
717
        finishMovement();
hjk's avatar
hjk committed
718
    } else if (key == Key_Home) {
hjk's avatar
hjk committed
719
        moveToStartOfLine();
hjk's avatar
hjk committed
720
721
        finishMovement();
    } else if (key == '$' || key == Key_End) {
722
        int submode = m_submode;
hjk's avatar
hjk committed
723
        moveToEndOfLine();
hjk's avatar
hjk committed
724
        finishMovement();
725
726
        if (submode == NoSubMode)
            m_desiredColumn = -1;
727
728
729
730
    } else if (key == ',') {
        // FIXME: use some other mechanism
        m_mode = PassingMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
731
732
733
734
    } else if (key == '.') {
        qDebug() << "REPEATING" << m_dotCommand;
        for (int i = count(); --i >= 0; )
            foreach (QChar c, m_dotCommand)
735
                handleKey(c.unicode(), c.unicode(), QString(c));
736
737
    } else if (key == '=') {
        m_submode = IndentSubMode;
738
    } else if (key == '%') {
739
        moveToMatchingParanthesis();
740
        finishMovement();
hjk's avatar
hjk committed
741
    } else if (key == 'a') {
hjk's avatar
hjk committed
742
        m_mode = InsertMode;
hjk's avatar
hjk committed
743
        recordBeginGroup();
hjk's avatar
hjk committed
744
        m_lastInsertion.clear();
hjk's avatar
hjk committed
745
        moveRight();
746
        updateMiniBuffer();
hjk's avatar
hjk committed
747
    } else if (key == 'A') {
hjk's avatar
hjk committed
748
        m_mode = InsertMode;
hjk's avatar
hjk committed
749
750
        moveToEndOfLine();
        recordBeginGroup();
hjk's avatar
hjk committed
751
        m_lastInsertion.clear();
hjk's avatar
hjk committed
752
    } else if (key == 'b') {
hjk's avatar
hjk committed
753
        moveToWordBoundary(false, false);
hjk's avatar
hjk committed
754
755
        finishMovement();
    } else if (key == 'B') {
hjk's avatar
hjk committed
756
        moveToWordBoundary(true, false);
hjk's avatar
hjk committed
757
        finishMovement();
hjk's avatar
hjk committed
758
    } else if (key == 'c') {
hjk's avatar
hjk committed
759
760
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
761
762
        m_submode = ChangeSubMode;
    } else if (key == 'C') {
hjk's avatar
hjk committed
763
764
765
766
767
        setAnchor();
        recordBeginGroup();
        moveToEndOfLine();
        m_registers[m_register] = recordRemoveSelectedText();
        m_mode = InsertMode;
hjk's avatar
hjk committed
768
        finishMovement();
769
    } else if (key == 'd' && m_visualMode == NoVisualMode) {
hjk's avatar
hjk committed
770
        if (atEol())
hjk's avatar
hjk committed
771
772
773
            moveLeft();
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
774
775
776
        m_opcount = m_mvcount;
        m_mvcount.clear();
        m_submode = DeleteSubMode;
777
    } else if (key == 'd') {
hjk's avatar
hjk committed
778
        setAnchor();
779
780
781
        leaveVisualMode();
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
hjk's avatar
hjk committed
782
        selectRange(beginLine, endLine);
hjk's avatar
hjk committed
783
        recordRemoveSelectedText();
hjk's avatar
hjk committed
784
    } else if (key == 'D') {
hjk's avatar
hjk committed
785
786
        setAnchor();
        recordBeginGroup();
hjk's avatar
hjk committed
787
        m_submode = DeleteSubMode;
hjk's avatar
hjk committed
788
789
        moveDown(qMax(count() - 1, 0));
        moveRight(rightDist());
hjk's avatar
hjk committed
790
        finishMovement();
hjk's avatar
hjk committed
791
    } else if (key == 'e') {
hjk's avatar
hjk committed
792
        moveToWordBoundary(false, true);
hjk's avatar
hjk committed
793
794
        finishMovement();
    } else if (key == 'E') {
hjk's avatar
hjk committed
795
        moveToWordBoundary(true, true);
hjk's avatar
hjk committed
796
        finishMovement();
hjk's avatar
hjk committed
797
798
799
    } else if (key == 'f' || key == 'F') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
800
801
    } else if (key == 'g') {
        m_gflag = true;
hjk's avatar
hjk committed
802
803
    } else if (key == 'G') {
        int n = m_mvcount.isEmpty() ? linesInDocument() : count();
Martin Aumueller's avatar
Martin Aumueller committed
804
        m_tc.setPosition(positionForLine(n), KeepAnchor);
hjk's avatar
hjk committed
805
        if (m_config[ConfigStartOfLine] == ConfigOn)
hjk's avatar
hjk committed
806
807
            moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
808
809
    } else if (key == 'h' || key == Key_Left
            || key == Key_Backspace || key == control('h')) {
hjk's avatar
hjk committed
810
811
812
        int n = qMin(count(), leftDist());
        if (m_fakeEnd && m_tc.block().length() > 1)
            ++n;
hjk's avatar
hjk committed
813
        moveLeft(n);
hjk's avatar
hjk committed
814
        finishMovement();
hjk's avatar
hjk committed
815
    } else if (key == 'H') {
816
        m_tc = EDITOR(cursorForPosition(QPoint(0, 0)));
hjk's avatar
hjk committed
817
        moveDown(qMax(count() - 1, 0));
hjk's avatar
hjk committed
818
819
        moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
820
    } else if (key == 'i') {
821
        enterInsertMode();
822
        updateMiniBuffer();
823
        if (atEol())
hjk's avatar
hjk committed
824
            moveLeft(MoveAnchor);
hjk's avatar
hjk committed
825
    } else if (key == 'I') {
hjk's avatar
hjk committed
826
        setAnchor();
827
        enterInsertMode();
hjk's avatar
hjk committed
828
        if (m_gflag)
hjk's avatar
hjk committed
829
            moveToStartOfLine();
hjk's avatar
hjk committed
830
831
        else
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
832
    } else if (key == 'j' || key == Key_Down) {
833
        int savedColumn = m_desiredColumn;
hjk's avatar
hjk committed
834
835
        if (m_submode == NoSubMode || m_submode == ZSubMode
                || m_submode == RegisterSubMode) {
hjk's avatar
hjk committed
836
            moveDown(count());
837
            moveToDesiredColumn();
838
        } else {
hjk's avatar
hjk committed
839
840
            moveToStartOfLine();
            moveDown(count() + 1);
841
        }
hjk's avatar
hjk committed
842
        finishMovement();
843
        m_desiredColumn = savedColumn;
hjk's avatar
hjk committed
844
    } else if (key == 'J') {
hjk's avatar
hjk committed
845
        recordBeginGroup();
hjk's avatar
hjk committed
846
847
        if (m_submode == NoSubMode) {
            for (int i = qMax(count(), 2) - 1; --i >= 0; ) {
hjk's avatar
hjk committed
848
                moveToEndOfLine();
hjk's avatar
hjk committed
849
                recordRemoveNextChar();
hjk's avatar
hjk committed
850
                if (!m_gflag)
hjk's avatar
hjk committed
851
                    recordInsertText(" ");
hjk's avatar
hjk committed
852
            }
hjk's avatar
hjk committed
853
            if (!m_gflag)
hjk's avatar
hjk committed
854
                moveLeft();
hjk's avatar
hjk committed
855
        }
hjk's avatar
hjk committed
856
        recordEndGroup();
hjk's avatar
hjk committed
857
    } else if (key == 'k' || key == Key_Up) {
858
        int savedColumn = m_desiredColumn;
hjk's avatar
hjk committed
859
860
861
        if (m_submode == NoSubMode || m_submode == ZSubMode
                || m_submode == RegisterSubMode) {
            moveUp(count());
862
            moveToDesiredColumn();
863
        } else {
hjk's avatar
hjk committed
864
865
866
            moveToStartOfLine();
            moveDown();
            moveUp(count() + 1);
867
        }
hjk's avatar
hjk committed
868
        finishMovement();
869
        m_desiredColumn = savedColumn;
hjk's avatar
hjk committed
870
    } else if (key == 'l' || key == Key_Right) {
hjk's avatar
hjk committed
871
        moveRight(qMin(count(), rightDist()));
hjk's avatar
hjk committed
872
        finishMovement();
hjk's avatar
hjk committed
873