basetexteditor.h 18.8 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
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 31 32 33 34
#ifndef BASETEXTEDITOR_H
#define BASETEXTEDITOR_H

#include "itexteditable.h"

35 36
#include <find/ifindsupport.h>

37 38
#include <coreplugin/editormanager/editormanager.h>

con's avatar
con committed
39 40 41 42
#include <QtGui/QPlainTextEdit>

QT_BEGIN_NAMESPACE
class QToolBar;
43
class QTimeLine;
con's avatar
con committed
44 45
QT_END_NAMESPACE

46 47
namespace Utils {
    class LineColumnLabel;
48
    class ChangeSet;
con's avatar
con committed
49 50 51
}

namespace TextEditor {
52
class TabSettings;
53 54
class RefactorOverlay;
struct RefactorMarker;
con's avatar
con committed
55 56 57

namespace Internal {
    class BaseTextEditorPrivate;
58
    class TextEditorOverlay;
59
    typedef QList<RefactorMarker> RefactorMarkers;
con's avatar
con committed
60 61 62 63 64
}

class ITextMarkable;

class BaseTextDocument;
65
class BaseTextEditorEditable;
con's avatar
con committed
66
class FontSettings;
67 68 69 70
class BehaviorSettings;
class CompletionSettings;
class DisplaySettings;
class StorageSettings;
71
class Indenter;
72
class AutoCompleter;
con's avatar
con committed
73

74 75 76 77 78 79 80
class TEXTEDITOR_EXPORT BaseTextEditorAnimator : public QObject
{
    Q_OBJECT

public:
    BaseTextEditorAnimator(QObject *parent);

81 82
    inline void setPosition(int position) { m_position = position; }
    inline int position() const { return m_position; }
83 84 85 86 87 88

    void setData(QFont f, QPalette pal, const QString &text);

    void draw(QPainter *p, const QPointF &pos);
    QRectF rect() const;

89 90
    inline qreal value() const { return m_value; }
    inline QPointF lastDrawPos() const { return m_lastDrawPos; }
91 92 93

