fakevimhandler.cpp 265 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
static bool substituteText(QString *text, QRegExp &pattern, const QString &replacement,
    bool global)
{
    bool substituted = false;
    int pos = 0;
626
    int right = -1;
627 628 629 630
    while (true) {
        pos = pattern.indexIn(*text, pos, QRegExp::CaretAtZero);
        if (pos == -1)
            break;
631 632 633 634 635 636 637 638 639 640 641

        // ensure that substitution is advancing towards end of line
        if (right == text->size() - pos) {
            ++pos;
            if (pos == text->size())
                break;
            continue;
        }

        right = text->size() - pos;

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        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 {
658
                if (c == QLatin1Char('\\'))
659
                    escape = true;
660
                else if (c == QLatin1Char('&'))
661 662 663 664 665 666
                    repl += pattern.cap(0);
                else
                    repl += c;
            }
        }
        text->replace(pos, matched.size(), repl);
667
        pos += (repl.isEmpty() && matched.isEmpty()) ? 1 : repl.size();
668 669 670 671 672 673 674 675

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

    return substituted;
}

676 677 678
static int findUnescaped(QChar c, const QString &line, int from)
{
    for (int i = from; i < line.size(); ++i) {
679
        if (line.at(i) == c && (i == 0 || line.at(i - 1) != QLatin1Char('\\')))
680 681 682 683 684
            return i;
    }
    return -1;
}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
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);
}

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
static QByteArray toLocalEncoding(const QString &text)
{
    return HostOsInfo::isWindowsHost() ? QString(text).replace(_("\n"), _("\r\n")).toLocal8Bit()
                                       : text.toLocal8Bit();
}

static QString fromLocalEncoding(const QByteArray &data)
{
    return HostOsInfo::isWindowsHost() ? QString::fromLocal8Bit(data).replace(_("\n"), _("\r\n"))
                                       : QString::fromLocal8Bit(data);
}

static QString getProcessOutput(const QString &command, const QString &input)
{
    QProcess proc;
    proc.start(command);
    proc.waitForStarted();
    proc.write(toLocalEncoding(input));
    proc.closeWriteChannel();

    // FIXME: Process should be interruptable by user.
    //        Solution is to create a QObject for each process and emit finished state.
    proc.waitForFinished();

    return fromLocalEncoding(proc.readAllStandardOutput());
}

735 736 737 738 739 740 741
static const QMap<QString, int> &vimKeyNames()
{
    static QMap<QString, int> k;
    if (!k.isEmpty())
        return k;

    // FIXME: Should be value of mapleader.
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
    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);
767
    k.insert(_("GT"), Key_Greater);
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

    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);
822 823 824 825

    return k;
}

826
static bool isOnlyControlModifier(const Qt::KeyboardModifiers &mods)
827
{
828
    return (mods ^ HostOsInfo::controlModifier()) == Qt::NoModifier;
829 830
}

831

832 833 834
Range::Range()
    : beginPos(-1), endPos(-1), rangemode(RangeCharMode)
{}
835

836 837 838
Range::Range(int b, int e, RangeMode m)
    : beginPos(qMin(b, e)), endPos(qMax(b, e)), rangemode(m)
{}
839

840
QString Range::toString() const
hjk's avatar
hjk committed
841
{
842
    return QString::fromLatin1("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
843 844 845
        .arg(rangemode);
}

846 847 848 849 850
bool Range::isValid() const
{
    return beginPos >= 0 && endPos >= 0;
}

851 852 853 854 855 856 857
QDebug operator<<(QDebug ts, const Range &range)
{
    return ts << '[' << range.beginPos << ',' << range.endPos << ']';
}


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

861 862 863 864 865
bool ExCommand::matches(const QString &min, const QString &full) const
{
    return cmd.startsWith(min) && full.startsWith(cmd);
}

hjk's avatar
hjk committed
866 867
QDebug operator<<(QDebug ts, const ExCommand &cmd)
{
868
    return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range;
hjk's avatar
hjk committed
869 870
}

871
QDebug operator<<(QDebug ts, const QList<QTextEdit::ExtraSelection> &sels)
872
{
873
    foreach (const QTextEdit::ExtraSelection &sel, sels)
874
        ts << "SEL: " << sel.cursor.anchor() << sel.cursor.position();
875 876
    return ts;
}
877

hjk's avatar
hjk committed
878
QString quoteUnprintable(const QString &ba)
hjk's avatar
hjk committed
879
{
hjk's avatar
hjk committed
880 881
    QString res;
    for (int i = 0, n = ba.size(); i != n; ++i) {
882 883
        const QChar c = ba.at(i);
        const int cc = c.unicode();
hjk's avatar
hjk committed
884 885
        if (c.isPrint())
            res += c;
886
        else if (cc == QLatin1Char('\n'))
hjk's avatar
hjk committed
887
            res += _("<CR>");
hjk's avatar
hjk committed
888
        else
889
            res += QString::fromLatin1("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
hjk's avatar
hjk committed
890 891
    }
    return res;
hjk's avatar
hjk committed
892 893
}

894 895 896 897 898
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();
899
        if (u != QLatin1Char(' ') && u != QLatin1Char('\t'))
900 901 902 903 904
            return false;
    }
    return true;
}

