fakevimhandler.cpp 50.6 KB
Newer Older
hjk's avatar
hjk committed
1
2
3
4
5
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
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** 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
#include <coreplugin/filemanager.h>
#include <coreplugin/icore.h>
40
41
#include <texteditor/basetexteditor.h>

hjk's avatar
hjk committed
42
#include <QtCore/QDebug>
43
#include <QtCore/QFile>
hjk's avatar
hjk committed
44
#include <QtCore/QObject>
hjk's avatar
hjk committed
45
#include <QtCore/QProcess>
hjk's avatar
hjk committed
46
#include <QtCore/QRegExp>
47
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
48
49
#include <QtCore/QStack>

hjk's avatar
hjk committed
50
#include <QtGui/QApplication>
hjk's avatar
hjk committed
51
52
53
54
55
56
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
57
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
58
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
59
60
61


using namespace FakeVim::Internal;
62
using namespace FakeVim::Constants;
hjk's avatar
hjk committed
63

64
65
66
67
68
69
70
71
72
#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
73
74
75
76
77
78
79


///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
80

81
82
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
83
84
85
86
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

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

hjk's avatar
hjk committed
97
98
99
100
101
102
enum SubMode
{
    NoSubMode,
    RegisterSubMode,
    ChangeSubMode,
    DeleteSubMode,
hjk's avatar
hjk committed
103
    FilterSubMode,
104
    ZSubMode,
hjk's avatar
hjk committed
105
};
hjk's avatar
hjk committed
106

hjk's avatar
hjk committed
107
108
109
enum SubSubMode
{
    NoSubSubMode,
110
111
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
112
    BackTickSubSubMode, // used for `
113
    TickSubSubMode      // used for '
hjk's avatar
hjk committed
114
115
};

116
117
118
119
120
121
122
123
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

124
125
struct EditOperation
{
hjk's avatar
hjk committed
126
    EditOperation() : m_position(-1), m_itemCount(0) {}
127
    int m_position;
hjk's avatar
hjk committed
128
129
130
    int m_itemCount; // used to combine several operations
    QString m_from;
    QString m_to;
131
132
};

hjk's avatar
hjk committed
133
134
135
136
137
138
139
140
141
142
143
QDebug &operator<<(QDebug &ts, const EditOperation &op)
{
    if (op.m_itemCount > 0) {
        ts << "EDIT BLOCK WITH" << op.m_itemCount << "ITEMS";
    } else {
        ts << "EDIT AT " << op.m_position
           << " FROM " << op.m_from << " TO " << op.m_to;
    }
    return ts;
}

hjk's avatar
hjk committed
144
145
146
147
148
class FakeVimHandler::Private
{
public:
    Private(FakeVimHandler *parent);

149
    bool handleEvent(QKeyEvent *ev);
150
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
151

152
private:
153
    friend class FakeVimHandler;
hjk's avatar
hjk committed
154
155
156
157
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
158
159
160
161
162
    bool handleKey(int key, const QString &text);
    bool handleInsertMode(int key, const QString &text);
    bool handleCommandMode(int key, const QString &text);
    bool handleRegisterMode(int key, const QString &text);
    bool handleMiniBufferModes(int key, const QString &text);
hjk's avatar
hjk committed
163
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
164
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
165

hjk's avatar
hjk committed
166
167
168
    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
169
170
171
    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
172

hjk's avatar
hjk committed
173
    int lastPositionInDocument() const;
hjk's avatar
hjk committed
174
175
    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
176

hjk's avatar
hjk committed
177
178
179
180
181
182
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
183
    int linesInDocument() const;
hjk's avatar
hjk committed
184
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
185

hjk's avatar
hjk committed
186
    void moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
187
188
189
    void moveToNextWord(bool simple);
    void moveToWordBoundary(bool simple, bool forward);
    void handleFfTt(int key);
hjk's avatar
hjk committed
190

hjk's avatar
hjk committed
191
192
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
193
    QTextCursor selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
194

195
    void setWidget(QWidget *ob);
196
    void enterInsertMode();
197
    void enterCommandMode();
hjk's avatar
hjk committed
198
199
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
200
201
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
202
    void quit();
203
    QWidget *editor() const;
204

205
206
207
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
208
    bool m_wasReadOnly; // saves read-only state of document
209

hjk's avatar
hjk committed
210
    FakeVimHandler *q;
211
    Core::ICore *m_core;
hjk's avatar
hjk committed
212
213
    Mode m_mode;
    SubMode m_submode;
hjk's avatar
hjk committed
214
215
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
216
217
218
219
    QString m_input;
    QTextCursor m_tc;
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
220
221
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
222
223
224

