fakevimhandler.cpp 59.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
#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
62
//#include <texteditor/basetexteditor.h>
//#include <texteditor/textblockiterator.h>
//#include <cppeditor/cppeditor.h>
63

64
//#include <indenter.h>
hjk's avatar
hjk committed
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,
109
    ReplaceSubMode,
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
117
enum SubSubMode
{
    NoSubSubMode,
118
119
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
120
    BackTickSubSubMode, // used for `
121
    TickSubSubMode      // used for '
hjk's avatar
hjk committed
122
123
};

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

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

hjk's avatar
hjk committed
141
142
143
144
145
146
147
148
149
150
151
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
152
153
154
155
156
class FakeVimHandler::Private
{
public:
    Private(FakeVimHandler *parent);

157
    bool handleEvent(QKeyEvent *ev);
158
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
159

160
private:
161
    friend class FakeVimHandler;
hjk's avatar
hjk committed
162
163
164
165
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
166
167
168
169
170
    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
171
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
172
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
173

hjk's avatar
hjk committed
174
175
176
    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
177
178
179
    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
180

hjk's avatar
hjk committed
181
    int lastPositionInDocument() const;
hjk's avatar
hjk committed
182
183
    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
184

hjk's avatar
hjk committed
185
186
187
188
189
190
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
191
    int linesInDocument() const;
hjk's avatar
hjk committed
192
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
193

194
195
196
197
198
199
    // helper functions for indenting
    bool isElectricCharacter(QChar c) const { return (c == '{' || c == '}' || c == '#'); }
    int indentDist() const;
    void indentRegion(QTextBlock first, QTextBlock last, QChar typedChar=0);
    void indentCurrentLine(QChar typedChar);

hjk's avatar
hjk committed
200
    void moveToFirstNonBlankOnLine();
201
    void moveToDesiredColumn();
hjk's avatar
hjk committed
202
    void moveToNextWord(bool simple);
203
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
204
205
    void moveToWordBoundary(bool simple, bool forward);
    void handleFfTt(int key);
hjk's avatar
hjk committed
206

hjk's avatar
hjk committed
207
208
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
209
    QTextCursor selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
210

211
    void setWidget(QWidget *ob);
212
    void enterInsertMode();
213
    void enterCommandMode();
hjk's avatar
hjk committed
214
215
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
216
217
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
218
    void quit();
219
    QWidget *editor() const;
220

221
222
223
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
224
    bool m_wasReadOnly; // saves read-only state of document
225

hjk's avatar
hjk committed
226
    FakeVimHandler *q;
227
    Core::ICore *m_core;
hjk's avatar
hjk committed
228
229
    Mode m_mode;
    SubMode m_submode;
hjk's avatar
hjk committed
230
231
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
232
233
234
235
    QString m_input;
    QTextCursor m_tc;
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
236
237
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
238
239
240

    bool m_fakeEnd;

241
242
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
243
    int m_gflag;  // whether current command started with 'g'
244

hjk's avatar
hjk committed
245
    QString m_commandBuffer;
246
    QString m_currentFileName;
247
    Core::IFile* m_currentFile;
248
    QString m_currentMessage;
hjk's avatar
hjk committed
249

250
    bool m_lastSearchForward;
hjk's avatar
hjk committed
251
    QString m_lastInsertion;
hjk's avatar
hjk committed
252

253
    // undo handling
hjk's avatar
hjk committed
254
    void recordOperation(const EditOperation &op);
255
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
256
    void recordRemove(int position, const QString &data);
257
    void recordRemove(int position, int length);
258
    void recordMove(int position, int nestedCount);
259
    void removeSelectedText(QTextCursor &tc);
260
261
262
263
264
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;

hjk's avatar
hjk committed
265
266
267
268
    // extra data for '.'
    QString m_dotCount;
    QString m_dotCommand;

hjk's avatar
hjk committed
269
    // history for '/'
hjk's avatar
hjk committed
270
271
272
273
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
274
    // history for ':'
hjk's avatar
hjk committed
275
276
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
277

hjk's avatar
hjk committed
278
    // visual line mode
279
280
281
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
282

283
284
285
    // marks as lines
    QHash<int, int> m_marks;

hjk's avatar
hjk committed
286
287
    // vi style configuration
    QHash<QString, QString> m_config;
288
289
290

