basetexteditor.cpp 185 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
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.
15
**
16
** GNU Lesser General Public License Usage
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.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

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

con's avatar
con committed
32 33 34 35 36
#include "texteditorconstants.h"
#ifndef TEXTEDITOR_STANDALONE
#include "texteditorplugin.h"
#include "completionsupport.h"
#endif
37
#include "behaviorsettings.h"
con's avatar
con committed
38 39 40
#include "basetextdocument.h"
#include "basetexteditor_p.h"
#include "codecselector.h"
41
#include "tabsettings.h"
con's avatar
con committed
42 43

#ifndef TEXTEDITOR_STANDALONE
44
#include <aggregation/aggregate.h>
con's avatar
con committed
45 46
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
47
#include <coreplugin/manhattanstyle.h>
48 49
#include <coreplugin/icore.h>
#include <coreplugin/actionmanager/actionmanager.h>
50
#include <extensionsystem/pluginmanager.h>
con's avatar
con committed
51
#include <find/basetextfind.h>
52
#include <utils/stylehelper.h>
con's avatar
con committed
53
#endif
54

con's avatar
con committed
55
#include <utils/linecolumnlabel.h>
hjk's avatar
hjk committed
56
#include <utils/qtcassert.h>
con's avatar
con committed
57 58 59 60 61 62

#include <QtCore/QCoreApplication>
#include <QtCore/QTextCodec>
#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
63
#include <QtCore/QTimeLine>
con's avatar
con committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include <QtGui/QAbstractTextDocumentLayout>
#include <QtGui/QApplication>
#include <QtGui/QKeyEvent>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
#include <QtGui/QPainter>
#include <QtGui/QPrinter>
#include <QtGui/QPrintDialog>
#include <QtGui/QScrollBar>
#include <QtGui/QShortcut>
#include <QtGui/QStyle>
#include <QtGui/QSyntaxHighlighter>
#include <QtGui/QTextCursor>
#include <QtGui/QTextBlock>
#include <QtGui/QTextLayout>
#include <QtGui/QToolBar>
#include <QtGui/QToolTip>
#include <QtGui/QInputDialog>
82
#include <QtGui/QMenu>
con's avatar
con committed
83 84 85 86 87 88

using namespace TextEditor;
using namespace TextEditor::Internal;


namespace TextEditor {
89
namespace Internal {
con's avatar
con committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

class TextEditExtraArea : public QWidget {
    BaseTextEditor *textEdit;
public:
    TextEditExtraArea(BaseTextEditor *edit):QWidget(edit) {
        textEdit = edit;
        setAutoFillBackground(true);
    }
public:

    QSize sizeHint() const {
        return QSize(textEdit->extraAreaWidth(), 0);
    }
protected:
    void paintEvent(QPaintEvent *event){
        textEdit->extraAreaPaintEvent(event);
    }
    void mousePressEvent(QMouseEvent *event){
        textEdit->extraAreaMouseEvent(event);
    }
    void mouseMoveEvent(QMouseEvent *event){
        textEdit->extraAreaMouseEvent(event);
    }
    void mouseReleaseEvent(QMouseEvent *event){
        textEdit->extraAreaMouseEvent(event);
    }
    void leaveEvent(QEvent *event){
        textEdit->extraAreaLeaveEvent(event);
    }

    void wheelEvent(QWheelEvent *event) {
        QCoreApplication::sendEvent(textEdit->viewport(), event);
    }
};

125 126
} // namespace Internal
} // namespace TextEditor
con's avatar
con committed
127

128

con's avatar
con committed
129
ITextEditor *BaseTextEditor::openEditorAt(const QString &fileName,
130 131 132
                                          int line,
                                          int column,
                                          const QString &editorKind)
con's avatar
con committed
133
{
134
    Core::EditorManager *editorManager = Core::EditorManager::instance();
135
    editorManager->addCurrentPositionToNavigationHistory();
mae's avatar
mae committed
136
    Core::IEditor *editor = editorManager->openEditor(fileName, editorKind, Core::EditorManager::IgnoreNavigationHistory);
con's avatar
con committed
137 138 139 140 141
    TextEditor::ITextEditor *texteditor = qobject_cast<TextEditor::ITextEditor *>(editor);
    if (texteditor) {
        texteditor->gotoLine(line, column);
        return texteditor;
    }
142

con's avatar
con committed
143 144 145
    return 0;
}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
static void convertToPlainText(QString &txt)
{
    QChar *uc = txt.data();
    QChar *e = uc + txt.size();

    for (; uc != e; ++uc) {
        switch (uc->unicode()) {
        case 0xfdd0: // QTextBeginningOfFrame
        case 0xfdd1: // QTextEndOfFrame
        case QChar::ParagraphSeparator:
        case QChar::LineSeparator:
            *uc = QLatin1Char('\n');
            break;
        case QChar::Nbsp:
            *uc = QLatin1Char(' ');
            break;
        default:
            ;
        }
    }
}

con's avatar
con committed
168 169 170 171 172 173 174 175 176
BaseTextEditor::BaseTextEditor(QWidget *parent)
    : QPlainTextEdit(parent)
{
    d = new BaseTextEditorPrivate();
    d->q = this;
    d->m_extraArea = new TextEditExtraArea(this);
    d->m_extraArea->setMouseTracking(true);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

177
    d->m_overlay = new TextEditorOverlay(this);
178
    d->m_snippetOverlay = new TextEditorOverlay(this);
179 180
    d->m_searchResultOverlay = new TextEditorOverlay(this);

con's avatar
con committed
181 182 183 184 185 186
    d->setupDocumentSignals(d->m_document);
    d->setupDocumentSignals(d->m_document);

    d->m_lastScrollPos = -1;
    setCursorWidth(2);

187
    d->m_allowSkippingOfBlockEnd = false;
con's avatar
con committed
188 189 190 191 192 193 194 195

    // from RESEARCH

    setLayoutDirection(Qt::LeftToRight);
    viewport()->setMouseTracking(true);
    d->extraAreaSelectionAnchorBlockNumber
        = d->extraAreaToggleMarkBlockNumber
        = d->extraAreaHighlightCollapseBlockNumber
196
        = d->extraAreaHighlightCollapseColumn
con's avatar
con committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        = -1;

    d->visibleCollapsedBlockNumber = d->suggestedVisibleCollapsedBlockNumber = -1;

    connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(slotUpdateExtraAreaWidth()));
    connect(this, SIGNAL(modificationChanged(bool)), this, SLOT(slotModificationChanged(bool)));
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
    connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(slotUpdateRequest(QRect, int)));
    connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged()));

