1 // Scintilla source code edit control
2 /** @file CellBuffer.cxx
3 ** Manages a buffer of cells.
5 // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
17 #include "Scintilla.h"
18 #include "SplitVector.h"
19 #include "Partitioning.h"
20 #include "CellBuffer.h"
21 #include "UniConversion.h"
24 using namespace Scintilla
;
27 LineVector::LineVector() : starts(256), perLine(0) {
31 LineVector::~LineVector() {
35 void LineVector::Init() {
42 void LineVector::SetPerLine(PerLine
*pl
) {
46 void LineVector::InsertText(int line
, int delta
) {
47 starts
.InsertText(line
, delta
);
50 void LineVector::InsertLine(int line
, int position
, bool lineStart
) {
51 starts
.InsertPartition(line
, position
);
53 if ((line
> 0) && lineStart
)
55 perLine
->InsertLine(line
);
59 void LineVector::SetLineStart(int line
, int position
) {
60 starts
.SetPartitionStartPosition(line
, position
);
63 void LineVector::RemoveLine(int line
) {
64 starts
.RemovePartition(line
);
66 perLine
->RemoveLine(line
);
70 int LineVector::LineFromPosition(int pos
) const {
71 return starts
.PartitionFromPosition(pos
);
86 void Action::Create(actionType at_
, int position_
, const char *data_
, int lenData_
, bool mayCoalesce_
) {
92 data
= new char[lenData_
];
93 memcpy(data
, data_
, lenData_
);
96 mayCoalesce
= mayCoalesce_
;
99 void Action::Destroy() {
104 void Action::Grab(Action
*source
) {
107 position
= source
->position
;
110 lenData
= source
->lenData
;
111 mayCoalesce
= source
->mayCoalesce
;
113 // Ownership of source data transferred to this
114 source
->position
= 0;
115 source
->at
= startAction
;
118 source
->mayCoalesce
= true;
121 // The undo history stores a sequence of user operations that represent the user's view of the
122 // commands executed on the text.
123 // Each user operation contains a sequence of text insertion and text deletion actions.
124 // All the user operations are stored in a list of individual actions with 'start' actions used
125 // as delimiters between user operations.
126 // Initially there is one start action in the history.
127 // As each action is performed, it is recorded in the history. The action may either become
128 // part of the current user operation or may start a new user operation. If it is to be part of the
129 // current operation, then it overwrites the current last action. If it is to be part of a new
130 // operation, it is appended after the current last action.
131 // After writing the new action, a new start action is appended at the end of the history.
132 // The decision of whether to start a new user operation is based upon two factors. If a
133 // compound operation has been explicitly started by calling BeginUndoAction and no matching
134 // EndUndoAction (these calls nest) has been called, then the action is coalesced into the current
135 // operation. If there is no outstanding BeginUndoAction call then a new operation is started
136 // unless it looks as if the new action is caused by the user typing or deleting a stream of text.
137 // Sequences that look like typing or deletion are coalesced into a single user operation.
139 UndoHistory::UndoHistory() {
142 actions
= new Action
[lenActions
];
145 undoSequenceDepth
= 0;
149 actions
[currentAction
].Create(startAction
);
152 UndoHistory::~UndoHistory() {
157 void UndoHistory::EnsureUndoRoom() {
158 // Have to test that there is room for 2 more actions in the array
159 // as two actions may be created by the calling function
160 if (currentAction
>= (lenActions
- 2)) {
161 // Run out of undo nodes so extend the array
162 int lenActionsNew
= lenActions
* 2;
163 Action
*actionsNew
= new Action
[lenActionsNew
];
164 for (int act
= 0; act
<= currentAction
; act
++)
165 actionsNew
[act
].Grab(&actions
[act
]);
167 lenActions
= lenActionsNew
;
168 actions
= actionsNew
;
172 const char *UndoHistory::AppendAction(actionType at
, int position
, const char *data
, int lengthData
,
173 bool &startSequence
, bool mayCoalesce
) {
175 //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction);
176 //Platform::DebugPrintf("^ %d action %d %d\n", actions[currentAction - 1].at,
177 // actions[currentAction - 1].position, actions[currentAction - 1].lenData);
178 if (currentAction
< savePoint
) {
181 int oldCurrentAction
= currentAction
;
182 if (currentAction
>= 1) {
183 if (0 == undoSequenceDepth
) {
184 // Top level actions may not always be coalesced
186 const Action
*actPrevious
= &(actions
[currentAction
+ targetAct
]);
187 // Container actions may forward the coalesce state of Scintilla Actions.
188 while ((actPrevious
->at
== containerAction
) && actPrevious
->mayCoalesce
) {
190 actPrevious
= &(actions
[currentAction
+ targetAct
]);
192 // See if current action can be coalesced into previous action
193 // Will work if both are inserts or deletes and position is same
194 #if defined(_MSC_VER) && defined(_PREFAST_)
195 // Visual Studio 2013 Code Analysis wrongly believes actions can be NULL at its next reference
196 __analysis_assume(actions
);
198 if ((currentAction
== savePoint
) || (currentAction
== tentativePoint
)) {
200 } else if (!actions
[currentAction
].mayCoalesce
) {
201 // Not allowed to coalesce if this set
203 } else if (!mayCoalesce
|| !actPrevious
->mayCoalesce
) {
205 } else if (at
== containerAction
|| actions
[currentAction
].at
== containerAction
) {
206 ; // A coalescible containerAction
207 } else if ((at
!= actPrevious
->at
) && (actPrevious
->at
!= startAction
)) {
209 } else if ((at
== insertAction
) &&
210 (position
!= (actPrevious
->position
+ actPrevious
->lenData
))) {
211 // Insertions must be immediately after to coalesce
213 } else if (at
== removeAction
) {
214 if ((lengthData
== 1) || (lengthData
== 2)) {
215 if ((position
+ lengthData
) == actPrevious
->position
) {
217 } else if (position
== actPrevious
->position
) {
220 // Removals must be at same position to coalesce
224 // Removals must be of one character to coalesce
232 // Actions not at top level are always coalesced unless this is after return to top level
233 if (!actions
[currentAction
].mayCoalesce
)
239 startSequence
= oldCurrentAction
!= currentAction
;
240 int actionWithData
= currentAction
;
241 actions
[currentAction
].Create(at
, position
, data
, lengthData
, mayCoalesce
);
243 actions
[currentAction
].Create(startAction
);
244 maxAction
= currentAction
;
245 return actions
[actionWithData
].data
;
248 void UndoHistory::BeginUndoAction() {
250 if (undoSequenceDepth
== 0) {
251 if (actions
[currentAction
].at
!= startAction
) {
253 actions
[currentAction
].Create(startAction
);
254 maxAction
= currentAction
;
256 actions
[currentAction
].mayCoalesce
= false;
261 void UndoHistory::EndUndoAction() {
262 PLATFORM_ASSERT(undoSequenceDepth
> 0);
265 if (0 == undoSequenceDepth
) {
266 if (actions
[currentAction
].at
!= startAction
) {
268 actions
[currentAction
].Create(startAction
);
269 maxAction
= currentAction
;
271 actions
[currentAction
].mayCoalesce
= false;
275 void UndoHistory::DropUndoSequence() {
276 undoSequenceDepth
= 0;
279 void UndoHistory::DeleteUndoHistory() {
280 for (int i
= 1; i
< maxAction
; i
++)
281 actions
[i
].Destroy();
284 actions
[currentAction
].Create(startAction
);
289 void UndoHistory::SetSavePoint() {
290 savePoint
= currentAction
;
293 bool UndoHistory::IsSavePoint() const {
294 return savePoint
== currentAction
;
297 void UndoHistory::TentativeStart() {
298 tentativePoint
= currentAction
;
301 void UndoHistory::TentativeCommit() {
303 // Truncate undo history
304 maxAction
= currentAction
;
307 int UndoHistory::TentativeSteps() {
308 // Drop any trailing startAction
309 if (actions
[currentAction
].at
== startAction
&& currentAction
> 0)
311 if (tentativePoint
>= 0)
312 return currentAction
- tentativePoint
;
317 bool UndoHistory::CanUndo() const {
318 return (currentAction
> 0) && (maxAction
> 0);
321 int UndoHistory::StartUndo() {
322 // Drop any trailing startAction
323 if (actions
[currentAction
].at
== startAction
&& currentAction
> 0)
326 // Count the steps in this action
327 int act
= currentAction
;
328 while (actions
[act
].at
!= startAction
&& act
> 0) {
331 return currentAction
- act
;
334 const Action
&UndoHistory::GetUndoStep() const {
335 return actions
[currentAction
];
338 void UndoHistory::CompletedUndoStep() {
342 bool UndoHistory::CanRedo() const {
343 return maxAction
> currentAction
;
346 int UndoHistory::StartRedo() {
347 // Drop any leading startAction
348 if (actions
[currentAction
].at
== startAction
&& currentAction
< maxAction
)
351 // Count the steps in this action
352 int act
= currentAction
;
353 while (actions
[act
].at
!= startAction
&& act
< maxAction
) {
356 return act
- currentAction
;
359 const Action
&UndoHistory::GetRedoStep() const {
360 return actions
[currentAction
];
363 void UndoHistory::CompletedRedoStep() {
367 CellBuffer::CellBuffer() {
370 collectingUndo
= true;
373 CellBuffer::~CellBuffer() {
376 char CellBuffer::CharAt(int position
) const {
377 return substance
.ValueAt(position
);
380 void CellBuffer::GetCharRange(char *buffer
, int position
, int lengthRetrieve
) const {
381 if (lengthRetrieve
<= 0)
385 if ((position
+ lengthRetrieve
) > substance
.Length()) {
386 Platform::DebugPrintf("Bad GetCharRange %d for %d of %d\n", position
,
387 lengthRetrieve
, substance
.Length());
390 substance
.GetRange(buffer
, position
, lengthRetrieve
);
393 char CellBuffer::StyleAt(int position
) const {
394 return style
.ValueAt(position
);
397 void CellBuffer::GetStyleRange(unsigned char *buffer
, int position
, int lengthRetrieve
) const {
398 if (lengthRetrieve
< 0)
402 if ((position
+ lengthRetrieve
) > style
.Length()) {
403 Platform::DebugPrintf("Bad GetStyleRange %d for %d of %d\n", position
,
404 lengthRetrieve
, style
.Length());
407 style
.GetRange(reinterpret_cast<char *>(buffer
), position
, lengthRetrieve
);
410 const char *CellBuffer::BufferPointer() {
411 return substance
.BufferPointer();
414 const char *CellBuffer::RangePointer(int position
, int rangeLength
) {
415 return substance
.RangePointer(position
, rangeLength
);
418 int CellBuffer::GapPosition() const {
419 return substance
.GapPosition();
422 // The char* returned is to an allocation owned by the undo history
423 const char *CellBuffer::InsertString(int position
, const char *s
, int insertLength
, bool &startSequence
) {
424 // InsertString and DeleteChars are the bottleneck though which all changes occur
425 const char *data
= s
;
427 if (collectingUndo
) {
428 // Save into the undo/redo stack, but only the characters - not the formatting
429 // This takes up about half load time
430 data
= uh
.AppendAction(insertAction
, position
, s
, insertLength
, startSequence
);
433 BasicInsertString(position
, s
, insertLength
);
438 bool CellBuffer::SetStyleAt(int position
, char styleValue
) {
439 char curVal
= style
.ValueAt(position
);
440 if (curVal
!= styleValue
) {
441 style
.SetValueAt(position
, styleValue
);
448 bool CellBuffer::SetStyleFor(int position
, int lengthStyle
, char styleValue
) {
449 bool changed
= false;
450 PLATFORM_ASSERT(lengthStyle
== 0 ||
451 (lengthStyle
> 0 && lengthStyle
+ position
<= style
.Length()));
452 while (lengthStyle
--) {
453 char curVal
= style
.ValueAt(position
);
454 if (curVal
!= styleValue
) {
455 style
.SetValueAt(position
, styleValue
);
463 // The char* returned is to an allocation owned by the undo history
464 const char *CellBuffer::DeleteChars(int position
, int deleteLength
, bool &startSequence
) {
465 // InsertString and DeleteChars are the bottleneck though which all changes occur
466 PLATFORM_ASSERT(deleteLength
> 0);
467 const char *data
= 0;
469 if (collectingUndo
) {
470 // Save into the undo/redo stack, but only the characters - not the formatting
471 // The gap would be moved to position anyway for the deletion so this doesn't cost extra
472 data
= substance
.RangePointer(position
, deleteLength
);
473 data
= uh
.AppendAction(removeAction
, position
, data
, deleteLength
, startSequence
);
476 BasicDeleteChars(position
, deleteLength
);
481 int CellBuffer::Length() const {
482 return substance
.Length();
485 void CellBuffer::Allocate(int newSize
) {
486 substance
.ReAllocate(newSize
);
487 style
.ReAllocate(newSize
);
490 void CellBuffer::SetLineEndTypes(int utf8LineEnds_
) {
491 if (utf8LineEnds
!= utf8LineEnds_
) {
492 utf8LineEnds
= utf8LineEnds_
;
497 void CellBuffer::SetPerLine(PerLine
*pl
) {
501 int CellBuffer::Lines() const {
505 int CellBuffer::LineStart(int line
) const {
508 else if (line
>= Lines())
511 return lv
.LineStart(line
);
514 bool CellBuffer::IsReadOnly() const {
518 void CellBuffer::SetReadOnly(bool set
) {
522 void CellBuffer::SetSavePoint() {
526 bool CellBuffer::IsSavePoint() const {
527 return uh
.IsSavePoint();
530 void CellBuffer::TentativeStart() {
534 void CellBuffer::TentativeCommit() {
535 uh
.TentativeCommit();
538 int CellBuffer::TentativeSteps() {
539 return uh
.TentativeSteps();
542 bool CellBuffer::TentativeActive() const {
543 return uh
.TentativeActive();
548 void CellBuffer::InsertLine(int line
, int position
, bool lineStart
) {
549 lv
.InsertLine(line
, position
, lineStart
);
552 void CellBuffer::RemoveLine(int line
) {
556 bool CellBuffer::UTF8LineEndOverlaps(int position
) const {
557 unsigned char bytes
[] = {
558 static_cast<unsigned char>(substance
.ValueAt(position
-2)),
559 static_cast<unsigned char>(substance
.ValueAt(position
-1)),
560 static_cast<unsigned char>(substance
.ValueAt(position
)),
561 static_cast<unsigned char>(substance
.ValueAt(position
+1)),
563 return UTF8IsSeparator(bytes
) || UTF8IsSeparator(bytes
+1) || UTF8IsNEL(bytes
+1);
566 void CellBuffer::ResetLineEnds() {
567 // Reinitialize line data -- too much work to preserve
571 int length
= Length();
573 bool atLineStart
= true;
574 lv
.InsertText(lineInsert
-1, length
);
575 unsigned char chBeforePrev
= 0;
576 unsigned char chPrev
= 0;
577 for (int i
= 0; i
< length
; i
++) {
578 unsigned char ch
= substance
.ValueAt(position
+ i
);
580 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
582 } else if (ch
== '\n') {
583 if (chPrev
== '\r') {
584 // Patch up what was end of line
585 lv
.SetLineStart(lineInsert
- 1, (position
+ i
) + 1);
587 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
590 } else if (utf8LineEnds
) {
591 unsigned char back3
[3] = {chBeforePrev
, chPrev
, ch
};
592 if (UTF8IsSeparator(back3
) || UTF8IsNEL(back3
+1)) {
593 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
597 chBeforePrev
= chPrev
;
602 void CellBuffer::BasicInsertString(int position
, const char *s
, int insertLength
) {
603 if (insertLength
== 0)
605 PLATFORM_ASSERT(insertLength
> 0);
607 unsigned char chAfter
= substance
.ValueAt(position
);
608 bool breakingUTF8LineEnd
= false;
609 if (utf8LineEnds
&& UTF8IsTrailByte(chAfter
)) {
610 breakingUTF8LineEnd
= UTF8LineEndOverlaps(position
);
613 substance
.InsertFromArray(position
, s
, 0, insertLength
);
614 style
.InsertValue(position
, insertLength
, 0);
616 int lineInsert
= lv
.LineFromPosition(position
) + 1;
617 bool atLineStart
= lv
.LineStart(lineInsert
-1) == position
;
618 // Point all the lines after the insertion point further along in the buffer
619 lv
.InsertText(lineInsert
-1, insertLength
);
620 unsigned char chBeforePrev
= substance
.ValueAt(position
- 2);
621 unsigned char chPrev
= substance
.ValueAt(position
- 1);
622 if (chPrev
== '\r' && chAfter
== '\n') {
623 // Splitting up a crlf pair at position
624 InsertLine(lineInsert
, position
, false);
627 if (breakingUTF8LineEnd
) {
628 RemoveLine(lineInsert
);
630 unsigned char ch
= ' ';
631 for (int i
= 0; i
< insertLength
; i
++) {
634 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
636 } else if (ch
== '\n') {
637 if (chPrev
== '\r') {
638 // Patch up what was end of line
639 lv
.SetLineStart(lineInsert
- 1, (position
+ i
) + 1);
641 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
644 } else if (utf8LineEnds
) {
645 unsigned char back3
[3] = {chBeforePrev
, chPrev
, ch
};
646 if (UTF8IsSeparator(back3
) || UTF8IsNEL(back3
+1)) {
647 InsertLine(lineInsert
, (position
+ i
) + 1, atLineStart
);
651 chBeforePrev
= chPrev
;
654 // Joining two lines where last insertion is cr and following substance starts with lf
655 if (chAfter
== '\n') {
657 // End of line already in buffer so drop the newly created one
658 RemoveLine(lineInsert
- 1);
660 } else if (utf8LineEnds
&& !UTF8IsAscii(chAfter
)) {
661 // May have end of UTF-8 line end in buffer and start in insertion
662 for (int j
= 0; j
< UTF8SeparatorLength
-1; j
++) {
663 unsigned char chAt
= substance
.ValueAt(position
+ insertLength
+ j
);
664 unsigned char back3
[3] = {chBeforePrev
, chPrev
, chAt
};
665 if (UTF8IsSeparator(back3
)) {
666 InsertLine(lineInsert
, (position
+ insertLength
+ j
) + 1, atLineStart
);
669 if ((j
== 0) && UTF8IsNEL(back3
+1)) {
670 InsertLine(lineInsert
, (position
+ insertLength
+ j
) + 1, atLineStart
);
673 chBeforePrev
= chPrev
;
679 void CellBuffer::BasicDeleteChars(int position
, int deleteLength
) {
680 if (deleteLength
== 0)
683 if ((position
== 0) && (deleteLength
== substance
.Length())) {
684 // If whole buffer is being deleted, faster to reinitialise lines data
685 // than to delete each line.
688 // Have to fix up line positions before doing deletion as looking at text in buffer
689 // to work out which lines have been removed
691 int lineRemove
= lv
.LineFromPosition(position
) + 1;
692 lv
.InsertText(lineRemove
-1, - (deleteLength
));
693 unsigned char chPrev
= substance
.ValueAt(position
- 1);
694 unsigned char chBefore
= chPrev
;
695 unsigned char chNext
= substance
.ValueAt(position
);
696 bool ignoreNL
= false;
697 if (chPrev
== '\r' && chNext
== '\n') {
699 lv
.SetLineStart(lineRemove
, position
);
701 ignoreNL
= true; // First \n is not real deletion
703 if (utf8LineEnds
&& UTF8IsTrailByte(chNext
)) {
704 if (UTF8LineEndOverlaps(position
)) {
705 RemoveLine(lineRemove
);
709 unsigned char ch
= chNext
;
710 for (int i
= 0; i
< deleteLength
; i
++) {
711 chNext
= substance
.ValueAt(position
+ i
+ 1);
713 if (chNext
!= '\n') {
714 RemoveLine(lineRemove
);
716 } else if (ch
== '\n') {
718 ignoreNL
= false; // Further \n are real deletions
720 RemoveLine(lineRemove
);
722 } else if (utf8LineEnds
) {
723 if (!UTF8IsAscii(ch
)) {
724 unsigned char next3
[3] = {ch
, chNext
,
725 static_cast<unsigned char>(substance
.ValueAt(position
+ i
+ 2))};
726 if (UTF8IsSeparator(next3
) || UTF8IsNEL(next3
)) {
727 RemoveLine(lineRemove
);
734 // May have to fix up end if last deletion causes cr to be next to lf
735 // or removes one of a crlf pair
736 char chAfter
= substance
.ValueAt(position
+ deleteLength
);
737 if (chBefore
== '\r' && chAfter
== '\n') {
738 // Using lineRemove-1 as cr ended line before start of deletion
739 RemoveLine(lineRemove
- 1);
740 lv
.SetLineStart(lineRemove
- 1, position
+ 1);
743 substance
.DeleteRange(position
, deleteLength
);
744 style
.DeleteRange(position
, deleteLength
);
747 bool CellBuffer::SetUndoCollection(bool collectUndo
) {
748 collectingUndo
= collectUndo
;
749 uh
.DropUndoSequence();
750 return collectingUndo
;
753 bool CellBuffer::IsCollectingUndo() const {
754 return collectingUndo
;
757 void CellBuffer::BeginUndoAction() {
758 uh
.BeginUndoAction();
761 void CellBuffer::EndUndoAction() {
765 void CellBuffer::AddUndoAction(int token
, bool mayCoalesce
) {
767 uh
.AppendAction(containerAction
, token
, 0, 0, startSequence
, mayCoalesce
);
770 void CellBuffer::DeleteUndoHistory() {
771 uh
.DeleteUndoHistory();
774 bool CellBuffer::CanUndo() const {
778 int CellBuffer::StartUndo() {
779 return uh
.StartUndo();
782 const Action
&CellBuffer::GetUndoStep() const {
783 return uh
.GetUndoStep();
786 void CellBuffer::PerformUndoStep() {
787 const Action
&actionStep
= uh
.GetUndoStep();
788 if (actionStep
.at
== insertAction
) {
789 BasicDeleteChars(actionStep
.position
, actionStep
.lenData
);
790 } else if (actionStep
.at
== removeAction
) {
791 BasicInsertString(actionStep
.position
, actionStep
.data
, actionStep
.lenData
);
793 uh
.CompletedUndoStep();
796 bool CellBuffer::CanRedo() const {
800 int CellBuffer::StartRedo() {
801 return uh
.StartRedo();
804 const Action
&CellBuffer::GetRedoStep() const {
805 return uh
.GetRedoStep();
808 void CellBuffer::PerformRedoStep() {
809 const Action
&actionStep
= uh
.GetRedoStep();
810 if (actionStep
.at
== insertAction
) {
811 BasicInsertString(actionStep
.position
, actionStep
.data
, actionStep
.lenData
);
812 } else if (actionStep
.at
== removeAction
) {
813 BasicDeleteChars(actionStep
.position
, actionStep
.lenData
);
815 uh
.CompletedRedoStep();