    // for restoring cursor position
    int m_savedPosition;
291
    int m_desiredColumn;
hjk's avatar
hjk committed
292
293
294
295
296
};

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

hjk's avatar
hjk committed
298
    m_mode = CommandMode;
hjk's avatar
hjk committed
299
300
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
301
    m_fakeEnd = false;
302
    m_lastSearchForward = true;
hjk's avatar
hjk committed
303
    m_register = '"';
hjk's avatar
hjk committed
304
    m_gflag = false;
305
306
    m_textedit = 0;
    m_plaintextedit = 0;
307
    m_visualMode = NoVisualMode;
308
    m_desiredColumn = 0;
hjk's avatar
hjk committed
309

310
311
    m_core = ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>();

hjk's avatar
hjk committed
312
    m_config[ConfigStartOfLine] = ConfigOn;
313
    m_config[ConfigTabStop]     = "8";
314
    m_config[ConfigSmartTab]    = ConfigOff;
315
    m_config[ConfigShiftWidth]  = "8";
316
    m_config[ConfigExpandTab]   = ConfigOff;
317
    m_config[ConfigAutoIndent]  = ConfigOff;
hjk's avatar
hjk committed
318
319
}

320
bool FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
hjk's avatar
hjk committed
321
{
322
323
    int key = ev->key();

324
    // FIXME
325
    if (m_mode == PassingMode && key != Qt::Key_Control && key != Qt::Key_Shift) {
326
327
328
329
        if (key == ',') { // use ',,' to leave, too.
            quit();
            return true;
        }
330
331
332
        return false;
    }

hjk's avatar
hjk committed
333
334
335
336
337
    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"
338
    m_tc = EDITOR(textCursor());
339
    m_tc.setVisualNavigation(true);
340

hjk's avatar
hjk committed
341
    if (m_fakeEnd)
hjk's avatar
hjk committed
342
343
        m_tc.movePosition(Right, MoveAnchor, 1);

344
    if ((ev->modifiers() & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
345
        key += 256;
346
347
348
349
350
        key += 32; // make it lower case
    } else if (key >= Key_A && key <= Key_Z
        && (ev->modifiers() & Qt::ShiftModifier) == 0) {
        key += 32;
    }
351
    bool handled = handleKey(key, ev->text());
hjk's avatar
hjk committed
352
353

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

hjk's avatar
hjk committed
356
    if (m_fakeEnd)
hjk's avatar
hjk committed
357
358
        m_tc.movePosition(Left, MoveAnchor, 1);

359
360
    EDITOR(setTextCursor(m_tc));
    EDITOR(ensureCursorVisible());
hjk's avatar
hjk committed
361
    return handled;
hjk's avatar
hjk committed
362
363
}

364
bool FakeVimHandler::Private::handleKey(int key, const QString &text)
hjk's avatar
hjk committed
365
{
366
367
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
368
    m_savedPosition = m_tc.position();
hjk's avatar
hjk committed
369
    if (m_mode == InsertMode)
370
371
372
373
        return handleInsertMode(key, text);
    if (m_mode == CommandMode)
        return handleCommandMode(key, text);
    if (m_mode == ExMode || m_mode == SearchForwardMode
374
            || m_mode == SearchBackwardMode)
375
376
        return handleMiniBufferModes(key, text);
    return false;
hjk's avatar
hjk committed
377
378
}

hjk's avatar
hjk committed
379
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
380
{
hjk's avatar
hjk committed
381
382
383
384
385
386
387
388
389
390
391
392
    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
393
    if (m_submode == ChangeSubMode) {
hjk's avatar
hjk committed
394
395
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
396
        m_registers[m_register] = m_tc.selectedText();
397
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
398
399
400
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
hjk's avatar
hjk committed
401
402
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
403
        recordRemove(qMin(m_tc.position(), m_tc.anchor()), m_tc.selectedText());
hjk's avatar
hjk committed
404
        m_registers[m_register] = m_tc.selectedText();
405
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
406
407
408
        m_submode = NoSubMode;
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
409
410
411
412
    } else if (m_submode == YankSubMode) {
        m_registers[m_register] = m_tc.selectedText();
        m_tc.setPosition(m_savedPosition);
        m_submode = NoSubMode;
413
414
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
415
416
417
418
419
420
421
422
423
424
425
    } else if (m_submode == IndentSubMode) {
        QTextDocument *doc = EDITOR(document());
        int start = m_tc.selectionStart();
        int end = m_tc.selectionEnd();
        if (start > end)
            std::swap(start, end);
        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
426
    }
hjk's avatar
hjk committed
427
428
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
429
    m_gflag = false;
hjk's avatar
hjk committed
430
431
    m_register = '"';
    m_tc.clearSelection();
432
433

    updateSelection();
hjk's avatar
hjk committed
434
    updateMiniBuffer();
435
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
436
437
}

438
439
440
441
442
443
444
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
445
446
447
448
        //sel.format.setFontWeight(QFont::Bold);
        //sel.format.setFontUnderline(true);
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
449
450
451
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
452
        if (m_visualMode == VisualCharMode) {
453
            sel.cursor.setPosition(anchorPos, KeepAnchor);
454
455
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
456
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
457
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
458
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
459
460
461
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
            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);
            }
