basetextdocument.cpp 23.2 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "basetextdocument.h"
34
35

#include "basetextdocumentlayout.h"
con's avatar
con committed
36
37
#include "basetexteditor.h"
#include "storagesettings.h"
38
#include "tabsettings.h"
39
#include "extraencodingsettings.h"
40
#include "syntaxhighlighter.h"
41
#include "texteditorconstants.h"
con's avatar
con committed
42

43
#include <QtCore/QStringList>
con's avatar
con committed
44
#include <QtCore/QFile>
45
#include <QtCore/QDir>
con's avatar
con committed
46
47
48
#include <QtCore/QFileInfo>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
49
#include <QtCore/QFutureInterface>
con's avatar
con committed
50
51
52
53
#include <QtGui/QMainWindow>
#include <QtGui/QSyntaxHighlighter>
#include <QtGui/QApplication>

54
#include <coreplugin/editormanager/editormanager.h>
55
#include <coreplugin/icore.h>
56
#include <coreplugin/progressmanager/progressmanager.h>
hjk's avatar
hjk committed
57
#include <utils/qtcassert.h>
58
#include <utils/fileutils.h>
59
#include <utils/reloadpromptutils.h>
con's avatar
con committed
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
namespace {
bool verifyDecodingError(const QString &text,
                         QTextCodec *codec,
                         const char *data,
                         const int dataSize,
                         const bool possibleHeader)
{
    QByteArray verifyBuf = codec->fromUnicode(text); // slow
    // the minSize trick lets us ignore unicode headers
    int minSize = qMin(verifyBuf.size(), dataSize);
    return (minSize < dataSize - (possibleHeader? 4 : 0)
            || memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
                      data + dataSize - minSize,
                      minSize));
}
}

78
79
80
81
82
83
84
85
86
namespace TextEditor {
namespace Internal {

class DocumentMarker : public ITextMarkable
{
    Q_OBJECT
public:
    DocumentMarker(QTextDocument *);

hjk's avatar
hjk committed
87
88
    TextMarks marks() const { return m_marksCache; }

89
90
91
92
93
94
95
96
    // ITextMarkable
    bool addMark(ITextMark *mark, int line);
    TextMarks marksAt(int line) const;
    void removeMark(ITextMark *mark);
    bool hasMark(ITextMark *mark) const;
    void updateMark(ITextMark *mark);

private:
hjk's avatar
hjk committed
97
98
99
    double recalculateMaxMarkWidthFactor() const;

    TextMarks m_marksCache; // not owned
100
101
    QTextDocument *document;
};
con's avatar
con committed
102
103
104
105
106
107

DocumentMarker::DocumentMarker(QTextDocument *doc)
  : ITextMarkable(doc), document(doc)
{
}

108
109
110
111
bool DocumentMarker::addMark(TextEditor::ITextMark *mark, int line)
{
    QTC_ASSERT(line >= 1, return false);
    int blockNumber = line - 1;
hjk's avatar
hjk committed
112
113
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
114
115
116
117
    QTC_ASSERT(documentLayout, return false);
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
118
        TextBlockUserData *userData = BaseTextDocumentLayout::userData(block);
119
        userData->addMark(mark);
hjk's avatar
hjk committed
120
        m_marksCache.append(mark);
121
122
123
        mark->updateLineNumber(blockNumber + 1);
        mark->updateBlock(block);
        documentLayout->hasMarks = true;
hjk's avatar
hjk committed
124
125
        documentLayout->maxMarkWidthFactor = qMax(mark->widthFactor(),
            documentLayout->maxMarkWidthFactor);
126
127
128
129
130
131
        documentLayout->requestUpdate();
        return true;
    }
    return false;
}

hjk's avatar
hjk committed
132
133
134
135
136
137
138
139
double DocumentMarker::recalculateMaxMarkWidthFactor() const
{
    double maxWidthFactor = 1.0;
    foreach (const ITextMark *mark, marks())
        maxWidthFactor = qMax(mark->widthFactor(), maxWidthFactor);
    return maxWidthFactor;
}

140
141
142
143
144
145
146
TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
    QTC_ASSERT(line >= 1, return TextMarks());
    int blockNumber = line - 1;
    QTextBlock block = document->findBlockByNumber(blockNumber);