905
inline QString msgMarkNotSet(const QString &text)
906
{
907
    return FakeVimHandler::tr("Mark '%1' not set.").arg(text);
908 909
}

hjk's avatar
hjk committed
910
class Input
hjk's avatar
hjk committed
911
{
hjk's avatar
hjk committed
912
public:
913
    // Remove some extra "information" on Mac.
914 915 916 917
    static Qt::KeyboardModifiers cleanModifier(Qt::KeyboardModifiers m)
    {
        return m & ~Qt::KeypadModifier;
    }
918

919 920
    Input()
        : m_key(0), m_xkey(0), m_modifiers(0) {}
hjk's avatar
hjk committed
921

922
    explicit Input(QChar x)
923 924 925 926
        : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x)
    {
        if (x.isUpper())
            m_modifiers = Qt::ShiftModifier;
927 928
        else if (x.isLower())
            m_key = x.toUpper().unicode();
929
    }
hjk's avatar
hjk committed
930

931
    Input(int k, Qt::KeyboardModifiers m, const QString &t = QString())
932
        : m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
933
    {
934 935 936 937 938 939 940 941 942
        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();
943
            else if (x.isLetter())
944 945
                m_key = x.toUpper().unicode();
        }
946 947

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

953 954 955 956
        // m_xkey is only a cache.
        m_xkey = (m_text.size() == 1 ? m_text.at(0).unicode() : m_key);
    }

957 958 959 960 961
    bool isValid() const
    {
        return m_key != 0 || !m_text.isNull();
    }

962 963
    bool isDigit() const
    {
hluk's avatar
hluk committed
964
        return m_xkey >= '0' && m_xkey <= '9';
965
    }
966

967 968 969 970 971
    bool isKey(int c) const
    {
        return !m_modifiers && m_key == c;
    }

972 973 974 975 976 977 978
    bool isBackspace() const
    {
        return m_key == Key_Backspace || isControl('h');
    }

    bool isReturn() const
    {
979
        return m_key == QLatin1Char('\n') || m_key == Key_Return || m_key == Key_Enter;
980 981
    }

hjk's avatar
hjk committed
982 983 984 985 986 987
    bool isEscape() const
    {
        return isKey(Key_Escape) || isKey(27) || isControl('c')
            || isControl(Key_BracketLeft);
    }

988 989
    bool is(int c) const
    {
990
        return m_xkey == c && !isControl();
991 992
    }

993 994
    bool isControl() const
    {
995
        return isOnlyControlModifier(m_modifiers);
996 997
    }

998 999
    bool isControl(int c) const
    {
1000
        return isControl()
1001
            && (m_xkey == c || m_xkey + 32 == c || m_xkey + 64 == c || m_xkey + 96 == c);
1002 1003
    }

1004 1005 1006 1007 1008
    bool isShift() const
    {
        return m_modifiers & Qt::ShiftModifier;
    }

1009 1010
    bool isShift(int c) const
    {
1011
        return isShift() && m_xkey == c;
1012 1013
    }

1014
    bool operator<(const Input &a) const
1015
    {
1016 1017 1018 1019 1020 1021 1022
        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;
1023 1024
    }

1025
    bool operator==(const Input &a) const
1026
    {
1027
        return !(*this < a || a < *this);
1028 1029
    }

1030 1031
    bool operator!=(const Input &a) const { return !operator==(a); }

1032 1033
    QString text() const { return m_text; }

hjk's avatar
hjk committed
1034 1035 1036 1037 1038
    QChar asChar() const
    {
        return (m_text.size() == 1 ? m_text.at(0) : QChar());
    }

1039 1040
    int key() const { return m_key; }

1041
    Qt::KeyboardModifiers modifiers() const { return m_modifiers; }
1042

1043
    // Return raw character for macro recording or dot command.
1044 1045 1046
    QChar raw() const
    {
        if (m_key == Key_Tab)
1047
            return QLatin1Char('\t');
1048
        if (m_key == Key_Return)
1049
            return QLatin1Char('\n');
1050 1051 1052
        if (m_key == Key_Escape)
            return QChar(27);
        return m_xkey;
1053 1054
    }

1055 1056 1057
    QString toString() const
    {
        QString key = vimKeyNames().key(m_key);
hluk's avatar
hluk committed
1058
        bool namedKey = !key.isEmpty();
1059

hluk's avatar
hluk committed
1060
        if (!namedKey) {
1061 1062
            if (m_xkey == '<')
                key = _("<LT>");
1063 1064
            else if (m_xkey == '>')
                key = _("<GT>");
1065 1066
            else
                key = QChar(m_xkey);
hluk's avatar
hluk committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        }

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

        if (namedKey || shift || ctrl) {
1077 1078 1079 1080 1081
            key.prepend(QLatin1Char('<'));
            key.append(QLatin1Char('>'));
        }

        return key;
1082 1083
    }

hjk's avatar
hjk committed
1084 1085 1086 1087 1088
    QDebug dump(QDebug ts) const