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

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

36
37
#include "fakevimconstants.h"

38
39
40
41
42
43
44
// Please do not add any direct dependencies to other Qt Creator code  here. 
// Instead emit signals and let the FakeVimPlugin channel the information to
// Qt Creator. The idea is to keep this file here in a "clean" state that
// allows easy reuse with any QTextEdit or QPlainTextEdit derived class.

//#include <indenter.h>

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

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


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

69
70
71
72
73
74
75
76
77
#define StartOfLine    QTextCursor::StartOfLine
#define EndOfLine      QTextCursor::EndOfLine
#define MoveAnchor     QTextCursor::MoveAnchor
#define KeepAnchor     QTextCursor::KeepAnchor
#define Up             QTextCursor::Up
#define Down           QTextCursor::Down
#define Right          QTextCursor::Right
#define Left           QTextCursor::Left
#define EndOfDocument  QTextCursor::End
hjk's avatar
hjk committed
78
79
80
81
82
83
84


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

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

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

using namespace Qt;

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

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

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

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

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

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

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

161
162
163
164
165
166
167
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
    foreach (QTextEdit::ExtraSelection sel, sels) 
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position(); 
    return ts;
}
        
hjk's avatar
hjk committed
168
169
170
171
172
173
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

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

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

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

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

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

hjk's avatar
hjk committed
199
200
201
    int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
    int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
    int count() const { return mvCount() * opCount(); }
hjk's avatar
hjk committed
202
203
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
204
205
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
206

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

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

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

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

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
237
238
239
240
241
242
243
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
    void moveToStartOfLine() { m_tc.movePosition(StartOfLine, MoveAnchor); }
    void moveToEndOfLine() { m_tc.movePosition(EndOfLine, MoveAnchor); }
    void moveUp(int n = 1) { m_tc.movePosition(Up, MoveAnchor, n); }
    void moveDown(int n = 1) { m_tc.movePosition(Down, MoveAnchor, n); }
    void moveRight(int n = 1) { m_tc.movePosition(Right, MoveAnchor, n); }
    void moveLeft(int n = 1) { m_tc.movePosition(Left, MoveAnchor, n); }
hjk's avatar
hjk committed
244
245
    void setAnchor() { m_anchor = m_tc.position(); }

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

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

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

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

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

    bool m_fakeEnd;

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

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

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

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

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

hjk's avatar
hjk committed
311

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

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

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

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

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

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

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

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

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

    QPointer<QObject> m_extraData;
351
    int m_cursorWidth;
352
353
354
355

    void recordJump();
    QList<int> m_jumpListUndo;
    QList<int> m_jumpListRedo;
hjk's avatar
hjk committed
356
357
};

358
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
359
360
{
    q = parent;
hjk's avatar
hjk committed
361

362
363
364
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);

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

    m_config[ConfigStartOfLine] = ConfigOn;
380
    m_config[ConfigTabStop]     = "8";
381
    m_config[ConfigSmartTab]    = ConfigOff;
382
    m_config[ConfigShiftWidth]  = "8";
383
    m_config[ConfigExpandTab]   = ConfigOff;
384
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
385
386
}

387
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
388
{
389
    int key = ev->key();
390
    const int um = key; // keep unmodified key around
391

392
    // FIXME
393
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
394
395
396
397
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
hjk's avatar
hjk committed
398
        m_mode = CommandMode;
399
        updateMiniBuffer();
400
401
402
        return false;
    }

hjk's avatar
hjk committed
403
404
405
406
407
    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"
408
    m_tc = EDITOR(textCursor());
409
    m_tc.setVisualNavigation(true);
410

hjk's avatar
hjk committed
411
    if (m_fakeEnd)
hjk's avatar
hjk committed
412
        moveRight();
hjk's avatar
hjk committed
413

414
    if ((ev->modifiers() & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
415
        key += 256;
416
417
418
419
420
        key += 32; // make it lower case
    } else if (key >= Key_A && key <= Key_Z
        && (ev->modifiers() & Qt::ShiftModifier) == 0) {
        key += 32;
    }
421
    bool handled = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
422
423

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

hjk's avatar
hjk committed
426
    if (m_fakeEnd)
hjk's avatar
hjk committed
427
        moveLeft();
hjk's avatar
hjk committed
428

429
430
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
431
    return handled;
hjk's avatar
hjk committed
432
433
}

434
435
436
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
437
438
    EDITOR(installEventFilter(q));
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
439
440
441
442
443
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
444
    m_wasReadOnly = EDITOR(isReadOnly());
