fakevimhandler.cpp 121 KB
Newer Older
1
/**************************************************************************
hjk's avatar
hjk committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
hjk's avatar
hjk committed
8
**
9
** Commercial Usage
hjk's avatar
hjk committed
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
hjk's avatar
hjk committed
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
hjk's avatar
hjk committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

30
#include "fakevimhandler.h"
hjk's avatar
hjk committed
31

32
//
33
34
35
36
37
38
39
40
41
42
43
// ATTENTION:
//
// 1 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.
//
// 2 There are a few auto tests located in ../../../tests/auto/fakevim.
//   Commands that are covered there are marked as "// tested" below.
//
// 3 Some conventions:
44
//
45
46
47
//   Use 1 based line numbers and 0 based column numbers. Even though
//   the 1 based line are not nice it matches vim's and QTextEdit's 'line'
//   concepts.
48
//
49
50
51
//   Do not pass QTextCursor etc around unless really needed. Convert
//   early to  line/column.
//
52
53
54
55
//   A QTextCursor is always between characters, whereas vi's cursor is always
//   over a character. FakeVim interprets the QTextCursor to be over the character
//   to the right of the QTextCursor's position().
//
56
//   There is always a "current" cursor (m_tc). A current "region of interest"
57
58
59
//   spans between m_anchor (== anchor()), i.e. the character below anchor()), and
//   m_tc.position() (== position()). The character below position() is not included
//   if the last movement command was exclusive (MoveExclusive).
60
//   The value of m_tc.anchor() is not used.
61

hjk's avatar
hjk committed
62
#include <utils/qtcassert.h>
63

hjk's avatar
hjk committed
64
#include <QtCore/QDebug>
65
#include <QtCore/QFile>
hjk's avatar
hjk committed
66
#include <QtCore/QObject>
67
#include <QtCore/QPointer>
hjk's avatar
hjk committed
68
#include <QtCore/QProcess>
hjk's avatar
hjk committed
69
#include <QtCore/QRegExp>
70
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
71
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
72
73
#include <QtCore/QStack>

hjk's avatar
hjk committed
74
#include <QtGui/QApplication>
hjk's avatar
hjk committed
75
76
77
78
79
80
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
81
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
82
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
83

84
#include <algorithm>
85
#include <climits>
86
#include <ctype.h>
87

88
89
90
91
92
93
94
//#define DEBUG_KEY  1
#if DEBUG_KEY
#   define KEY_DEBUG(s) qDebug() << s
#else
#   define KEY_DEBUG(s)
#endif

95
96
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
97
#   define UNDO_DEBUG(s) qDebug() << << m_tc.document()->availableUndoSteps() << s
98
99
100
101
#else
#   define UNDO_DEBUG(s)
#endif

102
using namespace Utils;
hjk's avatar
hjk committed
103
104
105
106

namespace FakeVim {
namespace Internal {

hjk's avatar
hjk committed
107
108
109
110
111
112
///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
113
114
115
116
117
118
119
120
121
122
#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
#define StartOfDocument QTextCursor::Start
hjk's avatar
hjk committed
123

124
125
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
126
127
128
129
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

130

hjk's avatar
hjk committed
131
132
133
134
enum Mode
{
    InsertMode,
    CommandMode,
135
136
137
    ExMode,
    SearchForwardMode,
    SearchBackwardMode,
hjk's avatar
hjk committed
138
};
hjk's avatar
hjk committed
139

hjk's avatar
hjk committed
140
141
142
enum SubMode
{
    NoSubMode,
143
144
145
    ChangeSubMode,     // used for c
    DeleteSubMode,     // used for d
    FilterSubMode,     // used for !
hjk's avatar
hjk committed
146
147
    IndentSubMode,     // used for =
    RegisterSubMode,   // used for "
hjk's avatar
hjk committed
148
    ReplaceSubMode,    // used for R and r
149
150
    ShiftLeftSubMode,  // used for <
    ShiftRightSubMode, // used for >
151
    TransformSubMode,  // used for ~/gu/gU
hjk's avatar
hjk committed
152
153
    WindowSubMode,     // used for Ctrl-w
    YankSubMode,       // used for y
154
155
    ZSubMode,          // used for z
    CapitalZSubMode    // used for Z
hjk's avatar
hjk committed
156
};
hjk's avatar
hjk committed
157

hjk's avatar
hjk committed
158
159
enum SubSubMode
{
hjk's avatar
hjk committed
160
161
    // typically used for things that require one more data item
    // and are 'nested' behind a mode
hjk's avatar
hjk committed
162
    NoSubSubMode,
163
164
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
165
    BackTickSubSubMode, // used for `
hjk's avatar
hjk committed
166
    TickSubSubMode,     // used for '
167
168
169
    InvertCaseSubSubMode, // used for ~
    DownCaseSubSubMode, // used for gu
    UpCaseSubSubMode,   // used for gU
hjk's avatar
hjk committed
170
171
};

172
173
174
175
176
177
178
179
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

hjk's avatar
hjk committed
180
181
182
183
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
hjk's avatar
hjk committed
184
    MoveLineWise,
hjk's avatar
hjk committed
185
186
};

187
188
enum RangeMode
{
189
190
    RangeCharMode,  // v
    RangeLineMode,  // V
191
    RangeLineModeExclusive, // like above, but keep one newline when deleting
192
193
    RangeBlockMode, // Ctrl-v
    RangeBlockAndTailMode, // Ctrl-v for D and X
194
195
196
197
198
199
200
201
202
};

enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

203
struct Column
204
{
205
206
207
    Column(int p, int l) : physical(p), logical(l) {}
    int physical; // number of characters in the data
    int logical; // column on screen
208
209
};

210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
struct CursorPosition
{
    // for jump history
    CursorPosition() : position(-1), scrollLine(-1) {}
    CursorPosition(int pos, int line) : position(pos), scrollLine(line) {}
    int position; // Position in document
    int scrollLine; // First visible line
};

struct Register
{
    Register() : rangemode(RangeCharMode) {}
    Register(const QString &c, RangeMode m) : contents(c), rangemode(m) {}
    QString contents;
    RangeMode rangemode;
};

struct Range
{
    Range()
        : beginPos(-1), endPos(-1), rangemode(RangeCharMode)
    {}

    Range(int b, int e, RangeMode m = RangeCharMode)
        : beginPos(qMin(b, e)), endPos(qMax(b, e)), rangemode(m)
con's avatar
con committed
235
    {}
236

237
    QString toString() const
238
239
240
241
242
    {
        return QString("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
            .arg(rangemode);
    }

243
244
245
246
247
    int beginPos;
    int endPos;
    RangeMode rangemode;
};

248
249
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
250
    foreach (const QTextEdit::ExtraSelection &sel, sels)
251
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
252
253
    return ts;
}
254

hjk's avatar
hjk committed
255
QString quoteUnprintable(const QString &ba)
hjk's avatar
hjk committed
256
{
hjk's avatar
hjk committed
257
258
259
260
261
262
263
264
265
    QString res;
    for (int i = 0, n = ba.size(); i != n; ++i) {
        QChar c = ba.at(i);
        if (c.isPrint())
            res += c;
        else
            res += QString("\\x%1").arg(c.unicode(), 2, 16);
    }
    return res;
hjk's avatar
hjk committed
266
267
}

268
269
270
271
272
273
274
275
276
277
278
static bool startsWithWhitespace(const QString &str, int col)
{
    QTC_ASSERT(str.size() >= col, return false);
    for (int i = 0; i < col; ++i) {
        uint u = str.at(i).unicode();
        if (u != ' ' && u != '\t')
            return false;
    }
    return true;
}

279
280
281
282
283
inline QString msgE20MarkNotSet(const QString &text)
{
    return FakeVimHandler::tr("E20: Mark '%1' not set").arg(text);
}

hjk's avatar
hjk committed
284
285
286
class FakeVimHandler::Private
{
public:
287
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
288

289
290
    EventResult handleEvent(QKeyEvent *ev);
    bool wantsOverride(QKeyEvent *ev);
hjk's avatar
hjk committed
291
    void handleCommand(const QString &cmd); // sets m_tc + handleExCommand
292
    void handleExCommand(const QString &cmd);
293
    void fixMarks(int positionAction, int positionChange); //Updates marks positions by the difference in positionChange
hjk's avatar
hjk committed
294

295
    void installEventFilter();
296
    void passShortcuts(bool enable);
297
298
299
    void setupWidget();
    void restoreWidget();

300
    friend class FakeVimHandler;
hjk's avatar
hjk committed
301
302
303
304
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
305
306
307
308
309
    EventResult handleKey(int key, int unmodified, const QString &text);
    EventResult handleInsertMode(int key, int unmodified, const QString &text);
    EventResult handleCommandMode(int key, int unmodified, const QString &text);
    EventResult handleRegisterMode(int key, int unmodified, const QString &text);
    EventResult handleMiniBufferModes(int key, int unmodified, const QString &text);
310
311
    void finishMovement(const QString &dotCommand = QString());
    void finishMovement(const QString &dotCommand, int count);
312
    void resetCommandMode();
hjk's avatar
hjk committed
313
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
314
    void highlightMatches(const QString &needle);
315
    void stopIncrementalFind();
hjk's avatar
hjk committed
316

hjk's avatar
hjk committed
317
318
319
    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
320
321
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
322
323
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
324

hjk's avatar
hjk committed
325
    int lastPositionInDocument() const; // last valid pos in doc
326
327
    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
328
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
329
330
    QString lineContents(int line) const; // 1 based line
    void setLineContents(int line, const QString &contents) const; // 1 based line
hjk's avatar
hjk committed
331

hjk's avatar
hjk committed
332
333
    int linesOnScreen() const;
    int columnsOnScreen() const;
334
335
336
337
    int linesInDocument() const;

    // all zero-based counting
    int cursorLineOnScreen() const;
hjk's avatar
hjk committed
338
    int cursorLineInDocument() const;
339
340
341
    int physicalCursorColumnInDocument() const; // as stored in the data
    int logicalCursorColumnInDocument() const; // as visible on screen
    Column cursorColumnInDocument() const; // as visible on screen
342
    int firstVisibleLineInDocument() const;
hjk's avatar
hjk committed
343
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
344
345
    void scrollUp(int count);
    void scrollDown(int count) { scrollUp(-count); }
hjk's avatar
hjk committed
346

347
348
349
350
351
    CursorPosition cursorPosition() const
        { return CursorPosition(position(), firstVisibleLineInDocument()); }
    void setCursorPosition(const CursorPosition &p)
        { setPosition(p.position); scrollToLineInDocument(p.scrollLine); }

352
    // helper functions for indenting
353
    bool isElectricCharacter(QChar c) const;
354
355
    void indentSelectedText(QChar lastTyped = QChar());
    int indentText(const Range &range, QChar lastTyped = QChar());
hjk's avatar
hjk committed
356
357
    void shiftRegionLeft(int repeat = 1);
    void shiftRegionRight(int repeat = 1);
358

hjk's avatar
hjk committed
359
    void moveToFirstNonBlankOnLine();
360
    void moveToTargetColumn();
361
362
    void setTargetColumn() {
        m_targetColumn = leftDist();
363
        m_visualTargetColumn = m_targetColumn;
364
365
        //qDebug() << "TARGET: " << m_targetColumn;
    }
366
    void moveToNextWord(bool simple, bool deleteWord = false);
367
    void moveToMatchingParanthesis();
368
    void moveToWordBoundary(bool simple, bool forward, bool changeWord = false);
hjk's avatar
hjk committed
369
370

    // to reduce line noise
hjk's avatar
hjk committed
371
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
372
    void moveToStartOfLine();
hjk's avatar
hjk committed
373
    void moveToEndOfLine();
hjk's avatar
hjk committed
374
    void moveBehindEndOfLine();
hjk's avatar
hjk committed
375
376
    void moveUp(int n = 1) { moveDown(-n); }
    void moveDown(int n = 1); // { m_tc.movePosition(Down, MoveAnchor, n); }
hjk's avatar
hjk committed
377
378
    void moveRight(int n = 1) { m_tc.movePosition(Right, MoveAnchor, n); }
    void moveLeft(int n = 1) { m_tc.movePosition(Left, MoveAnchor, n); }
379
380
    void setAnchor() { if (!isVisualMode()) m_anchor = m_tc.position(); }
    void setAnchor(int position) { if (!isVisualMode()) m_anchor = position; }
381
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
382

383
    bool handleFfTt(int key);
hjk's avatar
hjk committed
384

hjk's avatar
hjk committed
385
    // helper function for handleExCommand. return 1 based line index.
hjk's avatar
hjk committed
386
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
387
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
388

389
    void enterInsertMode();
390
    void enterCommandMode();
391
    void enterExMode();
hjk's avatar
hjk committed
392
393
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
394
    void notImplementedYet();
395
396
    void updateMiniBuffer();
    void updateSelection();
397
    QWidget *editor() const;
398
399
    QChar characterAtCursor() const
        { return m_tc.document()->characterAt(m_tc.position()); }
hjk's avatar
hjk committed
400
    void beginEditBlock() { UNDO_DEBUG("BEGIN EDIT BLOCK"); m_tc.beginEditBlock(); }
401
    void beginEditBlock(int pos) { setUndoPosition(pos); beginEditBlock(); }
hjk's avatar
hjk committed
402
403
    void endEditBlock() { UNDO_DEBUG("END EDIT BLOCK"); m_tc.endEditBlock(); }
    void joinPreviousEditBlock() { UNDO_DEBUG("JOIN EDIT BLOCK"); m_tc.joinPreviousEditBlock(); }
404

405
406
407
    // this asks the layer above (e.g. the fake vim plugin or the
    // stand-alone test application to handle the command)
    void passUnknownExCommand(const QString &cmd);
408
409
410
    // this asks the layer above (e.g. the fake vim plugin or the
    // stand-alone test application to handle the set command)
    void passUnknownSetCommand(const QString &cmd);
411

412
413
414
415
416
    bool isVisualMode() const { return m_visualMode != NoVisualMode; }
    bool isNoVisualMode() const { return m_visualMode == NoVisualMode; }
    bool isVisualCharMode() const { return m_visualMode == VisualCharMode; }
    bool isVisualLineMode() const { return m_visualMode == VisualLineMode; }
    bool isVisualBlockMode() const { return m_visualMode == VisualBlockMode; }
hjk's avatar
hjk committed
417
    void updateEditor();
418

419
420
421
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
422
    bool m_wasReadOnly; // saves read-only state of document
423

hjk's avatar
hjk committed
424
425
    FakeVimHandler *q;
    Mode m_mode;
426
    bool m_passing; // let the core see the next event
hjk's avatar
hjk committed
427
    SubMode m_submode;
hjk's avatar
hjk committed
428
429
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
430
431
    QString m_input;
    QTextCursor m_tc;
432
    int m_oldPosition; // copy from last event to check for external changes
433
    int m_anchor;
434
    static QHash<int, Register> m_registers;
hjk's avatar
hjk committed
435
    int m_register;
hjk's avatar
hjk committed
436
437
    QString m_mvcount;
    QString m_opcount;
438
439
    MoveType m_movetype;
    RangeMode m_rangemode;
440
    int m_visualInsertCount;
hjk's avatar
hjk committed
441
442

    bool m_fakeEnd;
hjk's avatar
hjk committed
443
444
    bool m_anchorPastEnd;
    bool m_positionPastEnd; // '$' & 'l' in visual mode can move past eol
hjk's avatar
hjk committed
445

446
447
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
448
    int m_gflag;  // whether current command started with 'g'
449

hjk's avatar
hjk committed
450
    QString m_commandBuffer;
451
452
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
453

454
    bool m_lastSearchForward;
455
    bool m_findPending;
hjk's avatar
hjk committed
456
    QString m_lastInsertion;
hjk's avatar
hjk committed
457

hjk's avatar
hjk committed
458
459
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
460

hjk's avatar
hjk committed
461
462
    typedef void (FakeVimHandler::Private::*Transformation)(int, QTextCursor *);
    void transformText(const Range &range, Transformation transformation);
463

464
    void removeSelectedText(bool exclusive = false);
465
    void removeText(const Range &range);
466
467
468
469
470
471
472
473
474
475
    void removeTransform(int, QTextCursor *);

    void invertCaseSelectedText();
    void invertCaseTransform(int, QTextCursor *);

    void upCaseSelectedText();
    void upCaseTransform(int, QTextCursor *);

    void downCaseSelectedText();
    void downCaseTransform(int, QTextCursor *);
476
477
478
479
480
481
482
483

    QString selectedText() const { return text(Range(position(), anchor())); }
    QString text(const Range &range) const;

    void yankSelectedText();
    void yankText(const Range &range, int toregister = '"');

    void pasteText(bool afterCursor);
484

485
    // undo handling
486
487
    void undo();
    void redo();
488
    void setUndoPosition(int pos);
489
    QMap<int, int> m_undoCursorPosition; // revision -> position
490
    bool m_beginEditBlock;
491

hjk's avatar
hjk committed
492
    // extra data for '.'
hjk's avatar
hjk committed
493
    void replay(const QString &text, int count);
494
495
    void setDotCommand(const QString &cmd) { m_dotCommand = cmd; }
    void setDotCommand(const QString &cmd, int n) { m_dotCommand = cmd.arg(n); }
hjk's avatar
hjk committed
496
    QString m_dotCommand;
hjk's avatar
hjk committed
497
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
498

hjk's avatar
hjk committed
499
500
501
502
503
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
504
    // history for '/'
hjk's avatar
hjk committed
505
    QString lastSearchString() const;
506
    static QStringList m_searchHistory;
hjk's avatar
hjk committed
507
508
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
509
    // history for ':'
510
    static QStringList m_commandHistory;
hjk's avatar
hjk committed
511
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
512

hjk's avatar
hjk committed
513
    // visual line mode
514
515
516
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
517

518
519
    // marks as lines
    QHash<int, int> m_marks;
hjk's avatar
hjk committed
520
    QString m_oldNeedle;
521

hjk's avatar
hjk committed
522
    // vi style configuration
hjk's avatar
hjk committed
523
524
525
526
    QVariant config(int code) const { return theFakeVimSetting(code)->value(); }
    bool hasConfig(int code) const { return config(code).toBool(); }
    bool hasConfig(int code, const char *value) const // FIXME
        { return config(code).toString().contains(value); }
527

528
529
    int m_targetColumn; // -1 if past end of line
    int m_visualTargetColumn; // 'l' can move past eol in visual mode only
530

531
    int m_cursorWidth;
532

hjk's avatar
hjk committed
533
    // auto-indent
534
    QString tabExpand(int len) const;
535
    Column indentation(const QString &line) const;
hjk's avatar
hjk committed
536
537
538
539
    void insertAutomaticIndentation(bool goingDown);
    bool removeAutomaticIndentation(); // true if something removed
    // number of autoindented characters
    int m_justAutoIndented;
540
    void handleStartOfLine();
hjk's avatar
hjk committed
541

542
    void recordJump();
543
    void recordNewUndo();
544
545
    QVector<CursorPosition> m_jumpListUndo;
    QVector<CursorPosition> m_jumpListRedo;
hjk's avatar
hjk committed
546
547

    QList<QTextEdit::ExtraSelection> m_searchSelections;
hjk's avatar
hjk committed
548
549
};

550
551
QStringList FakeVimHandler::Private::m_searchHistory;
QStringList FakeVimHandler::Private::m_commandHistory;
552
QHash<int, Register> FakeVimHandler::Private::m_registers;
553

554
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
555
556
{
    q = parent;
557
558
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
hjk's avatar
hjk committed
559
560
    init();
}
561

hjk's avatar
hjk committed
562
563
void FakeVimHandler::Private::init()
{
hjk's avatar
hjk committed
564
    m_mode = CommandMode;
hjk's avatar
hjk committed
565
566
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
567
    m_passing = false;
568
    m_findPending = false;
hjk's avatar
hjk committed
569
    m_fakeEnd = false;
570
    m_positionPastEnd = m_anchorPastEnd = false;
571
    m_lastSearchForward = true;
hjk's avatar
hjk committed
572
    m_register = '"';
hjk's avatar
hjk committed
573
    m_gflag = false;
574
    m_visualMode = NoVisualMode;
575
    m_targetColumn = 0;
576
    m_visualTargetColumn = 0;
577
    m_movetype = MoveInclusive;
hjk's avatar
hjk committed
578
    m_anchor = 0;
579
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
580
    m_inReplay = false;
hjk's avatar
hjk committed
581
    m_justAutoIndented = 0;
582
    m_rangemode = RangeCharMode;
583
    m_beginEditBlock = true;
hjk's avatar
hjk committed
584
585
}

586
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
hjk's avatar
hjk committed
587
{
588
589
590
    const int key = ev->key();
    const int mods = ev->modifiers();
    KEY_DEBUG("SHORTCUT OVERRIDE" << key << "  PASSING: " << m_passing);
591

592
    if (key == Key_Escape) {
hjk's avatar
hjk committed
593
        // Not sure this feels good. People often hit Esc several times
594
595
596
        if (isNoVisualMode() && m_mode == CommandMode)
            return false;
        return true;
597
598
599
    }

    // We are interested in overriding  most Ctrl key combinations
600
601
602
    if (mods == Qt::ControlModifier
            && ((key >= Key_A && key <= Key_Z && key != Key_K)
                || key == Key_BracketLeft || key == Key_BracketRight)) {
con's avatar
con committed
603
        // Ctrl-K is special as it is the Core's default notion of Locator
604
605
606
607
608
        if (m_passing) {
            KEY_DEBUG(" PASSING CTRL KEY");
            // We get called twice on the same key
            //m_passing = false;
            return false;
609
        }
610
611
612
        KEY_DEBUG(" NOT PASSING CTRL KEY");
        //updateMiniBuffer();
        return true;
613
614
    }

615
616
617
618
619
620
621
622
623
624
    // Let other shortcuts trigger
    return false;
}

EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
{
    int key = ev->key();
    const int um = key; // keep unmodified key around
    const int mods = ev->modifiers();

hjk's avatar
hjk committed
625
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
626
627
628
629
630
631
632
            || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
    {
        KEY_DEBUG("PLAIN MODIFIER");
        return EventUnhandled;
    }

    if (m_passing) {
633
        passShortcuts(false);
634
635
636
637
638
639
640
641
642
643
        KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
        //if (key == ',') { // use ',,' to leave, too.
        //    qDebug() << "FINISHED...";
        //    return EventHandled;
        //}
        m_passing = false;
        updateMiniBuffer();
        KEY_DEBUG("   PASS TO CORE");
        return EventPassedToCore;
    }
hjk's avatar
hjk committed
644
645

    // Fake "End of line"
646
647
    m_tc = EDITOR(textCursor());

648
649
    // Position changed externally
    if (m_tc.position() != m_oldPosition) {
650
        setTargetColumn();
651
652
653
        if (m_mode == InsertMode) {
            int dist = m_tc.position() - m_oldPosition;
            // Try to compensate for code completion
654
            if (dist > 0 && dist <= physicalCursorColumnInDocument()) {
655
656
657
                Range range(m_oldPosition, m_tc.position());
                m_lastInsertion.append(text(range));
            }
658
659
660
        } else if (!isVisualMode()) {
            if (atEndOfLine())
                moveLeft();
661
662
        }
    }
663
664

    m_tc.setVisualNavigation(true);
con's avatar
con committed
665

hjk's avatar
hjk committed
666
    if (m_fakeEnd)
hjk's avatar
hjk committed
667
        moveRight();
hjk's avatar
hjk committed
668

669
    if ((mods & Qt::ControlModifier) != 0) {
670
        if (key >= Key_A && key <= Key_Z)
671
672
            key = shift(key); // make it lower case
        key = control(key);
673
    } else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
674
        key = shift(key);
675
    }
676

677
678
679
    QTC_ASSERT(!(m_mode != InsertMode && m_tc.atBlockEnd() && m_tc.block().length() > 1),
               qDebug() << "Cursor at EOL before key handler");

hjk's avatar
hjk committed
680
681
682
683
    //if (m_mode == InsertMode)
    //    joinPreviousEditBlock();
    //else
    //    beginEditBlock();
684
    EventResult result = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
685
    //endEditBlock();
hjk's avatar
hjk committed
686

687
688
689
690
    // the command might have destroyed the editor
    if (m_textedit || m_plaintextedit) {
        // We fake vi-style end-of-line behaviour
        m_fakeEnd = atEndOfLine() && m_mode == CommandMode && !isVisualBlockMode();
hjk's avatar
hjk committed
691

692
693
        QTC_ASSERT(!(m_mode != InsertMode && m_tc.atBlockEnd() && m_tc.block().length() > 1),
                   qDebug() << "Cursor at EOL after key handler");
694

695
696
        if (m_fakeEnd)
            moveLeft();
hjk's avatar
hjk committed
697

698
699
700
        EDITOR(setTextCursor(m_tc));
        m_oldPosition = m_tc.position();
    }
701
    return result;
hjk's avatar
hjk committed
702
703
}

704
705
706
void FakeVimHandler::Private::installEventFilter()
{
    EDITOR(installEventFilter(q));
hjk's avatar
hjk committed
707
    updateEditor();
708
709
}

710
711
712
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
713
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
714
715
716
717
718
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
719
    m_wasReadOnly = EDITOR(isReadOnly());
720
    //EDITOR(setReadOnly(true));
721

hjk's avatar
hjk committed
722
723
    updateEditor();

724
725
726
727
728
729
730
731
732
733
734
735
736
737
    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();
    }

738
    //showBlackMessage("vi emulation mode. Type :q to leave. Use , Ctrl-R to trigger run.");
739
740
741
    updateMiniBuffer();
}

hjk's avatar
hjk committed
742
743
744
745
746
747
void FakeVimHandler::Private::updateEditor()
{
    const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
    EDITOR(setTabStopWidth(charWidth * config(ConfigTabStop).toInt()));
}

748
749
750
751
void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
752
    //EDITOR(removeEventFilter(q));
753
    EDITOR(setReadOnly(m_wasReadOnly));
754
755
    EDITOR(setCursorWidth(m_cursorWidth));
    EDITOR(setOverwriteMode(false));
756

757
    if (isVisualLineMode()) {
758
759
760
761
762
763
        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));
764
    } else if (isVisualCharMode()) {
765
766
767
768
769
770
771
772
        m_tc = EDITOR(textCursor());
        m_tc.setPosition(m_marks['<'], MoveAnchor);
        m_tc.setPosition(m_marks['>'], KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    }

    m_visualMode = NoVisualMode;
    updateSelection();
773
774
}

775
776
EventResult FakeVimHandler::Private::handleKey(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
777
{
778
    setUndoPosition(m_tc.position());
hjk's avatar
hjk committed
779
    if (m_mode == InsertMode)
780
        return handleInsertMode(key, unmodified, text);
781
    if (m_mode == CommandMode)
782
        return handleCommandMode(key, unmodified, text);
783
    if (m_mode == ExMode || m_mode == SearchForwardMode
784
            || m_mode == SearchBackwardMode)
785
        return handleMiniBufferModes(key, unmodified, text);
786
    return EventUnhandled;
hjk's avatar
hjk committed
787
788
}

789
790
791
792
793
794
795
796
797
798
void FakeVimHandler::Private::stopIncrementalFind()
{
    if (m_findPending) {
        m_findPending = false;
        QTextCursor tc = EDITOR(textCursor());
        tc.setPosition(tc.selectionStart());
        EDITOR(setTextCursor(tc));
    }
}

799
800
801
802
803
804
void FakeVimHandler::Private::setUndoPosition(int pos)
{
    //qDebug() << " CURSOR POS: " << m_undoCursorPosition;
    m_undoCursorPosition[m_tc.document()->availableUndoSteps()] = pos;
}

hjk's avatar
hjk committed
805
806
void FakeVimHandler::Private::moveDown(int n)
{
hjk's avatar
hjk committed
807
808
809
810
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(Down, MoveAnchor, n);
#else
hjk's avatar
hjk committed
811
    const int col = m_tc.position() - m_tc.block().position();
812
813
814
    const int lastLine = m_tc.document()->lastBlock().blockNumber();
    const int targetLine = qMax(0, qMin(lastLine, m_tc.block().blockNumber() + n));
    const QTextBlock &block = m_tc.document()->findBlockByNumber(targetLine);
hjk's avatar
hjk committed
815
    const int pos = block.position();
816
    setPosition(pos + qMax(0, qMin(block.length() - 2, col)));
hjk's avatar
hjk committed
817
    moveToTargetColumn();
hjk's avatar
hjk committed
818
#endif
hjk's avatar
hjk committed
819
820
821
822
}

void FakeVimHandler::Private::moveToEndOfLine()
{
hjk's avatar
hjk committed
823
824
825
826
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(EndOfLine, MoveAnchor);
#else
hjk's avatar
hjk committed
827
    const QTextBlock &block = m_tc.block();
828
829
    const int pos = block.position() + block.length() - 2;
    setPosition(qMax(block.position(), pos));
hjk's avatar
hjk committed
830
#endif
hjk's avatar
hjk committed
831
832
}

hjk's avatar
hjk committed
833
834
835
void FakeVimHandler::Private::moveBehindEndOfLine()
{
    const QTextBlock &block = m_tc.block();
836
    int pos = qMin(block.position() + block.length() - 1, lastPositionInDocument());
hjk's avatar
hjk committed
837
838
839
    setPosition(pos);
}

840
841
842
843
844
845
846
847
848
849
850
void FakeVimHandler::Private::moveToStartOfLine()
{
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(StartOfLine, MoveAnchor);
#else
    const QTextBlock &block = m_tc.block();
    setPosition(block.position());
#endif
}

851
852
853
854
855
void FakeVimHandler::Private::finishMovement(const QString &dotCommand, int count)
{
    finishMovement(dotCommand.arg(count));
}

hjk's avatar
hjk committed
856
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
857
{
858
    //qDebug() << "ANCHOR: " << position() << anchor();
hjk's avatar
hjk committed
859
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
860
861
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
862
        setPosition(qMin(anchor(), position()));
863
        enterExMode();
hjk's avatar
hjk committed
864
        m_currentMessage.clear();
hjk's avatar
hjk committed
865
866
867
868
869
870
871
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

872
    if (isVisualMode())
873
874
        m_marks['>'] = m_tc.position();

875
876
877
878
879
880
    if (m_submode == ChangeSubMode
        || m_submode == DeleteSubMode
        || m_submode == YankSubMode
        || m_submode == TransformSubMode) {
        if (m_submode != YankSubMode)
            beginEditBlock();
881
        if (m_movetype == MoveLineWise)
882
883
884
885
886
887
888
889
890
891
892
893
894
            m_rangemode = (m_submode == ChangeSubMode)
                ? RangeLineModeExclusive
                : RangeLineMode;

        if (m_movetype == MoveInclusive) {
            if (anchor() <= position()) {
                if ( !m_tc.atBlockEnd())
                    moveRight(); // correction
            } else {
                m_anchor++;
            }
        }

895
896
897
898
899
900
901
902
903
        if (m_positionPastEnd) {
            moveBehindEndOfLine();
            moveRight();
        }

        if (m_anchorPastEnd) {
            m_anchor++;
        }

904
905
906
907
        if (m_submode != TransformSubMode) {
            yankSelectedText();
            if (m_movetype == MoveLineWise)
                m_registers[m_register].rangemode = RangeLineMode;
908
        }
909
910

        m_positionPastEnd = m_anchorPastEnd = false;
911
912
913
914
    }

    if (m_submode == ChangeSubMode) {
        removeSelectedText(true);
hjk's avatar
hjk committed
915
        if (!dotCommand.isEmpty())
916
            setDotCommand(QLatin1Char('c') + dotCommand);
917
918
919
        if (m_movetype == MoveLineWise) {
            insertAutomaticIndentation(true);
        }
920
        endEditBlock();
921
        enterInsertMode();
922
        m_beginEditBlock = false;