    bool m_fakeEnd;

225
226
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
227
    int m_gflag;  // whether current command started with 'g'
228

hjk's avatar
hjk committed
229
    QString m_commandBuffer;
230
    QString m_currentFileName;
231
    Core::IFile* m_currentFile;
232
    QString m_currentMessage;
hjk's avatar
hjk committed
233

234
    bool m_lastSearchForward;
hjk's avatar
hjk committed
235
    QString m_lastInsertion;
hjk's avatar
hjk committed
236

237
    // undo handling
hjk's avatar
hjk committed
238
    void recordOperation(const EditOperation &op);
239
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
240
    void recordRemove(int position, const QString &data);
241
    void recordRemove(int position, int length);
242
    void recordMove(int position, int nestedCount);
243
    void removeSelectedText(QTextCursor &tc);
244
245
246
247
248
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;

hjk's avatar
hjk committed
249
250
251
252
    // extra data for '.'
    QString m_dotCount;
    QString m_dotCommand;

hjk's avatar
hjk committed
253
    // history for '/'
hjk's avatar
hjk committed
254
255
256
257
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
258
    // history for ':'
hjk's avatar
hjk committed
259
260
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
261

hjk's avatar
hjk committed
262
    // visual line mode
263
264
265
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
266

267
268
269
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
270
271
    // vi style configuration
    QHash<QString, QString> m_config;
hjk's avatar
hjk committed
272
273
274
275
276
};

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

hjk's avatar
hjk committed
278
    m_mode = CommandMode;
hjk's avatar
hjk committed
279
280
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
281
    m_fakeEnd = false;
282
    m_lastSearchForward = true;
hjk's avatar
hjk committed
283
    m_register = '"';
hjk's avatar
hjk committed
284
    m_gflag = false;
285
286
    m_textedit = 0;
    m_plaintextedit = 0;
287
    m_visualMode = NoVisualMode;
hjk's avatar
hjk committed
288

289
290
    m_core = ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>();

hjk's avatar
hjk committed
291
    m_config[ConfigStartOfLine] = ConfigOn;
292
    m_config[ConfigTabStop]     = "8";
293
    m_config[ConfigSmartTab]    = ConfigOff;
294
    m_config[ConfigShiftWidth]  = "8";
295
    m_config[ConfigExpandTab]   = ConfigOff;
hjk's avatar
hjk committed
296
297
}

298
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
299
{
300
301
    int key = ev->key();

302
    // FIXME
303
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
304
305
306
307
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
308
309
310
        return false;
    }

hjk's avatar
hjk committed
311
312
313
314
315
    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"
316
317
    m_tc = EDITOR(textCursor());

hjk's avatar
hjk committed
318
    if (m_fakeEnd)
hjk's avatar
hjk committed
319
320
321
        m_tc.movePosition(Right, MoveAnchor, 1);

    if (key >= Key_A && key <= Key_Z
322
        && (ev->modifiers() & Qt::ShiftModifier) == 0)
hjk's avatar
hjk committed
323
        key += 32;
324
    if ((ev->modifiers() & Qt::ControlModifier) != 0)
hjk's avatar
hjk committed
325
        key += 256;
326
    bool handled = handleKey(key, ev->text());
