fakevimhandler.cpp 262 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
hjk's avatar
hjk committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
hjk's avatar
hjk committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
hjk's avatar
hjk committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
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
24
25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

30
//
31
32
33
34
35
36
37
38
39
40
41
// 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:
42
//
43
44
45
//   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.
46
//
47
48
49
//   Do not pass QTextCursor etc around unless really needed. Convert
//   early to  line/column.
//
50
51
52
53
//   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().
//
54
//   A current "region of interest"
hjk's avatar
hjk committed
55
56
//   spans between anchor(), (i.e. the character below anchor()), and
//   position(). The character below position() is not included
57
//   if the last movement command was exclusive (MoveExclusive).
hjk's avatar
hjk committed
58
//
59

60
61
#include "fakevimhandler.h"

62
63
#include "fakevimactions.h"

64
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
65
#include <utils/qtcassert.h>
66

67
68
69
70
71
72
73
74
75
76
#include <QDebug>
#include <QFile>
#include <QObject>
#include <QPointer>
#include <QProcess>
#include <QRegExp>
#include <QTextStream>
#include <QTimer>
#include <QtAlgorithms>
#include <QStack>
hjk's avatar
hjk committed
77

78
#include <QApplication>
79
#include <QClipboard>
80
81
82
83
84
85
86
87
88
#include <QInputMethodEvent>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QScrollBar>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QTextEdit>
Friedemann Kleint's avatar
Friedemann Kleint committed
89
#include <QMimeData>
hjk's avatar
hjk committed
90

91
#include <algorithm>
92
#include <climits>
93
#include <ctype.h>
94

95
96
97
98
99
100
101
//#define DEBUG_KEY  1
#if DEBUG_KEY
#   define KEY_DEBUG(s) qDebug() << s
#else
#   define KEY_DEBUG(s)
#endif

102
103
//#define DEBUG_UNDO  1
#if DEBUG_UNDO
Lukas Holecek's avatar
Lukas Holecek committed
104
#   define UNDO_DEBUG(s) qDebug() << << revision() << s
105
106
107
108
#else
#   define UNDO_DEBUG(s)
#endif

109
using namespace Utils;
110
111
112
#ifdef FAKEVIM_STANDALONE
using namespace FakeVim::Internal::Utils;
#endif
hjk's avatar
hjk committed
113
114
115
116

namespace FakeVim {
namespace Internal {

hjk's avatar
hjk committed
117
118
119
120
121
122
///////////////////////////////////////////////////////////////////////
//
// FakeVimHandler
//
///////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
123
124
125
126
127
128
129
130
131
132
#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
Lukas Holecek's avatar
Lukas Holecek committed
133
#define NextBlock       QTextCursor::NextBlock
hjk's avatar
hjk committed
134

135
136
#define ParagraphSeparator QChar::ParagraphSeparator

137
138
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)

139
140
#define MetaModifier     // Use HostOsInfo::controlModifier() instead
#define ControlModifier  // Use HostOsInfo::controlModifier() instead
hjk's avatar
hjk committed
141

hjk's avatar
hjk committed
142
typedef QLatin1String _;
hjk's avatar
hjk committed
143

144
/* Clipboard MIME types used by Vim. */
145
146
static const QString vimMimeText = _("_VIM_TEXT");
static const QString vimMimeTextEncoded = _("_VIMENC_TEXT");
147

hjk's avatar
hjk committed
148
149
using namespace Qt;

hjk's avatar
hjk committed
150
151
/*! A \e Mode represents one of the basic modes of operation of FakeVim.
*/
152

hjk's avatar
hjk committed
153
154
155
enum Mode
{
    InsertMode,
156
    ReplaceMode,
hjk's avatar
hjk committed
157
    CommandMode,
158
    ExMode
hjk's avatar
hjk committed
159
};
hjk's avatar
hjk committed
160

hjk's avatar
hjk committed
161
162
163
/*! A \e SubMode is used for things that require one more data item
    and are 'nested' behind a \l Mode.
*/
hjk's avatar
hjk committed
164
165
166
enum SubMode
{
    NoSubMode,
hjk's avatar
hjk committed
167
168
169
170
171
172
173
    ChangeSubMode,       // Used for c
    DeleteSubMode,       // Used for d
    FilterSubMode,       // Used for !
    IndentSubMode,       // Used for =
    RegisterSubMode,     // Used for "
    ShiftLeftSubMode,    // Used for <
    ShiftRightSubMode,   // Used for >
Lukas Holecek's avatar
Lukas Holecek committed
174
175
176
    InvertCaseSubMode,   // Used for g~
    DownCaseSubMode,     // Used for gu
    UpCaseSubMode,       // Used for gU
hjk's avatar
hjk committed
177
178
179
180
    WindowSubMode,       // Used for Ctrl-w
    YankSubMode,         // Used for y
    ZSubMode,            // Used for z
    CapitalZSubMode,     // Used for Z
181
182
183
    ReplaceSubMode,      // Used for r
    MacroRecordSubMode,  // Used for q
    MacroExecuteSubMode  // Used for @
hjk's avatar
hjk committed
184
};
hjk's avatar
hjk committed
185

hjk's avatar
hjk committed
186
187
188
/*! A \e SubSubMode is used for things that require one more data item
    and are 'nested' behind a \l SubMode.
*/
hjk's avatar
hjk committed
189
190
191
enum SubSubMode
{
    NoSubSubMode,
192
193
194
195
196
197
198
199
    FtSubSubMode,          // Used for f, F, t, T.
    MarkSubSubMode,        // Used for m.
    BackTickSubSubMode,    // Used for `.
    TickSubSubMode,        // Used for '.
    TextObjectSubSubMode,  // Used for thing like iw, aW, as etc.
    ZSubSubMode,           // Used for zj, zk
    OpenSquareSubSubMode,  // Used for [{, {(, [z
    CloseSquareSubSubMode, // Used for ]}, ]), ]z
200
    SearchSubSubMode
hjk's avatar
hjk committed
201
202
};

203
204
205
206
207
enum VisualMode
{
    NoVisualMode,
    VisualCharMode,
    VisualLineMode,
208
    VisualBlockMode
209
210
};

hjk's avatar
hjk committed
211
212
213
214
enum MoveType
{
    MoveExclusive,
    MoveInclusive,
215
    MoveLineWise
hjk's avatar
hjk committed
216
217
};

hjk's avatar
hjk committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*!
    \enum RangeMode