//     (void) new QShortcut(tr("CTRL+L"), this, SLOT(centerCursor()), 0, Qt::WidgetShortcut);
//     (void) new QShortcut(tr("F9"), this, SLOT(slotToggleMark()), 0, Qt::WidgetShortcut);
//     (void) new QShortcut(tr("F11"), this, SLOT(slotToggleBlockVisible()));


    // parentheses matcher
    d->m_parenthesesMatchingEnabled = false;
    d->m_formatRange = true;
    d->m_matchFormat.setForeground(Qt::red);
    d->m_rangeFormat.setBackground(QColor(0xb4, 0xee, 0xb4));
    d->m_mismatchFormat.setBackground(Qt::magenta);
    d->m_parenthesesMatchingTimer = new QTimer(this);
    d->m_parenthesesMatchingTimer->setSingleShot(true);
    connect(d->m_parenthesesMatchingTimer, SIGNAL(timeout()), this, SLOT(_q_matchParentheses()));

222 223 224 225
    d->m_highlightBlocksTimer = new QTimer(this);
    d->m_highlightBlocksTimer->setSingleShot(true);
    connect(d->m_highlightBlocksTimer, SIGNAL(timeout()), this, SLOT(_q_highlightBlocks()));

226
    d->m_animator = 0;
con's avatar
con committed
227 228 229 230 231 232 233

    d->m_searchResultFormat.setBackground(QColor(0xffef0b));

    slotUpdateExtraAreaWidth();
    slotCursorPositionChanged();
    setFrameStyle(QFrame::NoFrame);

234 235 236 237
    d->m_delayedUpdateTimer = new QTimer(this);
    d->m_delayedUpdateTimer->setSingleShot(true);
    connect(d->m_delayedUpdateTimer, SIGNAL(timeout()), viewport(), SLOT(update()));

con's avatar
con committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(currentEditorChanged(Core::IEditor*)));
}

BaseTextEditor::~BaseTextEditor()
{
    delete d;
    d = 0;
}

QString BaseTextEditor::mimeType() const
{
    return d->m_document->mimeType();
}

void BaseTextEditor::setMimeType(const QString &mt)
{
    d->m_document->setMimeType(mt);
}

void BaseTextEditor::print(QPrinter *printer)
{
    const bool oldFullPage =  printer->fullPage();
    printer->setFullPage(true);
    QPrintDialog *dlg = new QPrintDialog(printer, this);
    dlg->setWindowTitle(tr("Print Document"));
    if (dlg->exec() == QDialog::Accepted) {
        d->print(printer);
    }
    printer->setFullPage(oldFullPage);
    delete dlg;
}

271 272 273 274 275 276
static int collapseBoxWidth(const QFontMetrics &fm)
{
    const int lineSpacing = fm.lineSpacing();
    return lineSpacing + lineSpacing%2 + 1;
}

con's avatar
con committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
static void printPage(int index, QPainter *painter, const QTextDocument *doc,
                      const QRectF &body, const QRectF &titleBox,
                      const QString &title)
{
    painter->save();

    painter->translate(body.left(), body.top() - (index - 1) * body.height());
    QRectF view(0, (index - 1) * body.height(), body.width(), body.height());

    QAbstractTextDocumentLayout *layout = doc->documentLayout();
    QAbstractTextDocumentLayout::PaintContext ctx;

    painter->setFont(QFont(doc->defaultFont()));
    QRectF box = titleBox.translated(0, view.top());
    int dpix = painter->device()->logicalDpiX();
    int dpiy = painter->device()->logicalDpiY();
    int mx = 5 * dpix / 72.0;
    int my = 2 * dpiy / 72.0;
    painter->fillRect(box.adjusted(-mx, -my, mx, my), QColor(210, 210, 210));
    if (!title.isEmpty())
        painter->drawText(box, Qt::AlignCenter, title);
    const QString pageString = QString::number(index);
    painter->drawText(box, Qt::AlignRight, pageString);

    painter->setClipRect(view);
    ctx.clip = view;
    // don't use the system palette text as default text color, on HP/UX
    // for example that's white, and white text on white paper doesn't
    // look that nice
    ctx.palette.setColor(QPalette::Text, Qt::black);

    layout->draw(painter, ctx);

    painter->restore();
}