hjk's avatar
hjk committed
327
328

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

hjk's avatar
hjk committed
331
    if (m_fakeEnd)
hjk's avatar
hjk committed
332
333
        m_tc.movePosition(Left, MoveAnchor, 1);

334
335
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
336
    return handled;
hjk's avatar
hjk committed
337
338
}

339
bool FakeVimHandler::Private::handleKey(int key, const QString &text)
hjk's avatar
hjk committed
340
{
341
342
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
hjk's avatar
hjk committed
343
    if (m_mode == InsertMode)
344
345
346
347
        return handleInsertMode(key, text);
    if (m_mode == CommandMode)
        return handleCommandMode(key, text);
    if (m_mode == ExMode || m_mode == SearchForwardMode
348
            || m_mode == SearchBackwardMode)
349
350
        return handleMiniBufferModes(key, text);
    return false;
hjk's avatar
hjk committed
351
352
}

hjk's avatar
hjk committed
353
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
354
{
hjk's avatar
hjk committed
355
356
357
358
359
360
361
362
363
364
365
366
    if (m_submode == FilterSubMode) {
        int beginLine = lineForPosition(m_tc.anchor());
        int endLine = lineForPosition(m_tc.position());
        m_tc.setPosition(qMin(m_tc.anchor(), m_tc.position()), MoveAnchor);
        m_mode = ExMode;
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

hjk's avatar
hjk committed
367
    if (m_submode == ChangeSubMode) {
hjk's avatar
hjk committed
368
369
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
370
        m_registers[m_register] = m_tc.selectedText();
371
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
372
373
374
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
hjk's avatar
hjk committed
375
376
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
377
        recordRemove(qMin(m_tc.position(), m_tc.anchor()), m_tc.selectedText());
hjk's avatar
hjk committed
378
        m_registers[m_register] = m_tc.selectedText();
379
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
380
381
382
383
        m_submode = NoSubMode;
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
    }
hjk's avatar
hjk committed
384
385
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
386
    m_gflag = false;
hjk's avatar
hjk committed
387
388
    m_register = '"';
    m_tc.clearSelection();
389
390

    updateSelection();
hjk's avatar
hjk committed
391
    updateMiniBuffer();
hjk's avatar
hjk committed
392
393
}

394
395
396
397
398
399
400
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
401
402
403
404
        //sel.format.setFontWeight(QFont::Bold);
        //sel.format.setFontUnderline(true);
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
405
406
407
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
408
        if (m_visualMode == VisualCharMode) {
409
            sel.cursor.setPosition(anchorPos, KeepAnchor);
410
411
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
412
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
413
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
414
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
415
416
417
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
            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);
            }
439
440
441
442
443
        }
    }
    EDITOR(setExtraSelections(selections));
}

hjk's avatar
hjk committed
444
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
445
{
hjk's avatar
hjk committed
446
    QString msg;
447
448
449
    if (m_mode == PassingMode) {
        msg = "-- PASSING --";
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
450
451
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
452
453
454
455
456
457
458
459
    } 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 --";
        }
460
461
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
462
    } else {
463
        if (m_mode == SearchForwardMode)
464
            msg += '/';
465
        else if (m_mode == SearchBackwardMode)
466
            msg += '?';
467
        else if (m_mode == ExMode)
468
            msg += ':';
hjk's avatar
hjk committed
469
        foreach (QChar c, m_commandBuffer) {
470
471
472
473
474
475
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
476
        }
hjk's avatar
hjk committed
477
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
478
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
479
    }
hjk's avatar
hjk committed
480
481
482
483
484
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
485
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
486
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
487
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
488
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
489
490
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
491
    } else {
hjk's avatar
hjk committed
492
        status += "All";
hjk's avatar
hjk committed
493
    }
hjk's avatar
hjk committed
494
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
495
496
}

hjk's avatar
hjk committed
497
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
498
{
499
500
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
501
    updateMiniBuffer();
hjk's avatar
hjk committed
502
503
}