    if (block.isValid()) {
147
        if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
148
149
150
151
152
153
154
            return userData->marks();
    }
    return TextMarks();
}

void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
hjk's avatar
hjk committed
155
156
157
158
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
    QTC_ASSERT(documentLayout, return)

159
160
161
162
163
164
165
166
    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();
    }
hjk's avatar
hjk committed
167
168
169
170
    m_marksCache.removeAll(mark);

    if (needUpdate) {
        documentLayout->maxMarkWidthFactor = recalculateMaxMarkWidthFactor();
171
        updateMark(0);
hjk's avatar
hjk committed
172
    }
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
}

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;
}

void DocumentMarker::updateMark(ITextMark *mark)
{
    Q_UNUSED(mark)
hjk's avatar
hjk committed
191
192
    BaseTextDocumentLayout *documentLayout =
        qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
193
194
195
196
    QTC_ASSERT(documentLayout, return);
    documentLayout->requestUpdate();
}

197
198
} // namespace Internal

199
200
class BaseTextDocumentPrivate
{
201
202
203
204
205
206
207
208
209
public:
    explicit BaseTextDocumentPrivate(BaseTextDocument *q);

    QString m_fileName;
    QString m_defaultPath;
    QString m_suggestedFileName;
    QString m_mimeType;
    StorageSettings m_storageSettings;
    TabSettings m_tabSettings;
210
    ExtraEncodingSettings m_extraEncodingSettings;
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
    QTextDocument *m_document;
    Internal::DocumentMarker *m_documentMarker;
    SyntaxHighlighter *m_highlighter;

    enum LineTerminatorMode {
        LFLineTerminator,
        CRLFLineTerminator,
        NativeLineTerminator =
#if defined (Q_OS_WIN)
        CRLFLineTerminator
#else
        LFLineTerminator
#endif
    };
    LineTerminatorMode m_lineTerminatorMode;
    QTextCodec *m_codec;
    bool m_fileHasUtf8Bom;

    bool m_fileIsReadOnly;
    bool m_hasDecodingError;
231
    bool m_hasHighlightWarning;
232
    QByteArray m_decodingErrorSample;
233
    static const int kChunkSize;
234
235

    int m_autoSaveRevision;
236
237
};

238
239
const int BaseTextDocumentPrivate::kChunkSize = 65536;

240
241
242
243
244
BaseTextDocumentPrivate::BaseTextDocumentPrivate(BaseTextDocument *q) :
    m_document(new QTextDocument(q)),
    m_documentMarker(new Internal::DocumentMarker(m_document)),
    m_highlighter(0),
    m_lineTerminatorMode(NativeLineTerminator),
245
    m_codec(Core::EditorManager::instance()->defaultTextCodec()),
246
247
    m_fileHasUtf8Bom(false),
    m_fileIsReadOnly(false),
248
    m_hasDecodingError(false),
249
    m_hasHighlightWarning(false),
250
    m_autoSaveRevision(-1)
251
252
{
}
253

254
BaseTextDocument::BaseTextDocument() : d(new BaseTextDocumentPrivate(this))
con's avatar
con committed
255
256
257
258
259
{
}

BaseTextDocument::~BaseTextDocument()
{
260
    documentClosing();
261
262
263
    delete d->m_document;
    d->m_document = 0;
    delete d;
con's avatar
con committed
264
265
266
267
}

QString BaseTextDocument::mimeType() const
{
268
    return d->m_mimeType;
con's avatar
con committed
269
270
271
272
}

void BaseTextDocument::setMimeType(const QString &mt)
{
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    d->m_mimeType = mt;
}

void BaseTextDocument::setStorageSettings(const StorageSettings &storageSettings)
{
    d->m_storageSettings = storageSettings;
}

const StorageSettings &BaseTextDocument::storageSettings() const
{
    return d->m_storageSettings;
}

void BaseTextDocument::setTabSettings(const TabSettings &tabSettings)
{
    d->m_tabSettings = tabSettings;
}

const TabSettings &BaseTextDocument::tabSettings() const
{
    return d->m_tabSettings;
}

296
297
298
299
300
301
302
303
304
305
void BaseTextDocument::setExtraEncodingSettings(const ExtraEncodingSettings &extraEncodingSettings)
{
    d->m_extraEncodingSettings = extraEncodingSettings;
}