    The \e RangeMode serves as a means to define how the "Range" between
    the \l cursor and the \l anchor position is to be interpreted.

    \value RangeCharMode   Entered by pressing \key v. The range includes
                           all characters between cursor and anchor.
    \value RangeLineMode   Entered by pressing \key V. The range includes
                           all lines between the line of the cursor and
                           the line of the anchor.
    \value RangeLineModeExclusice Like \l RangeLineMode, but keeps one
                           newline when deleting.
    \value RangeBlockMode  Entered by pressing \key Ctrl-v. The range includes
                           all characters with line and column coordinates
                           between line and columns coordinates of cursor and
                           anchor.
    \value RangeBlockAndTailMode Like \l RangeBlockMode, but also includes
                           all characters in the affected lines up to the end
                           of these lines.
*/
239
240
241
242
243

enum EventResult
{
    EventHandled,
    EventUnhandled,
244
    EventCancelled, // Event is handled but a sub mode was cancelled.
245
246
247
    EventPassedToCore
};

248
249
250
251
252
253
254
255
256
257
258
259
260
struct CursorPosition
{
    CursorPosition() : line(-1), column(-1) {}
    CursorPosition(int block, int column) : line(block), column(column) {}
    explicit CursorPosition(const QTextCursor &tc)
        : line(tc.block().blockNumber()), column(tc.positionInBlock()) {}
    CursorPosition(const QTextDocument *document, int position)
    {
        QTextBlock block = document->findBlock(position);
        line = block.blockNumber();
        column = position - block.position();
    }
    bool isValid() const { return line >= 0 && column >= 0; }
261
262
    bool operator>(const CursorPosition &other) const
        { return line > other.line || column > other.column; }
263
264
265
266
267
268
269
270
    bool operator==(const CursorPosition &other) const
        { return line == other.line && column == other.column; }
    bool operator!=(const CursorPosition &other) const { return !operator==(other); }

    int line; // Line in document (from 0, folded lines included).
    int column; // Position on line.
};

Lukas Holecek's avatar
Lukas Holecek committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
struct Mark
{
    Mark(const CursorPosition &pos = CursorPosition(), const QString &fileName = QString())
        : position(pos), fileName(fileName) {}

    bool isValid() const { return position.isValid(); }

    bool isLocal(const QString &localFileName) const
    {
        return fileName.isEmpty() || fileName == localFileName;
    }