    void finish();

mae's avatar
mae committed
94 95
    bool isRunning() const;

96
signals:
97
    void updateRequest(int position, QPointF lastPos, QRectF rect);
98 99 100 101 102 103 104 105 106


private slots:
    void step(qreal v);

private:
    QTimeLine *m_timeline;
    qreal m_value;
    int m_position;
107
    QPointF m_lastDrawPos;
108 109 110 111 112 113 114
    QFont m_font;
    QPalette m_palette;
    QString m_text;
    QSizeF m_size;
};


115
class TEXTEDITOR_EXPORT BaseTextEditor : public QPlainTextEdit
con's avatar
con committed
116 117
{
    Q_OBJECT
mae's avatar
mae committed
118 119
    Q_PROPERTY(int verticalBlockSelectionFirstColumn READ verticalBlockSelectionFirstColumn)
    Q_PROPERTY(int verticalBlockSelectionLastColumn READ verticalBlockSelectionLastColumn)
con's avatar
con committed
120 121 122 123
public:
    BaseTextEditor(QWidget *parent);
    ~BaseTextEditor();

124
    static ITextEditor *openEditorAt(const QString &fileName, int line, int column = 0,
125 126
                                     const QString &editorId =  QString(),
                                     Core::EditorManager::OpenEditorFlags flags = Core::EditorManager::IgnoreNavigationHistory,
127
                                     bool *newEditor = 0);
con's avatar
con committed
128

129 130 131
    const Utils::ChangeSet &changeSet() const;
    void setChangeSet(const Utils::ChangeSet &changeSet);

con's avatar
con committed
132 133 134
    // EditorInterface
    Core::IFile * file();
    bool createNew(const QString &contents);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
135
    virtual bool open(const QString &fileName = QString());
con's avatar
con committed
136 137 138 139 140 141
    QByteArray saveState() const;
    bool restoreState(const QByteArray &state);
    QString displayName() const;

    // ITextEditor

142
    void gotoLine(int line, int column = 0);
con's avatar
con committed
143 144 145 146 147 148

    int position(
        ITextEditor::PositionOperation posOp = ITextEditor::Current
        , int at = -1) const;
    void convertPosition(int pos, int *line, int *column) const;

149
    BaseTextEditorEditable *editableInterface() const;
con's avatar
con committed
150 151 152
    ITextMarkable *markableInterface() const;

    virtual void triggerCompletions();
Roberto Raggi's avatar
Roberto Raggi committed
153
    virtual void triggerQuickFix();
con's avatar
con committed
154 155 156 157 158 159 160

    QChar characterAt(int pos) const;

    void print(QPrinter *);

    void setSuggestedFileName(const QString &suggestedFileName);
    QString mimeType() const;
Erik Verbruggen's avatar
Erik Verbruggen committed
161
    virtual void setMimeType(const QString &mt);
con's avatar
con committed
162 163


164 165
    void appendStandardContextMenuActions(QMenu *menu);

con's avatar
con committed
166 167 168 169 170
    // Works only in conjunction with a syntax highlighter that puts
    // parentheses into text block user data
    void setParenthesesMatchingEnabled(bool b);
    bool isParenthesesMatchingEnabled() const;

171 172 173
    void setAutoParenthesesEnabled(bool b);
    bool isAutoParenthesesEnabled() const;

con's avatar
con committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    void setHighlightCurrentLine(bool b);
    bool highlightCurrentLine() const;

    void setLineNumbersVisible(bool b);
    bool lineNumbersVisible() const;

    void setMarksVisible(bool b);
    bool marksVisible() const;

    void setRequestMarkEnabled(bool b);
    bool requestMarkEnabled() const;

    void setLineSeparatorsAllowed(bool b);
    bool lineSeparatorsAllowed() const;

189
    void updateCodeFoldingVisible();
con's avatar
con committed
190 191
    bool codeFoldingVisible() const;

192 193 194
    void setCodeFoldingSupported(bool b);
    bool codeFoldingSupported() const;

195 196 197
    void setMouseNavigationEnabled(bool b);
    bool mouseNavigationEnabled() const;

198 199 200
    void setScrollWheelZoomingEnabled(bool b);
    bool scrollWheelZoomingEnabled() const;

con's avatar
con committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214
    void setRevisionsVisible(bool b);
    bool revisionsVisible() const;

    void setVisibleWrapColumn(int column);
    int visibleWrapColumn() const;

    void setActionHack(QObject *);
    QObject *actionHack() const;

    void setTextCodec(QTextCodec *codec);
    QTextCodec *textCodec() const;

    void setReadOnly(bool b);

215 216
    void setTextCursor(const QTextCursor &cursor);

mae's avatar
mae committed
217
    void insertCodeSnippet(const QTextCursor &cursor, const QString &snippet);
218

219 220
    void setBlockSelection(bool on);
    bool hasBlockSelection() const;
221

mae's avatar
mae committed
222 223
    int verticalBlockSelectionFirstColumn() const;
    int verticalBlockSelectionLastColumn() const;
224

225 226
    QRegion translatedLineRegion(int lineStart, int lineEnd) const;

227
    void setIndenter(Indenter *indenter);
228
    Indenter *indenter() const;
229

230 231 232
    void setAutoCompleter(AutoCompleter *autoCompleter);
    AutoCompleter *autoCompleter() const;

con's avatar
con committed
233 234 235
public slots:
    void setDisplayName(const QString &title);

mae's avatar
mae committed
236 237
    virtual void paste();
    virtual void cut();
con's avatar
con committed
238 239 240

    void zoomIn(int range = 1);
    void zoomOut(int range = 1);
mae's avatar
mae committed
241
    void zoomReset();
con's avatar
con committed
242

243
    void cutLine();
con's avatar
con committed
244
    void deleteLine();
mae's avatar
mae committed
245 246 247
    void unfoldAll();
    void fold();
    void unfold();
con's avatar
con committed
248 249
    void selectEncoding();

250 251 252 253 254
    void gotoBlockStart();
    void gotoBlockEnd();
    void gotoBlockStartWithSelection();
    void gotoBlockEndWithSelection();

mae's avatar
mae committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    void gotoLineStart();
    void gotoLineStartWithSelection();
    void gotoLineEnd();
    void gotoLineEndWithSelection();
    void gotoNextLine();
    void gotoNextLineWithSelection();
    void gotoPreviousLine();
    void gotoPreviousLineWithSelection();
    void gotoPreviousCharacter();
    void gotoPreviousCharacterWithSelection();
    void gotoNextCharacter();
    void gotoNextCharacterWithSelection();
    void gotoPreviousWord();
    void gotoPreviousWordWithSelection();
    void gotoNextWord();
    void gotoNextWordWithSelection();
mae's avatar
mae committed
271 272 273 274
    void gotoPreviousWordCamelCase();
    void gotoPreviousWordCamelCaseWithSelection();
    void gotoNextWordCamelCase();
    void gotoNextWordCamelCaseWithSelection();
275

276 277 278
    void selectBlockUp();
    void selectBlockDown();

279 280 281
    void moveLineUp();
    void moveLineDown();

282 283 284
    void copyLineUp();
    void copyLineDown();

285
    void joinLines();
286

287 288 289
    void insertLineAbove();
    void insertLineBelow();

290 291
    void cleanWhitespace();

con's avatar
con committed
292 293 294 295 296 297 298 299 300 301 302
signals:
    void changed();

    // ITextEditor
    void contentsChanged();

protected:
    bool event(QEvent *e);
    void keyPressEvent(QKeyEvent *e);
    void wheelEvent(QWheelEvent *e);
    void changeEvent(QEvent *e);
303
    void focusInEvent(QFocusEvent *e);
mae's avatar
mae committed
304
    void focusOutEvent(QFocusEvent *e);
con's avatar
con committed
305

mae's avatar
mae committed
306 307
    void showEvent(QShowEvent *);

con's avatar
con committed
308 309 310 311 312
    // reimplemented to support block selection
    QMimeData *createMimeDataFromSelection() const;
    bool canInsertFromMimeData(const QMimeData *source) const;
    void insertFromMimeData(const QMimeData *source);

313 314
    static QString msgTextTooLarge(quint64 size);

315 316 317
private:
    void maybeSelectLine();

con's avatar
con committed
318 319
public:
    void duplicateFrom(BaseTextEditor *editor);
320

con's avatar
con committed
321 322 323 324 325 326 327 328 329 330
protected:
    BaseTextDocument *baseTextDocument() const;
    void setBaseTextDocument(BaseTextDocument *doc);

    void setDefaultPath(const QString &defaultPath);

    virtual BaseTextEditorEditable *createEditableInterface() = 0;

private slots:
    void editorContentsChange(int position, int charsRemoved, int charsAdded);
mae's avatar
mae committed
331 332
    void documentAboutToBeReloaded();
    void documentReloaded();
333
    void highlightSearchResults(const QString &txt, Find::FindFlags findFlags);
mae's avatar
mae committed
334 335 336
    void setFindScope(const QTextCursor &start, const QTextCursor &end, int, int);
    bool inFindScope(const QTextCursor &cursor);
    bool inFindScope(int selectionStart, int selectionEnd);
con's avatar
con committed
337 338 339 340 341
    void currentEditorChanged(Core::IEditor *editor);

private:
    Internal::BaseTextEditorPrivate *d;
    friend class Internal::BaseTextEditorPrivate;
342
    friend class Internal::TextEditorOverlay;
343
    friend class RefactorOverlay;
con's avatar
con committed
344 345 346 347 348 349

public:
    QWidget *extraArea() const;
    virtual int extraAreaWidth(int *markWidthPtr = 0) const;
    virtual void extraAreaPaintEvent(QPaintEvent *);
    virtual void extraAreaLeaveEvent(QEvent *);
350
    virtual void extraAreaMouseEvent(QMouseEvent *);
con's avatar
con committed
351 352 353 354 355 356 357 358

    const TabSettings &tabSettings() const;
    const DisplaySettings &displaySettings() const;

    void markBlocksAsChanged(QList<int> blockNumbers);

    void ensureCursorVisible();

359 360 361 362 363
    enum ExtraSelectionKind {
        CurrentLineSelection,
        ParenthesesMatchingSelection,
        CodeWarningsSelection,
        CodeSemanticsSelection,
364
        UndefinedSymbolSelection,
Roberto Raggi's avatar
Roberto Raggi committed
365
        UnusedSymbolSelection,
hjk's avatar
hjk committed
366
        FakeVimSelection,
Roberto Raggi's avatar
Roberto Raggi committed
367
        OtherSelection,
368
        SnippetPlaceholderSelection,
Erik Verbruggen's avatar
Erik Verbruggen committed
369
        ObjCSelection,
370 371 372 373
        NExtraSelectionKinds
    };
    void setExtraSelections(ExtraSelectionKind kind, const QList<QTextEdit::ExtraSelection> &selections);
    QList<QTextEdit::ExtraSelection> extraSelections(ExtraSelectionKind kind) const;
374
    QString extraSelectionTooltip(int pos) const;
con's avatar
con committed
375

376 377 378

    void setRefactorMarkers(const Internal::RefactorMarkers &markers);
signals:
379
    void refactorMarkerClicked(const TextEditor::RefactorMarker &marker);
380 381 382

public:

383 384 385 386 387 388
    struct BlockRange
    {
        BlockRange() : first(0), last(-1) {}
        BlockRange(int first_position, int last_position)
          : first(first_position), last(last_position)
        {}
con's avatar
con committed
389 390 391 392 393 394
        int first;
        int last;
        inline bool isNull() const { return last < first; }
    };

    // the blocks list must be sorted
395
    void setIfdefedOutBlocks(const QList<BlockRange> &blocks);
con's avatar
con committed
396 397

public slots:
398
    virtual void format();
399
    virtual void rewrapParagraph();
400 401
    virtual void unCommentSelection();
    virtual void setFontSettings(const TextEditor::FontSettings &);
mae's avatar
mae committed
402
    void setFontSettingsIfVisible(const TextEditor::FontSettings &);
con's avatar
con committed
403 404
    virtual void setTabSettings(const TextEditor::TabSettings &);
    virtual void setDisplaySettings(const TextEditor::DisplaySettings &);
405
    virtual void setBehaviorSettings(const TextEditor::BehaviorSettings &);
406
    virtual void setStorageSettings(const TextEditor::StorageSettings &);
407
    virtual void setCompletionSettings(const TextEditor::CompletionSettings &);
con's avatar
con committed
408 409 410 411 412 413 414 415 416

protected:
    bool viewportEvent(QEvent *event);

    void resizeEvent(QResizeEvent *);
    void paintEvent(QPaintEvent *);
    void timerEvent(QTimerEvent *);
    void mouseMoveEvent(QMouseEvent *);
    void mousePressEvent(QMouseEvent *);
417 418 419
    void mouseReleaseEvent(QMouseEvent *);
    void leaveEvent(QEvent *);
    void keyReleaseEvent(QKeyEvent *);
con's avatar
con committed
420

421 422
    void dragEnterEvent(QDragEnterEvent *e);

423
public:
424 425 426 427
    // Returns the text to complete at the cursor position, or an empty string
    virtual QString autoComplete(QTextCursor &cursor, const QString &text) const;
    // Handles backspace. When returning true, backspace processing is stopped
    virtual bool autoBackspace(QTextCursor &cursor);
428 429
    // Hook to insert special characters on enter. Returns the number of extra blocks inserted.
    virtual int paragraphSeparatorAboutToBeInserted(QTextCursor &cursor);
430 431

    void indentInsertedText(const QTextCursor &tc);
432 433
    void indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar);
    void reindent(QTextDocument *doc, const QTextCursor &cursor);
con's avatar
con committed
434

435
protected:
436 437 438 439 440
    static void countBracket(QChar open, QChar close, QChar c, int *errors, int *stillopen);