void BaseTextEditorPrivate::print(QPrinter *printer)
{

    QTextDocument *doc = q->document();

    QString title = q->displayName();
    if (title.isEmpty())
        printer->setDocName(title);


    QPainter p(printer);

    // Check that there is a valid device to print to.
    if (!p.isActive())
        return;

    doc = doc->clone(doc);

    QTextOption opt = doc->defaultTextOption();
    opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    doc->setDefaultTextOption(opt);

    (void)doc->documentLayout(); // make sure that there is a layout


    QColor background = q->palette().color(QPalette::Base);
    bool backgroundIsDark = background.value() < 128;

    for (QTextBlock srcBlock = q->document()->firstBlock(), dstBlock = doc->firstBlock();
         srcBlock.isValid() && dstBlock.isValid();
         srcBlock = srcBlock.next(), dstBlock = dstBlock.next()) {


        QList<QTextLayout::FormatRange> formatList = srcBlock.layout()->additionalFormats();
        if (backgroundIsDark) {
            // adjust syntax highlighting colors for better contrast
            for (int i = formatList.count() - 1; i >=0; --i) {
                QTextCharFormat &format = formatList[i].format;
                if (format.background().color() == background) {
                    QBrush brush = format.foreground();
                    QColor color = brush.color();
                    int h,s,v,a;
                    color.getHsv(&h, &s, &v, &a);
                    color.setHsv(h, s, qMin(128, v), a);
                    brush.setColor(color);
                    format.setForeground(brush);
                }
                format.setBackground(Qt::white);
            }
        }

        dstBlock.layout()->setAdditionalFormats(formatList);
    }

    QAbstractTextDocumentLayout *layout = doc->documentLayout();
    layout->setPaintDevice(p.device());

    int dpiy = p.device()->logicalDpiY();
    int margin = (int) ((2/2.54)*dpiy); // 2 cm margins

    QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
    fmt.setMargin(margin);
    doc->rootFrame()->setFrameFormat(fmt);

    QRectF pageRect(printer->pageRect());
    QRectF body = QRectF(0, 0, pageRect.width(), pageRect.height());
    QFontMetrics fontMetrics(doc->defaultFont(), p.device());

    QRectF titleBox(margin,
                    body.top() + margin
                    - fontMetrics.height()
                    - 6 * dpiy / 72.0,
                    body.width() - 2*margin,
                    fontMetrics.height());
    doc->setPageSize(body.size());

    int docCopies;
    int pageCopies;
    if (printer->collateCopies() == true){
        docCopies = 1;
        pageCopies = printer->numCopies();
    } else {
        docCopies = printer->numCopies();
        pageCopies = 1;
    }

    int fromPage = printer->fromPage();
    int toPage = printer->toPage();
    bool ascending = true;

    if (fromPage == 0 && toPage == 0) {
        fromPage = 1;
        toPage = doc->pageCount();
    }
    // paranoia check
    fromPage = qMax(1, fromPage);
    toPage = qMin(doc->pageCount(), toPage);

    if (printer->pageOrder() == QPrinter::LastPageFirst) {
        int tmp = fromPage;
        fromPage = toPage;
        toPage = tmp;
        ascending = false;
    }

    for (int i = 0; i < docCopies; ++i) {

        int page = fromPage;
        while (true) {
            for (int j = 0; j < pageCopies; ++j) {
                if (printer->printerState() == QPrinter::Aborted
                    || printer->printerState() == QPrinter::Error)
                    goto UserCanceled;
                printPage(page, &p, doc, body, titleBox, title);
                if (j < pageCopies - 1)
                    printer->newPage();
            }

            if (page == toPage)
                break;

            if (ascending)
                ++page;
            else
                --page;

            printer->newPage();
        }

        if ( i < docCopies - 1)
            printer->newPage();
    }

UserCanceled:
    delete doc;
}


bool DocumentMarker::addMark(TextEditor::ITextMark *mark, int line)
{
hjk's avatar
hjk committed
453
    QTC_ASSERT(line >= 1, return false);
con's avatar
con committed
454 455
    int blockNumber = line - 1;
    TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(document->documentLayout());
hjk's avatar
hjk committed
456
    QTC_ASSERT(documentLayout, return false);
con's avatar
con committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
        TextBlockUserData *userData = TextEditDocumentLayout::userData(block);
        userData->addMark(mark);
        mark->updateLineNumber(blockNumber + 1);
        mark->updateBlock(block);
        documentLayout->hasMarks = true;
        documentLayout->requestUpdate();
        return true;
    }
    return false;
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
int BaseTextEditorPrivate::visualIndent(const QTextBlock &block) const
{
    if (!block.isValid())
        return 0;
    const QTextDocument *document = block.document();
    int i = 0;
    while (i < block.length()) {
        if (!document->characterAt(block.position() + i).isSpace()) {
            QTextCursor cursor(block);
            cursor.setPosition(block.position() + i);
            return q->cursorRect(cursor).x();
        }
        ++i;
    }

    return 0;
}
con's avatar
con committed
488 489 490

TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
hjk's avatar
hjk committed
491
    QTC_ASSERT(line >= 1, return TextMarks());
con's avatar
con committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    int blockNumber = line - 1;
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
        if (TextBlockUserData *userData = TextEditDocumentLayout::testUserData(block))
            return userData->marks();
    }
    return TextMarks();
}

void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
    bool needUpdate = false;
    QTextBlock block = document->begin();
    while (block.isValid()) {
        if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
            needUpdate |= data->removeMark(mark);
        }
        block = block.next();
    }
    if (needUpdate)
        updateMark(0);
}


bool DocumentMarker::hasMark(TextEditor::ITextMark *mark) const
{
    QTextBlock block = document->begin();
    while (block.isValid()) {
        if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
            if (data->hasMark(mark))
                return true;
        }
        block = block.next();
    }
    return false;
}

ITextMarkable *BaseTextEditor::markableInterface() const
{
    return baseTextDocument()->documentMarker();
}

ITextEditable *BaseTextEditor::editableInterface() const
{
    if (!d->m_editable) {
        d->m_editable = const_cast<BaseTextEditor*>(this)->createEditableInterface();
        connect(this, SIGNAL(textChanged()),
                d->m_editable, SIGNAL(contentsChanged()));
        connect(this, SIGNAL(changed()),
                d->m_editable, SIGNAL(changed()));
    }
    return d->m_editable;
}