    CursorPosition position;
    QString fileName;
};
typedef QHash<QChar, Mark> Marks;
typedef QHashIterator<QChar, Mark> MarksIterator;

Lukas Holecek's avatar
Lukas Holecek committed
289
290
struct State
{
291
    State() : revision(-1), position(), marks(), lastVisualMode(NoVisualMode),
292
        lastVisualModeInverted(false) {}
293
294
    State(int revision, const CursorPosition &position, const Marks &marks,
        VisualMode lastVisualMode, bool lastVisualModeInverted) : revision(revision),
295
296
        position(position), marks(marks), lastVisualMode(lastVisualMode),
        lastVisualModeInverted(lastVisualModeInverted) {}
297

298
299
    bool isValid() const { return position.isValid(); }

300
    int revision;
301
    CursorPosition position;
Lukas Holecek's avatar
Lukas Holecek committed
302
    Marks marks;
303
    VisualMode lastVisualMode;
304
    bool lastVisualModeInverted;
Lukas Holecek's avatar
Lukas Holecek committed
305
306
};

307
struct Column
308
{
309
    Column(int p, int l) : physical(p), logical(l) {}
hjk's avatar
hjk committed
310
311
    int physical; // Number of characters in the data.
    int logical; // Column on screen.
312
313
};

314
315
316
317
318
QDebug operator<<(QDebug ts, const Column &col)
{
    return ts << "(p: " << col.physical << ", l: " << col.logical << ")";
}

319
320
321
struct Register
{
    Register() : rangemode(RangeCharMode) {}
hjk's avatar
hjk committed
322
    Register(const QString &c) : contents(c), rangemode(RangeCharMode) {}
323
324
325
326
327
    Register(const QString &c, RangeMode m) : contents(c), rangemode(m) {}
    QString contents;
    RangeMode rangemode;
};

hjk's avatar
hjk committed
328
329
330
331
332
QDebug operator<<(QDebug ts, const Register &reg)
{
    return ts << reg.contents;
}

hjk's avatar
hjk committed
333
334
struct SearchData
{
hjk's avatar
hjk committed
335
336
337
338
339
    SearchData()
    {
        forward = true;
        highlightMatches = true;
    }
hjk's avatar
hjk committed
340
341
342
343
344