const ExtraEncodingSettings &BaseTextDocument::extraEncodingSettings() const
{
    return d->m_extraEncodingSettings;
}

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
QString BaseTextDocument::fileName() const
{
    return d->m_fileName;
}

bool BaseTextDocument::isSaveAsAllowed() const
{
    return true;
}

QString BaseTextDocument::defaultPath() const
{
    return d->m_defaultPath;
}

QString BaseTextDocument::suggestedFileName() const
{
    return d->m_suggestedFileName;
}

void BaseTextDocument::setDefaultPath(const QString &defaultPath)
{
    d->m_defaultPath = defaultPath;
}

void BaseTextDocument::setSuggestedFileName(const QString &suggestedFileName)
{
    d->m_suggestedFileName = suggestedFileName;
}

QTextDocument *BaseTextDocument::document() const
{
    return d->m_document;
}

SyntaxHighlighter *BaseTextDocument::syntaxHighlighter() const
{
    return d->m_highlighter;
}

bool BaseTextDocument::hasDecodingError() const
{
348
    return d->m_hasDecodingError;
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
}

QTextCodec *BaseTextDocument::codec() const
{
    return d->m_codec;
}

void BaseTextDocument::setCodec(QTextCodec *c)
{
    d->m_codec = c;
}

QByteArray BaseTextDocument::decodingErrorSample() const
{
    return d->m_decodingErrorSample;
}

ITextMarkable *BaseTextDocument::documentMarker() const
{
    return d->m_documentMarker;
con's avatar
con committed
369
370
}

371
bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool autoSave)
con's avatar
con committed
372
{
373
    QTextCursor cursor(d->m_document);
con's avatar
con committed
374

375
376
377
378
379
    // When autosaving, we don't want to modify the document/location under the user's fingers.
    BaseTextEditorWidget *editorWidget = 0;
    int savedPosition, savedAnchor;
    int undos = d->m_document->availableUndoSteps();

380
381
    // When saving the current editor, make sure to maintain the cursor position for undo
    Core::IEditor *currentEditor = Core::EditorManager::instance()->currentEditor();
382
    if (BaseTextEditor *editable = qobject_cast<BaseTextEditor*>(currentEditor)) {
383
384
385
386
387
388
389
        if (editable->file() == this) {
            editorWidget = editable->editorWidget();
            QTextCursor cur = editorWidget->textCursor();
            savedPosition = cur.position();
            savedAnchor = cur.anchor();
            cursor.setPosition(cur.position());
        }
390
391
    }

con's avatar
con committed
392
    cursor.beginEditBlock();
393
394
    cursor.movePosition(QTextCursor::Start);

395
396
397
    if (d->m_storageSettings.m_cleanWhitespace)
        cleanWhitespace(cursor, d->m_storageSettings.m_cleanIndentation, d->m_storageSettings.m_inEntireDocument);
    if (d->m_storageSettings.m_addFinalNewLine)
con's avatar
con committed
398
399
400
        ensureFinalNewLine(cursor);
    cursor.endEditBlock();

401
    QString fName = d->m_fileName;
con's avatar
con committed
402
403
404
    if (!fileName.isEmpty())
        fName = fileName;

405
406
407
    Utils::FileSaver saver(fName);
    if (!saver.hasError()) {
        QString plainText = d->m_document->toPlainText();
con's avatar
con committed
408

409
410
        if (d->m_lineTerminatorMode == BaseTextDocumentPrivate::CRLFLineTerminator)
            plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
con's avatar
con committed
411

412
413
414
415
416
417
        if (d->m_codec->name() == "UTF-8"
                && (d->m_extraEncodingSettings.m_utf8BomSetting == ExtraEncodingSettings::AlwaysAdd
                    || (d->m_extraEncodingSettings.m_utf8BomSetting == ExtraEncodingSettings::OnlyKeep
                        && d->m_fileHasUtf8Bom))) {
            saver.write("\xef\xbb\xbf", 3);
        }
con's avatar
con committed
418

419
        saver.write(d->m_codec->fromUnicode(plainText));
Takumi ASAKI's avatar
Takumi ASAKI committed
420
    }
421
422
423
424
425
426
427
428
429
430
431

    if (autoSave && undos < d->m_document->availableUndoSteps()) {
        d->m_document->undo();
        if (editorWidget) {
            QTextCursor cur = editorWidget->textCursor();
            cur.setPosition(savedAnchor);
            cur.setPosition(savedPosition, QTextCursor::KeepAnchor);
            editorWidget->setTextCursor(cur);
        }
    }

432
    if (!saver.finalize(errorString))
con's avatar
con committed
433
        return false;
434
435
436
    d->m_autoSaveRevision = d->m_document->revision();
    if (autoSave)
        return true;
con's avatar
con committed
437
438

    const QFileInfo fi(fName);
439
    d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
con's avatar
con committed
440

441
    d->m_document->setModified(false);
con's avatar
con committed
442
443
444
    emit titleChanged(fi.fileName());
    emit changed();

445
446
    d->m_hasDecodingError = false;
    d->m_decodingErrorSample.clear();
con's avatar
con committed
447
448
449
450

    return true;
}