483
484
        }
    }
485
    emit q->selectionChanged(editor(), selections);
486
487
}

hjk's avatar
hjk committed
488
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
489
{
hjk's avatar
hjk committed
490
    QString msg;
491
492
493
    if (m_mode == PassingMode) {
        msg = "-- PASSING --";
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
494
495
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
496
497
498
499
500
501
502
503
    } 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 --";
        }
504
505
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
506
    } else {
507
        if (m_mode == SearchForwardMode)
508
            msg += '/';
509
        else if (m_mode == SearchBackwardMode)
510
            msg += '?';
511
        else if (m_mode == ExMode)
512
            msg += ':';
hjk's avatar
hjk committed
513
        foreach (QChar c, m_commandBuffer) {
514
515
516
517
518
519
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
520
        }
hjk's avatar
hjk committed
521
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
522
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
523
    }
hjk's avatar
hjk committed
524
525
526
527
528
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
529
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
530
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
531
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
532
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
533
534
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
535
    } else {
hjk's avatar
hjk committed
536
        status += "All";
hjk's avatar
hjk committed
537
    }
hjk's avatar
hjk committed
538
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
539
540
}

hjk's avatar
hjk committed
541
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
542
{
543
544
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
545
    updateMiniBuffer();
hjk's avatar
hjk committed
546
547
}

hjk's avatar
hjk committed
548
549
550
551
552
553
554
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

555
bool FakeVimHandler::Private::handleCommandMode(int key, const QString &text)
hjk's avatar
hjk committed
556
{
557
    bool handled = true;
558

hjk's avatar
hjk committed
559
560
561
562
563
564
565
    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
566
        finishMovement("c");
hjk's avatar
hjk committed
567
568
569
570
    } 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
571
        finishMovement("d");
