fakevimhandler.cpp 123 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
170
    ReplaceSubSubMode, // used for r after visual mode
hjk's avatar
hjk committed
171
172
};

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

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

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

enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

204
struct Column
205
{
206
207
208
    Column(int p, int l) : physical(p), logical(l) {}
    int physical; // number of characters in the data
    int logical; // column on screen
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
235
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
236
    {}
237

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

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

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

hjk's avatar
hjk committed
256
QString quoteUnprintable(const QString &ba)
hjk's avatar
hjk committed
257
{
hjk's avatar
hjk committed
258
259
260
261
262
263
264
265
266
    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
267
268
}

269
270
271
272
273
274
275
276
277
278
279
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;
}

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

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

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

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

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

    void init();
306
307
308
309
310
    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);
311
312
    void finishMovement(const QString &dotCommand = QString());
    void finishMovement(const QString &dotCommand, int count);
313
    void resetCommandMode();
hjk's avatar
hjk committed
314
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
315
    void highlightMatches(const QString &needle);
316
    void stopIncrementalFind();
hjk's avatar
hjk committed
317

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

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

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

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

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

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

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

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

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

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

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

406
407
408
    // 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);
409
410
411
    // 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);
412

413
414
415
416
417
    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
418
    void updateEditor();
419

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

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

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

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

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

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

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

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

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

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

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

    void downCaseSelectedText();
    void downCaseTransform(int, QTextCursor *);
477

478
479
480
481
    QChar m_replacingCharacter;
    void replaceSelectedText(); // replace each character with m_replacingCharacter
    void replaceTransform(int, QTextCursor *);

482
483
484
485
486
487
488
    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);
489

490
    // undo handling
491
492
    void undo();
    void redo();
493
    void setUndoPosition(int pos);
494
    QMap<int, int> m_undoCursorPosition; // revision -> position
495
    bool m_beginEditBlock;
496

hjk's avatar
hjk committed
497
    // extra data for '.'
hjk's avatar
hjk committed
498
    void replay(const QString &text, int count);
499
500
    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
501
    QString m_dotCommand;
hjk's avatar
hjk committed
502
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
503

hjk's avatar
hjk committed
504
505
506
507
508
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
509
    // history for '/'
hjk's avatar
hjk committed
510
    QString lastSearchString() const;
511
    static QStringList m_searchHistory;
hjk's avatar
hjk committed
512
513
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
514
    // history for ':'
515
    static QStringList m_commandHistory;
hjk's avatar
hjk committed
516
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
517

hjk's avatar
hjk committed
518
    // visual line mode
519
520
521
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
522

523
524
    // marks as lines
    QHash<int, int> m_marks;
hjk's avatar
hjk committed
525
    QString m_oldNeedle;
526

hjk's avatar
hjk committed
527
    // vi style configuration
hjk's avatar
hjk committed
528
529
530
531
    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); }
532

533
534
    int m_targetColumn; // -1 if past end of line
    int m_visualTargetColumn; // 'l' can move past eol in visual mode only
535

536
    int m_cursorWidth;
537

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

547
    void recordJump();
548
    void recordNewUndo();
549
550
    QVector<CursorPosition> m_jumpListUndo;
    QVector<CursorPosition> m_jumpListRedo;
hjk's avatar
hjk committed
551
552

    QList<QTextEdit::ExtraSelection> m_searchSelections;
hjk's avatar
hjk committed
553
554
};

555
556
QStringList FakeVimHandler::Private::m_searchHistory;
QStringList FakeVimHandler::Private::m_commandHistory;
557
QHash<int, Register> FakeVimHandler::Private::m_registers;
558

559
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
560
561
{
    q = parent;
562
563
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
hjk's avatar
hjk committed
564
565
    init();
}
566

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

591
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
hjk's avatar
hjk committed
592
{
593
594
595
    const int key = ev->key();
    const int mods = ev->modifiers();
    KEY_DEBUG("SHORTCUT OVERRIDE" << key << "  PASSING: " << m_passing);
596

597
    if (key == Key_Escape) {
hjk's avatar
hjk committed
598
        // Not sure this feels good. People often hit Esc several times
599
600
601
        if (isNoVisualMode() && m_mode == CommandMode)
            return false;
        return true;
602
603
604
    }

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

620
621
622
623
624
625
626
627
628
629
    // 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
630
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
631
632
633
634
635
636
637
            || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
    {
        KEY_DEBUG("PLAIN MODIFIER");
        return EventUnhandled;
    }

    if (m_passing) {
638
        passShortcuts(false);
639
640
641
642
643
644
645
646
647
648
        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
649
650

    // Fake "End of line"
651
652
    m_tc = EDITOR(textCursor());

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

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

hjk's avatar
hjk committed
671
    if (m_fakeEnd)
hjk's avatar
hjk committed
672
        moveRight();
hjk's avatar
hjk committed
673

674
    if ((mods & Qt::ControlModifier) != 0) {
675
        if (key >= Key_A && key <= Key_Z)
676
677
            key = shift(key); // make it lower case
        key = control(key);
678
    } else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
679
        key = shift(key);
680
    }
681

682
683
684
    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
685
686
687
688
    //if (m_mode == InsertMode)
    //    joinPreviousEditBlock();
    //else
    //    beginEditBlock();
689
    EventResult result = handleKey(key, um, ev->text());
hjk's avatar
hjk committed
690
    //endEditBlock();
hjk's avatar
hjk committed
691

692
693
694
695
    // 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
696

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

700
701
        if (m_fakeEnd)
            moveLeft();
hjk's avatar
hjk committed
702

703
704
705
        EDITOR(setTextCursor(m_tc));
        m_oldPosition = m_tc.position();
    }