hjk's avatar
hjk committed
504
505
506
507
508
509
510
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

511
bool FakeVimHandler::Private::handleCommandMode(int key, const QString &text)
hjk's avatar
hjk committed
512
{
513
514
    Q_UNUSED(text)

hjk's avatar
hjk committed
515
516
517
518
519
520
521
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
        m_tc.movePosition(StartOfLine, MoveAnchor);
        m_tc.movePosition(Down, KeepAnchor, count());
        m_registers[m_register] = m_tc.selectedText();
hjk's avatar
hjk committed
522
        finishMovement("c");
hjk's avatar
hjk committed
523
524
525
526
    } else if (m_submode == DeleteSubMode && key == 'd') {
        m_tc.movePosition(StartOfLine, MoveAnchor);
        m_tc.movePosition(Down, KeepAnchor, count());
        m_registers[m_register] = m_tc.selectedText();
hjk's avatar
hjk committed
527
        finishMovement("d");
hjk's avatar
hjk committed
528
529
    } else if (m_submode == ZSubMode) {
        if (key == Key_Return) {
hjk's avatar
hjk committed
530
            // cursor line to top of window, cursor on first non-blank
hjk's avatar
hjk committed
531
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
532
533
            moveToFirstNonBlankOnLine();
            finishMovement();
hjk's avatar
hjk committed
534
        } else {
hjk's avatar
hjk committed
535
536
537
            qDebug() << "Ignored z + " << key << text;
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
538
539
540
    } else if (m_subsubmode == FtSubSubMode) {
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
541
        finishMovement(QString(QChar(m_subsubdata)) + QChar(key));
542
543
544
545
546
547
    } 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
548
            m_tc.setPosition(m_marks[key], MoveAnchor);
549
550
551
552
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
553
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
554
555
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
556
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
557
        if (key == '0' && m_mvcount.isEmpty()) {
hjk's avatar
hjk committed
558
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
559
560
            finishMovement();
        } else {
hjk's avatar
hjk committed
561
            m_mvcount.append(QChar(key));
hjk's avatar
hjk committed
562
        }
563
    } else if (key == ':') {
hjk's avatar
hjk committed
564
        m_mode = ExMode;
hjk's avatar
hjk committed
565
        m_commandBuffer.clear();
566
567
568
        if (m_visualMode != NoVisualMode) {
            m_commandBuffer = "'<,'>";
            leaveVisualMode();
hjk's avatar
hjk committed
569
        }
570
571
572
573
574
575
576
577
        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
578
        updateMiniBuffer();
579
580
581
582
    } else if (key == '`') {
        m_subsubmode = BackTickSubSubMode;
    } else if (key == '\'') {
        m_subsubmode = TickSubSubMode;
hjk's avatar
hjk committed
583
584
585
586
    } else if (key == '|') {
        m_tc.movePosition(StartOfLine, KeepAnchor);
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()) - 1);
        finishMovement();
