fakevimhandler.cpp 81.4 KB
Newer Older
1
/**************************************************************************
hjk's avatar
hjk committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
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
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
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
#include "fakevimconstants.h"

34
35
36
37
// 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.
hjk's avatar
hjk committed
38
39


40
41
42
43
44
45
46
47
48
49
50
51
52
// Some conventions:
//
// 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.
//
// Do not pass QTextCursor etc around unless really needed. Convert
// early to  line/column.
//
// There is always a "current" cursor (m_tc). A current "region of interest"
// spans between m_anchor (== anchor()) and  m_tc.position() (== position())
// The value of m_tc.anchor() is not used.

53

hjk's avatar
hjk committed
54
#include <QtCore/QDebug>
55
#include <QtCore/QFile>
hjk's avatar
hjk committed
56
#include <QtCore/QObject>
57
#include <QtCore/QPointer>
hjk's avatar
hjk committed
58
#include <QtCore/QProcess>
hjk's avatar
hjk committed
59
#include <QtCore/QRegExp>
60
#include <QtCore/QTextStream>
hjk's avatar
hjk committed
61
#include <QtCore/QtAlgorithms>
hjk's avatar
hjk committed
62
63
#include <QtCore/QStack>

hjk's avatar
hjk committed
64
#include <QtGui/QApplication>
hjk's avatar
hjk committed
65
66
67
68
69
70
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
hjk's avatar
hjk committed
71
#include <QtGui/QTextDocumentFragment>
hjk's avatar
hjk committed
72
#include <QtGui/QTextEdit>
hjk's avatar
hjk committed
73
74


75
76
77
78
79
80
81
//#define DEBUG_KEY  1
#if DEBUG_KEY
#   define KEY_DEBUG(s) qDebug() << s
#else
#   define KEY_DEBUG(s)
#endif

82
83
84
85
86
87
88
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
#   define UNDO_DEBUG(s) qDebug() << s
#else
#   define UNDO_DEBUG(s)
#endif

hjk's avatar
hjk committed
89
using namespace FakeVim::Internal;
90
using namespace FakeVim::Constants;
hjk's avatar
hjk committed
91

hjk's avatar
hjk committed
92
93
94
95
96
97
98

///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////

99
100
101
102
103
104
105
106
107
#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
108

109
110
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

hjk's avatar
hjk committed
111
112
113
114
const int ParagraphSeparator = 0x00002029;

using namespace Qt;

hjk's avatar
hjk committed
115
116
117
118
enum Mode
{
    InsertMode,
    CommandMode,
119
120
121
    ExMode,
    SearchForwardMode,
    SearchBackwardMode,
hjk's avatar
hjk committed
122
};
hjk's avatar
hjk committed
123

hjk's avatar
hjk committed
124
125
126
enum SubMode
{
    NoSubMode,
127
128
129
130
    RegisterSubMode,   // used for "
    ChangeSubMode,     // used for c
    DeleteSubMode,     // used for d
    FilterSubMode,     // used for !
hjk's avatar
hjk committed
131
    ReplaceSubMode,    // used for R and r
132
133
134
135
    YankSubMode,       // used for y
    ShiftLeftSubMode,  // used for <
    ShiftRightSubMode, // used for >
    IndentSubMode,     // used for =
136
    ZSubMode,
hjk's avatar
hjk committed
137
};
hjk's avatar
hjk committed
138

hjk's avatar
hjk committed
139
140
enum SubSubMode
{
hjk's avatar
hjk committed
141
142
    // typically used for things that require one more data item
    // and are 'nested' behind a mode
hjk's avatar
hjk committed
143
    NoSubSubMode,
144
145
    FtSubSubMode,       // used for f, F, t, T
    MarkSubSubMode,     // used for m
146
    BackTickSubSubMode, // used for `
hjk's avatar
hjk committed
147
    TickSubSubMode,     // used for '
hjk's avatar
hjk committed
148
149
};

150
151
152
153
154
155
156
157
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
    VisualBlockMode,
};

hjk's avatar
hjk committed
158
159
160
161
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
hjk's avatar
hjk committed
162
    MoveLineWise,
hjk's avatar
hjk committed
163
164
};

165
166
struct EditOperation
{
hjk's avatar
hjk committed
167
168
169
170
171
    EditOperation() : position(-1), itemCount(0) {}
    int position;
    int itemCount; // used to combine several operations
    QString from;
    QString to;
172
173
};

hjk's avatar
hjk committed
174
QDebug &operator<<(QDebug &ts, const EditOperation &op)
hjk's avatar
hjk committed
175
{
hjk's avatar
hjk committed
176
177
    if (op.itemCount > 0) {
        ts << "\n  EDIT BLOCK WITH " << op.itemCount << " ITEMS";
hjk's avatar
hjk committed
178
    } else {
hjk's avatar
hjk committed
179
        ts << "\n  EDIT AT " << op.position
hjk's avatar
hjk committed
180
           << "  FROM   " << op.from << "   TO    " << op.to;
hjk's avatar
hjk committed
181
182
183
184
    }
    return ts;
}

185
186
187
188
189
190
191
QDebug &operator<<(QDebug &ts, const QList<QTextEdit::ExtraSelection> &sels)
{
    foreach (QTextEdit::ExtraSelection sel, sels) 
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position(); 
    return ts;
}
        
hjk's avatar
hjk committed
192
193
194
195
196
197
int lineCount(const QString &text)
{
    //return text.count(QChar(ParagraphSeparator));
    return text.count(QChar('\n'));
}

198
199
200
201
202
203
204
enum EventResult
{
    EventHandled,
    EventUnhandled,
    EventPassedToCore
};

hjk's avatar
hjk committed
205
206
207
class FakeVimHandler::Private
{
public:
208
    Private(FakeVimHandler *parent, QWidget *widget);
hjk's avatar
hjk committed
209

210
211
    EventResult handleEvent(QKeyEvent *ev);
    bool wantsOverride(QKeyEvent *ev);
212
    void handleExCommand(const QString &cmd);
hjk's avatar
hjk committed
213

214
215
216
    void setupWidget();
    void restoreWidget();

217
private:
218
    friend class FakeVimHandler;
hjk's avatar
hjk committed
219
220
221
222
    static int shift(int key) { return key + 32; }
    static int control(int key) { return key + 256; }

    void init();
223
224
225
226
227
    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);
hjk's avatar
hjk committed
228
    void finishMovement(const QString &text = QString());
hjk's avatar
hjk committed
229
    void search(const QString &needle, bool forward);
hjk's avatar
hjk committed
230
    void highlightMatches(const QString &needle);
hjk's avatar
hjk committed
231

hjk's avatar
hjk committed
232
233
234
    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
235
236
    int leftDist() const { return m_tc.position() - m_tc.block().position(); }
    int rightDist() const { return m_tc.block().length() - leftDist() - 1; }
237
238
    bool atEndOfLine() const
        { return m_tc.atBlockEnd() && m_tc.block().length() > 1; }
hjk's avatar
hjk committed
239

hjk's avatar
hjk committed
240
    int lastPositionInDocument() const;
241
242
    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
243
    int lineForPosition(int pos) const;  // 1 based line, 0 based pos
hjk's avatar
hjk committed
244

hjk's avatar
hjk committed
245
246
247
248
249
250
    // all zero-based counting
    int cursorLineOnScreen() const;
    int linesOnScreen() const;
    int columnsOnScreen() const;
    int cursorLineInDocument() const;
    int cursorColumnInDocument() const;
hjk's avatar
hjk committed
251
    int linesInDocument() const;
hjk's avatar
hjk committed
252
    void scrollToLineInDocument(int line);
hjk's avatar
hjk committed
253
254
    void scrollUp(int count);
    void scrollDown(int count) { scrollUp(-count); }
hjk's avatar
hjk committed
255

256
    // helper functions for indenting
hjk's avatar
hjk committed
257
    bool isElectricCharacter(QChar c) const
258
        { return c == '{' || c == '}' || c == '#'; }
259
    int indentDist() const;
hjk's avatar
hjk committed
260
261
262
    void indentRegion(QChar lastTyped = QChar());
    void shiftRegionLeft(int repeat = 1);
    void shiftRegionRight(int repeat = 1);
263

hjk's avatar
hjk committed
264
    void moveToFirstNonBlankOnLine();
265
    void moveToDesiredColumn();
hjk's avatar
hjk committed
266
    void moveToNextWord(bool simple);
267
    void moveToMatchingParanthesis();
hjk's avatar
hjk committed
268
    void moveToWordBoundary(bool simple, bool forward);
hjk's avatar
hjk committed
269
270
271
272

    // to reduce line noise
    typedef QTextCursor::MoveOperation MoveOperation;
    typedef QTextCursor::MoveMode MoveMode;
hjk's avatar
hjk committed
273
274
275
276
277
278
279
    void moveToEndOfDocument() { m_tc.movePosition(EndOfDocument, MoveAnchor); }
    void moveToStartOfLine() { m_tc.movePosition(StartOfLine, MoveAnchor); }
    void moveToEndOfLine() { m_tc.movePosition(EndOfLine, MoveAnchor); }
    void moveUp(int n = 1) { m_tc.movePosition(Up, MoveAnchor, n); }
    void moveDown(int n = 1) { m_tc.movePosition(Down, MoveAnchor, n); }
    void moveRight(int n = 1) { m_tc.movePosition(Right, MoveAnchor, n); }
    void moveLeft(int n = 1) { m_tc.movePosition(Left, MoveAnchor, n); }
hjk's avatar
hjk committed
280
    void setAnchor() { m_anchor = m_tc.position(); }
281
282
    void setAnchor(int position) { m_anchor = position; }
    void setPosition(int position) { m_tc.setPosition(position, MoveAnchor); }
hjk's avatar
hjk committed
283

hjk's avatar
hjk committed
284
    void handleFfTt(int key);
hjk's avatar
hjk committed
285

hjk's avatar
hjk committed
286
287
    // helper function for handleCommand. return 1 based line index.
    int readLineCode(QString &cmd);
hjk's avatar
hjk committed
288
    void selectRange(int beginLine, int endLine);
hjk's avatar
hjk committed
289

290
    void enterInsertMode();
291
    void enterCommandMode();
292
    void enterExMode();
hjk's avatar
hjk committed
293
294
    void showRedMessage(const QString &msg);
    void showBlackMessage(const QString &msg);
295
    void notImplementedYet();
296
297
    void updateMiniBuffer();
    void updateSelection();
hjk's avatar
hjk committed
298
    void quit();
299
    QWidget *editor() const;
300
301
    QChar characterAtCursor() const
        { return m_tc.document()->characterAt(m_tc.position()); }
302

303
304
305
public:
    QTextEdit *m_textedit;
    QPlainTextEdit *m_plaintextedit;
306
    bool m_wasReadOnly; // saves read-only state of document
307

hjk's avatar
hjk committed
308
309
    FakeVimHandler *q;
    Mode m_mode;
310
    bool m_passing; // let the core see the next event
hjk's avatar
hjk committed
311
    SubMode m_submode;
hjk's avatar
hjk committed
312
313
    SubSubMode m_subsubmode;
    int m_subsubdata;
hjk's avatar
hjk committed
314
315
    QString m_input;
    QTextCursor m_tc;
hjk's avatar
hjk committed
316
    int m_anchor; 
hjk's avatar
hjk committed
317
318
    QHash<int, QString> m_registers;
    int m_register;
hjk's avatar
hjk committed
319
320
    QString m_mvcount;
    QString m_opcount;
hjk's avatar
hjk committed
321
    MoveType m_moveType;
hjk's avatar
hjk committed
322
323
324

    bool m_fakeEnd;

325
326
    bool isSearchMode() const
        { return m_mode == SearchForwardMode || m_mode == SearchBackwardMode; }
hjk's avatar
hjk committed
327
    int m_gflag;  // whether current command started with 'g'
328

hjk's avatar
hjk committed
329
    QString m_commandBuffer;
330
331
    QString m_currentFileName;
    QString m_currentMessage;
hjk's avatar
hjk committed
332

333
    bool m_lastSearchForward;
hjk's avatar
hjk committed
334
    QString m_lastInsertion;
hjk's avatar
hjk committed
335

336
    // undo handling
hjk's avatar
hjk committed
337
    void recordOperation(const EditOperation &op);
338
    void recordInsert(int position, const QString &data);
hjk's avatar
hjk committed
339
    void recordRemove(int position, const QString &data);
340
    void recordRemove(int position, int length);
hjk's avatar
hjk committed
341
342
343

    void recordRemoveNextChar();
    void recordInsertText(const QString &data);
hjk's avatar
hjk committed
344
    QString recordRemoveSelectedText();
345
    void recordPosition();
hjk's avatar
hjk committed
346
347
    void recordBeginGroup();
    void recordEndGroup();
hjk's avatar
hjk committed
348
349
    int anchor() const { return m_anchor; }
    int position() const { return m_tc.position(); }
350
351
    QString selectedText() const;

352
353
354
355
    void undo();
    void redo();
    QStack<EditOperation> m_undoStack;
    QStack<EditOperation> m_redoStack;
hjk's avatar
hjk committed
356
    QStack<int> m_undoGroupStack;
357
    QMap<int, int> m_undoCursorPosition;
358

hjk's avatar
hjk committed
359
360
    // extra data for '.'
    QString m_dotCommand;
hjk's avatar
hjk committed
361
    bool m_inReplay; // true if we are executing a '.'
hjk's avatar
hjk committed
362

hjk's avatar
hjk committed
363
364
365
366
367
    // extra data for ';'
    QString m_semicolonCount;
    int m_semicolonType;  // 'f', 'F', 't', 'T'
    int m_semicolonKey;

hjk's avatar
hjk committed
368
    // history for '/'
hjk's avatar
hjk committed
369
370
371
372
    QString lastSearchString() const;
    QStringList m_searchHistory;
    int m_searchHistoryIndex;

hjk's avatar
hjk committed
373
    // history for ':'
hjk's avatar
hjk committed
374
375
    QStringList m_commandHistory;
    int m_commandHistoryIndex;
hjk's avatar
hjk committed
376

hjk's avatar
hjk committed
377
    // visual line mode
378
379
380
    void enterVisualMode(VisualMode visualMode);
    void leaveVisualMode();
    VisualMode m_visualMode;
hjk's avatar
hjk committed
381

382
383
    // marks as lines
    QHash<int, int> m_marks;
hjk's avatar
hjk committed
384
    QString m_oldNeedle;
385

hjk's avatar
hjk committed
386
387
    // vi style configuration
    QHash<QString, QString> m_config;
388
389
390
391
    bool hasConfig(const char *name) const
        { return m_config[name] == ConfigOn; }
    bool hasConfig(const char *name, const char *value) const
        { return m_config[name].contains(value); } // FIXME
392
393

    // for restoring cursor position
hjk's avatar
hjk committed
394
    int m_savedYankPosition;
395
    int m_desiredColumn;
396
397

    QPointer<QObject> m_extraData;
398
    int m_cursorWidth;
399
400
401
402

    void recordJump();
    QList<int> m_jumpListUndo;
    QList<int> m_jumpListRedo;
hjk's avatar
hjk committed
403
404

    QList<QTextEdit::ExtraSelection> m_searchSelections;
hjk's avatar
hjk committed
405
406
};

407
FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
hjk's avatar
hjk committed
408
409
{
    q = parent;
hjk's avatar
hjk committed
410

411
412
413
    m_textedit = qobject_cast<QTextEdit *>(widget);
    m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);

hjk's avatar
hjk committed
414
    m_mode = CommandMode;
hjk's avatar
hjk committed
415
416
    m_submode = NoSubMode;
    m_subsubmode = NoSubSubMode;
417
    m_passing = false;
hjk's avatar
hjk committed
418
    m_fakeEnd = false;
419
    m_lastSearchForward = true;
hjk's avatar
hjk committed
420
    m_register = '"';
hjk's avatar
hjk committed
421
    m_gflag = false;
422
    m_visualMode = NoVisualMode;
423
    m_desiredColumn = 0;
hjk's avatar
hjk committed
424
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
425
426
    m_anchor = 0;
    m_savedYankPosition = 0;
427
    m_cursorWidth = EDITOR(cursorWidth());
hjk's avatar
hjk committed
428
    m_inReplay = false;
hjk's avatar
hjk committed
429

hjk's avatar
hjk committed
430
#if 0
431
    // Plain
hjk's avatar
hjk committed
432
    m_config[ConfigStartOfLine] = ConfigOn;
hjk's avatar
hjk committed
433
    m_config[ConfigHlSearch]    = ConfigOn;
434
    m_config[ConfigTabStop]     = "8";
435
    m_config[ConfigSmartTab]    = ConfigOff;
436
    m_config[ConfigShiftWidth]  = "8";
437
    m_config[ConfigExpandTab]   = ConfigOff;
438
    m_config[ConfigAutoIndent]  = ConfigOff;
439
440
441
442
443
444
445
446
447
448
    m_config[ConfigBackspace]   = "";
#else
    // Qt Local
    m_config[ConfigStartOfLine] = ConfigOn;
    m_config[ConfigHlSearch]    = ConfigOn;
    m_config[ConfigTabStop]     = "4";
    m_config[ConfigSmartTab]    = ConfigOff;
    m_config[ConfigShiftWidth]  = "4";
    m_config[ConfigExpandTab]   = ConfigOn;
    m_config[ConfigAutoIndent]  = ConfigOff;
449
    m_config[ConfigBackspace]   = "indent,eol,start";
450
#endif
hjk's avatar
hjk committed
451
452
}

453
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
hjk's avatar
hjk committed
454
{
455
456
457
    const int key = ev->key();
    const int mods = ev->modifiers();
    KEY_DEBUG("SHORTCUT OVERRIDE" << key << "  PASSING: " << m_passing);
458

459
    if (key == Key_Escape) {
hjk's avatar
hjk committed
460
        // Not sure this feels good. People often hit Esc several times
461
462
463
464
465
466
467
468
469
470
471
472
473
        if (m_visualMode == NoVisualMode && m_mode == CommandMode)
            return false;
        return true;
    }

    // We are interested in overriding  most Ctrl key combinations
    if (mods == Qt::ControlModifier && key >= Key_A && key <= Key_Z && key != Key_K) {
        // Ctrl-K is special as it is the Core's default notion of QuickOpen
        if (m_passing) {
            KEY_DEBUG(" PASSING CTRL KEY");
            // We get called twice on the same key
            //m_passing = false;
            return false;
474
        }
475
476
477
        KEY_DEBUG(" NOT PASSING CTRL KEY");
        //updateMiniBuffer();
        return true;
478
479
    }

480
481
482
483
484
485
486
487
488
489
    // 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
490
    if (key == Key_Shift || key == Key_Alt || key == Key_Control
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
            || key == Key_Alt || key == Key_AltGr || key == Key_Meta)
    {
        KEY_DEBUG("PLAIN MODIFIER");
        return EventUnhandled;
    }

    if (m_passing) {
        KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
        //if (key == ',') { // use ',,' to leave, too.
        //    qDebug() << "FINISHED...";
        //    quit();
        //    return EventHandled;
        //}
        m_passing = false;
        updateMiniBuffer();
        KEY_DEBUG("   PASS TO CORE");
        return EventPassedToCore;
    }
hjk's avatar
hjk committed
509
510

    // Fake "End of line"
511
    m_tc = EDITOR(textCursor());
512
    m_tc.setVisualNavigation(true);
513

hjk's avatar
hjk committed
514
    if (m_fakeEnd)
hjk's avatar
hjk committed
515
        moveRight();
hjk's avatar
hjk committed
516

517
    if ((mods & Qt::ControlModifier) != 0) {
hjk's avatar
hjk committed
518
        key += 256;
519
        key += 32; // make it lower case
520
    } else if (key >= Key_A && key <= Key_Z && (mods & Qt::ShiftModifier) == 0) {
521
522
        key += 32;
    }
523
524
525
526
527
528

    m_undoCursorPosition[EDITOR(document())->revision()] = m_tc.position();
    if (m_mode == InsertMode)
        m_tc.joinPreviousEditBlock();
    else
        m_tc.beginEditBlock();
529
    EventResult result = handleKey(key, um, ev->text());
530
    m_tc.endEditBlock();
hjk's avatar
hjk committed
531
532

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

hjk's avatar
hjk committed
535
    if (m_fakeEnd)
hjk's avatar
hjk committed
536
        moveLeft();
hjk's avatar
hjk committed
537

538
    EDITOR(setTextCursor(m_tc));
hjk's avatar
hjk committed
539
    //EDITOR(ensureCursorVisible());
540
    return result;
hjk's avatar
hjk committed
541
542
}

543
544
545
void FakeVimHandler::Private::setupWidget()
{
    enterCommandMode();
546
547
    EDITOR(installEventFilter(q));
    //EDITOR(setCursorWidth(QFontMetrics(ed->font()).width(QChar('x')));
548
549
550
551
552
    if (m_textedit) {
        m_textedit->setLineWrapMode(QTextEdit::NoWrap);
    } else if (m_plaintextedit) {
        m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
553
    m_wasReadOnly = EDITOR(isReadOnly());
554
    //EDITOR(setReadOnly(true)); 
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

    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();
    }

570
571
572
573
574
575
576
577
    showBlackMessage("vi emulation mode.");
    updateMiniBuffer();
}

void FakeVimHandler::Private::restoreWidget()
{
    //showBlackMessage(QString());
    //updateMiniBuffer();
578
579
    EDITOR(removeEventFilter(q));
    EDITOR(setReadOnly(m_wasReadOnly));
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
    
    if (m_visualMode == VisualLineMode) {
        m_tc = EDITOR(textCursor());
        int beginLine = lineForPosition(m_marks['<']);
        int endLine = lineForPosition(m_marks['>']);
        m_tc.setPosition(firstPositionInLine(beginLine), MoveAnchor);
        m_tc.setPosition(lastPositionInLine(endLine), KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    } else if (m_visualMode == VisualCharMode) {
        m_tc = EDITOR(textCursor());
        m_tc.setPosition(m_marks['<'], MoveAnchor);
        m_tc.setPosition(m_marks['>'], KeepAnchor);
        EDITOR(setTextCursor(m_tc));
    }

    m_visualMode = NoVisualMode;
    updateSelection();
597
598
}

599
600
EventResult FakeVimHandler::Private::handleKey(int key, int unmodified,
    const QString &text)
hjk's avatar
hjk committed
601
{
602
603
    //qDebug() << "KEY: " << key << text << "POS: " << m_tc.position();
    //qDebug() << "\nUNDO: " << m_undoStack << "\nREDO: " << m_redoStack;
hjk's avatar
hjk committed
604
    if (m_mode == InsertMode)
605
        return handleInsertMode(key, unmodified, text);
606
    if (m_mode == CommandMode)
607
        return handleCommandMode(key, unmodified, text);
608
    if (m_mode == ExMode || m_mode == SearchForwardMode
609
            || m_mode == SearchBackwardMode)
610
        return handleMiniBufferModes(key, unmodified, text);
611
    return EventUnhandled;
hjk's avatar
hjk committed
612
613
}

hjk's avatar
hjk committed
614
void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
hjk's avatar
hjk committed
615
{
616
    //qDebug() << "ANCHOR: " << m_anchor;
hjk's avatar
hjk committed
617
    if (m_submode == FilterSubMode) {
hjk's avatar
hjk committed
618
619
        int beginLine = lineForPosition(anchor());
        int endLine = lineForPosition(position());
620
        setPosition(qMin(anchor(), position()));
621
        enterExMode();
hjk's avatar
hjk committed
622
623
624
625
626
627
628
        m_commandBuffer = QString(".,+%1!").arg(qAbs(endLine - beginLine));
        m_commandHistory.append(QString());
        m_commandHistoryIndex = m_commandHistory.size() - 1;
        updateMiniBuffer();
        return;
    }

629
630
631
    if (m_visualMode != NoVisualMode)
        m_marks['>'] = m_tc.position();

hjk's avatar
hjk committed
632
    if (m_submode == ChangeSubMode) {
633
634
        if (m_moveType == MoveInclusive)
            moveRight(); // correction
635
636
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
637
638
        if (!dotCommand.isEmpty())
            m_dotCommand = "c" + dotCommand;
hjk's avatar
hjk committed
639
        QString text = recordRemoveSelectedText();
640
        //qDebug() << "CHANGING TO INSERT MODE" << text;
hjk's avatar
hjk committed
641
        m_registers[m_register] = text;
hjk's avatar
hjk committed
642
643
644
        m_mode = InsertMode;
        m_submode = NoSubMode;
    } else if (m_submode == DeleteSubMode) {
645
        if (m_moveType == MoveInclusive)
646
            moveRight(); // correction
647
648
        if (anchor() >= position())
           m_anchor++;
hjk's avatar
hjk committed
649
650
        if (!dotCommand.isEmpty())
            m_dotCommand = "d" + dotCommand;
hjk's avatar
hjk committed
651
652
        m_registers[m_register] = recordRemoveSelectedText();
        recordEndGroup();
hjk's avatar
hjk committed
653
        m_submode = NoSubMode;
654
        if (atEndOfLine())
hjk's avatar
hjk committed
655
            moveLeft();
656
    } else if (m_submode == YankSubMode) {
hjk's avatar
hjk committed
657
        m_registers[m_register] = selectedText();
658
        setPosition(m_savedYankPosition);
659
        m_submode = NoSubMode;
660
661
    } else if (m_submode == ReplaceSubMode) {
        m_submode = NoSubMode;
662
    } else if (m_submode == IndentSubMode) {
hjk's avatar
hjk committed
663
        indentRegion();
664
        m_submode = NoSubMode;
665
    } else if (m_submode == ShiftRightSubMode) {
666
        shiftRegionRight(1);
667
668
669
        m_submode = NoSubMode;
        updateMiniBuffer();
    } else if (m_submode == ShiftLeftSubMode) {
670
        shiftRegionLeft(1);
671
672
        m_submode = NoSubMode;
        updateMiniBuffer();
hjk's avatar
hjk committed
673
    }
674

hjk's avatar
hjk committed
675
    m_moveType = MoveInclusive;
hjk's avatar
hjk committed
676
677
    m_mvcount.clear();
    m_opcount.clear();
hjk's avatar
hjk committed
678
    m_gflag = false;
hjk's avatar
hjk committed
679
680
    m_register = '"';
    m_tc.clearSelection();
681
682

    updateSelection();
hjk's avatar
hjk committed
683
    updateMiniBuffer();
684
    m_desiredColumn = leftDist();
hjk's avatar
hjk committed
685
686
}

687
688
void FakeVimHandler::Private::updateSelection()
{
hjk's avatar
hjk committed
689
    QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
690
691
692
693
    if (m_visualMode != NoVisualMode) {
        QTextEdit::ExtraSelection sel;
        sel.cursor = m_tc;
        sel.format = m_tc.blockCharFormat();
694
695
696
697
#if 0
        sel.format.setFontWeight(QFont::Bold);
        sel.format.setFontUnderline(true);
#else
hjk's avatar
hjk committed
698
699
        sel.format.setForeground(Qt::white);
        sel.format.setBackground(Qt::black);
700
#endif
701
702
703
        int cursorPos = m_tc.position();
        int anchorPos = m_marks['<'];
        //qDebug() << "POS: " << cursorPos << " ANCHOR: " << anchorPos;
704
        if (m_visualMode == VisualCharMode) {
705
            sel.cursor.setPosition(anchorPos, KeepAnchor);
706
707
            selections.append(sel);
        } else if (m_visualMode == VisualLineMode) {
708
            sel.cursor.setPosition(qMin(cursorPos, anchorPos), MoveAnchor);
709
            sel.cursor.movePosition(StartOfLine, MoveAnchor);
710
            sel.cursor.setPosition(qMax(cursorPos, anchorPos), KeepAnchor);
711
712
713
            sel.cursor.movePosition(EndOfLine, KeepAnchor);
            selections.append(sel);
        } else if (m_visualMode == VisualBlockMode) {
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
            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);
            }
735
736
        }
    }
737
    //qDebug() << "SELECTION: " << selections;
738
    emit q->selectionChanged(selections);
739
740
}

hjk's avatar
hjk committed
741
void FakeVimHandler::Private::updateMiniBuffer()
hjk's avatar
hjk committed
742
{
hjk's avatar
hjk committed
743
    QString msg;
744
745
    if (m_passing) {
        msg = "-- PASSING --  ";
746
    } else if (!m_currentMessage.isEmpty()) {
hjk's avatar
hjk committed
747
748
        msg = m_currentMessage;
        m_currentMessage.clear();
hjk's avatar
hjk committed
749
750
751
752
753
754
755
756
    } 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 --";
        }
757
758
    } else if (m_mode == InsertMode) {
        msg = "-- INSERT --";
hjk's avatar
hjk committed
759
    } else {
760
        if (m_mode == SearchForwardMode)
761
            msg += '/';
762
        else if (m_mode == SearchBackwardMode)
763
            msg += '?';
764
        else if (m_mode == ExMode)
765
            msg += ':';
hjk's avatar
hjk committed
766
        foreach (QChar c, m_commandBuffer) {
767
768
769
770
771
772
            if (c.unicode() < 32) {
                msg += '^';
                msg += QChar(c.unicode() + 64);
            } else {
                msg += c;
            }
hjk's avatar
hjk committed
773
        }
hjk's avatar
hjk committed
774
        if (!msg.isEmpty() && m_mode != CommandMode)
hjk's avatar
hjk committed
775
            msg += QChar(10073); // '|'; // FIXME: Use a real "cursor"
hjk's avatar
hjk committed
776
    }
777

hjk's avatar
hjk committed
778
779
780
781
782
    emit q->commandBufferChanged(msg);

    int linesInDoc = linesInDocument();
    int l = cursorLineInDocument();
    QString status;
hjk's avatar
hjk committed
783
    QString pos = tr("%1,%2").arg(l + 1).arg(cursorColumnInDocument() + 1);
hjk's avatar
hjk committed
784
    status += tr("%1").arg(pos, -10);
hjk's avatar
hjk committed
785
    // FIXME: physical "-" logical
hjk's avatar
hjk committed
786
    if (linesInDoc != 0) {
hjk's avatar
hjk committed
787
788
        status += tr("%1").arg(l * 100 / linesInDoc, 4);
        status += "%";
hjk's avatar
hjk committed
789
    } else {
hjk's avatar
hjk committed
790
        status += "All";
hjk's avatar
hjk committed
791
    }
hjk's avatar
hjk committed
792
    emit q->statusDataChanged(status);
hjk's avatar
hjk committed
793
794
}

hjk's avatar
hjk committed
795
void FakeVimHandler::Private::showRedMessage(const QString &msg)
hjk's avatar
hjk committed
796
{
797
798
    //qDebug() << "MSG: " << msg;
    m_currentMessage = msg;
hjk's avatar
hjk committed
799
    updateMiniBuffer();
hjk's avatar
hjk committed
800
801
}

hjk's avatar
hjk committed
802
803
804
805
806
807
808
void FakeVimHandler::Private::showBlackMessage(const QString &msg)
{
    //qDebug() << "MSG: " << msg;
    m_commandBuffer = msg;
    updateMiniBuffer();
}

809
810
void FakeVimHandler::Private::notImplementedYet()
{
hjk's avatar
hjk committed
811
    qDebug() << "Not implemented in FakeVim";
812
813
814
815
    showRedMessage("Not implemented in FakeVim");
    updateMiniBuffer();
}

816
EventResult FakeVimHandler::Private::handleCommandMode(int key, int unmodified,
817
    const QString &text)
hjk's avatar
hjk committed
818
{
819
    EventResult handled = EventHandled;
820

hjk's avatar
hjk committed
821
822
823
824
    if (m_submode == RegisterSubMode) {
        m_register = key;
        m_submode = NoSubMode;
    } else if (m_submode == ChangeSubMode && key == 'c') {
hjk's avatar
hjk committed
825
826
827
        moveToStartOfLine();
        setAnchor();
        moveDown(count());
828
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
829
        finishMovement("c");
hjk's avatar
hjk committed
830
    } else if (m_submode == DeleteSubMode && key == 'd') {
hjk's avatar
hjk committed
831
        moveToStartOfLine();
hjk's avatar
hjk committed
832
        setAnchor();
hjk's avatar
hjk committed
833
        moveDown(count());
834
        m_moveType = MoveLineWise;
hjk's avatar
hjk committed
835
        finishMovement("d");
836
    } else if (m_submode == YankSubMode && key == 'y') {
hjk's avatar
hjk committed
837
        moveToStartOfLine();
hjk's avatar
hjk committed
838
        setAnchor();
hjk's avatar
hjk committed
839
        moveDown(count());
hjk's avatar
hjk committed
840
841
        m_moveType = MoveLineWise;
        finishMovement("y");
842
843
844
845
846
847
848
849
850
851
852
853
    } else if (m_submode == ShiftLeftSubMode && key == '<') {
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1<<").arg(count());
        finishMovement();
    } else if (m_submode == ShiftRightSubMode && key == '>') {
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1>>").arg(count());
        finishMovement();
854
    } else if (m_submode == IndentSubMode && key == '=') {
hjk's avatar
hjk committed
855
856
857
858
        setAnchor();
        moveDown(count() - 1);
        m_moveType = MoveLineWise;
        m_dotCommand = QString("%1>>").arg(count());
859
        finishMovement();
hjk's avatar
hjk committed
860
    } else if (m_submode == ZSubMode) {
hjk's avatar
hjk committed
861
862
863
        //qDebug() << "Z_MODE " << cursorLineInDocument() << linesOnScreen();
        if (key == Key_Return || key == 't') { // cursor line to top of window
            if (!m_mvcount.isEmpty())
864
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
865
            scrollUp(- cursorLineOnScreen());
hjk's avatar
hjk committed
866
867
            if (key == Key_Return)
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
868
            finishMovement();
hjk's avatar
hjk committed
869
870
        } else if (key == '.' || key == 'z') { // cursor line to center of window
            if (!m_mvcount.isEmpty())
871
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
872
            scrollUp(linesOnScreen() / 2 - cursorLineOnScreen());
hjk's avatar
hjk committed
873
874
            if (key == '.')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
875
            finishMovement();
hjk's avatar
hjk committed
876
877
        } else if (key == '-' || key == 'b') { // cursor line to bottom of window
            if (!m_mvcount.isEmpty())
878
                setPosition(firstPositionInLine(count()));
hjk's avatar
hjk committed
879
            scrollUp(linesOnScreen() - cursorLineOnScreen());
hjk's avatar
hjk committed
880
881
            if (key == '-')
                moveToFirstNonBlankOnLine();
hjk's avatar
hjk committed
882
            finishMovement();
hjk's avatar
hjk committed
883
        } else {
hjk's avatar
hjk committed
884
            qDebug() << "IGNORED Z_MODE " << key << text;
hjk's avatar
hjk committed
885
886
        }
        m_submode = NoSubMode;
hjk's avatar
hjk committed
887
    } else if (m_subsubmode == FtSubSubMode) {
hjk's avatar
hjk committed
888
889
        m_semicolonType = m_subsubdata;
        m_semicolonKey = key;
hjk's avatar
hjk committed
890
891
        handleFfTt(key);
        m_subsubmode = NoSubSubMode;
892
893
894
895
        finishMovement(QString("%1%2%3")
            .arg(count())
            .arg(QChar(m_semicolonType))
            .arg(QChar(m_semicolonKey)));
hjk's avatar
hjk committed
896
    } else if (m_submode == ReplaceSubMode) {
hjk's avatar
hjk committed
897
898
899
900
901
902
903
904
905
        if (count() < rightDist() && text.size() == 1
                && (text.at(0).isPrint() || text.at(0).isSpace())) {
            recordBeginGroup();
            setAnchor();
            moveRight(count());
            recordRemoveSelectedText();
            recordInsertText(QString(count(), text.at(0)));
            recordEndGroup();
            m_moveType = MoveExclusive;
hjk's avatar
hjk committed
906
            m_submode = NoSubMode;