basetexteditor.h 18.5 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>

con's avatar
con committed
37 38 39 40
#include <QtGui/QPlainTextEdit>

QT_BEGIN_NAMESPACE
class QToolBar;
41
class QTimeLine;
con's avatar
con committed
42 43
QT_END_NAMESPACE

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

namespace TextEditor {

namespace Internal {
    class BaseTextEditorPrivate;
53
    class TextEditorOverlay;
54
    class RefactorOverlay;
Friedemann Kleint's avatar
Friedemann Kleint committed
55
    struct RefactorMarker;
56 57
    typedef QList<RefactorMarker> RefactorMarkers;

con's avatar
con committed
58 59 60 61 62
}

class ITextMarkable;

class BaseTextDocument;
63
class BaseTextEditorEditable;
con's avatar
con committed
64
class FontSettings;
65
struct BehaviorSettings;
66
struct CompletionSettings;
67
struct DisplaySettings;
con's avatar
con committed
68
struct StorageSettings;
69
struct TabSettings;
con's avatar
con committed
70 71


72 73 74 75 76 77 78
class TEXTEDITOR_EXPORT BaseTextEditorAnimator : public QObject
{
    Q_OBJECT

public:
    BaseTextEditorAnimator(QObject *parent);

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

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

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

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

    void finish();

mae's avatar
mae committed
92 93
    bool isRunning() const;

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


private slots:
    void step(qreal v);

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


113
class TEXTEDITOR_EXPORT BaseTextEditor : public QPlainTextEdit
con's avatar
con committed
114 115
{
    Q_OBJECT
116
    Q_PROPERTY(int verticalBlockSelection READ verticalBlockSelection)
con's avatar
con committed
117 118 119 120 121

public:
    BaseTextEditor(QWidget *parent);
    ~BaseTextEditor();

122
    static ITextEditor *openEditorAt(const QString &fileName, int line, int column = 0,
123 124
                                     const QString &editorId = QString(),
                                     bool *newEditor = 0);
con's avatar
con committed
125

126 127 128
    const Utils::ChangeSet &changeSet() const;
    void setChangeSet(const Utils::ChangeSet &changeSet);

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

    // ITextEditor

139
    void gotoLine(int line, int column = 0);
con's avatar
con committed
140 141 142 143 144 145

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

146
    BaseTextEditorEditable *editableInterface() const;
con's avatar
con committed
147 148 149
    ITextMarkable *markableInterface() const;

    virtual void triggerCompletions();
Roberto Raggi's avatar
Roberto Raggi committed
150
    virtual void triggerQuickFix();
con's avatar
con committed
151 152 153 154 155 156 157

    QChar characterAt(int pos) const;

    void print(QPrinter *);

    void setSuggestedFileName(const QString &suggestedFileName);
    QString mimeType() const;
Erik Verbruggen's avatar
Erik Verbruggen committed
158
    virtual void setMimeType(const QString &mt);
con's avatar
con committed
159 160


161 162
    void appendStandardContextMenuActions(QMenu *menu);

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

168 169 170
    void setAutoParenthesesEnabled(bool b);
    bool isAutoParenthesesEnabled() const;

con's avatar
con committed
171 172 173 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;

    void setCodeFoldingVisible(bool b);
    bool codeFoldingVisible() const;

189 190 191
    void setCodeFoldingSupported(bool b);
    bool codeFoldingSupported() const;

192 193 194
    void setMouseNavigationEnabled(bool b);
    bool mouseNavigationEnabled() const;

195 196 197
    void setScrollWheelZoomingEnabled(bool b);
    bool scrollWheelZoomingEnabled() const;

con's avatar
con committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211
    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);

212 213
    void setTextCursor(const QTextCursor &cursor);

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

216 217 218

    int verticalBlockSelection() const;

219 220
    QRegion translatedLineRegion(int lineStart, int lineEnd) const;

con's avatar
con committed
221 222 223
public slots:
    void setDisplayName(const QString &title);

mae's avatar
mae committed
224 225
    virtual void paste();
    virtual void cut();
con's avatar
con committed
226 227 228

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

231
    void cutLine();
con's avatar
con committed
232
    void deleteLine();
mae's avatar
mae committed
233 234 235
    void unfoldAll();
    void fold();
    void unfold();
con's avatar
con committed
236 237
    void selectEncoding();

238 239 240 241 242
    void gotoBlockStart();
    void gotoBlockEnd();
    void gotoBlockStartWithSelection();
    void gotoBlockEndWithSelection();

mae's avatar
mae committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    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();
259

260 261 262
    void selectBlockUp();
    void selectBlockDown();

263 264 265
    void moveLineUp();
    void moveLineDown();

266 267 268
    void copyLineUp();
    void copyLineDown();

269
    void joinLines();
270

271 272 273
    void insertLineAbove();
    void insertLineBelow();

274 275
    void cleanWhitespace();

con's avatar
con committed
276 277 278 279 280 281 282 283 284 285 286
signals:
    void changed();