    QString needle;
    bool forward;
    bool highlightMatches;
};
345

346
// If string begins with given prefix remove it with trailing spaces and return true.
347
static bool eatString(const char *prefix, QString *str)
348
{
349
    if (!str->startsWith(_(prefix)))
350
        return false;
351
    *str = str->mid(strlen(prefix)).trimmed();
352
353
354
    return true;
}

355
static QRegExp vimPatternToQtPattern(QString needle, bool ignoreCaseOption, bool smartCaseOption)
356
{
357
    /* Transformations (Vim regexp -> QRegExp):
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
     *   \a -> [A-Za-z]
     *   \A -> [^A-Za-z]
     *   \h -> [A-Za-z_]
     *   \H -> [^A-Za-z_]
     *   \l -> [a-z]
     *   \L -> [^a-z]
     *   \o -> [0-7]
     *   \O -> [^0-7]
     *   \u -> [A-Z]
     *   \U -> [^A-Z]
     *   \x -> [0-9A-Fa-f]
     *   \X -> [^0-9A-Fa-f]
     *
     *   \< -> \b
     *   \> -> \b
     *   [] -> \[\]
     *   \= -> ?
     *
     *   (...)  <-> \(...\)
     *   {...}  <-> \{...\}
     *   |      <-> \|
     *   ?      <-> \?
     *   +      <-> \+
     *   \{...} -> {...}
     *
     *   \c - set ignorecase for rest
     *   \C - set noignorecase for rest
     */
386
387
388
    // FIXME: Option smartcase should be used only if search was typed by user.
    bool ignorecase = ignoreCaseOption
        && !(smartCaseOption && needle.contains(QRegExp(_("[A-Z]"))));
389
390
391
392
393
    QString pattern;
    pattern.reserve(2 * needle.size());

    bool escape = false;
    bool brace = false;
394
395
    bool embraced = false;
    bool range = false;
396
397
398
399
    bool curly = false;
    foreach (const QChar &c, needle) {
        if (brace) {
            brace = false;
400
            if (c == QLatin1Char(']')) {
401
402
403
                pattern.append(_("\\[\\]"));
                continue;
            }
404
            pattern.append(QLatin1Char('['));
405
406
            escape = true;
            embraced = true;
407
        }
408
409
410
411
        if (embraced) {
            if (range) {
                QChar c2 = pattern[pattern.size() - 2];
                pattern.remove(pattern.size() - 2, 2);
412
413
                pattern.append(c2.toUpper() + QLatin1Char('-') + c.toUpper());
                pattern.append(c2.toLower() + QLatin1Char('-') + c.toLower());
414
415
416
417
                range = false;
            } else if (escape) {
                escape = false;
                pattern.append(c);
418
            } else if (c == QLatin1Char('\\')) {
419
                escape = true;
420
421
            } else if (c == QLatin1Char(']')) {
                pattern.append(QLatin1Char(']'));
422
                embraced = false;
423
            } else if (c == QLatin1Char('-')) {
424
                range = ignorecase && pattern[pattern.size() - 1].isLetter();
425
                pattern.append(QLatin1Char('-'));
426
            } else if (c.isLetter() && ignorecase) {
Orgad Shaneh's avatar
Orgad Shaneh committed
427
                pattern.append(c.toLower()).append(c.toUpper());
428
429
430
            } else {
                pattern.append(c);
            }
431
432
        } else if (QString::fromLatin1("(){}+|?").indexOf(c) != -1) {
            if (c == QLatin1Char('{')) {
433
                curly = escape;
434
            } else if (c == QLatin1Char('}') && curly) {
435
436
437
438
439
440
441
                curly = false;
                escape = true;
            }

            if (escape)
                escape = false;
            else
442
                pattern.append(QLatin1Char('\\'));
443
444
445
446
            pattern.append(c);
        } else if (escape) {
            // escape expression
            escape = false;
447
            if (c == QLatin1Char('<') || c == QLatin1Char('>'))
448
                pattern.append(_("\\b"));
449
            else if (c == QLatin1Char('a'))
450
                pattern.append(_("[a-zA-Z]"));
451
            else if (c == QLatin1Char('A'))
452
                pattern.append(_("[^a-zA-Z]"));
453
            else if (c == QLatin1Char('h'))
454
                pattern.append(_("[A-Za-z_]"));
455
            else if (c == QLatin1Char('H'))
456
                pattern.append(_("[^A-Za-z_]"));
457
458
459
            else if (c == QLatin1Char('c') || c == QLatin1Char('C'))
                ignorecase = (c == QLatin1Char('c'));
            else if (c == QLatin1Char('l'))
460
                pattern.append(_("[a-z]"));
461
            else if (c == QLatin1Char('L'))
462
                pattern.append(_("[^a-z]"));
463
            else if (c == QLatin1Char('o'))
464
                pattern.append(_("[0-7]"));
465
            else if (c == QLatin1Char('O'))
466
                pattern.append(_("[^0-7]"));
467
            else if (c == QLatin1Char('u'))
468
                pattern.append(_("[A-Z]"));
469
            else if (c == QLatin1Char('U'))
470
                pattern.append(_("[^A-Z]"));
471
            else if (c == QLatin1Char('x'))
472
                pattern.append(_("[0-9A-Fa-f]"));
473
            else if (c == QLatin1Char('X'))
474
                pattern.append(_("[^0-9A-Fa-f]"));
475
            else if (c == QLatin1Char('='))
476
477
                pattern.append(_("?"));
            else
478
                pattern.append(QLatin1Char('\\') + c);
479
480
        } else {
            // unescaped expression
481
            if (c == QLatin1Char('\\'))
482
                escape = true;
483
            else if (c == QLatin1Char('['))
484
485
                brace = true;
            else if (c.isLetter() && ignorecase)
486
                pattern.append(QLatin1Char('[') + c.toLower() + c.toUpper() + QLatin1Char(']'));
487
488
489
490
491
            else
                pattern.append(c);
        }
    }
    if (escape)
492
        pattern.append(QLatin1Char('\\'));
493
    else if (brace)
494
        pattern.append(QLatin1Char('['));
495
496
497
498

    return QRegExp(pattern);
}

499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
static bool afterEndOfLine(const QTextDocument *doc, int position)
{
    return doc->characterAt(position) == ParagraphSeparator
        && doc->findBlock(position).length() > 1;
}

static void searchForward(QTextCursor *tc, QRegExp &needleExp, int *repeat)
{
    const QTextDocument *doc = tc->document();
    const int startPos = tc->position();

    // Search from beginning of line so that matched text is the same.
    tc->movePosition(StartOfLine);

    // forward to current position
    *tc = doc->find(needleExp, *tc);
    while (!tc->isNull() && tc->anchor() < startPos) {
        if (!tc->hasSelection())
            tc->movePosition(Right);
        if (tc->atBlockEnd())
Lukas Holecek's avatar
Lukas Holecek committed
519
            tc->movePosition(NextBlock);
520
521
522
523
524
525
526
527
528
529
530
531
        *tc = doc->find(needleExp, *tc);
    }

    if (tc->isNull())
        return;

    --*repeat;

    while (*repeat > 0) {
        if (!tc->hasSelection())
            tc->movePosition(Right);
        if (tc->atBlockEnd())
Lukas Holecek's avatar
Lukas Holecek committed
532
            tc->movePosition(NextBlock);
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
        *tc = doc->find(needleExp, *tc);
        if (tc->isNull())
            return;
        --*repeat;
    }

    if (!tc->isNull() && afterEndOfLine(doc, tc->anchor()))
        tc->movePosition(Left);
}

static void searchBackward(QTextCursor *tc, QRegExp &needleExp, int *repeat)
{
    // Search from beginning of line so that matched text is the same.
    QTextBlock block = tc->block();
    QString line = block.text();

    int i = line.indexOf(needleExp, 0);
    while (i != -1 && i < tc->positionInBlock()) {
        --*repeat;
        i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
        if (i == line.size())
            i = -1;
    }

    if (i == tc->positionInBlock())
        --*repeat;

    while (*repeat > 0) {
        block = block.previous();
        if (!block.isValid())
            break;
        line = block.text();
        i = line.indexOf(needleExp, 0);
        while (i != -1) {
            --*repeat;
            i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
            if (i == line.size())
                i = -1;
        }
    }

    if (!block.isValid()) {
        *tc = QTextCursor();
        return;
    }

    i = line.indexOf(needleExp, 0);
    while (*repeat < 0) {
        i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
        ++*repeat;
    }
    tc->setPosition(block.position() + i);
}

hluk's avatar
hluk committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// Commands [[, []
static void bracketSearchBackward(QTextCursor *tc, const QString &needleExp, int repeat)
{
    QRegExp re(needleExp);
    QTextCursor tc2 = *tc;
    tc2.setPosition(tc2.position() - 1);
    searchBackward(&tc2, re, &repeat);
    if (repeat <= 1)
        tc->setPosition(tc2.isNull() ? 0 : tc2.position(), KeepAnchor);
}

// Commands ][, ]]
// When ]] is used after an operator, then also stops below a '}' in the first column.
static void bracketSearchForward(QTextCursor *tc, const QString &needleExp, int repeat,
                                 bool searchWithCommand)
{
    QRegExp re(searchWithCommand ? QString(_("^\\}|^\\{")) : needleExp);
    QTextCursor tc2 = *tc;
    tc2.setPosition(tc2.position() + 1);
    searchForward(&tc2, re, &repeat);
    if (repeat <= 1) {
        if (tc2.isNull()) {
            tc->setPosition(tc->document()->characterCount() - 1, KeepAnchor);
        } else {
            tc->setPosition(tc2.position() - 1, KeepAnchor);
            if (searchWithCommand && tc->document()->characterAt(tc->position()).unicode() == '}') {
                QTextBlock block = tc->block().next();
                if (block.isValid())
                    tc->setPosition(block.position(), KeepAnchor);
            }
        }
    }
}

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
static bool substituteText(QString *text, QRegExp &pattern, const QString &replacement,
    bool global)
{
    bool substituted = false;
    int pos = 0;
    while (true) {
        pos = pattern.indexIn(*text, pos, QRegExp::CaretAtZero);
        if (pos == -1)
            break;
        substituted = true;
        QString matched = text->mid(pos, pattern.cap(0).size());
        QString repl;
        bool escape = false;
        // insert captured texts
        for (int i = 0; i < replacement.size(); ++i) {
            const QChar &c = replacement[i];
            if (escape) {
                escape = false;
                if (c.isDigit()) {
                    if (c.digitValue() <= pattern.captureCount())
                        repl += pattern.cap(c.digitValue());
                } else {
                    repl += c;
                }
            } else {
646
                if (c == QLatin1Char('\\'))
647
                    escape = true;
648
                else if (c == QLatin1Char('&'))
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
                    repl += pattern.cap(0);
                else
                    repl += c;
            }
        }
        text->replace(pos, matched.size(), repl);
        pos += qMax(1, repl.size());

        if (pos >= text->size() || !global)
            break;
    }

    return substituted;
}

664
665
666
static int findUnescaped(QChar c, const QString &line, int from)
{
    for (int i = from; i < line.size(); ++i) {
667
        if (line.at(i) == c && (i == 0 || line.at(i - 1) != QLatin1Char('\\')))
668
669
670
671
672
            return i;
    }
    return -1;
}

673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
static void setClipboardData(const QString &content, RangeMode mode,
    QClipboard::Mode clipboardMode)
{
    QClipboard *clipboard = QApplication::clipboard();
    char vimRangeMode = mode;

    QByteArray bytes1;
    bytes1.append(vimRangeMode);
    bytes1.append(content.toUtf8());

    QByteArray bytes2;
    bytes2.append(vimRangeMode);
    bytes2.append("utf-8");
    bytes2.append('\0');
    bytes2.append(content.toUtf8());

    QMimeData *data = new QMimeData;
    data->setText(content);
    data->setData(vimMimeText, bytes1);
    data->setData(vimMimeTextEncoded, bytes2);
    clipboard->setMimeData(data, clipboardMode);
}

696
697
698
699
700
701
702
static const QMap<QString, int> &vimKeyNames()
{
    static QMap<QString, int> k;
    if (!k.isEmpty())
        return k;

    // FIXME: Should be value of mapleader.
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    k.insert(_("LEADER"), Key_Backslash);

    k.insert(_("SPACE"), Key_Space);
    k.insert(_("TAB"), Key_Tab);
    k.insert(_("NL"), Key_Return);
    k.insert(_("NEWLINE"), Key_Return);
    k.insert(_("LINEFEED"), Key_Return);
    k.insert(_("LF"), Key_Return);
    k.insert(_("CR"), Key_Return);
    k.insert(_("RETURN"), Key_Return);
    k.insert(_("ENTER"), Key_Return);
    k.insert(_("BS"), Key_Backspace);
    k.insert(_("BACKSPACE"), Key_Backspace);
    k.insert(_("ESC"), Key_Escape);
    k.insert(_("BAR"), Key_Bar);
    k.insert(_("BSLASH"), Key_Backslash);
    k.insert(_("DEL"), Key_Delete);
    k.insert(_("DELETE"), Key_Delete);
    k.insert(_("KDEL"), Key_Delete);
    k.insert(_("UP"), Key_Up);
    k.insert(_("DOWN"), Key_Down);
    k.insert(_("LEFT"), Key_Left);
    k.insert(_("RIGHT"), Key_Right);

    k.insert(_("LT"), Key_Less);

    k.insert(_("F1"), Key_F1);
    k.insert(_("F2"), Key_F2);
    k.insert(_("F3"), Key_F3);
    k.insert(_("F4"), Key_F4);
    k.insert(_("F5"), Key_F5);
    k.insert(_("F6"), Key_F6);
    k.insert(_("F7"), Key_F7);
    k.insert(_("F8"), Key_F8);
    k.insert(_("F9"), Key_F9);
    k.insert(_("F10"), Key_F10);

    k.insert(_("F11"), Key_F11);
    k.insert(_("F12"), Key_F12);
    k.insert(_("F13"), Key_F13);
    k.insert(_("F14"), Key_F14);
    k.insert(_("F15"), Key_F15);
    k.insert(_("F16"), Key_F16);
    k.insert(_("F17"), Key_F17);
    k.insert(_("F18"), Key_F18);
    k.insert(_("F19"), Key_F19);
    k.insert(_("F20"), Key_F20);

    k.insert(_("F21"), Key_F21);
    k.insert(_("F22"), Key_F22);
    k.insert(_("F23"), Key_F23);
    k.insert(_("F24"), Key_F24);
    k.insert(_("F25"), Key_F25);
    k.insert(_("F26"), Key_F26);
    k.insert(_("F27"), Key_F27);
    k.insert(_("F28"), Key_F28);
    k.insert(_("F29"), Key_F29);
    k.insert(_("F30"), Key_F30);

    k.insert(_("F31"), Key_F31);
    k.insert(_("F32"), Key_F32);
    k.insert(_("F33"), Key_F33);
    k.insert(_("F34"), Key_F34);
    k.insert(_("F35"), Key_F35);

    k.insert(_("INSERT"), Key_Insert);
    k.insert(_("INS"), Key_Insert);
    k.insert(_("KINSERT"), Key_Insert);
    k.insert(_("HOME"), Key_Home);
    k.insert(_("END"), Key_End);
    k.insert(_("PAGEUP"), Key_PageUp);
    k.insert(_("PAGEDOWN"), Key_PageDown);

    k.insert(_("KPLUS"), Key_Plus);
    k.insert(_("KMINUS"), Key_Minus);
    k.insert(_("KDIVIDE"), Key_Slash);
    k.insert(_("KMULTIPLY"), Key_Asterisk);
    k.insert(_("KENTER"), Key_Enter);
    k.insert(_("KPOINT"), Key_Period);
782
783
784
785

    return k;
}

786

787
788
789
Range::Range()
    : beginPos(-1), endPos(-1), rangemode(RangeCharMode)
{}
790

791
792
793
Range::Range(int b, int e, RangeMode m)
    : beginPos(qMin(b, e)), endPos(qMax(b, e)), rangemode(m)
{}
794

795
QString Range::toString() const
hjk's avatar
hjk committed
796
{
797
    return QString::fromLatin1("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
798
799
800
801
802
803
804
805
806
807
        .arg(rangemode);
}

QDebug operator<<(QDebug ts, const Range &range)
{
    return ts << '[' << range.beginPos << ',' << range.endPos << ']';
}


ExCommand::ExCommand(const QString &c, const QString &a, const Range &r)
808
    : cmd(c), hasBang(false), args(a), range(r), count(1)
809
{}
hjk's avatar
hjk committed
810

811
812
813
814
815
bool ExCommand::matches(const QString &min, const QString &full) const
{
    return cmd.startsWith(min) && full.startsWith(cmd);
}

hjk's avatar
hjk committed
816
817
QDebug operator<<(QDebug ts, const ExCommand &cmd)
{
818
    return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range;
hjk's avatar
hjk committed
819
820
}

821
QDebug operator<<(QDebug ts, const QList<QTextEdit::ExtraSelection> &sels)
822
{
823
    foreach (const QTextEdit::ExtraSelection &sel, sels)
824
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
825
826
    return ts;
}
827

hjk's avatar
hjk committed
828
QString quoteUnprintable(const QString &ba)
hjk's avatar
hjk committed
829
{
hjk's avatar
hjk committed
830
831
    QString res;
    for (int i = 0, n = ba.size(); i != n; ++i) {
832
833
        const QChar c = ba.at(i);
        const int cc = c.unicode();
hjk's avatar
hjk committed
834
835
        if (c.isPrint())
            res += c;
836
        else if (cc == QLatin1Char('\n'))
hjk's avatar
hjk committed
837
            res += _("<CR>");
hjk's avatar
hjk committed
838
        else
839
            res += QString::fromLatin1("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
hjk's avatar
hjk committed
840
841
    }
    return res;
hjk's avatar
hjk committed
842
843
}

844
845
846
847
848
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();
849
        if (u != QLatin1Char(' ') && u != QLatin1Char('\t'))
850
851
852
853
854
            return false;
    }
    return true;
}

855
inline QString msgMarkNotSet(const QString &text)
856
{
857
    return FakeVimHandler::tr("Mark '%1' not set.").arg(text);
858
859
}

hjk's avatar
hjk committed
860
class Input
hjk's avatar
hjk committed
861
{
hjk's avatar
hjk committed
862
public:
863
864
865
    // Remove some extra "information" on Mac.
    static int cleanModifier(int m)  { return m & ~Qt::KeypadModifier; }

866
867
    Input()
        : m_key(0), m_xkey(0), m_modifiers(0) {}
hjk's avatar
hjk committed
868

869
    explicit Input(QChar x)
870
871
872
873
        : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x)
    {
        if (x.isUpper())
            m_modifiers = Qt::ShiftModifier;
874
875
        else if (x.isLower())
            m_key = x.toUpper().unicode();
876
    }
hjk's avatar
hjk committed
877

878
    Input(int k, int m, const QString &t = QString())
879
        : m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
880
    {
881
882
883
884
885
886
887
888
889
        if (m_text.size() == 1) {
            QChar x = m_text.at(0);

            // On Mac, QKeyEvent::text() returns non-empty strings for
            // cursor keys. This breaks some of the logic later on
            // relying on text() being empty for "special" keys.
            // FIXME: Check the real conditions.
            if (x.unicode() < ' ')
                m_text.clear();
890
            else if (x.isLetter())
891
892
                m_key = x.toUpper().unicode();
        }
893
894

        // Set text only if input is ascii key without control modifier.
895
        if (m_text.isEmpty() && k >= 0 && k <= 0x7f && (m & (HostOsInfo::controlModifier())) == 0) {
896
            QChar c = QChar::fromLatin1(k);
897
898
899
            m_text = QString((m & ShiftModifier) != 0 ? c.toUpper() : c.toLower());
        }

900
901
902
903
        // m_xkey is only a cache.
        m_xkey = (m_text.size() == 1 ? m_text.at(0).unicode() : m_key);
    }

904
905
906
907
908
    bool isValid() const
    {
        return m_key != 0 || !m_text.isNull();
    }

909
910
    bool isDigit() const
    {
hluk's avatar
hluk committed
911
        return m_xkey >= '0' && m_xkey <= '9';
912
    }
913

914
915
916
917
918
    bool isKey(int c) const
    {
        return !m_modifiers && m_key == c;
    }

919
920
921
922
923
924
925
    bool isBackspace() const
    {
        return m_key == Key_Backspace || isControl('h');
    }

