/
Document.cxx
3340 lines (3060 loc) · 102 KB
/
Document.cxx
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
// Scintilla source code edit control
/** @file Document.cxx
** Text document that handles notifications, DBCS, styling, words and end of line.
**/
// Copyright 1998-2011 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <forward_list>
#include <optional>
#include <algorithm>
#include <memory>
#include <chrono>
#ifndef NO_CXX11_REGEX
#include <regex>
#endif
#include "ScintillaTypes.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Debugging.h"
#include "CharacterType.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "CellBuffer.h"
#include "PerLine.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "RESearch.h"
#include "UniConversion.h"
#include "ElapsedPeriod.h"
using namespace Scintilla;
using namespace Scintilla::Internal;
LexInterface::LexInterface(Document *pdoc_) noexcept : pdoc(pdoc_), performingStyle(false) {
}
LexInterface::~LexInterface() noexcept = default;
void LexInterface::SetInstance(ILexer5 *instance_) {
instance.reset(instance_);
pdoc->LexerChanged();
}
void LexInterface::Colourise(Sci::Position start, Sci::Position end) {
if (pdoc && instance && !performingStyle) {
// Protect against reentrance, which may occur, for example, when
// fold points are discovered while performing styling and the folding
// code looks for child lines which may trigger styling.
performingStyle = true;
const Sci::Position lengthDoc = pdoc->Length();
if (end == -1)
end = lengthDoc;
const Sci::Position len = end - start;
PLATFORM_ASSERT(len >= 0);
PLATFORM_ASSERT(start + len <= lengthDoc);
int styleStart = 0;
if (start > 0)
styleStart = pdoc->StyleAt(start - 1);
if (len > 0) {
instance->Lex(start, len, styleStart, pdoc);
instance->Fold(start, len, styleStart, pdoc);
}
performingStyle = false;
}
}
LineEndType LexInterface::LineEndTypesSupported() {
if (instance) {
return static_cast<LineEndType>(instance->LineEndTypesSupported());
}
return LineEndType::Default;
}
bool LexInterface::UseContainerLexing() const noexcept {
return !instance;
}
ActionDuration::ActionDuration(double duration_, double minDuration_, double maxDuration_) noexcept :
duration(duration_), minDuration(minDuration_), maxDuration(maxDuration_) {
}
void ActionDuration::AddSample(size_t numberActions, double durationOfActions) noexcept {
// Only adjust for multiple actions to avoid instability
if (numberActions < 8)
return;
// Alpha value for exponential smoothing.
// Most recent value contributes 25% to smoothed value.
constexpr double alpha = 0.25;
const double durationOne = durationOfActions / numberActions;
duration = std::clamp(alpha * durationOne + (1.0 - alpha) * duration,
minDuration, maxDuration);
}
double ActionDuration::Duration() const noexcept {
return duration;
}
size_t ActionDuration::ActionsInAllowedTime(double secondsAllowed) const noexcept {
return std::lround(secondsAllowed / Duration());
}
Document::Document(DocumentOption options) :
cb(!FlagSet(options, DocumentOption::StylesNone), FlagSet(options, DocumentOption::TextLarge)),
durationStyleOneByte(0.000001, 0.0000001, 0.00001) {
refCount = 0;
#ifdef _WIN32
eolMode = EndOfLine::CrLf;
#else
eolMode = EndOfLine::Lf;
#endif
dbcsCodePage = CpUtf8;
lineEndBitSet = LineEndType::Default;
endStyled = 0;
styleClock = 0;
enteredModification = 0;
enteredStyling = 0;
enteredReadOnlyCount = 0;
insertionSet = false;
tabInChars = 8;
indentInChars = 0;
actualIndentInChars = 8;
useTabs = true;
tabIndents = true;
backspaceUnindents = false;
matchesValid = false;
perLineData[ldMarkers] = std::make_unique<LineMarkers>();
perLineData[ldLevels] = std::make_unique<LineLevels>();
perLineData[ldState] = std::make_unique<LineState>();
perLineData[ldMargin] = std::make_unique<LineAnnotation>();
perLineData[ldAnnotation] = std::make_unique<LineAnnotation>();
perLineData[ldEOLAnnotation] = std::make_unique<LineAnnotation>();
decorations = DecorationListCreate(IsLarge());
cb.SetPerLine(this);
cb.SetUTF8Substance(CpUtf8 == dbcsCodePage);
}
Document::~Document() {
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyDeleted(this, watcher.userData);
}
}
// Increase reference count and return its previous value.
int Document::AddRef() {
return refCount++;
}
// Decrease reference count and return its previous value.
// Delete the document if reference count reaches zero.
int SCI_METHOD Document::Release() {
const int curRefCount = --refCount;
if (curRefCount == 0)
delete this;
return curRefCount;
}
void Document::Init() {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->Init();
}
}
void Document::InsertLine(Sci::Line line) {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->InsertLine(line);
}
}
void Document::InsertLines(Sci::Line line, Sci::Line lines) {
for (const auto &pl : perLineData) {
if (pl)
pl->InsertLines(line, lines);
}
}
void Document::RemoveLine(Sci::Line line) {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->RemoveLine(line);
}
}
LineMarkers *Document::Markers() const noexcept {
return dynamic_cast<LineMarkers *>(perLineData[ldMarkers].get());
}
LineLevels *Document::Levels() const noexcept {
return dynamic_cast<LineLevels *>(perLineData[ldLevels].get());
}
LineState *Document::States() const noexcept {
return dynamic_cast<LineState *>(perLineData[ldState].get());
}
LineAnnotation *Document::Margins() const noexcept {
return dynamic_cast<LineAnnotation *>(perLineData[ldMargin].get());
}
LineAnnotation *Document::Annotations() const noexcept {
return dynamic_cast<LineAnnotation *>(perLineData[ldAnnotation].get());
}
LineAnnotation *Document::EOLAnnotations() const noexcept {
return dynamic_cast<LineAnnotation *>(perLineData[ldEOLAnnotation].get());
}
LineEndType Document::LineEndTypesSupported() const {
if ((CpUtf8 == dbcsCodePage) && pli)
return pli->LineEndTypesSupported();
else
return LineEndType::Default;
}
bool Document::SetDBCSCodePage(int dbcsCodePage_) {
if (dbcsCodePage != dbcsCodePage_) {
dbcsCodePage = dbcsCodePage_;
SetCaseFolder(nullptr);
cb.SetLineEndTypes(lineEndBitSet & LineEndTypesSupported());
cb.SetUTF8Substance(CpUtf8 == dbcsCodePage);
ModifiedAt(0); // Need to restyle whole document
return true;
} else {
return false;
}
}
bool Document::SetLineEndTypesAllowed(LineEndType lineEndBitSet_) {
if (lineEndBitSet != lineEndBitSet_) {
lineEndBitSet = lineEndBitSet_;
const LineEndType lineEndBitSetActive = lineEndBitSet & LineEndTypesSupported();
if (lineEndBitSetActive != cb.GetLineEndTypes()) {
ModifiedAt(0);
cb.SetLineEndTypes(lineEndBitSetActive);
return true;
} else {
return false;
}
} else {
return false;
}
}
void Document::SetSavePoint() {
cb.SetSavePoint();
NotifySavePoint(true);
}
void Document::TentativeUndo() {
if (!TentativeActive())
return;
CheckReadOnly();
if (enteredModification == 0) {
enteredModification++;
if (!cb.IsReadOnly()) {
const bool startSavePoint = cb.IsSavePoint();
bool multiLine = false;
const int steps = cb.TentativeSteps();
//Platform::DebugPrintf("Steps=%d\n", steps);
for (int step = 0; step < steps; step++) {
const Sci::Line prevLinesTotal = LinesTotal();
const Action &action = cb.GetUndoStep();
if (action.at == ActionType::remove) {
NotifyModified(DocModification(
ModificationFlags::BeforeInsert | ModificationFlags::Undo, action));
} else if (action.at == ActionType::container) {
DocModification dm(ModificationFlags::Container | ModificationFlags::Undo);
dm.token = action.position;
NotifyModified(dm);
} else {
NotifyModified(DocModification(
ModificationFlags::BeforeDelete | ModificationFlags::Undo, action));
}
cb.PerformUndoStep();
if (action.at != ActionType::container) {
ModifiedAt(action.position);
}
ModificationFlags modFlags = ModificationFlags::Undo;
// With undo, an insertion action becomes a deletion notification
if (action.at == ActionType::remove) {
modFlags |= ModificationFlags::InsertText;
} else if (action.at == ActionType::insert) {
modFlags |= ModificationFlags::DeleteText;
}
if (steps > 1)
modFlags |= ModificationFlags::MultiStepUndoRedo;
const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
if (linesAdded != 0)
multiLine = true;
if (step == steps - 1) {
modFlags |= ModificationFlags::LastStepInUndoRedo;
if (multiLine)
modFlags |= ModificationFlags::MultilineUndoRedo;
}
NotifyModified(DocModification(modFlags, action.position, action.lenData,
linesAdded, action.data.get()));
}
const bool endSavePoint = cb.IsSavePoint();
if (startSavePoint != endSavePoint)
NotifySavePoint(endSavePoint);
cb.TentativeCommit();
}
enteredModification--;
}
}
int Document::GetMark(Sci::Line line) const noexcept {
return Markers()->MarkValue(line);
}
Sci::Line Document::MarkerNext(Sci::Line lineStart, int mask) const noexcept {
return Markers()->MarkerNext(lineStart, mask);
}
int Document::AddMark(Sci::Line line, int markerNum) {
if (line >= 0 && line <= LinesTotal()) {
const int prev = Markers()->AddMark(line, markerNum, LinesTotal());
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
return prev;
} else {
return -1;
}
}
void Document::AddMarkSet(Sci::Line line, int valueSet) {
if (line < 0 || line > LinesTotal()) {
return;
}
unsigned int m = valueSet;
for (int i = 0; m; i++, m >>= 1) {
if (m & 1)
Markers()->AddMark(line, i, LinesTotal());
}
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
}
void Document::DeleteMark(Sci::Line line, int markerNum) {
Markers()->DeleteMark(line, markerNum, false);
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
}
void Document::DeleteMarkFromHandle(int markerHandle) {
Markers()->DeleteMarkFromHandle(markerHandle);
DocModification mh(ModificationFlags::ChangeMarker);
mh.line = -1;
NotifyModified(mh);
}
void Document::DeleteAllMarks(int markerNum) {
bool someChanges = false;
for (Sci::Line line = 0; line < LinesTotal(); line++) {
if (Markers()->DeleteMark(line, markerNum, true))
someChanges = true;
}
if (someChanges) {
DocModification mh(ModificationFlags::ChangeMarker);
mh.line = -1;
NotifyModified(mh);
}
}
Sci::Line Document::LineFromHandle(int markerHandle) const noexcept {
return Markers()->LineFromHandle(markerHandle);
}
int Document::MarkerNumberFromLine(Sci::Line line, int which) const noexcept {
return Markers()->NumberFromLine(line, which);
}
int Document::MarkerHandleFromLine(Sci::Line line, int which) const noexcept {
return Markers()->HandleFromLine(line, which);
}
Sci_Position SCI_METHOD Document::LineStart(Sci_Position line) const {
return cb.LineStart(line);
}
bool Document::IsLineStartPosition(Sci::Position position) const {
return LineStart(LineFromPosition(position)) == position;
}
Sci_Position SCI_METHOD Document::LineEnd(Sci_Position line) const {
if (line >= LinesTotal() - 1) {
return LineStart(line + 1);
} else {
Sci::Position position = LineStart(line + 1);
if (LineEndType::Unicode == cb.GetLineEndTypes()) {
const unsigned char bytes[] = {
cb.UCharAt(position-3),
cb.UCharAt(position-2),
cb.UCharAt(position-1),
};
if (UTF8IsSeparator(bytes)) {
return position - UTF8SeparatorLength;
}
if (UTF8IsNEL(bytes+1)) {
return position - UTF8NELLength;
}
}
position--; // Back over CR or LF
// When line terminator is CR+LF, may need to go back one more
if ((position > LineStart(line)) && (cb.CharAt(position - 1) == '\r')) {
position--;
}
return position;
}
}
void SCI_METHOD Document::SetErrorStatus(int status) {
// Tell the watchers an error has occurred.
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyErrorOccurred(this, watcher.userData, static_cast<Status>(status));
}
}
Sci_Position SCI_METHOD Document::LineFromPosition(Sci_Position pos) const {
return cb.LineFromPosition(pos);
}
Sci::Line Document::SciLineFromPosition(Sci::Position pos) const noexcept {
// Avoids casting in callers for this very common function
return cb.LineFromPosition(pos);
}
Sci::Position Document::LineEndPosition(Sci::Position position) const {
return LineEnd(LineFromPosition(position));
}
bool Document::IsLineEndPosition(Sci::Position position) const {
return LineEnd(LineFromPosition(position)) == position;
}
bool Document::IsPositionInLineEnd(Sci::Position position) const {
return position >= LineEnd(LineFromPosition(position));
}
Sci::Position Document::VCHomePosition(Sci::Position position) const {
const Sci::Line line = SciLineFromPosition(position);
const Sci::Position startPosition = LineStart(line);
const Sci::Position endLine = LineEnd(line);
Sci::Position startText = startPosition;
while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t'))
startText++;
if (position == startText)
return startPosition;
else
return startText;
}
Sci::Position Document::IndexLineStart(Sci::Line line, LineCharacterIndexType lineCharacterIndex) const noexcept {
return cb.IndexLineStart(line, lineCharacterIndex);
}
Sci::Line Document::LineFromPositionIndex(Sci::Position pos, LineCharacterIndexType lineCharacterIndex) const noexcept {
return cb.LineFromPositionIndex(pos, lineCharacterIndex);
}
Sci::Line Document::LineFromPositionAfter(Sci::Line line, Sci::Position length) const noexcept {
const Sci::Position posAfter = cb.LineStart(line) + length;
if (posAfter >= LengthNoExcept()) {
return LinesTotal();
}
const Sci::Line lineAfter = SciLineFromPosition(posAfter);
if (lineAfter > line) {
return lineAfter;
} else {
// Want to make some progress so return next line
return lineAfter + 1;
}
}
int SCI_METHOD Document::SetLevel(Sci_Position line, int level) {
const int prev = Levels()->SetLevel(line, level, LinesTotal());
if (prev != level) {
DocModification mh(ModificationFlags::ChangeFold | ModificationFlags::ChangeMarker,
LineStart(line), 0, 0, nullptr, line);
mh.foldLevelNow = static_cast<FoldLevel>(level);
mh.foldLevelPrev = static_cast<FoldLevel>(prev);
NotifyModified(mh);
}
return prev;
}
int SCI_METHOD Document::GetLevel(Sci_Position line) const {
return Levels()->GetLevel(line);
}
FoldLevel Document::GetFoldLevel(Sci_Position line) const {
return static_cast<FoldLevel>(Levels()->GetLevel(line));
}
void Document::ClearLevels() {
Levels()->ClearLevels();
}
static bool IsSubordinate(FoldLevel levelStart, FoldLevel levelTry) noexcept {
if (LevelIsWhitespace(levelTry))
return true;
else
return LevelNumber(levelStart) < LevelNumber(levelTry);
}
Sci::Line Document::GetLastChild(Sci::Line lineParent, std::optional<FoldLevel> level, Sci::Line lastLine) {
const FoldLevel levelStart = LevelNumberPart(level ? *level : GetFoldLevel(lineParent));
const Sci::Line maxLine = LinesTotal();
const Sci::Line lookLastLine = (lastLine != -1) ? std::min(LinesTotal() - 1, lastLine) : -1;
Sci::Line lineMaxSubord = lineParent;
while (lineMaxSubord < maxLine - 1) {
EnsureStyledTo(LineStart(lineMaxSubord + 2));
if (!IsSubordinate(levelStart, GetFoldLevel(lineMaxSubord + 1)))
break;
if ((lookLastLine != -1) && (lineMaxSubord >= lookLastLine) && !LevelIsWhitespace(GetFoldLevel(lineMaxSubord)))
break;
lineMaxSubord++;
}
if (lineMaxSubord > lineParent) {
if (levelStart > LevelNumberPart(GetFoldLevel(lineMaxSubord + 1))) {
// Have chewed up some whitespace that belongs to a parent so seek back
if (LevelIsWhitespace(GetFoldLevel(lineMaxSubord))) {
lineMaxSubord--;
}
}
}
return lineMaxSubord;
}
Sci::Line Document::GetFoldParent(Sci::Line line) const {
const FoldLevel level = LevelNumberPart(GetFoldLevel(line));
Sci::Line lineLook = line - 1;
while ((lineLook > 0) && (
(!LevelIsHeader(GetFoldLevel(lineLook))) ||
(LevelNumberPart(GetFoldLevel(lineLook)) >= level))
) {
lineLook--;
}
if (LevelIsHeader(GetFoldLevel(lineLook)) &&
(LevelNumberPart(GetFoldLevel(lineLook)) < level)) {
return lineLook;
} else {
return -1;
}
}
void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, Sci::Line line, Sci::Line lastLine) {
const FoldLevel level = GetFoldLevel(line);
const Sci::Line lookLastLine = std::max(line, lastLine) + 1;
Sci::Line lookLine = line;
FoldLevel lookLineLevel = level;
FoldLevel lookLineLevelNum = LevelNumberPart(lookLineLevel);
while ((lookLine > 0) && (LevelIsWhitespace(lookLineLevel) ||
(LevelIsHeader(lookLineLevel) && (lookLineLevelNum >= LevelNumberPart(GetFoldLevel(lookLine + 1)))))) {
lookLineLevel = GetFoldLevel(--lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
}
Sci::Line beginFoldBlock = LevelIsHeader(lookLineLevel) ? lookLine : GetFoldParent(lookLine);
if (beginFoldBlock == -1) {
highlightDelimiter.Clear();
return;
}
Sci::Line endFoldBlock = GetLastChild(beginFoldBlock, {}, lookLastLine);
Sci::Line firstChangeableLineBefore = -1;
if (endFoldBlock < line) {
lookLine = beginFoldBlock - 1;
lookLineLevel = GetFoldLevel(lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
while ((lookLine >= 0) && (lookLineLevelNum >= FoldLevel::Base)) {
if (LevelIsHeader(lookLineLevel)) {
if (GetLastChild(lookLine, {}, lookLastLine) == line) {
beginFoldBlock = lookLine;
endFoldBlock = line;
firstChangeableLineBefore = line - 1;
}
}
if ((lookLine > 0) && (lookLineLevelNum == FoldLevel::Base) && (LevelNumberPart(GetFoldLevel(lookLine - 1)) > lookLineLevelNum))
break;
lookLineLevel = GetFoldLevel(--lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
}
}
if (firstChangeableLineBefore == -1) {
for (lookLine = line - 1, lookLineLevel = GetFoldLevel(lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel);
lookLine >= beginFoldBlock;
lookLineLevel = GetFoldLevel(--lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel)) {
if (LevelIsWhitespace(lookLineLevel) || (lookLineLevelNum > LevelNumberPart(level))) {
firstChangeableLineBefore = lookLine;
break;
}
}
}
if (firstChangeableLineBefore == -1)
firstChangeableLineBefore = beginFoldBlock - 1;
Sci::Line firstChangeableLineAfter = -1;
for (lookLine = line + 1, lookLineLevel = GetFoldLevel(lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel);
lookLine <= endFoldBlock;
lookLineLevel = GetFoldLevel(++lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel)) {
if (LevelIsHeader(lookLineLevel) && (lookLineLevelNum < LevelNumberPart(GetFoldLevel(lookLine + 1)))) {
firstChangeableLineAfter = lookLine;
break;
}
}
if (firstChangeableLineAfter == -1)
firstChangeableLineAfter = endFoldBlock + 1;
highlightDelimiter.beginFoldBlock = beginFoldBlock;
highlightDelimiter.endFoldBlock = endFoldBlock;
highlightDelimiter.firstChangeableLineBefore = firstChangeableLineBefore;
highlightDelimiter.firstChangeableLineAfter = firstChangeableLineAfter;
}
Sci::Position Document::ClampPositionIntoDocument(Sci::Position pos) const noexcept {
return std::clamp<Sci::Position>(pos, 0, LengthNoExcept());
}
bool Document::IsCrLf(Sci::Position pos) const noexcept {
if (pos < 0)
return false;
if (pos >= (LengthNoExcept() - 1))
return false;
return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
}
int Document::LenChar(Sci::Position pos) const noexcept {
if (pos < 0 || pos >= LengthNoExcept()) {
// Returning 1 instead of 0 to defend against hanging with a loop that goes (or starts) out of bounds.
return 1;
} else if (IsCrLf(pos)) {
return 2;
}
const unsigned char leadByte = cb.UCharAt(pos);
if (!dbcsCodePage || UTF8IsAscii(leadByte)) {
// Common case: ASCII character
return 1;
}
if (CpUtf8 == dbcsCodePage) {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
for (int b = 1; b < widthCharBytes; b++) {
charBytes[b] = cb.UCharAt(pos + b);
}
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Treat as invalid and use up just one byte
return 1;
} else {
return utf8status & UTF8MaskWidth;
}
} else {
if (IsDBCSLeadByteNoExcept(leadByte) && IsDBCSTrailByteNoExcept(cb.CharAt(pos + 1))) {
return 2;
} else {
return 1;
}
}
}
bool Document::InGoodUTF8(Sci::Position pos, Sci::Position &start, Sci::Position &end) const noexcept {
Sci::Position trail = pos;
while ((trail>0) && (pos-trail < UTF8MaxBytes) && UTF8IsTrailByte(cb.UCharAt(trail-1)))
trail--;
start = (trail > 0) ? trail-1 : trail;
const unsigned char leadByte = cb.UCharAt(start);
const int widthCharBytes = UTF8BytesOfLead[leadByte];
if (widthCharBytes == 1) {
return false;
} else {
const int trailBytes = widthCharBytes - 1;
const Sci::Position len = pos - start;
if (len > trailBytes)
// pos too far from lead
return false;
unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
for (Sci::Position b=1; b<widthCharBytes && ((start+b) < cb.Length()); b++)
charBytes[b] = cb.CharAt(start+b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid)
return false;
end = start + widthCharBytes;
return true;
}
}
// Normalise a position so that it is not part way through a multi-byte character.
// This can occur in two situations -
// When lines are terminated with \r\n pairs which should be treated as one character.
// When displaying DBCS text such as Japanese.
// If moving, move the position in the indicated direction.
Sci::Position Document::MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool checkLineEnd) const noexcept {
//Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
// If out of range, just return minimum/maximum value.
if (pos <= 0)
return 0;
if (pos >= LengthNoExcept())
return LengthNoExcept();
// PLATFORM_ASSERT(pos > 0 && pos < LengthNoExcept());
if (checkLineEnd && IsCrLf(pos - 1)) {
if (moveDir > 0)
return pos + 1;
else
return pos - 1;
}
if (dbcsCodePage) {
if (CpUtf8 == dbcsCodePage) {
const unsigned char ch = cb.UCharAt(pos);
// If ch is not a trail byte then pos is valid intercharacter position
if (UTF8IsTrailByte(ch)) {
Sci::Position startUTF = pos;
Sci::Position endUTF = pos;
if (InGoodUTF8(pos, startUTF, endUTF)) {
// ch is a trail byte within a UTF-8 character
if (moveDir > 0)
pos = endUTF;
else
pos = startUTF;
}
// Else invalid UTF-8 so return position of isolated trail byte
}
} else {
// Anchor DBCS calculations at start of line because start of line can
// not be a DBCS trail byte.
const Sci::Position posStartLine = cb.LineStart(cb.LineFromPosition(pos));
if (pos == posStartLine)
return pos;
// Step back until a non-lead-byte is found.
Sci::Position posCheck = pos;
while ((posCheck > posStartLine) && IsDBCSLeadByteNoExcept(cb.CharAt(posCheck-1)))
posCheck--;
// Check from known start of character.
while (posCheck < pos) {
const int mbsize = IsDBCSDualByteAt(posCheck) ? 2 : 1;
if (posCheck + mbsize == pos) {
return pos;
} else if (posCheck + mbsize > pos) {
if (moveDir > 0) {
return posCheck + mbsize;
} else {
return posCheck;
}
}
posCheck += mbsize;
}
}
}
return pos;
}
// NextPosition moves between valid positions - it can not handle a position in the middle of a
// multi-byte character. It is used to iterate through text more efficiently than MovePositionOutsideChar.
// A \r\n pair is treated as two characters.
Sci::Position Document::NextPosition(Sci::Position pos, int moveDir) const noexcept {
// If out of range, just return minimum/maximum value.
const int increment = (moveDir > 0) ? 1 : -1;
if (pos + increment <= 0)
return 0;
if (pos + increment >= cb.Length())
return cb.Length();
if (dbcsCodePage) {
if (CpUtf8 == dbcsCodePage) {
if (increment == 1) {
// Simple forward movement case so can avoid some checks
const unsigned char leadByte = cb.UCharAt(pos);
if (UTF8IsAscii(leadByte)) {
// Single byte character or invalid
pos++;
} else {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
for (int b=1; b<widthCharBytes; b++)
charBytes[b] = cb.CharAt(pos+b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid)
pos++;
else
pos += utf8status & UTF8MaskWidth;
}
} else {
// Examine byte before position
pos--;
const unsigned char ch = cb.UCharAt(pos);
// If ch is not a trail byte then pos is valid intercharacter position
if (UTF8IsTrailByte(ch)) {
// If ch is a trail byte in a valid UTF-8 character then return start of character
Sci::Position startUTF = pos;
Sci::Position endUTF = pos;
if (InGoodUTF8(pos, startUTF, endUTF)) {
pos = startUTF;
}
// Else invalid UTF-8 so return position of isolated trail byte
}
}
} else {
if (moveDir > 0) {
const int mbsize = IsDBCSDualByteAt(pos) ? 2 : 1;
pos += mbsize;
if (pos > cb.Length())
pos = cb.Length();
} else {
// Anchor DBCS calculations at start of line because start of line can
// not be a DBCS trail byte.
const Sci::Position posStartLine = cb.LineStart(cb.LineFromPosition(pos));
// See http://msdn.microsoft.com/en-us/library/cc194792%28v=MSDN.10%29.aspx
// http://msdn.microsoft.com/en-us/library/cc194790.aspx
if ((pos - 1) <= posStartLine) {
return pos - 1;
} else if (IsDBCSLeadByteNoExcept(cb.CharAt(pos - 1))) {
// Should actually be trail byte
if (IsDBCSDualByteAt(pos - 2)) {
return pos - 2;
} else {
// Invalid byte pair so treat as one byte wide
return pos - 1;
}
} else {
// Otherwise, step back until a non-lead-byte is found.
Sci::Position posTemp = pos - 1;
while (posStartLine <= --posTemp && IsDBCSLeadByteNoExcept(cb.CharAt(posTemp)))
;
// Now posTemp+1 must point to the beginning of a character,
// so figure out whether we went back an even or an odd
// number of bytes and go back 1 or 2 bytes, respectively.
const Sci::Position widthLast = ((pos - posTemp) & 1) + 1;
if ((widthLast == 2) && (IsDBCSDualByteAt(pos - widthLast))) {
return pos - widthLast;
}
// Byte before pos may be valid character or may be an invalid second byte
return pos - 1;
}
}
}
} else {
pos += increment;
}
return pos;
}
bool Document::NextCharacter(Sci::Position &pos, int moveDir) const noexcept {
// Returns true if pos changed
Sci::Position posNext = NextPosition(pos, moveDir);
if (posNext == pos) {
return false;
} else {
pos = posNext;
return true;
}
}
Document::CharacterExtracted Document::CharacterAfter(Sci::Position position) const noexcept {
if (position >= LengthNoExcept()) {
return CharacterExtracted(unicodeReplacementChar, 0);
}
const unsigned char leadByte = cb.UCharAt(position);
if (!dbcsCodePage || UTF8IsAscii(leadByte)) {
// Common case: ASCII character
return CharacterExtracted(leadByte, 1);
}
if (CpUtf8 == dbcsCodePage) {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
for (int b = 1; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(position + b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Treat as invalid and use up just one byte
return CharacterExtracted(unicodeReplacementChar, 1);
} else {
return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & UTF8MaskWidth);
}
} else {
if (IsDBCSLeadByteNoExcept(leadByte)) {
const unsigned char trailByte = cb.UCharAt(position + 1);
if (IsDBCSTrailByteNoExcept(trailByte)) {
return CharacterExtracted::DBCS(leadByte, trailByte);
}
}
return CharacterExtracted(leadByte, 1);
}
}
Document::CharacterExtracted Document::CharacterBefore(Sci::Position position) const noexcept {
if (position <= 0) {
return CharacterExtracted(unicodeReplacementChar, 0);
}
const unsigned char previousByte = cb.UCharAt(position - 1);
if (0 == dbcsCodePage) {
return CharacterExtracted(previousByte, 1);
}
if (CpUtf8 == dbcsCodePage) {
if (UTF8IsAscii(previousByte)) {
return CharacterExtracted(previousByte, 1);
}
position--;
// If previousByte is not a trail byte then its invalid
if (UTF8IsTrailByte(previousByte)) {
// If previousByte is a trail byte in a valid UTF-8 character then find start of character
Sci::Position startUTF = position;
Sci::Position endUTF = position;
if (InGoodUTF8(position, startUTF, endUTF)) {
const Sci::Position widthCharBytes = endUTF - startUTF;
unsigned char charBytes[UTF8MaxBytes] = { 0, 0, 0, 0 };
for (Sci::Position b = 0; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(startUTF + b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Treat as invalid and use up just one byte
return CharacterExtracted(unicodeReplacementChar, 1);
} else {
return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & UTF8MaskWidth);
}
}
// Else invalid UTF-8 so return position of isolated trail byte
}
return CharacterExtracted(unicodeReplacementChar, 1);
} else {
// Moving backwards in DBCS is complex so use NextPosition
const Sci::Position posStartCharacter = NextPosition(position, -1);
return CharacterAfter(posStartCharacter);
}
}
// Return -1 on out-of-bounds
Sci_Position SCI_METHOD Document::GetRelativePosition(Sci_Position positionStart, Sci_Position characterOffset) const {
Sci::Position pos = positionStart;
if (dbcsCodePage) {
const int increment = (characterOffset > 0) ? 1 : -1;
while (characterOffset != 0) {
const Sci::Position posNext = NextPosition(pos, increment);
if (posNext == pos)
return Sci::invalidPosition;
pos = posNext;
characterOffset -= increment;
}
} else {
pos = positionStart + characterOffset;
if ((pos < 0) || (pos > Length()))
return Sci::invalidPosition;
}
return pos;
}
Sci::Position Document::GetRelativePositionUTF16(Sci::Position positionStart, Sci::Position characterOffset) const noexcept {
Sci::Position pos = positionStart;
if (dbcsCodePage) {
const int increment = (characterOffset > 0) ? 1 : -1;
while (characterOffset != 0) {
const Sci::Position posNext = NextPosition(pos, increment);
if (posNext == pos)
return Sci::invalidPosition;
if (std::abs(pos-posNext) > 3) // 4 byte character = 2*UTF16.
characterOffset -= increment;
pos = posNext;