572
573
574
575
576
    } else if (m_submode == YankSubMode && key == 'y') {
        m_tc.movePosition(StartOfLine, MoveAnchor);
        m_tc.movePosition(Down, KeepAnchor, count());
        m_registers[m_register] = m_tc.selectedText();
        finishMovement();
577
578
579
580
581
582
    } else if (m_submode == ReplaceSubMode) {
        if (atEol())
            m_tc.movePosition(Left, KeepAnchor, 1);
        else
            m_tc.deleteChar();
        m_tc.insertText(text);
583
584
    } else if (m_submode == IndentSubMode && key == '=') {
        indentRegion(m_tc.block(), m_tc.block().next());
585
        finishMovement();
hjk's avatar
hjk committed
586
587
    } else if (m_submode == ZSubMode) {
        if (key == Key_Return) {
hjk's avatar
hjk committed
588
            // cursor line to top of window, cursor on first non-blank
hjk's avatar
hjk committed
589
            scrollToLineInDocument(cursorLineInDocument());
hjk's avatar
hjk committed
590
591
            moveToFirstNonBlankOnLine();
            finishMovement();
hjk's avatar
hjk committed
592
        } else {
hjk's avatar
hjk committed
593
594
595
            qDebug() << "Ignored z + " << key << text;
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
596
597
598
    } else if (m_subsubmode == FtSubSubMode) {
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
599
        finishMovement(QString(QChar(m_subsubdata)) + QChar(key));
600
601
602
603
604
605
    } 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
606
            m_tc.setPosition(m_marks[key], MoveAnchor);
607
608
609
610
            if (m_subsubmode == TickSubSubMode)
                moveToFirstNonBlankOnLine();
            finishMovement();
        } else {
hjk's avatar
hjk committed
611
            showRedMessage(tr("E20: Mark '%1' not set").arg(text));
612
613
        }
        m_subsubmode = NoSubSubMode;
hjk's avatar
hjk committed
614
    } else if (key >= '0' && key <= '9') {
hjk's avatar
hjk committed
615
        if (key == '0' && m_mvcount.isEmpty()) {
hjk's avatar
hjk committed
616
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
617
618
            finishMovement();
        } else {
hjk's avatar
hjk committed
619
            m_mvcount.append(QChar(key));
hjk's avatar
hjk committed
620
        }
621
    } else if (key == ':') {
hjk's avatar
hjk committed
622
        m_mode = ExMode;
hjk's avatar
hjk committed
623
        m_commandBuffer.clear();
624
625
626
        if (m_visualMode != NoVisualMode) {
            m_commandBuffer = "'<,'>";
            leaveVisualMode();
hjk's avatar
hjk committed
627
        }
628
629
630
631
632
633
634
635
        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
636
        updateMiniBuffer();
637
638
639
640
    } else if (key == '`') {
        m_subsubmode = BackTickSubSubMode;
    } else if (key == '\'') {
        m_subsubmode = TickSubSubMode;
hjk's avatar
hjk committed
641
642
643
644
    } else if (key == '|') {
        m_tc.movePosition(StartOfLine, KeepAnchor);
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()) - 1);
        finishMovement();
hjk's avatar
hjk committed
645
646
647
648
649
650
651
652
653
    } 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
