/
katedocument.cpp
5980 lines (4952 loc) · 185 KB
/
katedocument.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
271
272
273
274
275
276
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
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
689
690
691
692
693
694
695
696
697
698
699
700
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of the KDE libraries
Copyright (C) 2001-2004 Christoph Cullmann <cullmann@kde.org>
Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>
Copyright (C) 1999 Jochen Wilhelmy <digisnap@cs.tu-berlin.de>
Copyright (C) 2006 Hamish Rodda <rodda@kde.org>
Copyright (C) 2007 Mirko Stocker <me@misto.ch>
Copyright (C) 2009-2010 Michel Ludwig <michel.ludwig@kdemail.net>
Copyright (C) 2013 Gerald Senarclens de Grancy <oss@senarclens.eu>
Copyright (C) 2013 Andrey Matveyakin <a.matveyakin@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02111-13020, USA.
*/
//BEGIN includes
#include "katedocument.h"
#include "kateglobal.h"
#include "katedialogs.h"
#include "katehighlight.h"
#include "kateview.h"
#include "kateautoindent.h"
#include "katetextline.h"
#include "katehighlighthelpers.h"
#include "katerenderer.h"
#include "kateregexp.h"
#include "kateplaintextsearch.h"
#include "kateregexpsearch.h"
#include "kateconfig.h"
#include "katemodemanager.h"
#include "kateschema.h"
#include "katebuffer.h"
#include "kateundomanager.h"
#include "spellcheck/prefixstore.h"
#include "spellcheck/ontheflycheck.h"
#include "spellcheck/spellcheck.h"
#include "katescriptmanager.h"
#include "kateswapfile.h"
#include "katepartdebug.h"
#include "printing/kateprinter.h"
#include "kateabstractinputmode.h"
#include "katetemplatehandler.h"
#ifdef EDITORCONFIG_FOUND
#include "editorconfig.h"
#endif
#include <KTextEditor/DocumentCursor>
#include <KTextEditor/Attribute>
#include <KParts/OpenUrlArguments>
#include <KIO/Job>
#include <KIO/JobUiDelegate>
#include <KFileItem>
#include <KJobWidgets>
#include <KMessageBox>
#include <KStandardAction>
#include <KXMLGUIFactory>
#include <kdirwatch.h>
#include <KCodecs>
#include <KStringHandler>
#include <KConfigGroup>
#include <KMountPoint>
#include <QCryptographicHash>
#include <QFile>
#include <QMap>
#include <QTextCodec>
#include <QTextStream>
#include <QTimer>
#include <QClipboard>
#include <QApplication>
#include <QFileDialog>
#include <QMimeDatabase>
#include <QTemporaryFile>
#include <cmath>
#ifdef LIBGIT2_FOUND
#include <git2.h>
#include <git2/oid.h>
#include <git2/repository.h>
#endif
//END includes
#if 0
#define EDIT_DEBUG qCDebug(LOG_KTE)
#else
#define EDIT_DEBUG if (0) qCDebug(LOG_KTE)
#endif
static inline QChar matchingStartBracket(QChar c, bool withQuotes)
{
switch (c.toLatin1()) {
case '}': return QLatin1Char('{');
case ']': return QLatin1Char('[');
case ')': return QLatin1Char('(');
case '\'': return withQuotes ? QLatin1Char('\'') : QChar();
case '"': return withQuotes ? QLatin1Char('"') : QChar();
}
return QChar();
}
static inline QChar matchingEndBracket(QChar c, bool withQuotes)
{
switch (c.toLatin1()) {
case '{': return QLatin1Char('}');
case '[': return QLatin1Char(']');
case '(': return QLatin1Char(')');
case '\'': return withQuotes ? QLatin1Char('\'') : QChar();
case '"': return withQuotes ? QLatin1Char('"') : QChar();
}
return QChar();
}
static inline QChar matchingBracket(QChar c, bool withQuotes)
{
QChar bracket = matchingStartBracket(c, withQuotes);
if (bracket.isNull()) {
bracket = matchingEndBracket(c, false);
}
return bracket;
}
static inline bool isStartBracket(const QChar &c)
{
return ! matchingEndBracket(c, false).isNull();
}
static inline bool isEndBracket(const QChar &c)
{
return ! matchingStartBracket(c, false).isNull();
}
static inline bool isBracket(const QChar &c)
{
return isStartBracket(c) || isEndBracket(c);
}
/**
* normalize given url
* @param url input url
* @return normalized url
*/
static QUrl normalizeUrl (const QUrl &url)
{
/**
* only normalize local urls
*/
if (url.isEmpty() || !url.isLocalFile())
return url;
/**
* don't normalize if not existing!
* canonicalFilePath won't work!
*/
const QString normalizedUrl(QFileInfo(url.toLocalFile()).canonicalFilePath());
if (normalizedUrl.isEmpty())
return url;
/**
* else: use canonicalFilePath to normalize
*/
return QUrl::fromLocalFile(normalizedUrl);
}
//BEGIN d'tor, c'tor
//
// KTextEditor::DocumentPrivate Constructor
//
KTextEditor::DocumentPrivate::DocumentPrivate(bool bSingleViewMode,
bool bReadOnly, QWidget *parentWidget,
QObject *parent)
: KTextEditor::Document (this, parent),
m_bSingleViewMode(bSingleViewMode),
m_bReadOnly(bReadOnly),
m_activeView(nullptr),
editSessionNumber(0),
editIsRunning(false),
m_undoMergeAllEdits(false),
m_undoManager(new KateUndoManager(this)),
m_editableMarks(markType01),
m_annotationModel(nullptr),
m_buffer(new KateBuffer(this)),
m_indenter(new KateAutoIndent(this)),
m_hlSetByUser(false),
m_bomSetByUser(false),
m_indenterSetByUser(false),
m_userSetEncodingForNextReload(false),
m_modOnHd(false),
m_modOnHdReason(OnDiskUnmodified),
m_prevModOnHdReason(OnDiskUnmodified),
m_docName(QStringLiteral("need init")),
m_docNameNumber(0),
m_fileType(QStringLiteral("Normal")),
m_fileTypeSetByUser(false),
m_reloading(false),
m_config(new KateDocumentConfig(this)),
m_fileChangedDialogsActivated(false),
m_onTheFlyChecker(nullptr),
m_documentState(DocumentIdle),
m_readWriteStateBeforeLoading(false),
m_isUntitled(true),
m_openingError(false)
{
/**
* no plugins from kparts here
*/
setPluginLoadingMode (DoNotLoadPlugins);
/**
* pass on our component data, do this after plugin loading is off
*/
setComponentData(KTextEditor::EditorPrivate::self()->aboutData());
/**
* avoid spamming plasma and other window managers with progress dialogs
* we show such stuff inline in the views!
*/
setProgressInfoEnabled(false);
// register doc at factory
KTextEditor::EditorPrivate::self()->registerDocument(this);
// normal hl
m_buffer->setHighlight(0);
// swap file
m_swapfile = (config()->swapFileMode() == KateDocumentConfig::DisableSwapFile) ? nullptr : new Kate::SwapFile(this);
// important, fill in the config into the indenter we use...
m_indenter->updateConfig();
// some nice signals from the buffer
connect(m_buffer, SIGNAL(tagLines(int,int)), this, SLOT(tagLines(int,int)));
// if the user changes the highlight with the dialog, notify the doc
connect(KateHlManager::self(), SIGNAL(changed()), SLOT(internalHlChanged()));
// signals for mod on hd
connect(KTextEditor::EditorPrivate::self()->dirWatch(), SIGNAL(dirty(QString)),
this, SLOT(slotModOnHdDirty(QString)));
connect(KTextEditor::EditorPrivate::self()->dirWatch(), SIGNAL(created(QString)),
this, SLOT(slotModOnHdCreated(QString)));
connect(KTextEditor::EditorPrivate::self()->dirWatch(), SIGNAL(deleted(QString)),
this, SLOT(slotModOnHdDeleted(QString)));
/**
* singleshot timer to handle updates of mod on hd state delayed
*/
m_modOnHdTimer.setSingleShot(true);
m_modOnHdTimer.setInterval(200);
connect(&m_modOnHdTimer, SIGNAL(timeout()), this, SLOT(slotDelayedHandleModOnHd()));
/**
* load handling
* this is needed to ensure we signal the user if a file ist still loading
* and to disallow him to edit in that time
*/
connect(this, SIGNAL(started(KIO::Job*)), this, SLOT(slotStarted(KIO::Job*)));
connect(this, SIGNAL(completed()), this, SLOT(slotCompleted()));
connect(this, SIGNAL(canceled(QString)), this, SLOT(slotCanceled()));
connect(this, SIGNAL(urlChanged(QUrl)), this, SLOT(slotUrlChanged(QUrl)));
// update doc name
updateDocName();
// if single view mode, like in the konqui embedding, create a default view ;)
// be lazy, only create it now, if any parentWidget is given, otherwise widget()
// will create it on demand...
if (m_bSingleViewMode && parentWidget) {
KTextEditor::View *view = (KTextEditor::View *)createView(parentWidget);
insertChildClient(view);
view->setContextMenu(view->defaultContextMenu());
setWidget(view);
}
connect(m_undoManager, SIGNAL(undoChanged()), this, SIGNAL(undoChanged()));
connect(m_undoManager, SIGNAL(undoStart(KTextEditor::Document*)), this, SIGNAL(editingStarted(KTextEditor::Document*)));
connect(m_undoManager, SIGNAL(undoEnd(KTextEditor::Document*)), this, SIGNAL(editingFinished(KTextEditor::Document*)));
connect(m_undoManager, SIGNAL(redoStart(KTextEditor::Document*)), this, SIGNAL(editingStarted(KTextEditor::Document*)));
connect(m_undoManager, SIGNAL(redoEnd(KTextEditor::Document*)), this, SIGNAL(editingFinished(KTextEditor::Document*)));
connect(this, SIGNAL(sigQueryClose(bool*,bool*)), this, SLOT(slotQueryClose_save(bool*,bool*)));
connect(this, &KTextEditor::DocumentPrivate::textRemoved, this, &KTextEditor::DocumentPrivate::saveEditingPositions);
connect(this, &KTextEditor::DocumentPrivate::textInserted, this, &KTextEditor::DocumentPrivate::saveEditingPositions);
connect(this, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)), this, SLOT(clearEditingPosStack()));
onTheFlySpellCheckingEnabled(config()->onTheFlySpellCheck());
}
//
// KTextEditor::DocumentPrivate Destructor
//
KTextEditor::DocumentPrivate::~DocumentPrivate()
{
// delete pending mod-on-hd message, if applicable
delete m_modOnHdHandler;
/**
* we are about to delete cursors/ranges/...
*/
emit aboutToDeleteMovingInterfaceContent(this);
// kill it early, it has ranges!
delete m_onTheFlyChecker;
m_onTheFlyChecker = nullptr;
clearDictionaryRanges();
// Tell the world that we're about to close (== destruct)
// Apps must receive this in a direct signal-slot connection, and prevent
// any further use of interfaces once they return.
emit aboutToClose(this);
// remove file from dirwatch
deactivateDirWatch();
// thanks for offering, KPart, but we're already self-destructing
setAutoDeleteWidget(false);
setAutoDeletePart(false);
// clean up remaining views
qDeleteAll (m_views.keys());
m_views.clear();
// cu marks
for (QHash<int, KTextEditor::Mark *>::const_iterator i = m_marks.constBegin(); i != m_marks.constEnd(); ++i) {
delete i.value();
}
m_marks.clear();
delete m_config;
KTextEditor::EditorPrivate::self()->deregisterDocument(this);
}
//END
void KTextEditor::DocumentPrivate::saveEditingPositions(KTextEditor::Document *, const KTextEditor::Range &range)
{
if (m_editingStackPosition != m_editingStack.size() - 1) {
m_editingStack.resize(m_editingStackPosition);
}
KTextEditor::MovingInterface *moving = qobject_cast<KTextEditor::MovingInterface *>(this);
const auto c = range.start();
QSharedPointer<KTextEditor::MovingCursor> mc (moving->newMovingCursor(c));
if (!m_editingStack.isEmpty() && c.line() == m_editingStack.top()->line()) {
m_editingStack.pop();
}
m_editingStack.push(mc);
if (m_editingStack.size() > s_editingStackSizeLimit) {
m_editingStack.removeFirst();
}
m_editingStackPosition = m_editingStack.size() - 1;
}
KTextEditor::Cursor KTextEditor::DocumentPrivate::lastEditingPosition(EditingPositionKind nextOrPrev, KTextEditor::Cursor currentCursor)
{
if (m_editingStack.isEmpty()) {
return KTextEditor::Cursor::invalid();
}
auto targetPos = m_editingStack.at(m_editingStackPosition)->toCursor();
if (targetPos == currentCursor) {
if (nextOrPrev == Previous) {
m_editingStackPosition--;
}
else {
m_editingStackPosition++;
}
m_editingStackPosition = qBound(0, m_editingStackPosition, m_editingStack.size() - 1);
}
return m_editingStack.at(m_editingStackPosition)->toCursor();
}
void KTextEditor::DocumentPrivate::clearEditingPosStack()
{
m_editingStack.clear();
m_editingStackPosition = -1;
}
// on-demand view creation
QWidget *KTextEditor::DocumentPrivate::widget()
{
// no singleViewMode -> no widget()...
if (!singleViewMode()) {
return nullptr;
}
// does a widget exist already? use it!
if (KTextEditor::Document::widget()) {
return KTextEditor::Document::widget();
}
// create and return one...
KTextEditor::View *view = (KTextEditor::View *)createView(nullptr);
insertChildClient(view);
view->setContextMenu(view->defaultContextMenu());
setWidget(view);
return view;
}
//BEGIN KTextEditor::Document stuff
KTextEditor::View *KTextEditor::DocumentPrivate::createView(QWidget *parent, KTextEditor::MainWindow *mainWindow)
{
KTextEditor::ViewPrivate *newView = new KTextEditor::ViewPrivate(this, parent, mainWindow);
if (m_fileChangedDialogsActivated) {
connect(newView, SIGNAL(focusIn(KTextEditor::View*)), this, SLOT(slotModifiedOnDisk()));
}
emit viewCreated(this, newView);
// post existing messages to the new view, if no specific view is given
foreach (KTextEditor::Message *message, m_messageHash.keys()) {
if (!message->view()) {
newView->postMessage(message, m_messageHash[message]);
}
}
return newView;
}
KTextEditor::Range KTextEditor::DocumentPrivate::rangeOnLine(KTextEditor::Range range, int line) const
{
const int col1 = toVirtualColumn(range.start());
const int col2 = toVirtualColumn(range.end());
return KTextEditor::Range(line, fromVirtualColumn(line, col1), line, fromVirtualColumn(line, col2));
}
//BEGIN KTextEditor::EditInterface stuff
bool KTextEditor::DocumentPrivate::isEditingTransactionRunning() const
{
return editSessionNumber > 0;
}
QString KTextEditor::DocumentPrivate::text() const
{
return m_buffer->text();
}
QString KTextEditor::DocumentPrivate::text(const KTextEditor::Range &range, bool blockwise) const
{
if (!range.isValid()) {
qCWarning(LOG_KTE) << "Text requested for invalid range" << range;
return QString();
}
QString s;
if (range.start().line() == range.end().line()) {
if (range.start().column() > range.end().column()) {
return QString();
}
Kate::TextLine textLine = m_buffer->plainLine(range.start().line());
if (!textLine) {
return QString();
}
return textLine->string(range.start().column(), range.end().column() - range.start().column());
} else {
for (int i = range.start().line(); (i <= range.end().line()) && (i < m_buffer->count()); ++i) {
Kate::TextLine textLine = m_buffer->plainLine(i);
if (!blockwise) {
if (i == range.start().line()) {
s.append(textLine->string(range.start().column(), textLine->length() - range.start().column()));
} else if (i == range.end().line()) {
s.append(textLine->string(0, range.end().column()));
} else {
s.append(textLine->string());
}
} else {
KTextEditor::Range subRange = rangeOnLine(range, i);
s.append(textLine->string(subRange.start().column(), subRange.columnWidth()));
}
if (i < range.end().line()) {
s.append(QLatin1Char('\n'));
}
}
}
return s;
}
QChar KTextEditor::DocumentPrivate::characterAt(const KTextEditor::Cursor &position) const
{
Kate::TextLine textLine = m_buffer->plainLine(position.line());
if (!textLine) {
return QChar();
}
return textLine->at(position.column());
}
QString KTextEditor::DocumentPrivate::wordAt(const KTextEditor::Cursor &cursor) const
{
return text(wordRangeAt(cursor));
}
KTextEditor::Range KTextEditor::DocumentPrivate::wordRangeAt(const KTextEditor::Cursor &cursor) const
{
// get text line
const int line = cursor.line();
Kate::TextLine textLine = m_buffer->plainLine(line);
if (!textLine) {
return KTextEditor::Range::invalid();
}
// make sure the cursor is
const int lineLenth = textLine->length();
if (cursor.column() > lineLenth) {
return KTextEditor::Range::invalid();
}
int start = cursor.column();
int end = start;
while (start > 0 && highlight()->isInWord(textLine->at(start - 1), textLine->attribute(start - 1))) {
start--;
}
while (end < lineLenth && highlight()->isInWord(textLine->at(end), textLine->attribute(end))) {
end++;
}
return KTextEditor::Range(line, start, line, end);
}
bool KTextEditor::DocumentPrivate::isValidTextPosition(const KTextEditor::Cursor& cursor) const
{
const int ln = cursor.line();
const int col = cursor.column();
// cursor in document range?
if (ln < 0 || col < 0 || ln >= lines() || col > lineLength(ln)) {
return false;
}
const QString str = line(ln);
Q_ASSERT(str.length() >= col);
// cursor at end of line?
const int len = lineLength(ln);
if (col == 0 || col == len) {
return true;
}
// cursor in the middle of a valid utf32-surrogate?
return (! str.at(col).isLowSurrogate())
|| (! str.at(col-1).isHighSurrogate());
}
QStringList KTextEditor::DocumentPrivate::textLines(const KTextEditor::Range &range, bool blockwise) const
{
QStringList ret;
if (!range.isValid()) {
qCWarning(LOG_KTE) << "Text requested for invalid range" << range;
return ret;
}
if (blockwise && (range.start().column() > range.end().column())) {
return ret;
}
if (range.start().line() == range.end().line()) {
Q_ASSERT(range.start() <= range.end());
Kate::TextLine textLine = m_buffer->plainLine(range.start().line());
if (!textLine) {
return ret;
}
ret << textLine->string(range.start().column(), range.end().column() - range.start().column());
} else {
for (int i = range.start().line(); (i <= range.end().line()) && (i < m_buffer->count()); ++i) {
Kate::TextLine textLine = m_buffer->plainLine(i);
if (!blockwise) {
if (i == range.start().line()) {
ret << textLine->string(range.start().column(), textLine->length() - range.start().column());
} else if (i == range.end().line()) {
ret << textLine->string(0, range.end().column());
} else {
ret << textLine->string();
}
} else {
KTextEditor::Range subRange = rangeOnLine(range, i);
ret << textLine->string(subRange.start().column(), subRange.columnWidth());
}
}
}
return ret;
}
QString KTextEditor::DocumentPrivate::line(int line) const
{
Kate::TextLine l = m_buffer->plainLine(line);
if (!l) {
return QString();
}
return l->string();
}
bool KTextEditor::DocumentPrivate::setText(const QString &s)
{
if (!isReadWrite()) {
return false;
}
QList<KTextEditor::Mark> msave;
foreach (KTextEditor::Mark *mark, m_marks) {
msave.append(*mark);
}
editStart();
// delete the text
clear();
// insert the new text
insertText(KTextEditor::Cursor(), s);
editEnd();
foreach (KTextEditor::Mark mark, msave) {
setMark(mark.line, mark.type);
}
return true;
}
bool KTextEditor::DocumentPrivate::setText(const QStringList &text)
{
if (!isReadWrite()) {
return false;
}
QList<KTextEditor::Mark> msave;
foreach (KTextEditor::Mark *mark, m_marks) {
msave.append(*mark);
}
editStart();
// delete the text
clear();
// insert the new text
insertText(KTextEditor::Cursor::start(), text);
editEnd();
foreach (KTextEditor::Mark mark, msave) {
setMark(mark.line, mark.type);
}
return true;
}
bool KTextEditor::DocumentPrivate::clear()
{
if (!isReadWrite()) {
return false;
}
foreach (KTextEditor::ViewPrivate *view, m_views) {
view->clear();
view->tagAll();
view->update();
}
clearMarks();
emit aboutToInvalidateMovingInterfaceContent(this);
m_buffer->invalidateRanges();
emit aboutToRemoveText(documentRange());
return editRemoveLines(0, lastLine());
}
bool KTextEditor::DocumentPrivate::insertText(const KTextEditor::Cursor &position, const QString &text, bool block)
{
if (!isReadWrite()) {
return false;
}
if (text.isEmpty()) {
return true;
}
editStart();
int currentLine = position.line();
int currentLineStart = 0;
const int totalLength = text.length();
int insertColumn = position.column();
// pad with empty lines, if insert position is after last line
if (position.line() > lines()) {
int line = lines();
while (line <= position.line()) {
editInsertLine(line, QString());
line++;
}
}
const int tabWidth = config()->tabWidth();
static const QChar newLineChar(QLatin1Char('\n'));
int insertColumnExpanded = insertColumn;
Kate::TextLine l = plainKateTextLine(currentLine);
if (l) {
insertColumnExpanded = l->toVirtualColumn(insertColumn, tabWidth);
}
int positionColumnExpanded = insertColumnExpanded;
int pos = 0;
for (; pos < totalLength; pos++) {
const QChar &ch = text.at(pos);
if (ch == newLineChar) {
// Only perform the text insert if there is text to insert
if (currentLineStart < pos) {
editInsertText(currentLine, insertColumn, text.mid(currentLineStart, pos - currentLineStart));
}
if (!block) {
editWrapLine(currentLine, insertColumn + pos - currentLineStart);
insertColumn = 0;
}
currentLine++;
l = plainKateTextLine(currentLine);
if (block) {
if (currentLine == lastLine() + 1) {
editInsertLine(currentLine, QString());
}
insertColumn = positionColumnExpanded;
if (l) {
insertColumn = l->fromVirtualColumn(insertColumn, tabWidth);
}
}
currentLineStart = pos + 1;
if (l) {
insertColumnExpanded = l->toVirtualColumn(insertColumn, tabWidth);
}
}
}
// Only perform the text insert if there is text to insert
if (currentLineStart < pos) {
editInsertText(currentLine, insertColumn, text.mid(currentLineStart, pos - currentLineStart));
}
editEnd();
return true;
}
bool KTextEditor::DocumentPrivate::insertText(const KTextEditor::Cursor &position, const QStringList &textLines, bool block)
{
if (!isReadWrite()) {
return false;
}
// just reuse normal function
return insertText(position, textLines.join(QStringLiteral("\n")), block);
}
bool KTextEditor::DocumentPrivate::removeText(const KTextEditor::Range &_range, bool block)
{
KTextEditor::Range range = _range;
if (!isReadWrite()) {
return false;
}
// Should now be impossible to trigger with the new Range class
Q_ASSERT(range.start().line() <= range.end().line());
if (range.start().line() > lastLine()) {
return false;
}
if (!block) {
emit aboutToRemoveText(range);
}
editStart();
if (!block) {
if (range.end().line() > lastLine()) {
range.setEnd(KTextEditor::Cursor(lastLine() + 1, 0));
}
if (range.onSingleLine()) {
editRemoveText(range.start().line(), range.start().column(), range.columnWidth());
} else {
int from = range.start().line();
int to = range.end().line();
// remove last line
if (to <= lastLine()) {
editRemoveText(to, 0, range.end().column());
}
// editRemoveLines() will be called on first line (to remove bookmark)
if (range.start().column() == 0 && from > 0) {
--from;
}
// remove middle lines
editRemoveLines(from + 1, to - 1);
// remove first line if not already removed by editRemoveLines()
if (range.start().column() > 0 || range.start().line() == 0) {
editRemoveText(from, range.start().column(), m_buffer->plainLine(from)->length() - range.start().column());
editUnWrapLine(from);
}
}
} // if ( ! block )
else {
int startLine = qMax(0, range.start().line());
int vc1 = toVirtualColumn(range.start());
int vc2 = toVirtualColumn(range.end());
for (int line = qMin(range.end().line(), lastLine()); line >= startLine; --line) {
int col1 = fromVirtualColumn(line, vc1);
int col2 = fromVirtualColumn(line, vc2);
editRemoveText(line, qMin(col1, col2), qAbs(col2 - col1));
}
}
editEnd();
return true;
}
bool KTextEditor::DocumentPrivate::insertLine(int l, const QString &str)
{
if (!isReadWrite()) {
return false;
}
if (l < 0 || l > lines()) {
return false;
}
return editInsertLine(l, str);
}
bool KTextEditor::DocumentPrivate::insertLines(int line, const QStringList &text)
{
if (!isReadWrite()) {
return false;
}
if (line < 0 || line > lines()) {
return false;
}
bool success = true;
foreach (const QString &string, text) {
success &= editInsertLine(line++, string);
}
return success;
}
bool KTextEditor::DocumentPrivate::removeLine(int line)
{
if (!isReadWrite()) {
return false;
}
if (line < 0 || line > lastLine()) {
return false;
}
return editRemoveLine(line);
}
int KTextEditor::DocumentPrivate::totalCharacters() const
{
int l = 0;
for (int i = 0; i < m_buffer->count(); ++i) {
Kate::TextLine line = m_buffer->plainLine(i);
if (line) {
l += line->length();
}
}
return l;
}
int KTextEditor::DocumentPrivate::lines() const
{
return m_buffer->count();
}
int KTextEditor::DocumentPrivate::lineLength(int line) const
{
if (line < 0 || line > lastLine()) {
return -1;
}
Kate::TextLine l = m_buffer->plainLine(line);
if (!l) {
return -1;
}
return l->length();
}
bool KTextEditor::DocumentPrivate::isLineModified(int line) const
{
if (line < 0 || line >= lines()) {
return false;
}
Kate::TextLine l = m_buffer->plainLine(line);
Q_ASSERT(l);
return l->markedAsModified();
}
bool KTextEditor::DocumentPrivate::isLineSaved(int line) const
{
if (line < 0 || line >= lines()) {
return false;
}
Kate::TextLine l = m_buffer->plainLine(line);
Q_ASSERT(l);
return l->markedAsSavedOnDisk();
}
bool KTextEditor::DocumentPrivate::isLineTouched(int line) const
{
if (line < 0 || line >= lines()) {
return false;
}
Kate::TextLine l = m_buffer->plainLine(line);
Q_ASSERT(l);
return l->markedAsModified() || l->markedAsSavedOnDisk();
}
//END
//BEGIN KTextEditor::EditInterface internal stuff
//
// Starts an edit session with (or without) undo, update of view disabled during session
//
bool KTextEditor::DocumentPrivate::editStart()
{
editSessionNumber++;
if (editSessionNumber > 1) {
return false;
}
editIsRunning = true;
m_undoManager->editStart();
foreach (KTextEditor::ViewPrivate *view, m_views) {
view->editStart();
}