/
Editor.cxx
8862 lines (7778 loc) · 280 KB
/
Editor.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 Editor.cxx
** Main code for the edit control.
**/
// 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 <cstdint>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <set>
#include <forward_list>
#include <optional>
#include <algorithm>
#include <iterator>
#include <memory>
#include <chrono>
#include <atomic>
#include <mutex>
#include <thread>
#include <future>
#include "ScintillaTypes.h"
#include "ScintillaMessages.h"
#include "ScintillaStructures.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Debugging.h"
#include "Geometry.h"
#include "Platform.h"
#include "CharacterType.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "PerLine.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "UniConversion.h"
#include "DBCS.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "Editor.h"
#include "ElapsedPeriod.h"
using namespace Scintilla;
using namespace Scintilla::Internal;
namespace {
/*
return whether this modification represents an operation that
may reasonably be deferred (not done now OR [possibly] at all)
*/
constexpr bool CanDeferToLastStep(const DocModification &mh) noexcept {
if (FlagSet(mh.modificationType, (ModificationFlags::BeforeInsert | ModificationFlags::BeforeDelete)))
return true; // CAN skip
if (!FlagSet(mh.modificationType, (ModificationFlags::Undo | ModificationFlags::Redo)))
return false; // MUST do
if (FlagSet(mh.modificationType, ModificationFlags::MultiStepUndoRedo))
return true; // CAN skip
return false; // PRESUMABLY must do
}
constexpr bool CanEliminate(const DocModification &mh) noexcept {
return
FlagSet(mh.modificationType, (ModificationFlags::BeforeInsert | ModificationFlags::BeforeDelete));
}
/*
return whether this modification represents the FINAL step
in a [possibly lengthy] multi-step Undo/Redo sequence
*/
constexpr bool IsLastStep(const DocModification &mh) noexcept {
return
FlagSet(mh.modificationType, (ModificationFlags::Undo | ModificationFlags::Redo))
&& (FlagSet(mh.modificationType, ModificationFlags::MultiStepUndoRedo))
&& (FlagSet(mh.modificationType, ModificationFlags::LastStepInUndoRedo))
&& (FlagSet(mh.modificationType, ModificationFlags::MultilineUndoRedo));
}
}
Timer::Timer() noexcept :
ticking(false), ticksToWait(0), tickerID{} {}
Idler::Idler() noexcept :
state(false), idlerID(nullptr) {}
static constexpr bool IsAllSpacesOrTabs(std::string_view sv) noexcept {
for (const char ch : sv) {
// This is safe because IsSpaceOrTab() will return false for null terminators
if (!IsSpaceOrTab(ch))
return false;
}
return true;
}
Editor::Editor() : durationWrapOneByte(0.000001, 0.00000001, 0.00001) {
ctrlID = 0;
stylesValid = false;
technology = Technology::Default;
scaleRGBAImage = 100.0f;
cursorMode = CursorShape::Normal;
errorStatus = Status::Ok;
mouseDownCaptures = true;
mouseWheelCaptures = true;
lastClickTime = 0;
doubleClickCloseThreshold = Point(3, 3);
dwellDelay = TimeForever;
ticksToDwell = TimeForever;
dwelling = false;
ptMouseLast.x = 0;
ptMouseLast.y = 0;
inDragDrop = DragDrop::none;
dropWentOutside = false;
posDrop = SelectionPosition(Sci::invalidPosition);
hotSpotClickPos = Sci::invalidPosition;
selectionUnit = TextUnit::character;
lastXChosen = 0;
lineAnchorPos = 0;
originalAnchorPos = 0;
wordSelectAnchorStartPos = 0;
wordSelectAnchorEndPos = 0;
wordSelectInitialCaretPos = -1;
caretPolicies.x = { CaretPolicy::Slop | CaretPolicy::Even, 50 };
caretPolicies.y = { CaretPolicy::Even, 0 };
visiblePolicy = { 0, 0 };
searchAnchor = 0;
xCaretMargin = 50;
horizontalScrollBarVisible = true;
scrollWidth = 2000;
verticalScrollBarVisible = true;
endAtLastLine = true;
caretSticky = CaretSticky::Off;
marginOptions = MarginOption::None;
mouseSelectionRectangularSwitch = false;
multipleSelection = false;
additionalSelectionTyping = false;
multiPasteMode = MultiPaste::Once;
virtualSpaceOptions = VirtualSpace::None;
targetRange = SelectionSegment();
searchFlags = FindOption::None;
topLine = 0;
posTopLine = 0;
lengthForEncode = -1;
needUpdateUI = Update::None;
ContainerNeedsUpdate(Update::Content);
paintState = PaintState::notPainting;
paintAbandonedByStyling = false;
paintingAllText = false;
willRedrawAll = false;
idleStyling = IdleStyling::None;
needIdleStyling = false;
modEventMask = ModificationFlags::EventMaskAll;
commandEvents = true;
pdoc->AddWatcher(this, nullptr);
recordingMacro = false;
foldAutomatic = AutomaticFold::None;
convertPastes = true;
SetRepresentations();
}
Editor::~Editor() {
pdoc->RemoveWatcher(this, nullptr);
}
void Editor::Finalise() {
SetIdle(false);
CancelModes();
}
void Editor::SetRepresentations() {
reprs.SetDefaultRepresentations(pdoc->dbcsCodePage);
}
void Editor::DropGraphics() noexcept {
marginView.DropGraphics();
view.DropGraphics();
}
void Editor::InvalidateStyleData() noexcept {
stylesValid = false;
vs.technology = technology;
DropGraphics();
view.llc.Invalidate(LineLayout::ValidLevel::invalid);
view.posCache->Clear();
}
void Editor::InvalidateStyleRedraw() {
NeedWrapping();
InvalidateStyleData();
Redraw();
}
void Editor::RefreshStyleData() {
if (!stylesValid) {
stylesValid = true;
AutoSurface surface(this);
if (surface) {
vs.Refresh(*surface, pdoc->tabInChars);
}
SetScrollBars();
SetRectangularRange();
}
}
bool Editor::HasMarginWindow() const noexcept {
return wMargin.Created();
}
Point Editor::GetVisibleOriginInMain() const {
return Point(0, 0);
}
PointDocument Editor::DocumentPointFromView(Point ptView) const {
PointDocument ptDocument(ptView);
if (HasMarginWindow()) {
const Point ptOrigin = GetVisibleOriginInMain();
ptDocument.x += ptOrigin.x;
ptDocument.y += ptOrigin.y;
} else {
ptDocument.x += xOffset;
ptDocument.y += topLine * vs.lineHeight;
}
return ptDocument;
}
Sci::Line Editor::TopLineOfMain() const noexcept {
if (HasMarginWindow())
return 0;
else
return topLine;
}
Point Editor::ClientSize() const {
const PRectangle rcClient = GetClientRectangle();
return Point(rcClient.Width(), rcClient.Height());
}
PRectangle Editor::GetClientRectangle() const {
return wMain.GetClientPosition();
}
PRectangle Editor::GetClientDrawingRectangle() {
return GetClientRectangle();
}
PRectangle Editor::GetTextRectangle() const {
PRectangle rc = GetClientRectangle();
rc.left += vs.textStart;
rc.right -= vs.rightMarginWidth;
return rc;
}
Sci::Line Editor::LinesOnScreen() const {
const Point sizeClient = ClientSize();
const int htClient = static_cast<int>(sizeClient.y);
//Platform::DebugPrintf("lines on screen = %d\n", htClient / lineHeight + 1);
return htClient / vs.lineHeight;
}
Sci::Line Editor::LinesToScroll() const {
const Sci::Line retVal = LinesOnScreen() - 1;
if (retVal < 1)
return 1;
else
return retVal;
}
Sci::Line Editor::MaxScrollPos() const {
//Platform::DebugPrintf("Lines %d screen = %d maxScroll = %d\n",
//LinesTotal(), LinesOnScreen(), LinesTotal() - LinesOnScreen() + 1);
Sci::Line retVal = pcs->LinesDisplayed();
if (endAtLastLine) {
retVal -= LinesOnScreen();
} else {
retVal--;
}
if (retVal < 0) {
return 0;
} else {
return retVal;
}
}
SelectionPosition Editor::ClampPositionIntoDocument(SelectionPosition sp) const {
if (sp.Position() < 0) {
return SelectionPosition(0);
} else if (sp.Position() > pdoc->Length()) {
return SelectionPosition(pdoc->Length());
} else {
// If not at end of line then set offset to 0
if (!pdoc->IsLineEndPosition(sp.Position()))
sp.SetVirtualSpace(0);
return sp;
}
}
Point Editor::LocationFromPosition(SelectionPosition pos, PointEnd pe) {
const PRectangle rcClient = GetTextRectangle();
RefreshStyleData();
AutoSurface surface(this);
return view.LocationFromPosition(surface, *this, pos, topLine, vs, pe, rcClient);
}
Point Editor::LocationFromPosition(Sci::Position pos, PointEnd pe) {
return LocationFromPosition(SelectionPosition(pos), pe);
}
int Editor::XFromPosition(SelectionPosition sp) {
const Point pt = LocationFromPosition(sp);
return static_cast<int>(pt.x) - vs.textStart + xOffset;
}
SelectionPosition Editor::SPositionFromLocation(Point pt, bool canReturnInvalid, bool charPosition, bool virtualSpace) {
RefreshStyleData();
AutoSurface surface(this);
PRectangle rcClient = GetTextRectangle();
// May be in scroll view coordinates so translate back to main view
const Point ptOrigin = GetVisibleOriginInMain();
rcClient.Move(-ptOrigin.x, -ptOrigin.y);
if (canReturnInvalid) {
if (!rcClient.Contains(pt))
return SelectionPosition(Sci::invalidPosition);
if (pt.x < vs.textStart)
return SelectionPosition(Sci::invalidPosition);
if (pt.y < 0)
return SelectionPosition(Sci::invalidPosition);
}
const PointDocument ptdoc = DocumentPointFromView(pt);
return view.SPositionFromLocation(surface, *this, ptdoc, canReturnInvalid,
charPosition, virtualSpace, vs, rcClient);
}
Sci::Position Editor::PositionFromLocation(Point pt, bool canReturnInvalid, bool charPosition) {
return SPositionFromLocation(pt, canReturnInvalid, charPosition, false).Position();
}
/**
* Find the document position corresponding to an x coordinate on a particular document line.
* Ensure is between whole characters when document is in multi-byte or UTF-8 mode.
* This method is used for rectangular selections and does not work on wrapped lines.
*/
SelectionPosition Editor::SPositionFromLineX(Sci::Line lineDoc, int x) {
RefreshStyleData();
if (lineDoc >= pdoc->LinesTotal())
return SelectionPosition(pdoc->Length());
//Platform::DebugPrintf("Position of (%d,%d) line = %d top=%d\n", pt.x, pt.y, line, topLine);
AutoSurface surface(this);
return view.SPositionFromLineX(surface, *this, lineDoc, x, vs);
}
Sci::Position Editor::PositionFromLineX(Sci::Line lineDoc, int x) {
return SPositionFromLineX(lineDoc, x).Position();
}
Sci::Line Editor::LineFromLocation(Point pt) const noexcept {
return pcs->DocFromDisplay(static_cast<int>(pt.y) / vs.lineHeight + topLine);
}
void Editor::SetTopLine(Sci::Line topLineNew) {
if ((topLine != topLineNew) && (topLineNew >= 0)) {
topLine = topLineNew;
ContainerNeedsUpdate(Update::VScroll);
}
posTopLine = pdoc->LineStart(pcs->DocFromDisplay(topLine));
}
/**
* If painting then abandon the painting because a wider redraw is needed.
* @return true if calling code should stop drawing.
*/
bool Editor::AbandonPaint() {
if ((paintState == PaintState::painting) && !paintingAllText) {
paintState = PaintState::abandoned;
}
return paintState == PaintState::abandoned;
}
void Editor::RedrawRect(PRectangle rc) {
//Platform::DebugPrintf("Redraw %0d,%0d - %0d,%0d\n", rc.left, rc.top, rc.right, rc.bottom);
// Clip the redraw rectangle into the client area
const PRectangle rcClient = GetClientRectangle();
if (rc.top < rcClient.top)
rc.top = rcClient.top;
if (rc.bottom > rcClient.bottom)
rc.bottom = rcClient.bottom;
if (rc.left < rcClient.left)
rc.left = rcClient.left;
if (rc.right > rcClient.right)
rc.right = rcClient.right;
if ((rc.bottom > rc.top) && (rc.right > rc.left)) {
wMain.InvalidateRectangle(rc);
}
}
void Editor::DiscardOverdraw() {
// Overridden on platforms that may draw outside visible area.
}
void Editor::Redraw() {
if (redrawPendingText) {
return;
}
//Platform::DebugPrintf("Redraw all\n");
const PRectangle rcClient = GetClientRectangle();
wMain.InvalidateRectangle(rcClient);
if (HasMarginWindow()) {
wMargin.InvalidateAll();
} else if (paintState == PaintState::notPainting) {
redrawPendingText = true;
}
}
void Editor::RedrawSelMargin(Sci::Line line, bool allAfter) {
const bool markersInText = vs.maskInLine || vs.maskDrawInText;
if (!HasMarginWindow() || markersInText) { // May affect text area so may need to abandon and retry
if (AbandonPaint()) {
return;
}
}
if (HasMarginWindow() && markersInText) {
Redraw();
return;
}
if (redrawPendingMargin) {
return;
}
PRectangle rcMarkers = GetClientRectangle();
if (!markersInText) {
// Normal case: just draw the margin
rcMarkers.right = rcMarkers.left + vs.fixedColumnWidth;
}
const PRectangle rcMarkersFull = rcMarkers;
if (line != -1) {
PRectangle rcLine = RectangleFromRange(Range(pdoc->LineStart(line)), 0);
// Inflate line rectangle if there are image markers with height larger than line height
if (vs.largestMarkerHeight > vs.lineHeight) {
const int delta = (vs.largestMarkerHeight - vs.lineHeight + 1) / 2;
rcLine.top -= delta;
rcLine.bottom += delta;
if (rcLine.top < rcMarkers.top)
rcLine.top = rcMarkers.top;
if (rcLine.bottom > rcMarkers.bottom)
rcLine.bottom = rcMarkers.bottom;
}
rcMarkers.top = rcLine.top;
if (!allAfter)
rcMarkers.bottom = rcLine.bottom;
if (rcMarkers.Empty())
return;
}
if (HasMarginWindow()) {
const Point ptOrigin = GetVisibleOriginInMain();
rcMarkers.Move(-ptOrigin.x, -ptOrigin.y);
wMargin.InvalidateRectangle(rcMarkers);
} else {
wMain.InvalidateRectangle(rcMarkers);
if (rcMarkers == rcMarkersFull) {
redrawPendingMargin = true;
}
}
}
PRectangle Editor::RectangleFromRange(Range r, int overlap) {
const Sci::Line minLine = pcs->DisplayFromDoc(
pdoc->SciLineFromPosition(r.First()));
const Sci::Line maxLine = pcs->DisplayLastFromDoc(
pdoc->SciLineFromPosition(r.Last()));
const PRectangle rcClientDrawing = GetClientDrawingRectangle();
PRectangle rc;
const int leftTextOverlap = ((xOffset == 0) && (vs.leftMarginWidth > 0)) ? 1 : 0;
rc.left = static_cast<XYPOSITION>(vs.textStart - leftTextOverlap);
rc.top = static_cast<XYPOSITION>((minLine - TopLineOfMain()) * vs.lineHeight - overlap);
if (rc.top < rcClientDrawing.top)
rc.top = rcClientDrawing.top;
// Extend to right of prepared area if any to prevent artifacts from caret line highlight
rc.right = rcClientDrawing.right;
rc.bottom = static_cast<XYPOSITION>((maxLine - TopLineOfMain() + 1) * vs.lineHeight + overlap);
return rc;
}
void Editor::InvalidateRange(Sci::Position start, Sci::Position end) {
if (redrawPendingText) {
return;
}
RedrawRect(RectangleFromRange(Range(start, end), view.LinesOverlap() ? vs.lineOverlap : 0));
}
Sci::Position Editor::CurrentPosition() const noexcept {
return sel.MainCaret();
}
bool Editor::SelectionEmpty() const noexcept {
return sel.Empty();
}
SelectionPosition Editor::SelectionStart() noexcept {
return sel.RangeMain().Start();
}
SelectionPosition Editor::SelectionEnd() noexcept {
return sel.RangeMain().End();
}
void Editor::SetRectangularRange() {
if (sel.IsRectangular()) {
const int xAnchor = XFromPosition(sel.Rectangular().anchor);
int xCaret = XFromPosition(sel.Rectangular().caret);
if (sel.selType == Selection::SelTypes::thin) {
xCaret = xAnchor;
}
const Sci::Line lineAnchorRect =
pdoc->SciLineFromPosition(sel.Rectangular().anchor.Position());
const Sci::Line lineCaret =
pdoc->SciLineFromPosition(sel.Rectangular().caret.Position());
const int increment = (lineCaret > lineAnchorRect) ? 1 : -1;
AutoSurface surface(this);
for (Sci::Line line=lineAnchorRect; line != lineCaret+increment; line += increment) {
SelectionRange range(
view.SPositionFromLineX(surface, *this, line, xCaret, vs),
view.SPositionFromLineX(surface, *this, line, xAnchor, vs));
if (!FlagSet(virtualSpaceOptions, VirtualSpace::RectangularSelection))
range.ClearVirtualSpace();
if (line == lineAnchorRect)
sel.SetSelection(range);
else
sel.AddSelectionWithoutTrim(range);
}
}
}
void Editor::ThinRectangularRange() {
if (sel.IsRectangular()) {
sel.selType = Selection::SelTypes::thin;
if (sel.Rectangular().caret < sel.Rectangular().anchor) {
sel.Rectangular() = SelectionRange(sel.Range(sel.Count()-1).caret, sel.Range(0).anchor);
} else {
sel.Rectangular() = SelectionRange(sel.Range(sel.Count()-1).anchor, sel.Range(0).caret);
}
SetRectangularRange();
}
}
void Editor::InvalidateSelection(SelectionRange newMain, bool invalidateWholeSelection) {
if (sel.Count() > 1 || !(sel.RangeMain().anchor == newMain.anchor) || sel.IsRectangular()) {
invalidateWholeSelection = true;
}
Sci::Position firstAffected = std::min(sel.RangeMain().Start().Position(), newMain.Start().Position());
// +1 for lastAffected ensures caret repainted
Sci::Position lastAffected = std::max(newMain.caret.Position()+1, newMain.anchor.Position());
lastAffected = std::max(lastAffected, sel.RangeMain().End().Position());
if (invalidateWholeSelection) {
for (size_t r=0; r<sel.Count(); r++) {
firstAffected = std::min(firstAffected, sel.Range(r).caret.Position());
firstAffected = std::min(firstAffected, sel.Range(r).anchor.Position());
lastAffected = std::max(lastAffected, sel.Range(r).caret.Position()+1);
lastAffected = std::max(lastAffected, sel.Range(r).anchor.Position());
}
}
ContainerNeedsUpdate(Update::Selection);
InvalidateRange(firstAffected, lastAffected);
}
void Editor::InvalidateWholeSelection() {
InvalidateSelection(sel.RangeMain(), true);
}
/* For Line selection - the anchor and caret are always
at the beginning and end of the region lines. */
SelectionRange Editor::LineSelectionRange(SelectionPosition currentPos_, SelectionPosition anchor_) const {
if (currentPos_ > anchor_) {
anchor_ = SelectionPosition(
pdoc->LineStart(pdoc->LineFromPosition(anchor_.Position())));
currentPos_ = SelectionPosition(
pdoc->LineEnd(pdoc->LineFromPosition(currentPos_.Position())));
} else {
currentPos_ = SelectionPosition(
pdoc->LineStart(pdoc->LineFromPosition(currentPos_.Position())));
anchor_ = SelectionPosition(
pdoc->LineEnd(pdoc->LineFromPosition(anchor_.Position())));
}
return SelectionRange(currentPos_, anchor_);
}
void Editor::SetSelection(SelectionPosition currentPos_, SelectionPosition anchor_) {
currentPos_ = ClampPositionIntoDocument(currentPos_);
anchor_ = ClampPositionIntoDocument(anchor_);
const Sci::Line currentLine = pdoc->SciLineFromPosition(currentPos_.Position());
SelectionRange rangeNew(currentPos_, anchor_);
if (sel.selType == Selection::SelTypes::lines) {
rangeNew = LineSelectionRange(currentPos_, anchor_);
}
if (sel.Count() > 1 || !(sel.RangeMain() == rangeNew)) {
InvalidateSelection(rangeNew);
}
sel.RangeMain() = rangeNew;
SetRectangularRange();
ClaimSelection();
SetHoverIndicatorPosition(sel.MainCaret());
if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
RedrawSelMargin();
}
QueueIdleWork(WorkItems::updateUI);
}
void Editor::SetSelection(Sci::Position currentPos_, Sci::Position anchor_) {
SetSelection(SelectionPosition(currentPos_), SelectionPosition(anchor_));
}
// Just move the caret on the main selection
void Editor::SetSelection(SelectionPosition currentPos_) {
currentPos_ = ClampPositionIntoDocument(currentPos_);
const Sci::Line currentLine = pdoc->SciLineFromPosition(currentPos_.Position());
if (sel.Count() > 1 || !(sel.RangeMain().caret == currentPos_)) {
InvalidateSelection(SelectionRange(currentPos_));
}
if (sel.IsRectangular()) {
sel.Rectangular() =
SelectionRange(SelectionPosition(currentPos_), sel.Rectangular().anchor);
SetRectangularRange();
} else if (sel.selType == Selection::SelTypes::lines) {
sel.RangeMain() = LineSelectionRange(currentPos_, sel.RangeMain().anchor);
} else {
sel.RangeMain() =
SelectionRange(SelectionPosition(currentPos_), sel.RangeMain().anchor);
}
ClaimSelection();
SetHoverIndicatorPosition(sel.MainCaret());
if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
RedrawSelMargin();
}
QueueIdleWork(WorkItems::updateUI);
}
void Editor::SetEmptySelection(SelectionPosition currentPos_) {
const Sci::Line currentLine = pdoc->SciLineFromPosition(currentPos_.Position());
SelectionRange rangeNew(ClampPositionIntoDocument(currentPos_));
if (sel.Count() > 1 || !(sel.RangeMain() == rangeNew)) {
InvalidateSelection(rangeNew);
}
sel.Clear();
sel.RangeMain() = rangeNew;
SetRectangularRange();
ClaimSelection();
SetHoverIndicatorPosition(sel.MainCaret());
if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
RedrawSelMargin();
}
QueueIdleWork(WorkItems::updateUI);
}
void Editor::SetEmptySelection(Sci::Position currentPos_) {
SetEmptySelection(SelectionPosition(currentPos_));
}
void Editor::MultipleSelectAdd(AddNumber addNumber) {
if (SelectionEmpty() || !multipleSelection) {
// Select word at caret
const Sci::Position startWord = pdoc->ExtendWordSelect(sel.MainCaret(), -1, true);
const Sci::Position endWord = pdoc->ExtendWordSelect(startWord, 1, true);
TrimAndSetSelection(endWord, startWord);
} else {
if (!pdoc->HasCaseFolder())
pdoc->SetCaseFolder(CaseFolderForEncoding());
const Range rangeMainSelection(sel.RangeMain().Start().Position(), sel.RangeMain().End().Position());
const std::string selectedText = RangeText(rangeMainSelection.start, rangeMainSelection.end);
const Range rangeTarget(targetRange.start.Position(), targetRange.end.Position());
std::vector<Range> searchRanges;
// Search should be over the target range excluding the current selection so
// may need to search 2 ranges, after the selection then before the selection.
if (rangeTarget.Overlaps(rangeMainSelection)) {
// Common case is that the selection is completely within the target but
// may also have overlap at start or end.
if (rangeMainSelection.end < rangeTarget.end)
searchRanges.push_back(Range(rangeMainSelection.end, rangeTarget.end));
if (rangeTarget.start < rangeMainSelection.start)
searchRanges.push_back(Range(rangeTarget.start, rangeMainSelection.start));
} else {
// No overlap
searchRanges.push_back(rangeTarget);
}
for (const Range range : searchRanges) {
Sci::Position searchStart = range.start;
const Sci::Position searchEnd = range.end;
for (;;) {
Sci::Position lengthFound = selectedText.length();
const Sci::Position pos = pdoc->FindText(searchStart, searchEnd,
selectedText.c_str(), searchFlags, &lengthFound);
if (pos >= 0) {
sel.AddSelection(SelectionRange(pos + lengthFound, pos));
ContainerNeedsUpdate(Update::Selection);
ScrollRange(sel.RangeMain());
Redraw();
if (addNumber == AddNumber::one)
return;
searchStart = pos + lengthFound;
} else {
break;
}
}
}
}
}
bool Editor::RangeContainsProtected(Sci::Position start, Sci::Position end) const noexcept {
if (vs.ProtectionActive()) {
if (start > end) {
std::swap(start, end);
}
for (Sci::Position pos = start; pos < end; pos++) {
if (vs.styles[pdoc->StyleIndexAt(pos)].IsProtected())
return true;
}
}
return false;
}
bool Editor::SelectionContainsProtected() const noexcept {
for (size_t r=0; r<sel.Count(); r++) {
if (RangeContainsProtected(sel.Range(r).Start().Position(),
sel.Range(r).End().Position())) {
return true;
}
}
return false;
}
/**
* Asks document to find a good position and then moves out of any invisible positions.
*/
Sci::Position Editor::MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool checkLineEnd) const {
return MovePositionOutsideChar(SelectionPosition(pos), moveDir, checkLineEnd).Position();
}
SelectionPosition Editor::MovePositionOutsideChar(SelectionPosition pos, Sci::Position moveDir, bool checkLineEnd) const {
const Sci::Position posMoved = pdoc->MovePositionOutsideChar(pos.Position(), moveDir, checkLineEnd);
if (posMoved != pos.Position())
pos.SetPosition(posMoved);
if (vs.ProtectionActive()) {
if (moveDir > 0) {
if ((pos.Position() > 0) && vs.styles[pdoc->StyleIndexAt(pos.Position() - 1)].IsProtected()) {
while ((pos.Position() < pdoc->Length()) &&
(vs.styles[pdoc->StyleIndexAt(pos.Position())].IsProtected()))
pos.Add(1);
}
} else if (moveDir < 0) {
if (vs.styles[pdoc->StyleIndexAt(pos.Position())].IsProtected()) {
while ((pos.Position() > 0) &&
(vs.styles[pdoc->StyleIndexAt(pos.Position() - 1)].IsProtected()))
pos.Add(-1);
}
}
}
return pos;
}
void Editor::MovedCaret(SelectionPosition newPos, SelectionPosition previousPos,
bool ensureVisible, CaretPolicies policies) {
const Sci::Line currentLine = pdoc->SciLineFromPosition(newPos.Position());
if (ensureVisible) {
// In case in need of wrapping to ensure DisplayFromDoc works.
if (currentLine >= wrapPending.start) {
if (WrapLines(WrapScope::wsAll)) {
Redraw();
}
}
const XYScrollPosition newXY = XYScrollToMakeVisible(
SelectionRange(posDrag.IsValid() ? posDrag : newPos), XYScrollOptions::all, policies);
if (previousPos.IsValid() && (newXY.xOffset == xOffset)) {
// simple vertical scroll then invalidate
ScrollTo(newXY.topLine);
InvalidateSelection(SelectionRange(previousPos), true);
} else {
SetXYScroll(newXY);
}
}
ShowCaretAtCurrentPosition();
NotifyCaretMove();
ClaimSelection();
SetHoverIndicatorPosition(sel.MainCaret());
QueueIdleWork(WorkItems::updateUI);
if (marginView.highlightDelimiter.NeedsDrawing(currentLine)) {
RedrawSelMargin();
}
}
void Editor::MovePositionTo(SelectionPosition newPos, Selection::SelTypes selt, bool ensureVisible) {
const SelectionPosition spCaret = ((sel.Count() == 1) && sel.Empty()) ?
sel.Last() : SelectionPosition(Sci::invalidPosition);
const Sci::Position delta = newPos.Position() - sel.MainCaret();
newPos = ClampPositionIntoDocument(newPos);
newPos = MovePositionOutsideChar(newPos, delta);
if (!multipleSelection && sel.IsRectangular() && (selt == Selection::SelTypes::stream)) {
// Can't turn into multiple selection so clear additional selections
InvalidateSelection(SelectionRange(newPos), true);
sel.DropAdditionalRanges();
}
if (!sel.IsRectangular() && (selt == Selection::SelTypes::rectangle)) {
// Switching to rectangular
InvalidateSelection(sel.RangeMain(), false);
SelectionRange rangeMain = sel.RangeMain();
sel.Clear();
sel.Rectangular() = rangeMain;
}
if (selt != Selection::SelTypes::none) {
sel.selType = selt;
}
if (selt != Selection::SelTypes::none || sel.MoveExtends()) {
SetSelection(newPos);
} else {
SetEmptySelection(newPos);
}
MovedCaret(newPos, spCaret, ensureVisible, caretPolicies);
}
void Editor::MovePositionTo(Sci::Position newPos, Selection::SelTypes selt, bool ensureVisible) {
MovePositionTo(SelectionPosition(newPos), selt, ensureVisible);
}
SelectionPosition Editor::MovePositionSoVisible(SelectionPosition pos, int moveDir) {
pos = ClampPositionIntoDocument(pos);
pos = MovePositionOutsideChar(pos, moveDir);
const Sci::Line lineDoc = pdoc->SciLineFromPosition(pos.Position());
if (pcs->GetVisible(lineDoc)) {
return pos;
} else {
Sci::Line lineDisplay = pcs->DisplayFromDoc(lineDoc);
if (moveDir > 0) {
// lineDisplay is already line before fold as lines in fold use display line of line after fold
lineDisplay = std::clamp<Sci::Line>(lineDisplay, 0, pcs->LinesDisplayed());
return SelectionPosition(
pdoc->LineStart(pcs->DocFromDisplay(lineDisplay)));
} else {
lineDisplay = std::clamp<Sci::Line>(lineDisplay - 1, 0, pcs->LinesDisplayed());
return SelectionPosition(
pdoc->LineEnd(pcs->DocFromDisplay(lineDisplay)));
}
}
}
SelectionPosition Editor::MovePositionSoVisible(Sci::Position pos, int moveDir) {
return MovePositionSoVisible(SelectionPosition(pos), moveDir);
}
Point Editor::PointMainCaret() {
return LocationFromPosition(sel.RangeMain().caret);
}
/**
* Choose the x position that the caret will try to stick to
* as it moves up and down.
*/
void Editor::SetLastXChosen() {
const Point pt = PointMainCaret();
lastXChosen = static_cast<int>(pt.x) + xOffset;
}
void Editor::ScrollTo(Sci::Line line, bool moveThumb) {
const Sci::Line topLineNew = std::clamp<Sci::Line>(line, 0, MaxScrollPos());
if (topLineNew != topLine) {
// Try to optimise small scrolls
#ifndef UNDER_CE
const Sci::Line linesToMove = topLine - topLineNew;
const bool performBlit = (std::abs(linesToMove) <= 10) && (paintState == PaintState::notPainting);
willRedrawAll = !performBlit;
#endif
SetTopLine(topLineNew);
// Optimize by styling the view as this will invalidate any needed area
// which could abort the initial paint if discovered later.
StyleAreaBounded(GetClientRectangle(), true);
#ifndef UNDER_CE
// Perform redraw rather than scroll if many lines would be redrawn anyway.
if (performBlit) {
ScrollText(linesToMove);
} else {
Redraw();
}
willRedrawAll = false;
#else
Redraw();
#endif
if (moveThumb) {
SetVerticalScrollPos();
}
}
}
void Editor::ScrollText(Sci::Line /* linesToMove */) {
//Platform::DebugPrintf("Editor::ScrollText %d\n", linesToMove);
Redraw();
}
void Editor::HorizontalScrollTo(int xPos) {
//Platform::DebugPrintf("HorizontalScroll %d\n", xPos);
if (xPos < 0)
xPos = 0;
if (!Wrapping() && (xOffset != xPos)) {
xOffset = xPos;
ContainerNeedsUpdate(Update::HScroll);
SetHorizontalScrollPos();
RedrawRect(GetClientRectangle());
}
}
void Editor::VerticalCentreCaret() {
const Sci::Line lineDoc =
pdoc->SciLineFromPosition(sel.IsRectangular() ? sel.Rectangular().caret.Position() : sel.MainCaret());
const Sci::Line lineDisplay = pcs->DisplayFromDoc(lineDoc);
const Sci::Line newTop = lineDisplay - (LinesOnScreen() / 2);
if (topLine != newTop) {
SetTopLine(newTop > 0 ? newTop : 0);
SetVerticalScrollPos();
RedrawRect(GetClientRectangle());
}
}
void Editor::MoveSelectedLines(int lineDelta) {
if (sel.IsRectangular()) {
return;
}
// if selection doesn't start at the beginning of the line, set the new start
Sci::Position selectionStart = SelectionStart().Position();
const Sci::Line startLine = pdoc->SciLineFromPosition(selectionStart);
const Sci::Position beginningOfStartLine = pdoc->LineStart(startLine);
selectionStart = beginningOfStartLine;
// if selection doesn't end at the beginning of a line greater than that of the start,
// then set it at the beginning of the next one
Sci::Position selectionEnd = SelectionEnd().Position();
const Sci::Line endLine = pdoc->SciLineFromPosition(selectionEnd);
const Sci::Position beginningOfEndLine = pdoc->LineStart(endLine);