654
655
656
657
658
    } else if (key == '"') {
        m_submode = RegisterSubMode;
    } else if (key == Key_Return) {
        m_tc.movePosition(StartOfLine);
        m_tc.movePosition(Down);
659
        finishMovement();
hjk's avatar
hjk committed
660
661
662
663
    } else if (key == Key_Home) {
        m_tc.movePosition(StartOfLine, KeepAnchor);
        finishMovement();
    } else if (key == '$' || key == Key_End) {
664
        int submode = m_submode;
hjk's avatar
hjk committed
665
666
        m_tc.movePosition(EndOfLine, KeepAnchor);
        finishMovement();
667
668
        if (submode == NoSubMode)
            m_desiredColumn = -1;
669
670
671
672
    } else if (key == ',') {
        // FIXME: use some other mechanism
        m_mode = PassingMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
673
674
675
676
677
    } else if (key == '.') {
        qDebug() << "REPEATING" << m_dotCommand;
        for (int i = count(); --i >= 0; )
            foreach (QChar c, m_dotCommand)
                handleKey(c.unicode(), QString(c));
678
679
    } else if (key == '=') {
        m_submode = IndentSubMode;
680
    } else if (key == '%') {
681
        moveToMatchingParanthesis();
682
        finishMovement();
hjk's avatar
hjk committed
683
    } else if (key == 'a') {
hjk's avatar
hjk committed
684
        m_mode = InsertMode;
hjk's avatar
hjk committed
685
686
        m_lastInsertion.clear();
        m_tc.movePosition(Right, MoveAnchor, 1);
687
        updateMiniBuffer();
hjk's avatar
hjk committed
688
    } else if (key == 'A') {
hjk's avatar
hjk committed
689
        m_mode = InsertMode;
hjk's avatar
hjk committed
690
        m_tc.movePosition(EndOfLine, MoveAnchor);
hjk's avatar
hjk committed
691
        m_lastInsertion.clear();
hjk's avatar
hjk committed
692
    } else if (key == 'b') {
hjk's avatar
hjk committed
693
        moveToWordBoundary(false, false);
hjk's avatar
hjk committed
694
695
        finishMovement();
    } else if (key == 'B') {
hjk's avatar
hjk committed
696
        moveToWordBoundary(true, false);
hjk's avatar
hjk committed
697
        finishMovement();
hjk's avatar
hjk committed
698
699
700
701
702
703
    } else if (key == 'c') {
        m_submode = ChangeSubMode;
    } else if (key == 'C') {
        m_submode = ChangeSubMode;
        m_tc.movePosition(EndOfLine, KeepAnchor);
        finishMovement();
704
    } else if (key == 'd' && m_visualMode == NoVisualMode) {
hjk's avatar
hjk committed
705
706
707
708
709
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
        m_opcount = m_mvcount;
        m_mvcount.clear();
        m_submode = DeleteSubMode;
710
711
712
713
714
    } else if (key == 'd') {
        leaveVisualMode();
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
        m_tc = selectRange(beginLine, endLine);
715
        removeSelectedText(m_tc);
hjk's avatar
hjk committed
716
717
    } else if (key == 'D') {
        m_submode = DeleteSubMode;
hjk's avatar
hjk committed
718
719
        m_tc.movePosition(Down, KeepAnchor, qMax(count() - 1, 0));
        m_tc.movePosition(Right, KeepAnchor, rightDist());
hjk's avatar
hjk committed
720
        finishMovement();
hjk's avatar
hjk committed
721
    } else if (key == 'e') {
hjk's avatar
hjk committed
722
        moveToWordBoundary(false, true);
hjk's avatar
hjk committed
723
724
        finishMovement();
    } else if (key == 'E') {
hjk's avatar
hjk committed
725
        moveToWordBoundary(true, true);
hjk's avatar
hjk committed
726
        finishMovement();
hjk's avatar
hjk committed
727
728
729
    } else if (key == 'f' || key == 'F') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
730
731
    } else if (key == 'g') {
        m_gflag = true;
hjk's avatar
hjk committed
732
733
    } else if (key == 'G') {
        int n = m_mvcount.isEmpty() ? linesInDocument() : count();
Martin Aumueller's avatar
Martin Aumueller committed
734
        m_tc.setPosition(positionForLine(n), KeepAnchor);
hjk's avatar
hjk committed
735
736
737
        if (m_config.contains(ConfigStartOfLine))
            moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
738
739
740
741
742
743
    } 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