451
452
453
454
455
bool BaseTextDocument::shouldAutoSave() const
{
    return d->m_autoSaveRevision != d->m_document->revision();
}

dt's avatar
dt committed
456
457
458
void BaseTextDocument::rename(const QString &newName)
{
    const QFileInfo fi(newName);
459
    d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
dt's avatar
dt committed
460
461
462
463
    emit titleChanged(fi.fileName());
    emit changed();
}

con's avatar
con committed
464
465
bool BaseTextDocument::isReadOnly() const
{
466
    if (d->m_hasDecodingError)
con's avatar
con committed
467
        return true;
468
    if (d->m_fileName.isEmpty()) //have no corresponding file, so editing is ok
con's avatar
con committed
469
        return false;
470
    return d->m_fileIsReadOnly;
471
472
473
474
}

bool BaseTextDocument::isModified() const
{
475
    return d->m_document->isModified();
476
477
478
479
}

void BaseTextDocument::checkPermissions()
{
480
481
482
483
    bool previousReadOnly = d->m_fileIsReadOnly;
    if (!d->m_fileName.isEmpty()) {
        const QFileInfo fi(d->m_fileName);
        d->m_fileIsReadOnly = !fi.isWritable();
484
    } else {
485
        d->m_fileIsReadOnly = false;
486
    }
487
    if (previousReadOnly != d->m_fileIsReadOnly)
488
        emit changed();
con's avatar
con committed
489
490
}

491
bool BaseTextDocument::open(QString *errorString, const QString &fileName, const QString &realFileName)
con's avatar
con committed
492
493
494
495
{
    QString title = tr("untitled");
    if (!fileName.isEmpty()) {
        const QFileInfo fi(fileName);
496
497
        d->m_fileIsReadOnly = !fi.isWritable();
        d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
con's avatar
con committed
498
499
500

        title = fi.fileName();

501
502
        QByteArray buf;
        try {
503
            Utils::FileReader reader;
504
            if (!reader.fetch(realFileName, errorString))
505
506
                return false;
            buf = reader.data();
507
        } catch (std::bad_alloc) {
508
            *errorString = tr("Out of memory");
509
510
            return false;
        }
con's avatar
con committed
511
512
        int bytesRead = buf.size();

513
514
        QTextCodec *codec = d->m_codec;
        d->m_fileHasUtf8Bom = false;
con's avatar
con committed
515
516
517
518
519
520
521
522

        // code taken from qtextstream
        if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
                               || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-32");
        } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
                                      || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-16");
Takumi ASAKI's avatar
Takumi ASAKI committed
523
524
        } else if (bytesRead >= 3 && ((uchar(buf[0]) == 0xef && uchar(buf[1]) == 0xbb) && uchar(buf[2]) == 0xbf)) {
            codec = QTextCodec::codecForName("UTF-8");
525
            d->m_fileHasUtf8Bom = true;
con's avatar
con committed
526
527
528
529
530
        } else if (!codec) {
            codec = QTextCodec::codecForLocale();
        }
        // end code taken from qtextstream

531
        d->m_codec = codec;
con's avatar
con committed
532