445
    //EDITOR(setReadOnly(true)); 
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

    QTextCursor tc = EDITOR(textCursor());
    if (tc.hasSelection()) {
        int pos = tc.position();
        int anc = tc.anchor();
        m_marks['<'] = anc;
        m_marks['>'] = pos;
        m_anchor = anc;
        m_visualMode = VisualCharMode;
        tc.clearSelection();
        EDITOR(setTextCursor(tc));
        m_tc = tc; // needed in updateSelection
        updateSelection();
    }

461
462
463
464
465
466
467
468
    showBlackMessage("vi emulation mode.");
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
469
470
    EDITOR(removeEventFilter(q));
    EDITOR(setReadOnly(m_wasReadOnly));
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
    
    if (m_visualMode == VisualLineMode) {
        m_tc = EDITOR(textCursor());
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
        m_tc.setPosition(firstPositionInLine(beginLine), MoveAnchor);
        m_tc.setPosition(lastPositionInLine(endLine), KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    } else if (m_visualMode == VisualCharMode) {
        m_tc = EDITOR(textCursor());
        m_tc.setPosition(m_marks['<'], MoveAnchor);
        m_tc.setPosition(m_marks['>'], KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    }

    m_visualMode = NoVisualMode;
    updateSelection();
488
489
}

490
bool FakeVimHandler::Private::handleKey(int key, int unmodified, const QString &text)
hjk's avatar
hjk committed
491
{
492
493
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
hjk's avatar
hjk committed
494
    if (m_mode == InsertMode)
495
        return handleInsertMode(key, unmodified, text);
496
    if (m_mode == CommandMode)
497
        return handleCommandMode(key, unmodified, text);
498
    if (m_mode == ExMode || m_mode == SearchForwardMode
499
            || m_mode == SearchBackwardMode)
500
        return handleMiniBufferModes(key, unmodified, text);
501
    return false;
hjk's avatar
hjk committed
502
503
}

hjk's avatar
hjk committed
504
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
505
{
506
    //qDebug() << "ANCHOR: " << m_anchor;
hjk's avatar
hjk committed
507
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
508
509
510
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
        m_tc.setPosition(qMin(anchor(), position()));
511
        enterExMode();
hjk's avatar
hjk committed
512
513
514
515
516
517
518
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

519
520
521
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
522
    if (m_submode == ChangeSubMode) {
523
524
        if (m_moveType == MoveInclusive)
            moveRight(); // correction
hjk's avatar
hjk committed
525
526
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
527
        QString text = recordRemoveSelectedText();
528
        //qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
529
        m_registers[m_register] = text;
hjk's avatar
hjk committed
530
531
532
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
533
        if (m_moveType == MoveInclusive)
534
            moveRight(); // correction
hjk's avatar
hjk committed
535
536
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
537
538
        m_registers[m_register] = recordRemoveSelectedText();
        recordEndGroup();
hjk's avatar
hjk committed
539
        m_submode = NoSubMode;
540
        if (atEndOfLine())
hjk's avatar
hjk committed
541
            moveLeft();
542
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
543
544
        m_registers[m_register] = selectedText();
        m_tc.setPosition(m_savedYankPosition);
545
        m_submode = NoSubMode;
546
547
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
548
549
550
551
552
    } 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
553
            qSwap(start, end);
554
555
556
557
558
        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
559
    }
hjk's avatar
hjk committed
560
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
561
562
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
563
    m_gflag = false;
hjk's avatar
hjk committed
564
565
    m_register = '"';
    m_tc.clearSelection();
566
567

    updateSelection();
hjk's avatar
hjk committed
568
    updateMiniBuffer();
569
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
570
571
}

572
573
574
575
576
577
578
void FakeVimHandler::Private::updateSelection()
{
    QList<QTextEdit::ExtraSelection> selections;
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
579
580
581
582
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
583
584
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
585
#endif
586
587
588
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
589
        if (m_visualMode == VisualCharMode) {
590
            sel.cursor.setPosition(anchorPos, KeepAnchor);
591
592
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
593
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
594
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
595
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
596
597
598
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
            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);
            }
620
621
        }
    }
622
    //qDebug() << "SELECTION: " << selections;
623
    emit q->selectionChanged(selections);
624
625
}

hjk's avatar
hjk committed
626
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
627
{
hjk's avatar
hjk committed
628
    QString msg;
629
630
631
    if (m_mode == PassingMode) {
        msg = "-- PASSING --";
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
632
633
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
634
635
636
637
638
639
640
641
    } 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 --";
        }
642
643
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
644
    } else {
645
        if (m_mode == SearchForwardMode)
646
            msg += '/';
647
        else if (m_mode == SearchBackwardMode)
648
            msg += '?';
649
        else if (m_mode == ExMode)
650
            msg += ':';
hjk's avatar
hjk committed
651
        foreach (QChar c, m_commandBuffer) {
652
653
654
655
656
657
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
658
        }
hjk's avatar
hjk committed
659
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
660
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
661
    }