void BaseTextEditor::currentEditorChanged(Core::IEditor *editor)
{
    if (editor == d->m_editable) {
        if (d->m_document->hasDecodingError()) {
            Core::EditorManager::instance()->showEditorInfoBar(QLatin1String(Constants::SELECT_ENCODING),
553 554
                tr("<b>Error:</b> Could not decode \"%1\" with \"%2\"-encoding. Editing not possible.")
                    .arg(displayName()).arg(QString::fromLatin1(d->m_document->codec()->name())),
con's avatar
con committed
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
                tr("Select Encoding"),
                this, SLOT(selectEncoding()));
        }
    }
}

void BaseTextEditor::selectEncoding()
{
    BaseTextDocument *doc = d->m_document;
    CodecSelector codecSelector(this, doc);

    switch (codecSelector.exec()) {
    case CodecSelector::Reload:
        doc->reload(codecSelector.selectedCodec());
        setReadOnly(d->m_document->hasDecodingError());
        if (doc->hasDecodingError())
            currentEditorChanged(Core::EditorManager::instance()->currentEditor());
        else
            Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String(Constants::SELECT_ENCODING));
        break;
    case CodecSelector::Save:
        doc->setCodec(codecSelector.selectedCodec());
        Core::EditorManager::instance()->saveEditor(editableInterface());
        break;
    case CodecSelector::Cancel:
        break;
    }
}

void DocumentMarker::updateMark(ITextMark *mark)
{
586
    Q_UNUSED(mark)
hjk's avatar
hjk committed
587 588
    TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(document->documentLayout());
    QTC_ASSERT(documentLayout, return);
con's avatar
con committed
589 590 591 592 593 594 595 596 597
    documentLayout->requestUpdate();
}


void BaseTextEditor::triggerCompletions()
{
    emit requestAutoCompletion(editableInterface(), true);
}

Roberto Raggi's avatar
Roberto Raggi committed
598 599 600 601 602
void BaseTextEditor::triggerQuickFix()
{
    emit requestQuickFix(editableInterface());
}

con's avatar
con committed
603 604 605 606 607 608 609 610 611 612 613
bool BaseTextEditor::createNew(const QString &contents)
{
    setPlainText(contents);
    document()->setModified(false);
    return true;
}

bool BaseTextEditor::open(const QString &fileName)
{
    if (d->m_document->open(fileName)) {
        moveCursor(QTextCursor::Start);
614 615
        if (d->m_displaySettings.m_autoFoldFirstComment)
            d->collapseLicenseHeader();
con's avatar
con committed
616 617 618 619 620 621
        setReadOnly(d->m_document->hasDecodingError());
        return true;
    }
    return false;
}

622 623 624 625 626 627 628 629 630 631
/*
  Collapses the first comment in a file, if there is only whitespace above
  */
void BaseTextEditorPrivate::collapseLicenseHeader()
{
    QTextDocument *doc = q->document();
    TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(doc->documentLayout());
    QTC_ASSERT(documentLayout, return);
    QTextBlock block = doc->firstBlock();
    const TabSettings &ts = m_document->tabSettings();
632
    while (block.isValid() && block.isVisible()) {
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        TextBlockUserData *data = TextBlockUserData::canCollapse(block);
        if (data && block.next().isVisible()) {
            QChar character;
            static_cast<TextBlockUserData*>(data)->collapseAtPos(&character);
            if (character != QLatin1Char('+'))
                break; // not a comment
            TextBlockUserData::doCollapse(block, false);
            moveCursorVisible();
            documentLayout->requestUpdate();
            documentLayout->emitDocumentSizeChanged();
            break;
        }
        QString text = block.text();
        if (ts.firstNonSpace(text) < text.size())
            break;
        block = block.next();
    }
}

652 653 654 655 656 657 658
const Utils::ChangeSet &BaseTextEditor::changeSet() const
{
    return d->m_changeSet;
}

void BaseTextEditor::setChangeSet(const Utils::ChangeSet &changeSet)
{
Roberto Raggi's avatar
Roberto Raggi committed
659 660
    using namespace Utils;

661
    d->m_changeSet = changeSet;
Roberto Raggi's avatar
Roberto Raggi committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

    foreach (const ChangeSet::EditOp &op, changeSet.operationList()) {
        // ### TODO: process the edit operation

        switch (op.type) {
        case ChangeSet::EditOp::Replace:
            break;

        case ChangeSet::EditOp::Move:
            break;

        case ChangeSet::EditOp::Insert:
            break;

        case ChangeSet::EditOp::Remove:
            break;

        case ChangeSet::EditOp::Flip:
            break;

        case ChangeSet::EditOp::Copy:
            break;

        default:
            break;
        } // switch
    }
689 690
}

691
Core::IFile *BaseTextEditor::file()
con's avatar
con committed
692 693 694 695 696 697
{
    return d->m_document;
}

void BaseTextEditor::editorContentsChange(int position, int charsRemoved, int charsAdded)
{
698 699 700
    if (d->m_animator)
        d->m_animator->finish();

con's avatar
con committed
701 702 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
    d->m_contentsChanged = true;

    // Keep the line numbers and the block information for the text marks updated
    if (charsRemoved != 0) {
        d->updateMarksLineNumber();
        d->updateMarksBlock(document()->findBlock(position));
    } else {
        const QTextBlock posBlock = document()->findBlock(position);
        const QTextBlock nextBlock = document()->findBlock(position + charsAdded);
        if (posBlock != nextBlock) {
            d->updateMarksLineNumber();
            d->updateMarksBlock(posBlock);
            d->updateMarksBlock(nextBlock);
        } else {
            d->updateMarksBlock(posBlock);
        }
    }
}