533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
        // An alternative to the code below would be creating a decoder from the codec,
        // but failure detection doesn't seem be working reliably.
        QStringList content;
        if (bytesRead <= BaseTextDocumentPrivate::kChunkSize) {
            QString text = d->m_codec->toUnicode(buf);
            d->m_hasDecodingError = verifyDecodingError(
                text, d->m_codec, buf.constData(), bytesRead, true);
            content.append(text);
        } else {
            // Avoid large allocation of contiguous memory.
            QTextCodec::ConverterState state;
            int offset = 0;
            while (offset < bytesRead) {
                int currentSize = qMin(BaseTextDocumentPrivate::kChunkSize, bytesRead - offset);
                QString text = d->m_codec->toUnicode(buf.constData() + offset, currentSize, &state);
                if (state.remainingChars) {
                    if (currentSize < BaseTextDocumentPrivate::kChunkSize && !d->m_hasDecodingError)
                        d->m_hasDecodingError = true;

                    // Process until the end of the current multi-byte character. Remaining might
                    // actually contain more than needed so try one-be-one.
                    while (state.remainingChars) {
                        text.append(d->m_codec->toUnicode(
                            buf.constData() + offset + currentSize, 1, &state));
                        ++currentSize;
                    }
                }

                if (!d->m_hasDecodingError) {
                    d->m_hasDecodingError = verifyDecodingError(
                        text, d->m_codec, buf.constData() + offset, currentSize, offset == 0);
                }

                offset += currentSize;
                content.append(text);
            }
        }
con's avatar
con committed
570

571
        if (d->m_hasDecodingError) {
con's avatar
con committed
572
573
            int p = buf.indexOf('\n', 16384);
            if (p < 0)
574
                d->m_decodingErrorSample = buf;
con's avatar
con committed
575
            else
576
                d->m_decodingErrorSample = buf.left(p);
con's avatar
con committed
577
        } else {
578
            d->m_decodingErrorSample.clear();
con's avatar
con committed
579
        }
580
        buf.clear();
con's avatar
con committed
581

582
583
584
585
586
587
588
589
590
591
        foreach (const QString &text, content) {
            int lf = text.indexOf('\n');
            if (lf >= 0) {
                if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
                    d->m_lineTerminatorMode = BaseTextDocumentPrivate::CRLFLineTerminator;
                } else {
                    d->m_lineTerminatorMode = BaseTextDocumentPrivate::LFLineTerminator;
                }
                break;
            }
con's avatar
con committed
592
593
        }

594
        d->m_document->setModified(false);
595
596
597
        const int chunks = content.size();
        if (chunks == 1) {
            d->m_document->setPlainText(content.at(0));
598
        } else {
599
600
601
602
603
            QFutureInterface<void> interface;
            interface.setProgressRange(0, chunks);
            Core::ICore::instance()->progressManager()->addTask(
                interface.future(), tr("Opening file"), Constants::TASK_OPEN_FILE);
            interface.reportStarted();
604
            d->m_document->setUndoRedoEnabled(false);
605
            QTextCursor c(d->m_document);
606
607
            c.beginEditBlock();
            d->m_document->clear();
608
609
610
611
            for (int i = 0; i < chunks; ++i) {
                c.insertText(content.at(i));
                interface.setProgressValue(i + 1);
                QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
612
            }
613
            c.endEditBlock();
614
            d->m_document->setUndoRedoEnabled(true);
615
            interface.reportFinished();
616
617
618
        }
        BaseTextDocumentLayout *documentLayout =
            qobject_cast<BaseTextDocumentLayout*>(d->m_document->documentLayout());
hjk's avatar
hjk committed
619
        QTC_ASSERT(documentLayout, return true);
620
621
        documentLayout->lastSaveRevision = d->m_autoSaveRevision = d->m_document->revision();
        d->m_document->setModified(fileName != realFileName);
con's avatar
con committed
622
623
624
625
626
627
        emit titleChanged(title);
        emit changed();
    }
    return true;
}

628
bool BaseTextDocument::reload(QString *errorString, QTextCodec *codec)
con's avatar
con committed
629
{
630
    QTC_ASSERT(codec, return false);
631
    d->m_codec = codec;
632
    return reload(errorString);
con's avatar
con committed
633
634
}