    // ITextEditor
    void contentsChanged();

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

mae's avatar
mae committed
290 291
    void showEvent(QShowEvent *);

con's avatar
con committed
292 293 294 295 296
    // reimplemented to support block selection
    QMimeData *createMimeDataFromSelection() const;
    bool canInsertFromMimeData(const QMimeData *source) const;
    void insertFromMimeData(const QMimeData *source);

297 298 299
private:
    void maybeSelectLine();

con's avatar
con committed
300 301
public:
    void duplicateFrom(BaseTextEditor *editor);
302

con's avatar
con committed
303 304 305 306 307 308 309 310 311 312
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
313 314
    void documentAboutToBeReloaded();
    void documentReloaded();
315
    void highlightSearchResults(const QString &txt, Find::IFindSupport::FindFlags findFlags);
mae's avatar
mae committed
316
    void setFindScope(const QTextCursor &start, const QTextCursor &end, int);
con's avatar
con committed
317
    void currentEditorChanged(Core::IEditor *editor);
318
    void maybeEmitContentsChangedBecauseOfUndo();
con's avatar
con committed
319 320 321 322

private:
    Internal::BaseTextEditorPrivate *d;
    friend class Internal::BaseTextEditorPrivate;
323
    friend class Internal::TextEditorOverlay;
324
    friend class Internal::RefactorOverlay;
con's avatar
con committed
325 326 327 328 329 330

public:
    QWidget *extraArea() const;
    virtual int extraAreaWidth(int *markWidthPtr = 0) const;
    virtual void extraAreaPaintEvent(QPaintEvent *);
    virtual void extraAreaLeaveEvent(QEvent *);
331
    virtual void extraAreaMouseEvent(QMouseEvent *);
con's avatar
con committed
332 333 334 335 336 337 338 339

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

    void markBlocksAsChanged(QList<int> blockNumbers);

    void ensureCursorVisible();

340 341 342 343 344
    enum ExtraSelectionKind {
        CurrentLineSelection,
        ParenthesesMatchingSelection,
        CodeWarningsSelection,
        CodeSemanticsSelection,
345
        UndefinedSymbolSelection,
Roberto Raggi's avatar
Roberto Raggi committed
346
        UnusedSymbolSelection,
hjk's avatar
hjk committed
347
        FakeVimSelection,
Roberto Raggi's avatar
Roberto Raggi committed
348
        OtherSelection,
349
        SnippetPlaceholderSelection,
Roberto Raggi's avatar
Roberto Raggi committed
350
        TypeSelection,
Erik Verbruggen's avatar
Erik Verbruggen committed
351
        ObjCSelection,
352 353 354 355
        NExtraSelectionKinds
    };
    void setExtraSelections(ExtraSelectionKind kind, const QList<QTextEdit::ExtraSelection> &selections);
    QList<QTextEdit::ExtraSelection> extraSelections(ExtraSelectionKind kind) const;
356
    QString extraSelectionTooltip(int pos) const;
con's avatar
con committed
357

358 359 360 361 362 363 364

    void setRefactorMarkers(const Internal::RefactorMarkers &markers);
signals:
    void refactorMarkerClicked(const Internal::RefactorMarker &marker);

public:

365 366 367 368 369 370
    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
371 372 373 374 375 376
        int first;
        int last;
        inline bool isNull() const { return last < first; }
    };

    // the blocks list must be sorted
377
    void setIfdefedOutBlocks(const QList<BlockRange> &blocks);
con's avatar
con committed
378 379

public slots:
380
    virtual void format();
381
    virtual void rewrapParagraph();
382 383
    virtual void unCommentSelection();
    virtual void setFontSettings(const TextEditor::FontSettings &);
mae's avatar
mae committed
384
    void setFontSettingsIfVisible(const TextEditor::FontSettings &);
con's avatar
con committed
385 386
    virtual void setTabSettings(const TextEditor::TabSettings &);
    virtual void setDisplaySettings(const TextEditor::DisplaySettings &);
387
    virtual void setBehaviorSettings(const TextEditor::BehaviorSettings &);
388
    virtual void setStorageSettings(const TextEditor::StorageSettings &);
389
    virtual void setCompletionSettings(const TextEditor::CompletionSettings &);
con's avatar
con committed
390 391 392 393 394 395 396 397 398

protected:
    bool viewportEvent(QEvent *event);

    void resizeEvent(QResizeEvent *);
    void paintEvent(QPaintEvent *);
    void timerEvent(QTimerEvent *);
    void mouseMoveEvent(QMouseEvent *);
    void mousePressEvent(QMouseEvent *);
399 400 401
    void mouseReleaseEvent(QMouseEvent *);
    void leaveEvent(QEvent *);
    void keyReleaseEvent(QKeyEvent *);
con's avatar
con committed
402

403 404
    void dragEnterEvent(QDragEnterEvent *e);

405
public:
406
    // Returns true if key triggers an indent.
407
    virtual bool isElectricCharacter(QChar ch) const;
408 409 410

