fakevimhandler.cpp 62.8 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,
};

hjk's avatar
hjk committed
131
132
133
134
135
136
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
};

137
138
struct EditOperation
{
hjk's avatar
hjk committed
139
    EditOperation() : m_position(-1), m_itemCount(0) {}
140
    int m_position;
hjk's avatar
hjk committed
141
142
143
    int m_itemCount; // used to combine several operations
    QString m_from;
    QString m_to;
144
145
};

hjk's avatar
hjk committed
146
static QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
147
148
{
    if (op.m_itemCount > 0) {
hjk's avatar
hjk committed
149
        ts << "\n  EDIT BLOCK WITH " << op.m_itemCount << " ITEMS";
hjk's avatar
hjk committed
150
    } else {
hjk's avatar
hjk committed
151
152
        ts << "\n  EDIT AT " << op.m_position
           << "\n      FROM " << op.m_from << "\n      TO " << op.m_to;
hjk's avatar
hjk committed
153
154
155
156
    }
    return ts;
}

hjk's avatar
hjk committed
157
158
159
160
161
162
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

hjk's avatar
hjk committed
163
164
165
166
167
class FakeVimHandler::Private
{
public:
    Private(FakeVimHandler *parent);

168
    bool handleEvent(QKeyEvent *ev);
169
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
170

171
private:
172
    friend class FakeVimHandler;
hjk's avatar
hjk committed
173
174
175
176
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
177
178
179
180
181
    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
182
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
183
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
184

hjk's avatar
hjk committed
185
186
187
    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
188
189
190
    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
191

hjk's avatar
hjk committed
192
    int lastPositionInDocument() const;
hjk's avatar
hjk committed
193
194
    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
195

hjk's avatar
hjk committed
196
197
198
199
200
201
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
202
    int linesInDocument() const;
hjk's avatar
hjk committed
203
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
204

205
    // helper functions for indenting
hjk's avatar
hjk committed
206
207
    bool isElectricCharacter(QChar c) const
        { return (c == '{' || c == '}' || c == '#'); }
208
209
210
211
    int indentDist() const;
    void indentRegion(QTextBlock first, QTextBlock last, QChar typedChar=0);
    void indentCurrentLine(QChar typedChar);

hjk's avatar
hjk committed
212
    void moveToFirstNonBlankOnLine();
213
    void moveToDesiredColumn();
hjk's avatar
hjk committed
214
    void moveToNextWord(bool simple);
215
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
216
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
217
218
219
220

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    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
238

hjk's avatar
hjk committed
239
    void handleFfTt(int key);
hjk's avatar
hjk committed
240

hjk's avatar
hjk committed
241
242
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
243
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
244

245
    void setWidget(QWidget *ob);
246
    void enterInsertMode();
247
    void enterCommandMode();
hjk's avatar
hjk committed
248
249
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
250
    void notImplementedYet();
251
252
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
253
    void quit();
254
    QWidget *editor() const;
255

256
257
258
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
259
    bool m_wasReadOnly; // saves read-only state of document
260

hjk's avatar
hjk committed
261
262
263
    FakeVimHandler *q;
    Mode m_mode;
    SubMode m_submode;
hjk's avatar
hjk committed
264
265
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
266
267
    QString m_input;
    QTextCursor m_tc;
hjk's avatar
hjk committed
268
    int m_anchor; 
hjk's avatar
hjk committed
269
270
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
271
272
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
273
    MoveType m_moveType;
hjk's avatar
hjk committed
274
275
276

    bool m_fakeEnd;

277
278
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
279
    int m_gflag;  // whether current command started with 'g'
280

hjk's avatar
hjk committed
281
    QString m_commandBuffer;
282
283
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
284

285
    bool m_lastSearchForward;
hjk's avatar
hjk committed
286
    QString m_lastInsertion;
hjk's avatar
hjk committed
287

288
    // undo handling
hjk's avatar
hjk committed
289
    void recordOperation(const EditOperation &op);
290
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
291
    void recordRemove(int position, const QString &data);
292
    void recordRemove(int position, int length);
293
    void recordMove(int position, int nestedCount);
hjk's avatar
hjk committed
294
295
296

    void recordRemoveNextChar();
    void recordInsertText(const QString &data);
hjk's avatar
hjk committed
297
    QString recordRemoveSelectedText();
hjk's avatar
hjk committed
298
299
    void recordBeginGroup();
    void recordEndGroup();
hjk's avatar
hjk committed
300
301
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
hjk's avatar
hjk committed
302

303
304
305
306
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;
hjk's avatar
hjk committed
307
    QStack<int> m_undoGroupStack;
308

hjk's avatar
hjk committed
309
310
311
312
    // extra data for '.'
    QString m_dotCount;
    QString m_dotCommand;

hjk's avatar
hjk committed
313
    // history for '/'
hjk's avatar
hjk committed
314
315
316
317
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
318
    // history for ':'
hjk's avatar
hjk committed
319
320
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
321

hjk's avatar
hjk committed
322
    // visual line mode
323
324
325
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
326

327
328
329
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
330
331
    // vi style configuration
    QHash<QString, QString> m_config;
332
333
334