    bool isReturn() const
    {
926
        return m_key == QLatin1Char('\n') || m_key == Key_Return || m_key == Key_Enter;
927
928
    }

hjk's avatar
hjk committed
929
930
931
932
933
934
    bool isEscape() const
    {
        return isKey(Key_Escape) || isKey(27) || isControl('c')
            || isControl(Key_BracketLeft);
    }

935
936
    bool is(int c) const
    {
937
        return m_xkey == c && m_modifiers != int(HostOsInfo::controlModifier());
938
939
    }

940
941
942
943
944
    bool isControl() const
    {
        return m_modifiers & HostOsInfo::controlModifier();
    }

945
946
    bool isControl(int c) const
    {
947
        return isControl()
948
            && (m_xkey == c || m_xkey + 32 == c || m_xkey + 64 == c || m_xkey + 96 == c);
949
950
    }

951
952
953
954
955
    bool isShift() const
    {
        return m_modifiers & Qt::ShiftModifier;
    }

956
957
    bool isShift(int c) const
    {
958
        return isShift() && m_xkey == c;
959
960
    }

961
    bool operator<(const Input &a) const
962
    {
963
964
965
966
967
968
969
        if (m_key != a.m_key)
            return m_key < a.m_key;
        // Text for some mapped key cannot be determined (e.g. <C-J>) so if text is not set for
        // one of compared keys ignore it.
        if (!m_text.isEmpty() && !a.m_text.isEmpty())
            return m_text < a.m_text;
        return m_modifiers < a.m_modifiers;
970
971
    }

972
    bool operator==(const Input &a) const
973
    {
974
        return !(*this < a || a < *this);
975
976
    }

977
978
    bool operator!=(const Input &a) const { return !operator==(a); }

979
980
    QString text() const { return m_text; }

hjk's avatar
hjk committed
981
982
983
984
985
    QChar asChar() const
    {
        return (m_text.size() == 1 ? m_text.at(0) : QChar());
    }

986
987
    int key() const { return m_key; }

988
989
    int modifiers() const { return m_modifiers; }

990
    // Return raw character for macro recording or dot command.
991
992
993
    QChar raw() const
    {
        if (m_key == Key_Tab)
994
            return QLatin1Char('\t');
995
        if (m_key == Key_Return)
996
            return QLatin1Char('\n');
997
998
999
        if (m_key == Key_Escape)
            return QChar(27);
        return m_xkey;
1000
1001
    }

1002
1003
1004
    QString toString() const
    {
        QString key = vimKeyNames().key(m_key);
hluk's avatar
hluk committed
1005
        bool namedKey = !key.isEmpty();
1006

hluk's avatar
hluk committed
1007
        if (!namedKey) {
1008
1009
1010
1011
            if (m_xkey == '<')
                key = _("<LT>");
            else
                key = QChar(m_xkey);
hluk's avatar
hluk committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
        }

        bool shift = isShift();
        bool ctrl = isControl();
        if (shift)
            key.prepend(_("S-"));
        if (ctrl)
            key.prepend(_("C-"));

        if (namedKey || shift || ctrl) {
1022
1023
1024
1025
1026
            key.prepend(QLatin1Char('<'));
            key.append(QLatin1Char('>'));
        }

        return key;
1027
1028
    }

hjk's avatar
hjk committed
1029
1030
1031
1032
1033
    QDebug dump(QDebug ts) const
    {
        return ts << m_key << '-' << m_modifiers << '-'
            << quoteUnprintable(m_text);
    }
1034
1035
1036
1037
1038
1039
private:
    int m_key;
    int m_xkey;
    int m_modifiers;
    QString m_text;
};
hjk's avatar
hjk committed
1040