void BaseTextEditor::slotSelectionChanged()
{
    bool changed = (d->m_inBlockSelectionMode != d->m_lastEventWasBlockSelectionEvent);
    d->m_inBlockSelectionMode = d->m_lastEventWasBlockSelectionEvent;
    if (changed || d->m_inBlockSelectionMode)
        viewport()->update();
    if (!d->m_inBlockSelectionMode)
        d->m_blockSelectionExtraX = 0;
729 730
    if (!d->m_selectBlockAnchor.isNull() && !textCursor().hasSelection())
        d->m_selectBlockAnchor = QTextCursor();
731 732 733

    // Clear any link which might be showing when the selection changes
    clearLink();
con's avatar
con committed
734 735
}

736 737 738
void BaseTextEditor::gotoBlockStart()
{
    QTextCursor cursor = textCursor();
739
    if (TextBlockUserData::findPreviousOpenParenthesis(&cursor, false)) {
740
        setTextCursor(cursor);
741 742
        _q_matchParentheses();
    }
743 744 745 746 747
}

void BaseTextEditor::gotoBlockEnd()
{
    QTextCursor cursor = textCursor();
748
    if (TextBlockUserData::findNextClosingParenthesis(&cursor, false)) {
749
        setTextCursor(cursor);
750 751
        _q_matchParentheses();
    }
752 753 754 755 756
}

void BaseTextEditor::gotoBlockStartWithSelection()
{
    QTextCursor cursor = textCursor();
757
    if (TextBlockUserData::findPreviousOpenParenthesis(&cursor, true)) {
758
        setTextCursor(cursor);
759 760
        _q_matchParentheses();
    }
761 762 763 764 765
}

void BaseTextEditor::gotoBlockEndWithSelection()
{
    QTextCursor cursor = textCursor();
766
    if (TextBlockUserData::findNextClosingParenthesis(&cursor, true)) {
767
        setTextCursor(cursor);
768 769 770 771 772 773 774 775 776
        _q_matchParentheses();
    }
}

static QTextCursor flippedCursor(const QTextCursor &cursor) {
    QTextCursor flipped = cursor;
    flipped.clearSelection();
    flipped.setPosition(cursor.anchor(), QTextCursor::KeepAnchor);
    return flipped;
777 778
}

779 780 781 782 783 784 785 786 787 788 789 790 791
void BaseTextEditor::selectBlockUp()
{
    QTextCursor cursor = textCursor();
    if (!cursor.hasSelection())
        d->m_selectBlockAnchor = cursor;
    else
        cursor.setPosition(cursor.selectionStart());


    if (!TextBlockUserData::findPreviousOpenParenthesis(&cursor, false))
        return;
    if (!TextBlockUserData::findNextClosingParenthesis(&cursor, true))
        return;
792 793
    setTextCursor(flippedCursor(cursor));
    _q_matchParentheses();
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
}

void BaseTextEditor::selectBlockDown()
{
    QTextCursor tc = textCursor();
    QTextCursor cursor = d->m_selectBlockAnchor;

    if (!tc.hasSelection() || cursor.isNull())
        return;
    tc.setPosition(tc.selectionStart());

    forever {
        QTextCursor ahead = cursor;
        if (!TextBlockUserData::findPreviousOpenParenthesis(&ahead, false))
            break;
        if (ahead.position() <= tc.position())
            break;
        cursor = ahead;
    }
    if ( cursor != d->m_selectBlockAnchor)
        TextBlockUserData::findNextClosingParenthesis(&cursor, true);

816 817
    setTextCursor(flippedCursor(cursor));
    _q_matchParentheses();
818 819
}

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
void BaseTextEditor::copyLineUp()
{
    copyLineUpDown(true);
}

void BaseTextEditor::copyLineDown()
{
    copyLineUpDown(false);
}

void BaseTextEditor::copyLineUpDown(bool up)
{
    QTextCursor cursor = textCursor();
    QTextCursor move = cursor;
    move.beginEditBlock();

    bool hasSelection = cursor.hasSelection();

    if (hasSelection) {
        move.setPosition(cursor.selectionStart());
        move.movePosition(QTextCursor::StartOfBlock);
        move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
        move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    } else {
        move.movePosition(QTextCursor::StartOfBlock);
        move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }

    QString text = move.selectedText();

    if (up) {
        move.setPosition(cursor.selectionStart());
        move.movePosition(QTextCursor::StartOfBlock);
        move.insertBlock();
        move.movePosition(QTextCursor::Left);
    } else {
        move.movePosition(QTextCursor::EndOfBlock);
        if (move.atBlockStart()) {
            move.movePosition(QTextCursor::NextBlock);
            move.insertBlock();
            move.movePosition(QTextCursor::Left);
        } else {
            move.insertBlock();
        }
    }

    int start = move.position();
    move.clearSelection();
    move.insertText(text);
    int end = move.position();

    move.setPosition(start);
    move.setPosition(end, QTextCursor::KeepAnchor);

    indent(document(), move, QChar::Null);
    move.endEditBlock();

    setTextCursor(move);
}

880
void BaseTextEditor::joinLines()
881 882 883 884
{
    QTextCursor move = textCursor();
    move.beginEditBlock();

885
    move.movePosition(QTextCursor::NextBlock);
886 887 888
    move.movePosition(QTextCursor::StartOfBlock);
    move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    QString cutLine = move.selectedText();
889

890
    // Collapse leading whitespaces to one or insert whitespace
891
    cutLine.replace(QRegExp("^\\s*"), " ");
892 893
    move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
    move.removeSelectedText();
894

895
    move.movePosition(QTextCursor::PreviousBlock);
896
    move.movePosition(QTextCursor::EndOfBlock);
897

898 899 900 901 902
    move.insertText(cutLine);
    move.endEditBlock();
    setTextCursor(move);
}

903 904 905 906 907 908 909 910 911 912 913 914 915 916
void BaseTextEditor::moveLineUp()
{
    moveLineUpDown(true);
}

void BaseTextEditor::moveLineDown()
{
    moveLineUpDown(false);
}

