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

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

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

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

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

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

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

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

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

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