hjk's avatar
hjk committed
587
588
589
590
591
592
593
594
595
    } else if (key == '!' && m_visualMode == NoVisualMode) {
        m_submode = FilterSubMode;
    } else if (key == '!' && m_visualMode == VisualLineMode) {
        m_mode = ExMode;
        m_marks['>'] = m_tc.position();
        m_commandBuffer = "'<,'>!";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
hjk's avatar
hjk committed
596
597
598
599
600
601
602
603
604
605
606
    } else if (key == '"') {
        m_submode = RegisterSubMode;
    } else if (key == Key_Return) {
        m_tc.movePosition(StartOfLine);
        m_tc.movePosition(Down);
    } else if (key == Key_Home) {
        m_tc.movePosition(StartOfLine, KeepAnchor);
        finishMovement();
    } else if (key == '$' || key == Key_End) {
        m_tc.movePosition(EndOfLine, KeepAnchor);
        finishMovement();
607
608
609
610
    } else if (key == ',') {
        // FIXME: use some other mechanism
        m_mode = PassingMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
611
612
613
614
615
    } else if (key == '.') {
        qDebug() << "REPEATING" << m_dotCommand;
        for (int i = count(); --i >= 0; )
            foreach (QChar c, m_dotCommand)
                handleKey(c.unicode(), QString(c));
hjk's avatar
hjk committed
616
    } else if (key == 'a') {
hjk's avatar
hjk committed
617
        m_mode = InsertMode;
hjk's avatar
hjk committed
618
619
        m_lastInsertion.clear();
        m_tc.movePosition(Right, MoveAnchor, 1);
620
        updateMiniBuffer();
hjk's avatar
hjk committed
621
    } else if (key == 'A') {
hjk's avatar
hjk committed
622
        m_mode = InsertMode;
hjk's avatar
hjk committed
623
        m_tc.movePosition(EndOfLine, MoveAnchor);
hjk's avatar
hjk committed
624
        m_lastInsertion.clear();
hjk's avatar
hjk committed
625
    } else if (key == 'b') {
hjk's avatar
hjk committed
626
        moveToWordBoundary(false, false);
hjk's avatar
hjk committed
627
628
        finishMovement();
    } else if (key == 'B') {
hjk's avatar
hjk committed
629
        moveToWordBoundary(true, false);
hjk's avatar
hjk committed
630
        finishMovement();
hjk's avatar
hjk committed
631
632
633
634
635
636
    } else if (key == 'c') {
        m_submode = ChangeSubMode;
    } else if (key == 'C') {
        m_submode = ChangeSubMode;
        m_tc.movePosition(EndOfLine, KeepAnchor);
        finishMovement();
637
    } else if (key == 'd' && m_visualMode == NoVisualMode) {
hjk's avatar
hjk committed
638
639
640
641
642
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
        m_opcount = m_mvcount;
        m_mvcount.clear();
        m_submode = DeleteSubMode;
643
644
645
646
647
    } else if (key == 'd') {
        leaveVisualMode();
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
        m_tc = selectRange(beginLine, endLine);
648
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
649
650
    } else if (key == 'D') {
        m_submode = DeleteSubMode;
hjk's avatar
hjk committed
651
652
        m_tc.movePosition(Down, KeepAnchor, qMax(count() - 1, 0));
        m_tc.movePosition(Right, KeepAnchor, rightDist());
hjk's avatar
hjk committed
653
        finishMovement();
hjk's avatar
hjk committed
654
    } else if (key == 'e') {
hjk's avatar
hjk committed
655
        moveToWordBoundary(false, true);
hjk's avatar
hjk committed
656
657
        finishMovement();
    } else if (key == 'E') {
hjk's avatar
hjk committed
658
        moveToWordBoundary(true, true);
hjk's avatar
hjk committed
659
        finishMovement();
hjk's avatar
hjk committed
660
661
662
    } else if (key == 'f' || key == 'F') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