    void indentInsertedText(const QTextCursor &tc);

411 412 413 414
    // 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);
415 416
    // Hook to insert special characters on enter. Returns the number of extra blocks inserted.
    virtual int paragraphSeparatorAboutToBeInserted(QTextCursor &cursor);
con's avatar
con committed
417 418 419 420
    // Indent a text block based on previous line. Default does nothing
    virtual void indentBlock(QTextDocument *doc, QTextBlock block, QChar typedChar);
    // Indent at cursor. Calls indentBlock for selection or current line.
    virtual void indent(QTextDocument *doc, const QTextCursor &cursor, QChar typedChar);
mae's avatar
mae committed
421 422
    // Reindent at cursor. Selection will be adjusted according to the indentation change of the first block
    virtual void reindent(QTextDocument *doc, const QTextCursor &cursor);
con's avatar
con committed
423

424
    virtual bool contextAllowsAutoParentheses(const QTextCursor &cursor, const QString &textToInsert = QString()) const;
425
    virtual bool contextAllowsElectricCharacters(const QTextCursor &cursor) const;
426 427 428 429

    // Returns true if the cursor is inside a comment.
    virtual bool isInComment(const QTextCursor &cursor) const;

430
    virtual QString insertMatchingBrace(const QTextCursor &tc, const QString &text, QChar la, int *skippedChars) const;
431 432 433 434

    // Returns the text that needs to be inserted
    virtual QString insertParagraphSeparator(const QTextCursor &tc) const;

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 442 443 444 445
    struct Link
    {
        Link(const QString &fileName = QString(),
             int line = 0,
             int column = 0)
446 447
            : begin(-1)
            , end(-1)
448 449 450 451 452 453
            , fileName(fileName)
            , line(line)
            , column(column)
        {}

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

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

459 460
        int begin;           // Link position
        int end;           // Link end position
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

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

    /*!
       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
477
       opened. Returns whether the link was opened successfully.
478 479 480
     */
    virtual bool openLink(const Link &link);

481 482
    void maybeClearSomeExtraSelections(const QTextCursor &cursor);

con's avatar
con committed
483 484 485 486 487 488 489 490
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
491 492
    void requestFontZoom(int zoom);
    void requestZoomReset();
con's avatar
con committed
493
    void requestBlockUpdate(const QTextBlock &);
494 495
    void requestAutoCompletion(TextEditor::ITextEditable *editor, bool forced);
    void requestQuickFix(TextEditor::ITextEditable *editor);
con's avatar
con committed
496 497 498 499 500

private:
    void indentOrUnindent(bool doIndent);
    void handleHomeKey(bool anchor);
    void handleBackspaceKey();
501
    void moveLineUpDown(bool up);
502
    void copyLineUpDown(bool up);
503
    void saveCurrentCursorPositionForNavigation();
con's avatar
con committed
504
    void updateHighlights();
505
    void updateCurrentLineHighlight();
con's avatar
con committed
506

507 508 509 510 511
    void drawFoldingMarker(QPainter *painter, const QPalette &pal,
                           const QRect &rect,
                           bool expanded,
                           bool active,
                           bool hovered) const;
512

513 514 515 516 517
    void drawCollapsedBlockPopup(QPainter &painter,
                                 const QTextBlock &block,
                                 QPointF offset,
                                 const QRect &clip);

con's avatar
con committed
518
    void toggleBlockVisible(const QTextBlock &block);
mae's avatar
mae committed
519
    QRect foldBox();
con's avatar
con committed
520

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

523
    void updateLink(QMouseEvent *e);
524 525
    void showLink(const Link &);
    void clearLink();
mae's avatar
mae committed
526

527 528
    void universalHelper(); // test function for development

con's avatar
con committed
529 530 531
    // parentheses matcher
private slots:
    void _q_matchParentheses();
532
    void _q_highlightBlocks();
con's avatar
con committed
533
    void slotSelectionChanged();
534
    void _q_animateUpdate(int position, QPointF lastPos, QRectF rect);
535
    void doFoo();
con's avatar
con committed
536 537 538
};


539
class TEXTEDITOR_EXPORT BaseTextEditorEditable : public ITextEditable
con's avatar
con committed
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
{
    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
562
    QWidget *toolBar();
con's avatar
con committed
563 564 565 566 567 568

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

    int currentLine() const;
    int currentColumn() const;
569
    void gotoLine(int line, int column = 0) { e->gotoLine(line, column); }
con's avatar
con committed
570 571 572 573 574 575 576 577 578 579 580 581 582

    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
583 584
    inline void triggerQuickFix() { e->triggerQuickFix(); } // slot?

con's avatar
con committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    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;
608
    Utils::LineColumnLabel *m_cursorPositionLabel;
con's avatar
con committed
609 610 611 612 613
};

} // namespace TextEditor

#endif // BASETEXTEDITOR_H