706
    return result;
hjk's avatar
hjk committed
707
708
}

709
710
711
void FakeVimHandler::Private::installEventFilter()
{
    EDITOR(installEventFilter(q));
hjk's avatar
hjk committed
712
    updateEditor();
713
714
}

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

hjk's avatar
hjk committed
727
728
    updateEditor();

729
730
731
732
733
734
735
736
737
738
739
740
741
742
    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();
    }

743
    //showBlackMessage("vi emulation mode. Type :q to leave. Use , Ctrl-R to trigger run.");
744
745
746
    updateMiniBuffer();
}

hjk's avatar
hjk committed
747
748
749
750
751
752
void FakeVimHandler::Private::updateEditor()
{
    const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
    EDITOR(setTabStopWidth(charWidth * config(ConfigTabStop).toInt()));
}

753
754
755
756
void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
757
    //EDITOR(removeEventFilter(q));
758
    EDITOR(setReadOnly(m_wasReadOnly));
759
760
    EDITOR(setCursorWidth(m_cursorWidth));
    EDITOR(setOverwriteMode(false));
761

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

    m_visualMode = NoVisualMode;
    updateSelection();
778
779
}

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

794
795
796
797
798
799
800
801
802
803
void FakeVimHandler::Private::stopIncrementalFind()
{
    if (m_findPending) {
        m_findPending = false;
        QTextCursor tc = EDITOR(textCursor());
        tc.setPosition(tc.selectionStart());
        EDITOR(setTextCursor(tc));
    }
}

804
805
806
807
808
809
void FakeVimHandler::Private::setUndoPosition(int pos)
{
    //qDebug() << " CURSOR POS: " << m_undoCursorPosition;
    m_undoCursorPosition[m_tc.document()->availableUndoSteps()] = pos;
}

hjk's avatar
hjk committed
810
811
void FakeVimHandler::Private::moveDown(int n)
{
hjk's avatar
hjk committed
812
813
814
815
#if 0
    // does not work for "hidden" documents like in the autotests
    m_tc.movePosition(Down, MoveAnchor, n);
#else
hjk's avatar
hjk committed
816
    const int col = m_tc.position() - m_tc.block().position();
817
818
819
    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
820
    const int pos = block.position();
821
    setPosition(pos + qMax(0, qMin(block.length() - 2, col)));
hjk's avatar
hjk committed
822
    moveToTargetColumn();
hjk's avatar
hjk committed
823
#endif
hjk's avatar
hjk committed
824
825
826
827
}

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

hjk's avatar
hjk committed
838
839
840
void FakeVimHandler::Private::moveBehindEndOfLine()
{
    const QTextBlock &block = m_tc.block();
841
    int pos = qMin(block.position() + block.length() - 1, lastPositionInDocument());
hjk's avatar
hjk committed
842
843
844
    setPosition(pos);
}

845
846
847
848
849
850
851
852
853
854
855
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
}

856
857
858
859
860
void FakeVimHandler::Private::finishMovement(const QString &dotCommand, int count)
{
    finishMovement(dotCommand.arg(count));
}

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

877
    if (isVisualMode())
878
879
        m_marks['>'] = m_tc.position();

880
881
882
883
884
885
    if (m_submode == ChangeSubMode
        || m_submode == DeleteSubMode
        || m_submode == YankSubMode
        || m_submode == TransformSubMode) {
        if (m_submode != YankSubMode)
            beginEditBlock();
886
        if (m_movetype == MoveLineWise)
887
888
889
890
891
892
893
894
895
896
897
898
899
            m_rangemode = (m_submode == ChangeSubMode)
                ? RangeLineModeExclusive
                : RangeLineMode;

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

900
901
902
903
904
905
906
907
908
        if (m_positionPastEnd) {
            moveBehindEndOfLine();
            moveRight();
        }

        if (m_anchorPastEnd) {
            m_anchor++;
        }

909
910
911
912
        if (m_submode != TransformSubMode) {
            yankSelectedText();
            if (m_movetype == MoveLineWise)
                m_registers[m_register].rangemode = RangeLineMode;
913
        }
914
915

        m_positionPastEnd = m_anchorPastEnd = false;
916
917
918
919
    }

    if (m_submode == ChangeSubMode) {
        removeSelectedText(true);
hjk's avatar
hjk committed
920
        if (!dotCommand.isEmpty())
921
            setDotCommand(QLatin1Char('c') + dotCommand);
922
923
924
        if (m_movetype == MoveLineWise) {
            insertAutomaticIndentation(true);
        }
925
        endEditBlock();
926
        enterInsertMode();
Martin Aumüller's avatar