void BaseTextEditor::moveLineUpDown(bool up)
{
    QTextCursor cursor = textCursor();
    QTextCursor move = cursor;
917 918 919 920
    if (d->m_moveLineUndoHack)
        move.joinPreviousEditBlock();
    else
        move.beginEditBlock();
921 922 923 924 925 926 927

    bool hasSelection = cursor.hasSelection();

    if (cursor.hasSelection()) {
        move.setPosition(cursor.selectionStart());
        move.movePosition(QTextCursor::StartOfBlock);
        move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
928
        move.movePosition(move.atBlockStart() ? QTextCursor::Left: QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
929 930 931 932 933 934 935
    } else {
        move.movePosition(QTextCursor::StartOfBlock);
        move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }
    QString text = move.selectedText();
    move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
    move.removeSelectedText();
936

937 938 939 940 941 942 943 944 945 946 947 948 949 950
    if (up) {
        move.movePosition(QTextCursor::PreviousBlock);
        move.insertBlock();
        move.movePosition(QTextCursor::Left);
    } else {
        move.movePosition(QTextCursor::EndOfBlock);
        if (move.atBlockStart()) { // empty block
            move.movePosition(QTextCursor::NextBlock);
            move.insertBlock();
            move.movePosition(QTextCursor::Left);
        } else {
            move.insertBlock();
        }
    }
951

952 953 954 955
    int start = move.position();
    move.clearSelection();
    move.insertText(text);
    int end = move.position();
956

957 958 959 960 961
    if (hasSelection) {
        move.setPosition(start);
        move.setPosition(end, QTextCursor::KeepAnchor);
    }

mae's avatar
mae committed
962
    reindent(document(), move);
963 964
    move.endEditBlock();

965
    setTextCursor(move);
966
    d->m_moveLineUndoHack = true;
967
}
968

969 970
void BaseTextEditor::cleanWhitespace()
{
971
    d->m_document->cleanWhitespace(textCursor());
972
}
973

con's avatar
con committed
974 975
void BaseTextEditor::keyPressEvent(QKeyEvent *e)
{
976 977 978
    viewport()->setCursor(Qt::BlankCursor);
    QToolTip::hideText();

979
    d->m_moveLineUndoHack = false;
con's avatar
con committed
980 981 982 983 984 985
    d->clearVisibleCollapsedBlock();

    QKeyEvent *original_e = e;
    d->m_lastEventWasBlockSelectionEvent = false;

    if (e->key() == Qt::Key_Escape) {
986 987 988 989 990 991 992 993 994
        if (d->m_snippetOverlay->isVisible()) {
            e->accept();
            d->m_snippetOverlay->hide();
            d->m_snippetOverlay->clear();
            QTextCursor cursor = textCursor();
            cursor.clearSelection();
            setTextCursor(cursor);
            return;
        }
con's avatar
con committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005
    }

    bool ro = isReadOnly();

    if (d->m_inBlockSelectionMode) {
        if (e == QKeySequence::Cut) {
            if (!ro) {
                cut();
                e->accept();
                return;
            }
1006
        } else if (e == QKeySequence::Delete || e->key() == Qt::Key_Backspace) {
con's avatar
con committed
1007 1008 1009 1010 1011
            if (!ro) {
                d->removeBlockSelection();
                e->accept();
                return;
            }
1012 1013 1014 1015 1016
        } else if (e == QKeySequence::Paste) {
            if (!ro) {
                d->removeBlockSelection();
                // continue
            }
con's avatar
con committed
1017 1018 1019 1020 1021 1022 1023 1024 1025
        }
    }


    if (!ro
        && (e == QKeySequence::InsertParagraphSeparator
            || (!d->m_lineSeparatorsAllowed && e == QKeySequence::InsertLineSeparator))
        ) {

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
        if (d->m_snippetOverlay->isVisible()) {
            e->accept();
            d->m_snippetOverlay->hide();
            d->m_snippetOverlay->clear();
            QTextCursor cursor = textCursor();
            cursor.movePosition(QTextCursor::EndOfBlock);
            setTextCursor(cursor);
            return;
        }


con's avatar
con committed
1037 1038 1039
        QTextCursor cursor = textCursor();
        if (d->m_inBlockSelectionMode)
            cursor.clearSelection();
1040
        const TabSettings &ts = d->m_document->tabSettings();
mae's avatar
mae committed
1041 1042
        cursor.beginEditBlock();

1043
        int extraBlocks = paragraphSeparatorAboutToBeInserted(cursor); // virtual
mae's avatar
mae committed
1044

1045
        if (ts.m_autoIndent) {
1046
            cursor.insertBlock();
con's avatar
con committed
1047
            indent(document(), cursor, QChar::Null);
1048 1049
        } else {
            cursor.insertBlock();
1050 1051 1052

            // After inserting the block, to avoid duplicating whitespace on the same line
            const QString previousBlockText = cursor.block().previous().text();
1053
            cursor.insertText(ts.indentationString(previousBlockText));
con's avatar
con committed
1054
        }
mae's avatar
mae committed
1055
        cursor.endEditBlock();
con's avatar
con committed
1056
        e->accept();
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

        if (extraBlocks > 0) {
            QTextCursor ensureVisible = cursor;
            while (extraBlocks > 0) {
                --extraBlocks;
                ensureVisible.movePosition(QTextCursor::NextBlock);
            }
            setTextCursor(ensureVisible);
        }

con's avatar
con committed
1067 1068
        setTextCursor(cursor);
        return;
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    } else if (!ro
               && (e == QKeySequence::MoveToStartOfBlock
                   || e == QKeySequence::SelectStartOfBlock)){
        if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier))
            d->m_lastEventWasBlockSelectionEvent = true;
        handleHomeKey(e == QKeySequence::SelectStartOfBlock);
        e->accept();
        return;
    } else if (!ro
               && (e == QKeySequence::MoveToStartOfLine
                   || e == QKeySequence::SelectStartOfLine)){
        if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier))
            d->m_lastEventWasBlockSelectionEvent = true;
        QTextCursor cursor = textCursor();
        if (QTextLayout *layout = cursor.block().layout()) {
            if (layout->lineForTextPosition(cursor.position() - cursor.block().position()).lineNumber() == 0) {
                handleHomeKey(e == QKeySequence::SelectStartOfLine);
                e->accept();
                return;
            }
        }
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    } else if (!ro
               && e == QKeySequence::DeleteStartOfWord
               && d->m_document->tabSettings().m_autoIndent
               && !textCursor().hasSelection()){
        e->accept();
        QTextCursor c = textCursor();
        int pos = c.position();
        c.movePosition(QTextCursor::PreviousWord);
        int targetpos = c.position();
        forever {
            handleBackspaceKey();
            int cpos = textCursor().position();
            if (cpos == pos || cpos <= targetpos)
                break;
            pos = cpos;
        }
        return;
con's avatar
con committed
1107 1108 1109 1110
    } else switch (e->key()) {


#if 0
1111 1112 1113 1114
    case Qt::Key_Dollar: {
            d->m_overlay->setVisible(!d->m_overlay->isVisible());
            d->m_overlay->setCursor(textCursor());
            e->accept();
con's avatar
con committed
1115 1116 1117 1118 1119
        return;

    } break;
#endif
    case Qt::Key_Tab:
Joel Nordell's avatar
Joel Nordell committed
1120
    case Qt::Key_Backtab: {
con's avatar
con committed
1121
        if (ro) break;
1122 1123 1124 1125 1126
        if (d->m_snippetOverlay->isVisible() && !d->m_snippetOverlay->isEmpty()) {
            d->snippetTabOrBacktab(e->key() == Qt::Key_Tab);
            e->accept();
            return;
        }
Joel Nordell's avatar
Joel Nordell committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        QTextCursor cursor = textCursor();
        int newPosition;
        if (d->m_document->tabSettings().tabShouldIndent(document(), cursor, &newPosition)) {
            if (newPosition != cursor.position() && !cursor.hasSelection()) {
                cursor.setPosition(newPosition);
                setTextCursor(cursor);
            }
            indent(document(), cursor, QChar::Null);
        } else {
            indentOrUnindent(e->key() == Qt::Key_Tab);
        }
con's avatar
con committed
1138 1139
        e->accept();
        return;
Joel Nordell's avatar
Joel Nordell committed
1140
    } break;
con's avatar
con committed
1141 1142
    case Qt::Key_Backspace:
        if (ro) break;
1143
        if ((e->modifiers() & (Qt::ControlModifier
con's avatar
con committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
                               | Qt::ShiftModifier
                               | Qt::AltModifier
                               | Qt::MetaModifier)) == Qt::NoModifier
            && !textCursor().hasSelection()) {
            handleBackspaceKey();
            e->accept();
            return;
        }
        break;
    case Qt::Key_Up:
    case Qt::Key_Down:
        if (e->modifiers() & Qt::ControlModifier) {
            verticalScrollBar()->triggerAction(
                    e->key() == Qt::Key_Up ? QAbstractSlider::SliderSingleStepSub :
                                             QAbstractSlider::SliderSingleStepAdd);
            e->accept();
            return;
        }
        // fall through
1163
    case Qt::Key_End:
con's avatar
con committed
1164 1165
    case Qt::Key_Right:
    case Qt::Key_Left:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1166
#ifndef Q_WS_MAC
con's avatar
con committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier)) {

            d->m_lastEventWasBlockSelectionEvent = true;

            if (d->m_inBlockSelectionMode) {
                if (e->key() == Qt::Key_Right && textCursor().atBlockEnd()) {
                    d->m_blockSelectionExtraX++;
                    viewport()->update();
                    e->accept();
                    return;
                } else if (e->key() == Qt::Key_Left && d->m_blockSelectionExtraX > 0) {
                    d->m_blockSelectionExtraX--;
                    e->accept();
                    viewport()->update();
                    return;
                }
            }

            e = new QKeyEvent(
                e->type(),
                e->key(),
                e->modifiers() & ~Qt::AltModifier,
                e->text(),
                e->isAutoRepeat(),
                e->count()
                );
        }