744
    } else if (key == 'H') {
745
        m_tc = EDITOR(cursorForPosition(QPoint(0, 0)));
hjk's avatar
hjk committed
746
747
748
        m_tc.movePosition(Down, KeepAnchor, qMax(count() - 1, 0));
        moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
749
    } else if (key == 'i') {
750
        enterInsertMode();
751
        updateMiniBuffer();
752
753
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
hjk's avatar
hjk committed
754
    } else if (key == 'I') {
755
        enterInsertMode();
hjk's avatar
hjk committed
756
757
758
759
        if (m_gflag)
            m_tc.movePosition(StartOfLine, KeepAnchor);
        else
            moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
760
    } else if (key == 'j' || key == Key_Down) {
761
        int savedColumn = m_desiredColumn;
762
763
        if (m_submode == NoSubMode || m_submode == ZSubMode || m_submode == RegisterSubMode) {
            m_tc.movePosition(Down, KeepAnchor, count());
764
            moveToDesiredColumn();
765
766
767
768
        } else {
            m_tc.movePosition(StartOfLine, MoveAnchor);
            m_tc.movePosition(Down, KeepAnchor, count()+1);
        }
hjk's avatar
hjk committed
769
        finishMovement();
770
        m_desiredColumn = savedColumn;
hjk's avatar
hjk committed
771
    } else if (key == 'J') {
hjk's avatar
hjk committed
772
        EditOperation op;
hjk's avatar
hjk committed
773
774
775
776
        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
777
778
                if (!m_gflag)
                    m_tc.insertText(" ");
hjk's avatar
hjk committed
779
            }
hjk's avatar
hjk committed
780
781
            if (!m_gflag)
                m_tc.movePosition(Left, MoveAnchor, 1);
hjk's avatar
hjk committed
782
        }
hjk's avatar
hjk committed
783
    } else if (key == 'k' || key == Key_Up) {
784
        int savedColumn = m_desiredColumn;
785
786
        if (m_submode == NoSubMode || m_submode == ZSubMode || m_submode == RegisterSubMode) {
            m_tc.movePosition(Up, KeepAnchor, count());
787
            moveToDesiredColumn();
788
789
790
791
792
        } else {
            m_tc.movePosition(StartOfLine, MoveAnchor);
            m_tc.movePosition(Down, MoveAnchor);
            m_tc.movePosition(Up, KeepAnchor, count()+1);
        }
hjk's avatar
hjk committed
793
        finishMovement();
794
        m_desiredColumn = savedColumn;
hjk's avatar
hjk committed
795
796
797
    } else if (key == 'l' || key == Key_Right) {
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
        finishMovement();
hjk's avatar
hjk committed
798
    } else if (key == 'L') {
hjk's avatar
hjk committed
799
        m_tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()))));
hjk's avatar
hjk committed
800
801
802
        m_tc.movePosition(Up, KeepAnchor, qMax(count(), 1));
        moveToFirstNonBlankOnLine();
        finishMovement();
803
804
    } else if (key == 'm') {
        m_subsubmode = MarkSubSubMode;
hjk's avatar
hjk committed
805
    } else if (key == 'M') {
hjk's avatar
hjk committed
806
        m_tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()) / 2)));
hjk's avatar
hjk committed
807
808
        moveToFirstNonBlankOnLine();
        finishMovement();