663
664
    } else if (key == 'g') {
        m_gflag = true;
hjk's avatar
hjk committed
665
666
    } else if (key == 'G') {
        int n = m_mvcount.isEmpty() ? linesInDocument() : count();
hjk's avatar
hjk committed
667
        m_tc.setPosition(positionForLine(n), MoveAnchor);
hjk's avatar
hjk committed
668
669
670
        if (m_config.contains(ConfigStartOfLine))
            moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
671
672
673
674
675
676
    } else if (key == 'h' || key == Key_Left) {
        int n = qMin(count(), leftDist());
        if (m_fakeEnd && m_tc.block().length() > 1)
            ++n;
        m_tc.movePosition(Left, KeepAnchor, n);
        finishMovement();
hjk's avatar
hjk committed
677
    } else if (key == 'H') {
678
        m_tc = EDITOR(cursorForPosition(QPoint(0, 0)));
hjk's avatar
hjk committed
679
680
681
        m_tc.movePosition(Down, KeepAnchor, qMax(count() - 1, 0));
        moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
682
    } else if (key == 'i') {
683
        enterInsertMode();
684
        updateMiniBuffer();
hjk's avatar
hjk committed
685
    } else if (key == 'I') {
686
        enterInsertMode();
hjk's avatar
hjk committed
687
688
689
690
        if (m_gflag)
            m_tc.movePosition(StartOfLine, KeepAnchor);
        else
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
691
692
693
    } else if (key == 'j' || key == Key_Down) {
        m_tc.movePosition(Down, KeepAnchor, count());
        finishMovement();
hjk's avatar
hjk committed
694
    } else if (key == 'J') {
hjk's avatar
hjk committed
695
        EditOperation op;
hjk's avatar
hjk committed
696
697
698
699
        if (m_submode == NoSubMode) {
            for (int i = qMax(count(), 2) - 1; --i >= 0; ) {
                m_tc.movePosition(EndOfLine);
                m_tc.deleteChar();
hjk's avatar
hjk committed
700
701
                if (!m_gflag)
                    m_tc.insertText(" ");
hjk's avatar
hjk committed
702
            }
hjk's avatar
hjk committed
703
704
            if (!m_gflag)
                m_tc.movePosition(Left, MoveAnchor, 1);
hjk's avatar
hjk committed
705
        }
hjk's avatar
hjk committed
706
707
708
709
710
711
    } else if (key == 'k' || key == Key_Up) {
        m_tc.movePosition(Up, KeepAnchor, count());
        finishMovement();
    } else if (key == 'l' || key == Key_Right) {
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
        finishMovement();
hjk's avatar
hjk committed
712
    } else if (key == 'L') {
hjk's avatar
hjk committed
713
        m_tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()))));
hjk's avatar
hjk committed
714
715
716
        m_tc.movePosition(Up, KeepAnchor, qMax(count(), 1));
        moveToFirstNonBlankOnLine();
        finishMovement();
717
718
    } else if (key == 'm') {
        m_subsubmode = MarkSubSubMode;
hjk's avatar
hjk committed
719
    } else if (key == 'M') {
hjk's avatar
hjk committed
720
        m_tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()) / 2)));
hjk's avatar
hjk committed
721
722
        moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
723
    } else if (key == 'n') {
hjk's avatar
hjk committed
724
        search(lastSearchString(), m_lastSearchForward);
hjk's avatar
hjk committed
725
    } else if (key == 'N') {
hjk's avatar
hjk committed
726
        search(lastSearchString(), !m_lastSearchForward);
hjk's avatar
hjk committed
727
    } else if (key == 'o') {
728
        enterInsertMode();
hjk's avatar
hjk committed
729
730
        m_tc.movePosition(EndOfLine, MoveAnchor);
        m_tc.insertText("\n");
hjk's avatar
hjk committed
731
    } else if (key == 'O') {
732
        enterInsertMode();
hjk's avatar
hjk committed
733
734
735
        m_tc.movePosition(StartOfLine, MoveAnchor);
        m_tc.movePosition(Left, MoveAnchor, 1);
        m_tc.insertText("\n");
hjk's avatar
hjk committed
736
    } else if (key == 'p' || key == 'P') {
hjk's avatar
hjk committed
737
738
739
740
        QString text = m_registers[m_register];
        int n = text.count(QChar(ParagraphSeparator));
        if (n > 0) {
            m_tc.movePosition(StartOfLine);
hjk's avatar
hjk committed
741
742
            if (key == 'p')
                m_tc.movePosition(Down);
hjk's avatar
hjk committed
743
744
745
            m_tc.insertText(text);
            m_tc.movePosition(Up, MoveAnchor, n);
        } else {
hjk's avatar
hjk committed
746
747
            if (key == 'p')
                m_tc.movePosition(Right);
hjk's avatar
hjk committed
748
749
750
            m_tc.insertText(text);
            m_tc.movePosition(Left);
        }
751
        m_dotCommand = "p";
hjk's avatar
hjk committed
752
    } else if (key == control('r')) {
753
        redo();
hjk's avatar
hjk committed
754
755
756
    } else if (key == 's') {
        m_submode = ChangeSubMode;
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
hjk's avatar
hjk committed
757
758
759
    } else if (key == 't' || key == 'T') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