1041
1042
1043
// mapping to <Nop> (do nothing)
static const Input Nop(-1, -1, QString());

hjk's avatar
hjk committed
1044
1045
1046
QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }

class Inputs : public QVector<Input>
1047
{
hjk's avatar
hjk committed
1048
public:
1049
1050
1051
1052
1053
1054
    Inputs() : m_noremap(true), m_silent(false) {}

    explicit Inputs(const QString &str, bool noremap = true, bool silent = false)
        : m_noremap(noremap), m_silent(silent)
    {
        parseFrom(str);
hluk's avatar
hluk committed
1055
        squeeze();
1056
1057
1058
1059
1060
1061
1062
    }

    bool noremap() const { return m_noremap; }

    bool silent() const { return m_silent; }

private:
hjk's avatar
hjk committed
1063
    void parseFrom(const QString &str);
1064
1065
1066

    bool m_noremap;
    bool m_silent;
hjk's avatar
hjk committed
1067
1068
};

1069
1070
1071
1072
1073
static Input parseVimKeyName(const QString &keyName)
{
    if (keyName.length() == 1)
        return Input(keyName.at(0));

1074
    const QStringList keys = keyName.split(QLatin1Char('-'));
1075
1076
    const int len = keys.length();

1077
    if (len == 1 && keys.at(0).toUpper() == _("NOP"))
1078
1079
1080
1081
1082
        return Nop;

    int mods = NoModifier;
    for (int i = 0; i < len - 1; ++i) {
        const QString &key = keys[i].toUpper();
1083
        if (key == _("S"))
1084
            mods |= Qt::ShiftModifier;
1085
        else if (key == _("C"))
1086
            mods |= HostOsInfo::controlModifier();
1087
1088
1089
1090
1091
1092
1093
1094
1095
        else
            return Input();
    }

    if (!keys.isEmpty()) {
        const QString key = keys.last();
        if (key.length() == 1) {
            // simple character
            QChar c = key.at(0).toUpper();
1096
            return Input(c.unicode(), mods);
1097
1098
1099
        }

        // find key name
1100
1101
        QMap<QString, int>::ConstIterator it = vimKeyNames().constFind(key.toUpper());
        if (it != vimKeyNames().end())
1102
            return Input(*it, mods);
1103
1104
1105
    }

    return Input();
1106
}
1107

hjk's avatar
hjk committed
1108
1109
1110
1111
void Inputs::parseFrom(const QString &str)
{
    const int n = str.size();
    for (int i = 0; i < n; ++i) {
1112
1113
        ushort c = str.at(i).unicode();
        if (c == '<') {
1114
            int j = str.indexOf(QLatin1Char('>'), i);
1115
            Input input;
1116
1117
            if (j != -1) {
                const QString key = str.mid(i+1, j - i - 1);
1118
                if (!key.contains(QLatin1Char('<')))
1119
1120
                    input = parseVimKeyName(key);
            }
1121
1122
1123
            if (input.isValid()) {
                append(input);
                i = j;
hjk's avatar
hjk committed
1124
            } else {
1125
                append(Input(c));
hjk's avatar
hjk committed
1126
1127
            }
        } else {
1128
            append(Input(c));
hjk's avatar
hjk committed
1129
1130
1131
        }
    }
}
hjk's avatar
hjk committed
1132

1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164