hjk's avatar
hjk committed
809
    } else if (key == 'n') {
hjk's avatar
hjk committed
810
        search(lastSearchString(), m_lastSearchForward);
hjk's avatar
hjk committed
811
    } else if (key == 'N') {
hjk's avatar
hjk committed
812
        search(lastSearchString(), !m_lastSearchForward);
813
    } else if (key == 'o' || key == 'O') {
814
        enterInsertMode();
815
816
817
818
819
        moveToFirstNonBlankOnLine();
        int numSpaces = leftDist();
        m_tc.movePosition(Up, MoveAnchor, 1);
        if (key == 'o')
            m_tc.movePosition(Down, MoveAnchor, 1);
hjk's avatar
hjk committed
820
821
        m_tc.movePosition(EndOfLine, MoveAnchor);
        m_tc.insertText("\n");
hjk's avatar
hjk committed
822
        m_tc.movePosition(StartOfLine, MoveAnchor);
823
824
825
        if (m_config[ConfigAutoIndent] == ConfigOn)
            m_tc.insertText(QString(indentDist(), ' '));
        else
826
            m_tc.insertText(QString(numSpaces, ' '));
hjk's avatar
hjk committed
827
    } else if (key == 'p' || key == 'P') {
hjk's avatar
hjk committed
828
829
830
831
        QString text = m_registers[m_register];
        int n = text.count(QChar(ParagraphSeparator));
        if (n > 0) {
            m_tc.movePosition(StartOfLine);
hjk's avatar
hjk committed
832
833
            if (key == 'p')
                m_tc.movePosition(Down);
hjk's avatar
hjk committed
834
835
836
            m_tc.insertText(text);
            m_tc.movePosition(Up, MoveAnchor, n);
        } else {
hjk's avatar
hjk committed
837
838
            if (key == 'p')
                m_tc.movePosition(Right);
hjk's avatar
hjk committed
839
840
841
            m_tc.insertText(text);
            m_tc.movePosition(Left);
        }
842
        m_dotCommand = "p";
843
844
845
    } else if (key == 'r') {
        m_submode = ReplaceSubMode;
        m_dotCommand = "r";
846
847
848
849
    } else if (key == 'R') {
        m_mode = InsertMode;
        m_submode = ReplaceSubMode;
        m_dotCommand = "R";
hjk's avatar
hjk committed
850
    } else if (key == control('r')) {
851
        redo();
hjk's avatar
hjk committed
852
853
854
    } else if (key == 's') {
        m_submode = ChangeSubMode;
        m_tc.movePosition(Right, KeepAnchor, qMin(count(), rightDist()));
hjk's avatar
hjk committed
855
856
857
    } else if (key == 't' || key == 'T') {
        m_subsubmode = FtSubSubMode;
        m_subsubdata = key;
hjk's avatar
hjk committed
858
    } else if (key == 'u') {
859
        undo();
860
861
862
863
    } else if (key == 'U') {
        // FIXME: this is non-vim, but as Ctrl-R is taken globally
        // we have a substitute here
        redo();
864
865
    } else if (key == 'v') {
        enterVisualMode(VisualCharMode);
hjk's avatar
hjk committed
866
    } else if (key == 'V') {
867
868
869
        enterVisualMode(VisualLineMode);
    } else if (key == control('v')) {
        enterVisualMode(VisualBlockMode);
hjk's avatar
hjk committed
870
    } else if (key == 'w') {
hjk's avatar
hjk committed
871
        moveToNextWord(false);
hjk's avatar
hjk committed
872
        finishMovement("w");
hjk's avatar
hjk committed
873
    } else if (key == 'W') {
hjk's avatar
hjk committed
874
        moveToNextWord(true);
hjk's avatar
hjk committed
875
        finishMovement("W");
hjk's avatar
hjk committed
876
877
878
879
880
    } 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
881
        finishMovement("l");
hjk's avatar
hjk committed
882
883
884
885
886
887
    } else if (key == 'X') {
        if (leftDist() > 0) {
            m_tc.movePosition(Left, KeepAnchor, qMin(count(), leftDist()));
            m_tc.deleteChar();
        }
        finishMovement();
888
889
890
891
    } else if (key == 'y') {
        if (atEol())
            m_tc.movePosition(Left, MoveAnchor, 1);
        m_submode = YankSubMode;
hjk's avatar
hjk committed
892
893
    } else if (key == 'z') {
        m_submode = ZSubMode;
hjk's avatar
hjk committed
894
    } else if (key == '~' && !atEol()) {
hjk's avatar
hjk committed
895
896
897
898
899
900
901
902
        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
903
904
905
906
907
908
    } 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
909
    } else if (key == Key_Backspace || key == control('h')) {
hjk's avatar
hjk committed
910
        m_tc.deletePreviousChar();
911
912
    } else if (key == Key_Delete) {
        m_tc.deleteChar();
hjk's avatar
hjk committed
913
    } else if (key == Key_Escape) {
914
915
        if (m_visualMode != NoVisualMode)
            leaveVisualMode();
hjk's avatar
hjk committed
916
    } else {
hjk's avatar
hjk committed
917
        qDebug() << "Ignored in command mode: " << key << text;
918
919
        if (text.isEmpty())
            handled = false;
hjk's avatar