hjk's avatar
hjk committed
662
663
664
665
666
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
667
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
668
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
669
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
670
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
671
672
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
673
    } else {
hjk's avatar
hjk committed
674
        status += "All";
hjk's avatar
hjk committed
675
    }
hjk's avatar
hjk committed
676
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
677
678
}

hjk's avatar
hjk committed
679
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
680
{
681
682
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
683
    updateMiniBuffer();
hjk's avatar
hjk committed
684
685
}

hjk's avatar
hjk committed
686
687
688
689
690
691
692
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

693
694
695
696
697
698
void FakeVimHandler::Private::notImplementedYet()
{
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

699
700
bool FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
701
{
702
    bool handled = true;
703

hjk's avatar
hjk committed
704
705
706
707
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
hjk's avatar
hjk committed
708
709
710
        moveToStartOfLine();
        setAnchor();
        moveDown(count());
711
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
712
        finishMovement("c");
hjk's avatar
hjk committed
713
    } else if (m_submode == DeleteSubMode && key == 'd') {
hjk's avatar
hjk committed
714
        moveToStartOfLine();
hjk's avatar
hjk committed
715
        setAnchor();
hjk's avatar
hjk committed
716
        moveDown(count());
717
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
718
        finishMovement("d");
719
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
720
        moveToStartOfLine();
hjk's avatar
hjk committed
721
        setAnchor();
hjk's avatar
hjk committed
722
        moveDown(count());
hjk's avatar
hjk committed
723
724
        m_moveType = MoveLineWise;
        finishMovement("y");
725
726
    } else if (m_submode == IndentSubMode && key == '=') {
        indentRegion(m_tc.block(), m_tc.block().next());
727
        finishMovement();
hjk's avatar
hjk committed
728
    } else if (m_submode == ZSubMode) {
hjk's avatar
hjk committed
729
730
731
        //qDebug() << "Z_MODE " << cursorLineInDocument() << linesOnScreen();
        if (key == Key_Return || key == 't') { // cursor line to top of window
            if (!m_mvcount.isEmpty())
732
                m_tc.setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
733
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
734
735
            if (key == Key_Return)
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
736
            finishMovement();
hjk's avatar
hjk committed
737
738
        } else if (key == '.' || key == 'z') { // cursor line to center of window
            if (!m_mvcount.isEmpty())
739
                m_tc.setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
740
            scrollToLineInDocument(cursorLineInDocument() - linesOnScreen() / 2);
hjk's avatar
hjk committed
741
742
            if (key == '.')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
743
            finishMovement();
hjk's avatar
hjk committed
744
745
        } else if (key == '-' || key == 'b') { // cursor line to bottom of window
            if (!m_mvcount.isEmpty())
746
                m_tc.setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
747
748
749
            scrollToLineInDocument(cursorLineInDocument() - linesOnScreen() - 1);
            if (key == '-')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
750
            finishMovement();
hjk's avatar
hjk committed
751
        } else {
hjk's avatar
hjk committed
752
            qDebug() << "IGNORED Z_MODE " << key << text;
hjk's avatar
hjk committed
753
754
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
755
    } else if (m_subsubmode == FtSubSubMode) {
hjk's avatar
hjk committed
756
757
        m_semicolonType = m_subsubdata;
        m_semicolonKey = key;
hjk's avatar
hjk committed
758
759
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
760
        finishMovement();
hjk's avatar
hjk committed
761
    } else if (m_submode == ReplaceSubMode) {
hjk's avatar
hjk committed
762
763
764
765
766
767
768
769
770
        if (count() < rightDist() && text.size() == 1
                && (text.at(0).isPrint() || text.at(0).isSpace())) {
            recordBeginGroup();
            setAnchor();
            moveRight(count());
            recordRemoveSelectedText();
            recordInsertText(QString(count(), text.at(0)));
            recordEndGroup();
            m_moveType = MoveExclusive;
hjk's avatar
hjk committed
771
            m_submode = NoSubMode;
hjk's avatar
hjk committed
772
773
774
            m_dotCommand = QString("%1r%2").arg(count()).arg(text);
            finishMovement();
        } else {
hjk's avatar
hjk committed
775
            m_submode = NoSubMode;
hjk's avatar
hjk committed
776
        }
777
778
779
780
781
782
    } 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
783
            m_tc.setPosition(m_marks[key]);
784
785
786
787
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
788
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
789
790
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
791
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
792
        if (key == '0' && m_mvcount.isEmpty()) {
hjk's avatar
hjk committed
793
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
794
795
            finishMovement();
        } else {
hjk's avatar
hjk committed
796
            m_mvcount.append(QChar(key));
hjk's avatar
hjk committed
797
        }
hjk's avatar
hjk committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
    } else if (0 && key == ',') {
        // FIXME: fakevim uses ',' by itself, so it is incompatible
        m_subsubmode = FtSubSubMode;
        // HACK: toggle 'f' <-> 'F', 't' <-> 'T'
        m_subsubdata = m_semicolonType ^ 32;
        handleFfTt(m_semicolonKey);
        m_subsubmode = NoSubSubMode;
        finishMovement();
    } else if (key == ';') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = m_semicolonType;
        handleFfTt(m_semicolonKey);
        m_subsubmode = NoSubSubMode;
        finishMovement();
812
    } else if (key == ':') {
813
        enterExMode();
hjk's avatar
hjk committed
814
        m_commandBuffer.clear();
815
        if (m_visualMode != NoVisualMode)
816
817
818
819
820
            m_commandBuffer = "'<,'>";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
    } else if (key == '/' || key == '?') {
821
        enterExMode(); // to get the cursor disabled
822
823
824
825
        m_mode = (key == '/') ? SearchForwardMode : SearchBackwardMode;
        m_commandBuffer.clear();
        m_searchHistory.append(QString());
        m_searchHistoryIndex = m_searchHistory.size() - 1;
hjk's avatar
hjk committed
826
        updateMiniBuffer();
827
828
    } else if (key == '`') {
        m_subsubmode = BackTickSubSubMode;
hjk's avatar
hjk committed
829
830
831
832
833
834
835
836
    } 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);