760
    } else if (key == 'u') {
761
        undo();
762
763
764
765
    } else if (key == 'U') {
        // FIXME: this is non-vim, but as Ctrl-R is taken globally
        // we have a substitute here
        redo();
766
767
    } else if (key == 'v') {
        enterVisualMode(VisualCharMode);
hjk's avatar
hjk committed
768
    } else if (key == 'V') {
769
770
771
        enterVisualMode(VisualLineMode);
    } else if (key == control('v')) {
        enterVisualMode(VisualBlockMode);
hjk's avatar
hjk committed
772
    } else if (key == 'w') {
hjk's avatar
hjk committed
773
        moveToNextWord(false);
hjk's avatar
hjk committed
774
        finishMovement("w");
hjk's avatar
hjk committed
775
    } else if (key == 'W') {
hjk's avatar
hjk committed
776
        moveToNextWord(true);
hjk's avatar
hjk committed
777
        finishMovement("W");
hjk's avatar
hjk committed
778
779
780
781
782
    } else if (key == 'x') { // = "dl"
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
        m_submode = DeleteSubMode;
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
hjk's avatar
hjk committed
783
        finishMovement("l");
hjk's avatar
hjk committed
784
785
786
787
788
789
    } else if (key == 'X') {
        if (leftDist() > 0) {
            m_tc.movePosition(Left, KeepAnchor, qMin(count(), leftDist()));
            m_tc.deleteChar();
        }
        finishMovement();
hjk's avatar
hjk committed
790
791
    } else if (key == 'z') {
        m_submode = ZSubMode;
hjk's avatar
hjk committed
792
    } else if (key == '~' && !atEol()) {
hjk's avatar
hjk committed
793
794
795
796
797
798
799
800
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
        QString str = m_tc.selectedText();
        for (int i = str.size(); --i >= 0; ) {
            QChar c = str.at(i);
            str[i] = c.isUpper() ? c.toLower() : c.toUpper();
        }
        m_tc.deleteChar();
        m_tc.insertText(str);
hjk's avatar
hjk committed
801
802
803
804
805
806
    } else if (key == Key_PageDown || key == control('f')) {
        m_tc.movePosition(Down, KeepAnchor, count() * (linesOnScreen() - 2));
        finishMovement();
    } else if (key == Key_PageUp || key == control('b')) {
        m_tc.movePosition(Up, KeepAnchor, count() * (linesOnScreen() - 2));
        finishMovement();
hjk's avatar
hjk committed
807
    } else if (key == Key_Backspace || key == control('h')) {
hjk's avatar
hjk committed
808
        m_tc.deletePreviousChar();
809
810
    } else if (key == Key_Delete) {
        m_tc.deleteChar();
hjk's avatar
hjk committed
811
    } else if (key == Key_Escape) {
812
813
        if (m_visualMode != NoVisualMode)
            leaveVisualMode();
hjk's avatar
hjk committed
814
    } else {
hjk's avatar
hjk committed
815
        qDebug() << "Ignored in command mode: " << key << text;
816
817
818
        return false;
    }
    return true;
hjk's avatar
hjk committed
819
820
}