#endif
        break;
    case Qt::Key_PageUp:
    case Qt::Key_PageDown:
        if (e->modifiers() == Qt::ControlModifier) {
            verticalScrollBar()->triggerAction(
                    e->key() == Qt::Key_PageUp ? QAbstractSlider::SliderPageStepSub :
                                                 QAbstractSlider::SliderPageStepAdd);
            e->accept();
            return;
        }
        break;

    default:
        break;
    }

    if (d->m_inBlockSelectionMode) {
        QString text = e->text();
        if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t'))) {
            d->removeBlockSelection(text);
            goto skip_event;
        }
    }

mae's avatar
mae committed
1219 1220 1221 1222 1223 1224 1225
    if (e->key() == Qt::Key_H && e->modifiers() ==
#ifdef Q_OS_DARWIN
        Qt::MetaModifier
#else
        Qt::ControlModifier
#endif
        ) {
1226 1227 1228 1229 1230
        universalHelper();
        e->accept();
        return;
    }

1231 1232
    if (d->m_snippetOverlay->isVisible()
        && (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace)) {
1233
        d->snippetCheckCursor(textCursor());
1234
    }
1235

mae's avatar
mae committed
1236 1237
    if (ro || e->text().isEmpty() || !e->text().at(0).isPrint()) {
        QPlainTextEdit::keyPressEvent(e);
mae's avatar
mae committed
1238
    } else if ((e->modifiers() & (Qt::ControlModifier|Qt::AltModifier)) != Qt::ControlModifier){
mae's avatar
mae committed
1239 1240
        QTextCursor cursor = textCursor();
        QString text = e->text();
1241
        QString autoText = autoComplete(cursor, text);
1242

mae's avatar
mae committed
1243 1244
        QChar electricChar;
        if (d->m_document->tabSettings().m_autoIndent) {
1245
            foreach (QChar c, text) {
mae's avatar
mae committed
1246 1247 1248 1249 1250 1251
                if (isElectricCharacter(c)) {
                    electricChar = c;
                    break;
                }
            }
        }
1252

1253 1254 1255
        if (d->m_snippetOverlay->isVisible())
            d->snippetCheckCursor(cursor);

1256 1257
        bool doEditBlock = !(electricChar.isNull() && autoText.isEmpty());
        if (doEditBlock)
mae's avatar
mae committed
1258
            cursor.beginEditBlock();
1259

mae's avatar
mae committed
1260
        cursor.insertText(text);
1261

1262
        if (!autoText.isEmpty()) {
mae's avatar
mae committed
1263 1264 1265 1266
            int pos = cursor.position();
            cursor.insertText(autoText);
            cursor.setPosition(pos);
        }
1267
        if (!electricChar.isNull())
mae's avatar
mae committed
1268
            indent(document(), cursor, electricChar);
1269 1270

        if (doEditBlock)
mae's avatar
mae committed
1271
            cursor.endEditBlock();
1272

mae's avatar
mae committed
1273 1274
        setTextCursor(cursor);
    }