    // for restoring cursor position
    int m_savedPosition;
335
    int m_desiredColumn;
hjk's avatar
hjk committed
336
337
338
339
340
};

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

hjk's avatar
hjk committed
342
    m_mode = CommandMode;
hjk's avatar
hjk committed
343
344
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
345
    m_fakeEnd = false;
346
    m_lastSearchForward = true;
hjk's avatar
hjk committed
347
    m_register = '"';
hjk's avatar
hjk committed
348
    m_gflag = false;
349
350
    m_textedit = 0;
    m_plaintextedit = 0;
351
    m_visualMode = NoVisualMode;
352
    m_desiredColumn = 0;
hjk's avatar
hjk committed
353
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
354
355

    m_config[ConfigStartOfLine] = ConfigOn;
356
    m_config[ConfigTabStop]     = "8";
357
    m_config[ConfigSmartTab]    = ConfigOff;
358
    m_config[ConfigShiftWidth]  = "8";
359
    m_config[ConfigExpandTab]   = ConfigOff;
360
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
361
362
}

363
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
364
{
365
    int key = ev->key();
366
    const int um = key; // keep unmodified key around
367

368
    // FIXME
369
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
370
371
372
373
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
374
375
376
        return false;
    }

hjk's avatar
hjk committed
377
378
379
380
381
    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"
382
    m_tc = EDITOR(textCursor());
383
    m_tc.setVisualNavigation(true);
384

hjk's avatar
hjk committed
385
    if (m_fakeEnd)
hjk's avatar
hjk committed
386
        moveRight(MoveAnchor);
hjk's avatar
hjk committed
387

388
    if ((ev->modifiers() & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
389
        key += 256;
390
391
392
393
394
        key += 32; // make it lower case
    } else if (key >= Key_A && key <= Key_Z
        && (ev->modifiers() & Qt::ShiftModifier) == 0) {
        key += 32;
    }
395
    bool handled = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
396
397

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

hjk's avatar
hjk committed
400
    if (m_fakeEnd)
hjk's avatar
hjk committed
401
        moveLeft(MoveAnchor);
hjk's avatar
hjk committed
402

403
404
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
405
    return handled;
hjk's avatar
hjk committed
406
407
}

408
bool FakeVimHandler::Private::handleKey(int key, int unmodified, const QString &text)
hjk's avatar
hjk committed
409
{
410
411
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
412
    m_savedPosition = m_tc.position();
hjk's avatar
hjk committed
413
    if (m_mode == InsertMode)
414
        return handleInsertMode(key, unmodified, text);
415
    if (m_mode == CommandMode)
416
        return handleCommandMode(key, unmodified, text);
417
    if (m_mode == ExMode || m_mode == SearchForwardMode
418
            || m_mode == SearchBackwardMode)
419
        return handleMiniBufferModes(key, unmodified, text);
420
    return false;
hjk's avatar
hjk committed
421
422
}

hjk's avatar
hjk committed
423
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
424
{
hjk's avatar
hjk committed
425
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
426
427
428
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
        m_tc.setPosition(qMin(anchor(), position()));
hjk's avatar
hjk committed
429
430
431
432
433
434
435
436
        m_mode = ExMode;
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

437
438
439
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

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

    updateSelection();
hjk's avatar
hjk committed
483
    updateMiniBuffer();
484
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
485
486
}

487
488
489
490
491
492
493
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
494
495
496
497
        //sel.format.setFontWeight(QFont::Bold);
        //sel.format.setFontUnderline(true);
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
498
499
500
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
501
        if (m_visualMode == VisualCharMode) {
502
            sel.cursor.setPosition(anchorPos, KeepAnchor);
503
504
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
505
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
506
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
507
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
508
509
510
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
            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);
            }
532
533
        }
    }
534
    emit q->selectionChanged(editor(), selections);
535
536
}

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

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
578
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
579
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
580
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
581
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
582
583
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
584
    } else {
hjk's avatar
hjk committed
585
        status += "All";
hjk's avatar
hjk committed
586
    }
hjk's avatar
hjk committed
587
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
588
589
}

hjk's avatar
hjk committed
590
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
591
{
592
593
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
594
    updateMiniBuffer();
hjk's avatar
hjk committed
595
596
}

hjk's avatar
hjk committed
597
598
599
600
601
602
603
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

604
605
606
607
608
609
void FakeVimHandler::Private::notImplementedYet()
{
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

610
611
bool FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
612
{
613
    bool handled = true;
614

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