821
bool FakeVimHandler::Private::handleInsertMode(int key, const QString &text)
hjk's avatar
hjk committed
822
823
{
    if (key == Key_Escape) {
824
825
826
827
        // start with '1', as one instance was already physically inserted
        // while typing
        QString data = m_lastInsertion;
        for (int i = 1; i < count(); ++i) {
hjk's avatar
hjk committed
828
            m_tc.insertText(m_lastInsertion);
829
830
831
            data += m_lastInsertion;
        }
        recordInsert(m_tc.position() - m_lastInsertion.size(), data);
hjk's avatar
hjk committed
832
        m_tc.movePosition(Left, MoveAnchor, qMin(1, leftDist()));
833
        enterCommandMode();
hjk's avatar
hjk committed
834
835
    } else if (key == Key_Left) {
        m_tc.movePosition(Left, MoveAnchor, 1);
hjk's avatar
hjk committed
836
        m_lastInsertion.clear();
hjk's avatar
hjk committed
837
838
    } else if (key == Key_Down) {
        m_tc.movePosition(Down, MoveAnchor, 1);
hjk's avatar
hjk committed
839
        m_lastInsertion.clear();
hjk's avatar
hjk committed
840
841
    } else if (key == Key_Up) {
        m_tc.movePosition(Up, MoveAnchor, 1);
hjk's avatar
hjk committed
842
        m_lastInsertion.clear();
hjk's avatar
hjk committed
843
844
    } else if (key == Key_Right) {
        m_tc.movePosition(Right, MoveAnchor, 1);
hjk's avatar
hjk committed
845
        m_lastInsertion.clear();
hjk's avatar
hjk committed
846
847
    } else if (key == Key_Return) {
        m_tc.insertBlock();
848
        m_lastInsertion += "\n";
hjk's avatar
hjk committed
849
    } else if (key == Key_Backspace || key == control('h')) {
hjk's avatar
hjk committed
850
        m_tc.deletePreviousChar();
hjk's avatar
hjk committed
851
        m_lastInsertion = m_lastInsertion.left(m_lastInsertion.size() - 1);
852
853
    } else if (key == Key_Delete) {
        m_tc.deleteChar();
hjk's avatar
hjk committed
854
        m_lastInsertion.clear();
hjk's avatar
hjk committed
855
856
    } else if (key == Key_PageDown || key == control('f')) {
        m_tc.movePosition(Down, KeepAnchor, count() * (linesOnScreen() - 2));
hjk's avatar
hjk committed
857
        m_lastInsertion.clear();
hjk's avatar
hjk committed
858
859
    } else if (key == Key_PageUp || key == control('b')) {
        m_tc.movePosition(Up, KeepAnchor, count() * (linesOnScreen() - 2));
hjk's avatar
hjk committed
860
        m_lastInsertion.clear();
861
862
863
864
    } else if (key == Key_Tab && m_config[ConfigExpandTab] == ConfigOn) {
        QString str = QString(m_config[ConfigTabStop].toInt(), ' ');
        m_lastInsertion.append(str);
        m_tc.insertText(str);
865
    } else if (!text.isEmpty()) {
hjk's avatar
hjk committed
866
        m_lastInsertion.append(text);
867
        m_tc.insertText(text);
868
869
    } else {
        return false;
870
871
    }
    updateMiniBuffer();
872
    return true;
hjk's avatar
hjk committed
873
874
}

875
bool FakeVimHandler::Private::handleMiniBufferModes(int key, const QString &text)
hjk's avatar
hjk committed
876
{
877
878
    Q_UNUSED(text)

hjk's avatar
hjk committed
879
880
    if (key == Key_Escape) {
        m_commandBuffer.clear();
881
        enterCommandMode();
hjk's avatar
hjk committed
882
        updateMiniBuffer();
hjk's avatar
hjk committed
883
884
    } else if (key == Key_Backspace) {
        if (m_commandBuffer.isEmpty())
885
            enterCommandMode();
hjk's avatar
hjk committed
886
887
        else
            m_commandBuffer.chop(1);
hjk's avatar
hjk committed
888
        updateMiniBuffer();
hjk's avatar
hjk committed
889
890
891
892
893
    } else if (key == Key_Left) {
        // FIXME:
        if (!m_commandBuffer.isEmpty())
            m_commandBuffer.chop(1);
        updateMiniBuffer();
894
    } else if (key == Key_Return && m_mode == ExMode) {
hjk's avatar
hjk committed
895
896
897