con's avatar
con committed
1275 1276 1277

skip_event:
    if (!ro && e->key() == Qt::Key_Delete && d->m_parenthesesMatchingEnabled)
1278 1279
        d->m_parenthesesMatchingTimer->start(50);

con's avatar
con committed
1280 1281 1282 1283 1284 1285 1286 1287

    if (!ro && d->m_contentsChanged && !e->text().isEmpty() && e->text().at(0).isPrint())
        emit requestAutoCompletion(editableInterface(), false);

    if (e != original_e)
        delete e;
}

1288
void BaseTextEditor::insertCodeSnippet(const QString &snippet)
1289 1290
{
    QList<QTextEdit::ExtraSelection> selections;
1291

1292
    QTextCursor cursor = textCursor();
1293
    const int startCursorPosition = cursor.position();
1294
    cursor.beginEditBlock();
1295 1296 1297 1298 1299 1300 1301

    if ((snippet.count('$') % 2) != 0) {
        qWarning() << "invalid snippet";
        return;
    }

    int pos = 0;
mae's avatar
mae committed
1302 1303
    QMap<int, int> positions;

1304
    while (pos < snippet.size()) {
1305
        if (snippet.at(pos) != QChar::ObjectReplacementCharacter) {
1306 1307
            const int start = pos;
            do { ++pos; }
1308
            while (pos < snippet.size() && snippet.at(pos) != QChar::ObjectReplacementCharacter);
1309 1310 1311 1312 1313
            cursor.insertText(snippet.mid(start, pos - start));
        } else {
            // the start of a place holder.
            const int start = ++pos;
            for (; pos < snippet.size(); ++pos) {
1314
                if (snippet.at(pos) == QChar::ObjectReplacementCharacter)
1315 1316 1317 1318
                    break;
            }

            Q_ASSERT(pos < snippet.size());
1319
            Q_ASSERT(snippet.at(pos) == QChar::ObjectReplacementCharacter);
1320 1321 1322 1323 1324 1325

            const QString textToInsert = snippet.mid(start, pos - start);

            int cursorPosition = cursor.position();
            cursor.insertText(textToInsert);

mae's avatar
mae committed
1326 1327 1328 1329 1330
            if (textToInsert.isEmpty()) {
                positions.insert(cursorPosition, 0);
            } else {
                positions.insert(cursorPosition-1, textToInsert.length()+1);
            }
1331 1332 1333 1334 1335

            ++pos;
        }
    }

mae's avatar
mae committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    QMapIterator<int,int> it(positions);
    while (it.hasNext()) {
        it.next();
        int length = it.value();
        int position = it.key();

        QTextCursor tc(document());
        tc.setPosition(position);
        tc.setPosition(position + length, QTextCursor::KeepAnchor);
        QTextEdit::ExtraSelection selection;
        selection.cursor = tc;
        selection.format.setBackground(length ? Qt::darkCyan : Qt::darkMagenta);
        selections.append(selection);
    }

1351 1352
    cursor.setPosition(startCursorPosition, QTextCursor::KeepAnchor);
    indent(cursor.document(), cursor, QChar());
mae's avatar
mae committed
1353
    cursor.endEditBlock();
1354

1355
    setExtraSelections(BaseTextEditor::SnippetPlaceholderSelection, selections);
1356 1357 1358 1359 1360

    if (! selections.isEmpty()) {
        const QTextEdit::ExtraSelection &selection = selections.first();

        cursor = textCursor();
1361 1362 1363 1364 1365 1366
        if (selection.cursor.hasSelection()) {
            cursor.setPosition(selection.cursor.selectionStart()+1);
            cursor.setPosition(selection.cursor.selectionEnd(), QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(selection.cursor.position());
        }
1367 1368
        setTextCursor(cursor);
    }
1369 1370
}

1371 1372 1373 1374 1375 1376
void BaseTextEditor::universalHelper()
{
    const QString snippet = QLatin1String("for ($initializer$; $condition$; $expresssion$) {\n$$\n}\n");
    insertCodeSnippet(snippet);
}

1377 1378 1379 1380
void BaseTextEditor::setTextCursor(const QTextCursor &cursor)
{
    // workaround for QTextControl bug
    bool selectionChange = cursor.hasSelection() || textCursor().hasSelection();
1381