635
bool BaseTextDocument::reload(QString *errorString)
con's avatar
con committed
636
637
{
    emit aboutToReload();
638
639
    documentClosing(); // removes text marks non-permanently

640
    if (!open(errorString, d->m_fileName, d->m_fileName))
641
642
643
        return false;
    emit reloaded();
    return true;
con's avatar
con committed
644
645
}

646
bool BaseTextDocument::reload(QString *errorString, ReloadFlag flag, ChangeType type)
647
648
{
    if (flag == FlagIgnore)
649
        return true;
650
    if (type == TypePermissions) {
651
        checkPermissions();
652
        return true;
653
    } else {
654
        return reload(errorString);
con's avatar
con committed
655
656
657
    }
}

658
void BaseTextDocument::setSyntaxHighlighter(SyntaxHighlighter *highlighter)
con's avatar
con committed
659
{
660
661
662
663
664
    if (d->m_highlighter)
        delete d->m_highlighter;
    d->m_highlighter = highlighter;
    d->m_highlighter->setParent(this);
    d->m_highlighter->setDocument(d->m_document);
con's avatar
con committed
665
666
}

667
668


669
void BaseTextDocument::cleanWhitespace(const QTextCursor &cursor)
670
{
671
672
    bool hasSelection = cursor.hasSelection();
    QTextCursor copyCursor = cursor;
mae's avatar
mae committed
673
    copyCursor.setVisualNavigation(false);
674
675
676
677
678
    copyCursor.beginEditBlock();
    cleanWhitespace(copyCursor, true, true);
    if (!hasSelection)
        ensureFinalNewLine(copyCursor);
    copyCursor.endEditBlock();
679
680
}

681
void BaseTextDocument::cleanWhitespace(QTextCursor &cursor, bool cleanIndentation, bool inEntireDocument)
con's avatar
con committed
682
{
683
    BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(d->m_document->documentLayout());
mae's avatar
mae committed
684
    Q_ASSERT(cursor.visualNavigation() == false);
con's avatar
con committed
685

686
    QTextBlock block = d->m_document->findBlock(cursor.selectionStart());
687
688
    QTextBlock end;
    if (cursor.hasSelection())
689
        end = d->m_document->findBlock(cursor.selectionEnd()-1).next();
690
691

    while (block.isValid() && block != end) {
con's avatar
con committed
692

693
        if (inEntireDocument || block.revision() != documentLayout->lastSaveRevision) {
con's avatar
con committed
694
695

            QString blockText = block.text();
696
            if (int trailing = d->m_tabSettings.trailingWhitespaces(blockText)) {
con's avatar
con committed
697
698
699
700
                cursor.setPosition(block.position() + block.length() - 1);
                cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing);
                cursor.removeSelectedText();
            }
701
            if (cleanIndentation && !d->m_tabSettings.isIndentationClean(block)) {
con's avatar
con committed
702
                cursor.setPosition(block.position());
703
                int firstNonSpace = d->m_tabSettings.firstNonSpace(blockText);
con's avatar
con committed
704
705
706
707
                if (firstNonSpace == blockText.length()) {
                    cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
                    cursor.removeSelectedText();
                } else {
708
                    int column = d->m_tabSettings.columnAt(blockText, firstNonSpace);
con's avatar
con committed
709
                    cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace);
710
                    QString indentationString = d->m_tabSettings.indentationString(0, column, block);
con's avatar
con committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
                    cursor.insertText(indentationString);
                }
            }
        }

        block = block.next();
    }
}

void BaseTextDocument::ensureFinalNewLine(QTextCursor& cursor)
{
    cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
    bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);

    if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator)
    {
        cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
        cursor.insertText(QLatin1String("\n"));
    }
}
731
732
733

void BaseTextDocument::documentClosing()
{
734
    QTextBlock block = d->m_document->begin();
735
736
737
738
739
740
    while (block.isValid()) {
        if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData()))
            data->documentClosing();
        block = block.next();
    }
}
741

742
743
744
745
746
747
748
749
750
751
bool BaseTextDocument::hasHighlightWarning() const
{
    return d->m_hasHighlightWarning;
}

void BaseTextDocument::setHighlightWarning(bool has)
{
    d->m_hasHighlightWarning = has;
}

752
753
754
} // namespace TextEditor

#include "basetextdocument.moc"