    static void countBrackets(QTextCursor cursor, int from, int end, QChar open, QChar close,
                              int *errors, int *stillopen);

441
public:
442 443 444 445 446
    struct Link
    {
        Link(const QString &fileName = QString(),
             int line = 0,
             int column = 0)
447 448
            : begin(-1)
            , end(-1)
449 450 451 452 453 454
            , fileName(fileName)
            , line(line)
            , column(column)
        {}

        bool isValid() const
455
        { return begin != end; }
456

457
        bool operator==(const Link &other) const
458
        { return begin == other.begin && end == other.end; }
459

460 461
        int begin;           // Link position
        int end;           // Link end position
462 463 464 465 466 467

        QString fileName;  // Target file
        int line;          // Target line
        int column;        // Target column
    };

468
protected:
469 470 471 472 473 474 475 476 477 478
    /*!
       Reimplement this function to enable code navigation.

       \a resolveTarget is set to true when the target of the link is relevant
       (it isn't until the link is used).
     */
    virtual Link findLinkAt(const QTextCursor &, bool resolveTarget = true);

    /*!
       Reimplement this function if you want to customize the way a link is
Tobias Hunger's avatar
Tobias Hunger committed
479
       opened. Returns whether the link was opened successfully.
480 481 482
     */
    virtual bool openLink(const Link &link);

483 484
    void maybeClearSomeExtraSelections(const QTextCursor &cursor);

con's avatar
con committed
485 486 487 488 489 490 491 492
protected slots:
    virtual void slotUpdateExtraAreaWidth();
    virtual void slotModificationChanged(bool);
    virtual void slotUpdateRequest(const QRect &r, int dy);
    virtual void slotCursorPositionChanged();
    virtual void slotUpdateBlockNotify(const QTextBlock &);

signals:
mae's avatar
mae committed
493 494
    void requestFontZoom(int zoom);
    void requestZoomReset();
con's avatar
con committed
495
    void requestBlockUpdate(const QTextBlock &);
496 497
    void requestAutoCompletion(TextEditor::ITextEditable *editor, bool forced);
    void requestQuickFix(TextEditor::ITextEditable *editor);
con's avatar
con committed
498 499

private:
500
    void maybeRequestAutoCompletion(const QChar &ch);
con's avatar
con committed
501 502 503
    void indentOrUnindent(bool doIndent);
    void handleHomeKey(bool anchor);
    void handleBackspaceKey();
504
    void moveLineUpDown(bool up);
505
    void copyLineUpDown(bool up);
506
    void saveCurrentCursorPositionForNavigation();
con's avatar
con committed
507
    void updateHighlights();
508
    void updateCurrentLineHighlight();
con's avatar
con committed
509

510 511 512 513 514
    void drawFoldingMarker(QPainter *painter, const QPalette &pal,
                           const QRect &rect,
                           bool expanded,
                           bool active,
                           bool hovered) const;
515

516 517 518 519 520
    void drawCollapsedBlockPopup(QPainter &painter,
                                 const QTextBlock &block,
                                 QPointF offset,
                                 const QRect &clip);

con's avatar
con committed
521
    void toggleBlockVisible(const QTextBlock &block);
mae's avatar
mae committed
522
    QRect foldBox();
con's avatar
con committed
523

mae's avatar
mae committed
524
    QTextBlock foldedBlockAt(const QPoint &pos, QRect *box = 0) const;
con's avatar
con committed
525

526
    void updateLink(QMouseEvent *e);
527 528
    void showLink(const Link &);
    void clearLink();
mae's avatar
mae committed
529

530 531
    void universalHelper(); // test function for development

532 533 534 535 536
    bool cursorMoveKeyEvent(QKeyEvent *e);
    bool camelCaseRight(QTextCursor &cursor, QTextCursor::MoveMode mode);
    bool camelCaseLeft(QTextCursor &cursor, QTextCursor::MoveMode mode);


con's avatar
con committed
537
private slots:
538 539 540
    // auto completion
    void _q_requestAutoCompletion();

mae's avatar
mae committed
541 542
    void handleBlockSelection(int diff_row, int diff_col);

543
    // parentheses matcher
con's avatar
con committed
544
    void _q_matchParentheses();
545
    void _q_highlightBlocks();
con's avatar
con committed
546
    void slotSelectionChanged();
547
    void _q_animateUpdate(int position, QPointF lastPos, QRectF rect);
548
    void doFoo();
549

con's avatar
con committed
550 551 552
};