837
        recordJump();
838
839
    } else if (key == '\'') {
        m_subsubmode = TickSubSubMode;
hjk's avatar
hjk committed
840
    } else if (key == '|') {
hjk's avatar
hjk committed
841
842
843
        setAnchor();
        moveToStartOfLine();
        moveRight(qMin(count(), rightDist()) - 1);
hjk's avatar
hjk committed
844
        finishMovement();
hjk's avatar
hjk committed
845
846
847
    } else if (key == '!' && m_visualMode == NoVisualMode) {
        m_submode = FilterSubMode;
    } else if (key == '!' && m_visualMode == VisualLineMode) {
848
        enterExMode();
hjk's avatar
hjk committed
849
850
851
852
        m_commandBuffer = "'<,'>!";
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
hjk's avatar
hjk committed
853
854
    } else if (key == '"') {
        m_submode = RegisterSubMode;
855
    } else if (unmodified == Key_Return) {
hjk's avatar
hjk committed
856
857
        moveToStartOfLine();
        moveDown();
858
        moveToFirstNonBlankOnLine();
859
        finishMovement();
hjk's avatar
hjk committed
860
    } else if (key == Key_Home) {
hjk's avatar
hjk committed
861
        moveToStartOfLine();
hjk's avatar
hjk committed
862
863
        finishMovement();
    } else if (key == '$' || key == Key_End) {
864
        int submode = m_submode;
hjk's avatar
hjk committed
865
        moveToEndOfLine();
hjk's avatar
hjk committed
866
        finishMovement();
867
868
        if (submode == NoSubMode)
            m_desiredColumn = -1;
869
870
871
872
    } else if (key == ',') {
        // FIXME: use some other mechanism
        m_mode = PassingMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
873
874
875
876
    } else if (key == '.') {
        qDebug() << "REPEATING" << m_dotCommand;
        for (int i = count(); --i >= 0; )
            foreach (QChar c, m_dotCommand)
877
                handleKey(c.unicode(), c.unicode(), QString(c));
878
879
    } else if (key == '=') {
        m_submode = IndentSubMode;
880
    } else if (key == '%') {
881
        moveToMatchingParanthesis();
882
        finishMovement();
hjk's avatar
hjk committed
883
    } else if (key == 'a') {
hjk's avatar
hjk committed
884
        m_mode = InsertMode;
hjk's avatar
hjk committed
885
        recordBeginGroup();
hjk's avatar
hjk committed
886
        m_lastInsertion.clear();
887
888
        if (!atEndOfLine())
            moveRight();
889
        updateMiniBuffer();
hjk's avatar
hjk committed
890
    } else if (key == 'A') {
hjk's avatar
hjk committed
891
        m_mode = InsertMode;
hjk's avatar
hjk committed
892
893
        moveToEndOfLine();
        recordBeginGroup();
hjk's avatar
hjk committed
894
        m_lastInsertion.clear();
hjk's avatar
hjk committed
895
    } else if (key == 'b') {
896
        m_moveType = MoveExclusive;
hjk's avatar
hjk committed
897
        moveToWordBoundary(false, false);
hjk's avatar
hjk committed
898
899
        finishMovement();
    } else if (key == 'B') {
900
        m_moveType = MoveExclusive;
hjk's avatar
hjk committed
901
        moveToWordBoundary(true, false);