553
class TEXTEDITOR_EXPORT BaseTextEditorEditable : public ITextEditable
con's avatar
con committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
{
    Q_OBJECT
    friend class BaseTextEditor;
public:
    BaseTextEditorEditable(BaseTextEditor *editor);
    ~BaseTextEditorEditable();

    inline BaseTextEditor *editor() const { return e; }

    // EditorInterface
    inline QWidget *widget() { return e; }
    inline Core::IFile * file() { return e->file(); }
    inline bool createNew(const QString &contents) { return e->createNew(contents); }
    inline bool open(const QString &fileName = QString())
    {
        return e->open(fileName);
    }
    inline QString displayName() const { return e->displayName(); }
    inline void setDisplayName(const QString &title) { e->setDisplayName(title); }

    inline QByteArray saveState() const { return e->saveState(); }
    inline bool restoreState(const QByteArray &state) { return e->restoreState(state); }
con's avatar
con committed
576
    QWidget *toolBar();
con's avatar
con committed
577 578 579 580 581 582

    // ITextEditor
    int find(const QString &string) const;

    int currentLine() const;
    int currentColumn() const;
583
    void gotoLine(int line, int column = 0) { e->gotoLine(line, column); }
con's avatar
con committed
584 585 586 587 588 589 590 591 592 593 594 595 596

    inline int position(
        ITextEditor::PositionOperation posOp = ITextEditor::Current
        , int at = -1) const { return e->position(posOp, at); }
    inline void convertPosition(int pos, int *line, int *column) const { e->convertPosition(pos, line, column); }
    QRect cursorRect(int pos = -1) const;

    QString contents() const;
    QString selectedText() const;
    QString textAt(int pos, int length) const;
    inline QChar characterAt(int pos) const { return e->characterAt(pos); }

    inline void triggerCompletions() { e->triggerCompletions(); } // slot?
Roberto Raggi's avatar
Roberto Raggi committed
597 598
    inline void triggerQuickFix() { e->triggerQuickFix(); } // slot?

con's avatar
con committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    inline ITextMarkable *markableInterface() { return e->markableInterface(); }

    void setContextHelpId(const QString &id) { m_contextHelpId = id; }
    QString contextHelpId() const; // from IContext

    inline void setTextCodec(QTextCodec *codec) { e->setTextCodec(codec); }
    inline QTextCodec *textCodec() const { return e->textCodec(); }


    // ITextEditable
    void remove(int length);
    void insert(const QString &string);
    void replace(int length, const QString &string);
    void setCurPos(int pos);
    void select(int toPos);

private slots:
    void updateCursorPosition();

private:
    BaseTextEditor *e;
    mutable QString m_contextHelpId;
    QToolBar *m_toolBar;
622
    Utils::LineColumnLabel *m_cursorPositionLabel;
con's avatar
con committed
623 624 625 626
};

} // namespace TextEditor

627 628
Q_DECLARE_METATYPE(TextEditor::BaseTextEditor::Link);

con's avatar
con committed
629
#endif // BASETEXTEDITOR_H