diff options
author | nyamatongwe <devnull@localhost> | 2000-03-30 11:41:02 +0000 |
---|---|---|
committer | nyamatongwe <devnull@localhost> | 2000-03-30 11:41:02 +0000 |
commit | 75f7cfc96a7cc20ba1886c45b5be9022be85b75b (patch) | |
tree | cce59a9b4ab9bc790bae4c92dd8d76f3fc70dce1 | |
parent | 327c5b3dcd851eaf45cc232f64d665fae509e027 (diff) | |
download | scintilla-mirror-75f7cfc96a7cc20ba1886c45b5be9022be85b75b.tar.gz |
Fixed bugs in handling undo history.
Fixed bugs with null fonts.
-rw-r--r-- | src/CellBuffer.cxx | 2050 | ||||
-rw-r--r-- | src/Document.cxx | 1596 | ||||
-rw-r--r-- | src/KeyWords.cxx | 88 | ||||
-rw-r--r-- | src/Style.cxx | 201 | ||||
-rw-r--r-- | src/ViewStyle.cxx | 453 |
5 files changed, 2195 insertions, 2193 deletions
diff --git a/src/CellBuffer.cxx b/src/CellBuffer.cxx index b9fe69660..c69070377 100644 --- a/src/CellBuffer.cxx +++ b/src/CellBuffer.cxx @@ -1,1025 +1,1025 @@ -// Scintilla source code edit control -// CellBuffer.cxx - manages a buffer of cells -// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org> -// The License.txt file describes the conditions under which this software may be distributed. - -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <stdarg.h> - -#include "Platform.h" - -#include "Scintilla.h" -#include "SVector.h" -#include "CellBuffer.h" - -MarkerHandleSet::MarkerHandleSet() { - root = 0; -} - -MarkerHandleSet::~MarkerHandleSet() { - MarkerHandleNumber *mhn = root; - while (mhn) { - MarkerHandleNumber *mhnToFree = mhn; - mhn = mhn->next; - delete mhnToFree; - } - root = 0; -} - -int MarkerHandleSet::Length() { - int c = 0; - MarkerHandleNumber *mhn = root; - while (mhn) { - c++; - mhn = mhn->next; - } - return c; -} - -int MarkerHandleSet::NumberFromHandle(int handle) { - MarkerHandleNumber *mhn = root; - while (mhn) { - if (mhn->handle == handle) { - return mhn->number; - } - mhn = mhn->next; - } - return - 1; -} - -int MarkerHandleSet::MarkValue() { - unsigned int m = 0; - MarkerHandleNumber *mhn = root; - while (mhn) { - m |= (1 << mhn->number); - mhn = mhn->next; - } - return m; -} - -bool MarkerHandleSet::Contains(int handle) { - MarkerHandleNumber *mhn = root; - while (mhn) { - if (mhn->handle == handle) { - return true; - } - mhn = mhn->next; - } - return false; -} - -bool MarkerHandleSet::InsertHandle(int handle, int markerNum) { - MarkerHandleNumber *mhn = new MarkerHandleNumber; - if (!mhn) - return false; - mhn->handle = handle; - mhn->number = markerNum; - mhn->next = root; - root = mhn; - return true; -} - -void MarkerHandleSet::RemoveHandle(int handle) { - MarkerHandleNumber **pmhn = &root; - while (*pmhn) { - MarkerHandleNumber *mhn = *pmhn; - if (mhn->handle == handle) { - *pmhn = mhn->next; - delete mhn; - return; - } - pmhn = &((*pmhn)->next); - } -} - -void MarkerHandleSet::RemoveNumber(int markerNum) { - MarkerHandleNumber **pmhn = &root; - while (*pmhn) { - MarkerHandleNumber *mhn = *pmhn; - if (mhn->number == markerNum) { - *pmhn = mhn->next; - delete mhn; - return; - } - pmhn = &((*pmhn)->next); - } -} - -void MarkerHandleSet::CombineWith(MarkerHandleSet *other) { - MarkerHandleNumber **pmhn = &root; - while (*pmhn) { - pmhn = &((*pmhn)->next); - } - *pmhn = other->root; - other->root = 0; -} - -LineVector::LineVector() { - linesData = 0; - lines = 0; - levels = 0; - Init(); -} - -LineVector::~LineVector() { - for (int line = 0; line < lines; line++) { - delete linesData[line].handleSet; - linesData[line].handleSet = 0; - } - delete []linesData; - linesData = 0; - delete []levels; - levels = 0; -} - -void LineVector::Init() { - for (int line = 0; line < lines; line++) { - delete linesData[line].handleSet; - linesData[line].handleSet = 0; - } - delete []linesData; - linesData = new LineData[static_cast<int>(growSize)]; - size = growSize; - lines = 1; - delete []levels; - levels = 0; - sizeLevels = 0; -} - -void LineVector::Expand(int sizeNew) { - LineData *linesDataNew = new LineData[sizeNew]; - if (linesDataNew) { - for (int i = 0; i < size; i++) - linesDataNew[i] = linesData[i]; - // Do not delete handleSets here as they are transferred to new linesData - delete []linesData; - linesData = linesDataNew; - size = sizeNew; - } else { - Platform::DebugPrintf("No memory available\n"); - // TODO: Blow up - } -} - -void LineVector::ExpandLevels(int sizeNew) { - if (sizeNew == -1) - sizeNew = size; - int *levelsNew = new int[sizeNew]; - if (levelsNew) { - int i = 0; - for (; i < sizeLevels; i++) - levelsNew[i] = levels[i]; - for (; i < sizeNew; i++) - levelsNew[i] = SC_FOLDLEVELBASE; - delete []levels; - levels = levelsNew; - sizeLevels = sizeNew; - } else { - Platform::DebugPrintf("No memory available\n"); - // TODO: Blow up - } -} - -void LineVector::InsertValue(int pos, int value) { - //Platform::DebugPrintf("InsertValue[%d] = %d\n", pos, value); - if ((lines + 2) >= size) { - Expand(size + growSize); - if (levels) { - ExpandLevels(size + growSize); - } - } - lines++; - for (int i = lines + 1; i > pos; i--) { - linesData[i] = linesData[i - 1]; - } - linesData[pos].startPosition = value; - linesData[pos].handleSet = 0; -} - -void LineVector::SetValue(int pos, int value) { - //Platform::DebugPrintf("SetValue[%d] = %d\n", pos, value); - if ((pos + 2) >= size) { - //Platform::DebugPrintf("Resize %d %d\n", size,pos); - Expand(pos + growSize); - //Platform::DebugPrintf("end Resize %d %d\n", size,pos); - lines = pos; - if (levels) { - ExpandLevels(pos + growSize); - } - } - linesData[pos].startPosition = value; -} - -void LineVector::Remove(int pos) { - //Platform::DebugPrintf("Remove %d\n", pos); - // Retain the markers from the deleted line by oring them into the previous line - if (pos > 0) { - MergeMarkers(pos - 1); - } - for (int i = pos; i < lines; i++) { - linesData[i] = linesData[i + 1]; - } - lines--; -} - -int LineVector::LineFromPosition(int pos) { - //Platform::DebugPrintf("LineFromPostion %d lines=%d end = %d\n", pos, lines, linesData[lines].startPosition); - if (lines == 0) - return 0; - //Platform::DebugPrintf("LineFromPosition %d\n", pos); - if (pos >= linesData[lines].startPosition) - return lines - 1; - int lower = 0; - int upper = lines; - int middle = 0; - do { - middle = (upper + lower + 1) / 2; // Round high - if (pos < linesData[middle].startPosition) { - upper = middle - 1; - } else { - lower = middle; - } - } while (lower < upper); - //Platform::DebugPrintf("LineFromPostion %d %d %d\n", pos, lower, linesData[lower].startPosition, linesData[lower > 1 ? lower - 1 : 0].startPosition); - return lower; -} - -int LineVector::AddMark(int line, int markerNum) { - handleCurrent++; - if (!linesData[line].handleSet) { - // Need new structure to hold marker handle - linesData[line].handleSet = new MarkerHandleSet; - if (!linesData[line].handleSet) - return - 1; - } - linesData[line].handleSet->InsertHandle(handleCurrent, markerNum); - - return handleCurrent; -} - -void LineVector::MergeMarkers(int pos) { - if (linesData[pos].handleSet || linesData[pos + 1].handleSet) { - if (linesData[pos].handleSet && linesData[pos + 1].handleSet) { - linesData[pos].handleSet->CombineWith(linesData[pos].handleSet); - linesData[pos].handleSet = 0; - } - } -} - -void LineVector::DeleteMark(int line, int markerNum) { - if (linesData[line].handleSet) { - if (markerNum == -1) { - delete linesData[line].handleSet; - linesData[line].handleSet = 0; - } else { - linesData[line].handleSet->RemoveNumber(markerNum); - if (linesData[line].handleSet->Length() == 0) { - delete linesData[line].handleSet; - linesData[line].handleSet = 0; - } - } - } -} - -void LineVector::DeleteMarkFromHandle(int markerHandle) { - int line = LineFromHandle(markerHandle); - if (line >= 0) { - linesData[line].handleSet->RemoveHandle(markerHandle); - if (linesData[line].handleSet->Length() == 0) { - delete linesData[line].handleSet; - linesData[line].handleSet = 0; - } - } -} - -int LineVector::LineFromHandle(int markerHandle) { - for (int line = 0; line < lines; line++) { - if (linesData[line].handleSet) { - if (linesData[line].handleSet->Contains(markerHandle)) { - return line; - } - } - } - return - 1; -} - -Action::Action() { - at = startAction; - position = 0; - data = 0; - lenData = 0; -} - -Action::~Action() { - Destroy(); -} - -void Action::Create(actionType at_, int position_, char *data_, int lenData_) { - delete []data; - position = position_; - at = at_; - data = data_; - lenData = lenData_; -} - -void Action::Destroy() { - delete []data; - data = 0; -} - -void Action::Grab(Action *source) { - delete []data; - - position = source->position; - at = source->at; - data = source->data; - lenData = source->lenData; - - // Ownership of source data transferred to this - source->position = 0; - source->at = startAction; - source->data = 0; - source->lenData = 0; -} - -// The undo history stores a sequence of user operations that represent the user's view of the -// commands executed on the text. -// Each user operation contains a sequence of text insertion and text deletion actions. -// All the user operations are stored in a list of individual actions with 'start' actions used -// as delimiters between user operations. -// Initially there is one start action in the history. -// As each action is performed, it is recorded in the history. The action may either become -// part of the current user operation or may start a new user operation. If it is to be part of the -// current operation, then it overwrites the current last action. If it is to be part of a new -// operation, it is appended after the current last action. -// After writing the new action, a new start action is appended at the end of the history. -// The decision of whether to start a new user operation is based upon two factors. If a -// compound operation has been explicitly started by calling BeginUndoAction and no matching -// EndUndoAction (these calls nest) has been called, then the action is coalesced into the current -// operation. If there is no outstanding BeginUndoAction call then a new operation is started -// unless it looks as if the new action is caused by the user typing or deleting a stream of text. -// Sequences that look like typing or deletion are coalesced into a single user operation. - -UndoHistory::UndoHistory() { - - lenActions = 100; - actions = new Action[lenActions]; - maxAction = 0; - currentAction = 0; - undoSequenceDepth = 0; - savePoint = 0; - - actions[currentAction].Create(startAction); -} - -UndoHistory::~UndoHistory() { - delete []actions; - actions = 0; -} - -void UndoHistory::EnsureUndoRoom() { - //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, length, currentAction); - if (currentAction >= 2) { - // Have to test that there is room for 2 more actions in the array - // as two actions may be created by this function - if (currentAction >= (lenActions - 2)) { - // Run out of undo nodes so extend the array - int lenActionsNew = lenActions * 2; - Action *actionsNew = new Action[lenActionsNew]; - if (!actionsNew) - return; - for (int act = 0; act <= currentAction; act++) - actionsNew[act].Grab(&actions[act]); - delete []actions; - lenActions = lenActionsNew; - actions = actionsNew; - } - } -} - -void UndoHistory::AppendAction(actionType at, int position, char *data, int lengthData) { - EnsureUndoRoom(); - Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction); - Platform::DebugPrintf("^ %d action %d %d\n", actions[currentAction - 1].at, - actions[currentAction - 1].position, actions[currentAction - 1].lenData); - if (currentAction >= 1) { - if (0 == undoSequenceDepth) { - // Top level actions may not always be coalesced - Action &actPrevious = actions[currentAction - 1]; - // See if current action can be coalesced into previous action - // Will work if both are inserts or deletes and position is same - if (at != actPrevious.at) { - currentAction++; - } else if (currentAction == savePoint) { - currentAction++; - } else if ((at == removeAction) && - ((position + lengthData * 2) != actPrevious.position)) { - // Removals must be at same position to coalesce - currentAction++; - } else if ((at == insertAction) && - (position != (actPrevious.position + actPrevious.lenData*2))) { - // Insertions must be immediately after to coalesce - currentAction++; - } else { - Platform::DebugPrintf("action coalesced\n"); - } - } else { - currentAction++; - } - } else { - currentAction++; - } - actions[currentAction].Create(at, position, data, lengthData); - currentAction++; - actions[currentAction].Create(startAction); - maxAction = currentAction; -} - -void UndoHistory::BeginUndoAction() { - EnsureUndoRoom(); - if (undoSequenceDepth == 0) { - if (actions[currentAction].at != startAction) { - currentAction++; - actions[currentAction].Create(startAction); - maxAction = currentAction; - } - } - undoSequenceDepth++; -} - -void UndoHistory::EndUndoAction() { - EnsureUndoRoom(); - undoSequenceDepth--; - if (0 == undoSequenceDepth) { - if (actions[currentAction].at != startAction) { - currentAction++; - actions[currentAction].Create(startAction); - maxAction = currentAction; - } - } -} - -void UndoHistory::DropUndoSequence() { - undoSequenceDepth = 0; -} - -void UndoHistory::DeleteUndoHistory() { - for (int i = 1; i < maxAction; i++) - actions[i].Destroy(); - maxAction = 0; - currentAction = 0; - actions[currentAction].Create(startAction); - savePoint = 0; -} - -void UndoHistory::SetSavePoint() { - savePoint = currentAction; -} - -bool UndoHistory::IsSavePoint() const { - return savePoint == currentAction; -} - -bool UndoHistory::CanUndo() const { - return (currentAction > 0) && (maxAction > 0); -} - -int UndoHistory::StartUndo() { - // Drop any trailing startAction - if (actions[currentAction].at == startAction && currentAction > 0) - currentAction--; - - // Count the steps in this action - int act = currentAction; - while (actions[act].at != startAction && act > 0) { - act--; - } - return currentAction - act; -} - -const Action &UndoHistory::UndoStep() { - return actions[currentAction--]; -} - -bool UndoHistory::CanRedo() const { - return maxAction > currentAction; -} - -int UndoHistory::StartRedo() { - // Drop any leading startAction - if (actions[currentAction].at == startAction && currentAction < maxAction) - currentAction++; - - // Count the steps in this action - int act = currentAction; - while (actions[act].at != startAction && act < maxAction) { - act++; - } - return act - currentAction; -} - -const Action &UndoHistory::RedoStep() { - return actions[currentAction++]; -} - -CellBuffer::CellBuffer(int initialLength) { - body = new char[initialLength]; - size = initialLength; - length = 0; - part1len = 0; - gaplen = initialLength; - part2body = body + gaplen; - readOnly = false; - collectingUndo = undoCollectAutoStart; -} - -CellBuffer::~CellBuffer() { - delete []body; - body = 0; -} - -void CellBuffer::GapTo(int position) { - if (position == part1len) - return; - if (position < part1len) { - int diff = part1len - position; - //Platform::DebugPrintf("Move gap backwards to %d diff = %d part1len=%d length=%d \n", position,diff, part1len, length); - for (int i = 0; i < diff; i++) - body[part1len + gaplen - i - 1] = body[part1len - i - 1]; - } else { // position > part1len - int diff = position - part1len; - //Platform::DebugPrintf("Move gap forwards to %d diff =%d\n", position,diff); - for (int i = 0; i < diff; i++) - body[part1len + i] = body[part1len + gaplen + i]; - } - part1len = position; - part2body = body + gaplen; -} - -void CellBuffer::RoomFor(int insertionLength) { - //Platform::DebugPrintf("need room %d %d\n", gaplen, insertionLength); - if (gaplen <= insertionLength) { - //Platform::DebugPrintf("need room %d %d\n", gaplen, insertionLength); - GapTo(length); - int newSize = size + insertionLength + 4000; - //Platform::DebugPrintf("moved gap %d\n", newSize); - char *newBody = new char[newSize]; - memcpy(newBody, body, size); - delete []body; - body = newBody; - gaplen += newSize - size; - part2body = body + gaplen; - size = newSize; - //Platform::DebugPrintf("end need room %d %d - size=%d length=%d\n", gaplen, insertionLength,size,length); - } -} - -// To make it easier to write code that uses ByteAt, a position outside the range of the buffer -// can be retrieved. All characters outside the range have the value '\0'. -char CellBuffer::ByteAt(int position) { - if (position < part1len) { - if (position < 0) { - return '\0'; - } else { - return body[position]; - } - } else { - if (position >= length) { - return '\0'; - } else { - return part2body[position]; - } - } -} - -void CellBuffer::SetByteAt(int position, char ch) { - - if (position < 0) { - //Platform::DebugPrintf("Bad position %d\n",position); - return; - } - if (position >= length + 11) { - Platform::DebugPrintf("Very Bad position %d of %d\n", position, length); - //exit(2); - return; - } - if (position >= length) { - //Platform::DebugPrintf("Bad position %d of %d\n",position,length); - return; - } - - if (position < part1len) { - body[position] = ch; - } else { - part2body[position] = ch; - } -} - -char CellBuffer::CharAt(int position) { - return ByteAt(position*2); -} - -void CellBuffer::GetCharRange(char *buffer, int position, int lengthRetrieve) { - if (lengthRetrieve < 0) - return; - if (position < 0) - return; - int bytePos = position * 2; - if ((bytePos + lengthRetrieve * 2) > length) { - Platform::DebugPrintf("Bad GetCharRange %d for %d of %d\n",bytePos, - lengthRetrieve, length); - return; - } - GapTo(0); // Move the buffer so its easy to subscript into it - char *pb = part2body + bytePos; - while (lengthRetrieve--) { - *buffer++ = *pb; - pb +=2; - } -} - -char CellBuffer::StyleAt(int position) { - return ByteAt(position*2 + 1); -} - -const char *CellBuffer::InsertString(int position, char *s, int insertLength) { - char *data = 0; - // InsertString and DeleteChars are the bottleneck though which all changes occur - if (!readOnly) { - if (collectingUndo) { - // Save into the undo/redo stack, but only the characters - not the formatting - // This takes up about half load time - data = new char[insertLength / 2]; - for (int i = 0; i < insertLength / 2; i++) { - data[i] = s[i * 2]; - } - uh.AppendAction(insertAction, position, data, insertLength / 2); - } - - BasicInsertString(position, s, insertLength); - } - return data; -} - -void CellBuffer::InsertCharStyle(int position, char ch, char style) { - char s[2]; - s[0] = ch; - s[1] = style; - InsertString(position*2, s, 2); -} - -bool CellBuffer::SetStyleAt(int position, char style, char mask) { - char curVal = ByteAt(position*2 + 1); - if ((curVal & mask) != style) { - SetByteAt(position*2 + 1, (curVal & ~mask) | style); - return true; - } else { - return false; - } -} - -bool CellBuffer::SetStyleFor(int position, int lengthStyle, char style, char mask) { - int bytePos = position * 2 + 1; - bool changed = false; - while (lengthStyle--) { - char curVal = ByteAt(bytePos); - if ((curVal & mask) != style) { - SetByteAt(bytePos, (curVal & ~mask) | style); - changed = true; - } - bytePos += 2; - } - return changed; -} - -const char *CellBuffer::DeleteChars(int position, int deleteLength) { - // InsertString and DeleteChars are the bottleneck though which all changes occur - char *data = 0; - if (!readOnly) { - if (collectingUndo) { - // Save into the undo/redo stack, but only the characters - not the formatting - data = new char[deleteLength / 2]; - for (int i = 0; i < deleteLength / 2; i++) { - data[i] = ByteAt(position + i * 2); - } - uh.AppendAction(removeAction, position, data, deleteLength / 2); - } - - BasicDeleteChars(position, deleteLength); - } - return data; -} - -int CellBuffer::ByteLength() { - return length; -} - -int CellBuffer::Length() { - return ByteLength() / 2; -} - -int CellBuffer::Lines() { - //Platform::DebugPrintf("Lines = %d\n", lv.lines); - return lv.lines; -} - -int CellBuffer::LineStart(int line) { - if (line < 0) - return 0; - else if (line > lv.lines) - return length; - else - return lv.linesData[line].startPosition; -} - -bool CellBuffer::IsReadOnly() { - return readOnly; -} - -void CellBuffer::SetReadOnly(bool set) { - readOnly = set; -} - -void CellBuffer::SetSavePoint() { - uh.SetSavePoint(); -} - -bool CellBuffer::IsSavePoint() { - return uh.IsSavePoint(); -} - -int CellBuffer::AddMark(int line, int markerNum) { - if ((line >= 0) && (line < lv.lines)) { - return lv.AddMark(line, markerNum); - } - return - 1; -} - -void CellBuffer::DeleteMark(int line, int markerNum) { - if ((line >= 0) && (line < lv.lines)) { - lv.DeleteMark(line, markerNum); - } -} - -void CellBuffer::DeleteMarkFromHandle(int markerHandle) { - lv.DeleteMarkFromHandle(markerHandle); -} - -int CellBuffer::GetMark(int line) { - if ((line >= 0) && (line < lv.lines) && (lv.linesData[line].handleSet)) - return lv.linesData[line].handleSet->MarkValue(); - return 0; -} - -void CellBuffer::DeleteAllMarks(int markerNum) { - for (int line = 0; line < lv.lines; line++) { - lv.DeleteMark(line, markerNum); - } -} - -int CellBuffer::LineFromHandle(int markerHandle) { - return lv.LineFromHandle(markerHandle); -} - -// Without undo - -void CellBuffer::BasicInsertString(int position, char *s, int insertLength) { - Platform::DebugPrintf("Inserting at %d for %d\n", position, insertLength); - if (insertLength == 0) - return; - RoomFor(insertLength); - GapTo(position); - - memcpy(body + part1len, s, insertLength); - length += insertLength; - part1len += insertLength; - gaplen -= insertLength; - part2body = body + gaplen; - - int lineInsert = lv.LineFromPosition(position / 2) + 1; - // Point all the lines after the insertion point further along in the buffer - for (int lineAfter = lineInsert; lineAfter <= lv.lines; lineAfter++) { - lv.linesData[lineAfter].startPosition += insertLength / 2; - } - char chPrev = ' '; - if ((position - 2) >= 0) - chPrev = ByteAt(position - 2); - char chAfter = ' '; - if ((position + insertLength) < length) - chAfter = ByteAt(position + insertLength); - if (chPrev == '\r' && chAfter == '\n') { - //Platform::DebugPrintf("Splitting a crlf pair at %d\n", lineInsert); - // Splitting up a crlf pair at position - lv.InsertValue(lineInsert, position / 2); - lineInsert++; - } - char ch = ' '; - for (int i = 0; i < insertLength; i += 2) { - ch = s[i]; - if (ch == '\r') { - //Platform::DebugPrintf("Inserting cr at %d\n", lineInsert); - lv.InsertValue(lineInsert, (position + i) / 2 + 1); - lineInsert++; - } else if (ch == '\n') { - if (chPrev == '\r') { - //Platform::DebugPrintf("Patching cr before lf at %d\n", lineInsert-1); - // Patch up what was end of line - lv.SetValue(lineInsert - 1, (position + i) / 2 + 1); - } else { - //Platform::DebugPrintf("Inserting lf at %d\n", lineInsert); - lv.InsertValue(lineInsert, (position + i) / 2 + 1); - lineInsert++; - } - } - chPrev = ch; - } - // Joining two lines where last insertion is cr and following text starts with lf - if (chAfter == '\n') { - if (ch == '\r') { - //Platform::DebugPrintf("Joining cr before lf at %d\n", lineInsert-1); - // End of line already in buffer so drop the newly created one - lv.Remove(lineInsert - 1); - } - } -} - -void CellBuffer::BasicDeleteChars(int position, int deleteLength) { - Platform::DebugPrintf("Deleting at %d for %d\n", position, deleteLength); - if (deleteLength == 0) - return; - - if ((position == 0) && (deleteLength == length)) { - // If whole buffer is being deleted, faster to reinitialise lines data - // than to delete each line. - //printf("Whole buffer being deleted\n"); - lv.Init(); - } else { - // Have to fix up line positions before doing deletion as looking at text in buffer - // to work out which lines have been removed - - int lineRemove = lv.LineFromPosition(position / 2) + 1; - // Point all the lines after the insertion point further along in the buffer - for (int lineAfter = lineRemove; lineAfter <= lv.lines; lineAfter++) { - lv.linesData[lineAfter].startPosition -= deleteLength / 2; - } - char chPrev = ' '; - if (position >= 2) - chPrev = ByteAt(position - 2); - char chBefore = chPrev; - char chNext = ' '; - if (position < length) - chNext = ByteAt(position); - bool ignoreNL = false; - if (chPrev == '\r' && chNext == '\n') { - //Platform::DebugPrintf("Deleting lf after cr, move line end to cr at %d\n", lineRemove); - // Move back one - lv.SetValue(lineRemove, position / 2); - lineRemove++; - ignoreNL = true; // First \n is not real deletion - } - - char ch = chNext; - for (int i = 0; i < deleteLength; i += 2) { - chNext = ' '; - if ((position + i + 2) < length) - chNext = ByteAt(position + i + 2); - //Platform::DebugPrintf("Deleting %d %x\n", i, ch); - if (ch == '\r') { - if (chNext != '\n') { - //Platform::DebugPrintf("Removing cr end of line\n"); - lv.Remove(lineRemove); - } - } else if ((ch == '\n') && !ignoreNL) { - //Platform::DebugPrintf("Removing lf end of line\n"); - lv.Remove(lineRemove); - ignoreNL = false; // Further \n are not real deletions - } - - ch = chNext; - } - // May have to fix up end if last deletion causes cr to be next to lf - // or removes one of a crlf pair - char chAfter = ' '; - if ((position + deleteLength) < length) - chAfter = ByteAt(position + deleteLength); - if (chBefore == '\r' && chAfter == '\n') { - //d.printf("Joining cr before lf at %d\n", lineRemove); - // Using lineRemove-1 as cr ended line before start of deletion - lv.Remove(lineRemove - 1); - lv.SetValue(lineRemove - 1, position / 2 + 1); - } - } - GapTo(position); - length -= deleteLength; - gaplen += deleteLength; - part2body = body + gaplen; -} - -undoCollectionType CellBuffer::SetUndoCollection(undoCollectionType collectUndo) { - collectingUndo = collectUndo; - uh.DropUndoSequence(); - return collectingUndo; -} - -bool CellBuffer::IsCollectingUndo() { - return collectingUndo; -} - -void CellBuffer::BeginUndoAction() { - uh.BeginUndoAction(); -} - -void CellBuffer::EndUndoAction() { - uh.EndUndoAction(); -} - -void CellBuffer::DeleteUndoHistory() { - uh.DeleteUndoHistory(); -} - -bool CellBuffer::CanUndo() { - return (!readOnly) && (uh.CanUndo()); -} - -int CellBuffer::StartUndo() { - return uh.StartUndo(); -} - -const Action &CellBuffer::UndoStep() { - const Action &actionStep = uh.UndoStep(); - if (actionStep.at == insertAction) { - BasicDeleteChars(actionStep.position, actionStep.lenData*2); - } else if (actionStep.at == removeAction) { - char *styledData = new char[actionStep.lenData * 2]; - for (int i = 0; i < actionStep.lenData; i++) { - styledData[i*2] = actionStep.data[i]; - styledData[i*2+1] = 0; - } - BasicInsertString(actionStep.position, styledData, actionStep.lenData*2); - delete []styledData; - } - return actionStep; -} - -bool CellBuffer::CanRedo() { - return (!readOnly) && (uh.CanRedo()); -} - -int CellBuffer::StartRedo() { - return uh.StartRedo(); -} - -const Action &CellBuffer::RedoStep() { - const Action &actionStep = uh.RedoStep(); - if (actionStep.at == insertAction) { - char *styledData = new char[actionStep.lenData * 2]; - for (int i = 0; i < actionStep.lenData; i++) { - styledData[i*2] = actionStep.data[i]; - styledData[i*2+1] = 0; - } - BasicInsertString(actionStep.position, styledData, actionStep.lenData*2); - delete []styledData; - } else if (actionStep.at == removeAction) { - BasicDeleteChars(actionStep.position, actionStep.lenData*2); - } - return actionStep; -} - -int CellBuffer::SetLineState(int line, int state) { - int stateOld = lineStates[line]; - lineStates[line] = state; - return stateOld; -} - -int CellBuffer::GetLineState(int line) { - return lineStates[line]; -} - -int CellBuffer::GetMaxLineState() { - return lineStates.Length(); -} - -int CellBuffer::SetLevel(int line, int level) { - int prev = 0; - if ((line >= 0) && (line < lv.lines)) { - if (!lv.levels) { - lv.ExpandLevels(); - } - prev = lv.levels[line]; - if (lv.levels[line] != level) { - lv.levels[line] = level; - } - } - return prev; -} - -int CellBuffer::GetLevel(int line) { - if (lv.levels && (line >= 0) && (line < lv.lines)) { - return lv.levels[line]; - } else { - return SC_FOLDLEVELBASE; - } -} - +// Scintilla source code edit control
+// CellBuffer.cxx - manages a buffer of cells
+// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "Platform.h"
+
+#include "Scintilla.h"
+#include "SVector.h"
+#include "CellBuffer.h"
+
+MarkerHandleSet::MarkerHandleSet() {
+ root = 0;
+}
+
+MarkerHandleSet::~MarkerHandleSet() {
+ MarkerHandleNumber *mhn = root;
+ while (mhn) {
+ MarkerHandleNumber *mhnToFree = mhn;
+ mhn = mhn->next;
+ delete mhnToFree;
+ }
+ root = 0;
+}
+
+int MarkerHandleSet::Length() {
+ int c = 0;
+ MarkerHandleNumber *mhn = root;
+ while (mhn) {
+ c++;
+ mhn = mhn->next;
+ }
+ return c;
+}
+
+int MarkerHandleSet::NumberFromHandle(int handle) {
+ MarkerHandleNumber *mhn = root;
+ while (mhn) {
+ if (mhn->handle == handle) {
+ return mhn->number;
+ }
+ mhn = mhn->next;
+ }
+ return - 1;
+}
+
+int MarkerHandleSet::MarkValue() {
+ unsigned int m = 0;
+ MarkerHandleNumber *mhn = root;
+ while (mhn) {
+ m |= (1 << mhn->number);
+ mhn = mhn->next;
+ }
+ return m;
+}
+
+bool MarkerHandleSet::Contains(int handle) {
+ MarkerHandleNumber *mhn = root;
+ while (mhn) {
+ if (mhn->handle == handle) {
+ return true;
+ }
+ mhn = mhn->next;
+ }
+ return false;
+}
+
+bool MarkerHandleSet::InsertHandle(int handle, int markerNum) {
+ MarkerHandleNumber *mhn = new MarkerHandleNumber;
+ if (!mhn)
+ return false;
+ mhn->handle = handle;
+ mhn->number = markerNum;
+ mhn->next = root;
+ root = mhn;
+ return true;
+}
+
+void MarkerHandleSet::RemoveHandle(int handle) {
+ MarkerHandleNumber **pmhn = &root;
+ while (*pmhn) {
+ MarkerHandleNumber *mhn = *pmhn;
+ if (mhn->handle == handle) {
+ *pmhn = mhn->next;
+ delete mhn;
+ return;
+ }
+ pmhn = &((*pmhn)->next);
+ }
+}
+
+void MarkerHandleSet::RemoveNumber(int markerNum) {
+ MarkerHandleNumber **pmhn = &root;
+ while (*pmhn) {
+ MarkerHandleNumber *mhn = *pmhn;
+ if (mhn->number == markerNum) {
+ *pmhn = mhn->next;
+ delete mhn;
+ return;
+ }
+ pmhn = &((*pmhn)->next);
+ }
+}
+
+void MarkerHandleSet::CombineWith(MarkerHandleSet *other) {
+ MarkerHandleNumber **pmhn = &root;
+ while (*pmhn) {
+ pmhn = &((*pmhn)->next);
+ }
+ *pmhn = other->root;
+ other->root = 0;
+}
+
+LineVector::LineVector() {
+ linesData = 0;
+ lines = 0;
+ levels = 0;
+ Init();
+}
+
+LineVector::~LineVector() {
+ for (int line = 0; line < lines; line++) {
+ delete linesData[line].handleSet;
+ linesData[line].handleSet = 0;
+ }
+ delete []linesData;
+ linesData = 0;
+ delete []levels;
+ levels = 0;
+}
+
+void LineVector::Init() {
+ for (int line = 0; line < lines; line++) {
+ delete linesData[line].handleSet;
+ linesData[line].handleSet = 0;
+ }
+ delete []linesData;
+ linesData = new LineData[static_cast<int>(growSize)];
+ size = growSize;
+ lines = 1;
+ delete []levels;
+ levels = 0;
+ sizeLevels = 0;
+}
+
+void LineVector::Expand(int sizeNew) {
+ LineData *linesDataNew = new LineData[sizeNew];
+ if (linesDataNew) {
+ for (int i = 0; i < size; i++)
+ linesDataNew[i] = linesData[i];
+ // Do not delete handleSets here as they are transferred to new linesData
+ delete []linesData;
+ linesData = linesDataNew;
+ size = sizeNew;
+ } else {
+ Platform::DebugPrintf("No memory available\n");
+ // TODO: Blow up
+ }
+}
+
+void LineVector::ExpandLevels(int sizeNew) {
+ if (sizeNew == -1)
+ sizeNew = size;
+ int *levelsNew = new int[sizeNew];
+ if (levelsNew) {
+ int i = 0;
+ for (; i < sizeLevels; i++)
+ levelsNew[i] = levels[i];
+ for (; i < sizeNew; i++)
+ levelsNew[i] = SC_FOLDLEVELBASE;
+ delete []levels;
+ levels = levelsNew;
+ sizeLevels = sizeNew;
+ } else {
+ Platform::DebugPrintf("No memory available\n");
+ // TODO: Blow up
+ }
+}
+
+void LineVector::InsertValue(int pos, int value) {
+ //Platform::DebugPrintf("InsertValue[%d] = %d\n", pos, value);
+ if ((lines + 2) >= size) {
+ Expand(size + growSize);
+ if (levels) {
+ ExpandLevels(size + growSize);
+ }
+ }
+ lines++;
+ for (int i = lines + 1; i > pos; i--) {
+ linesData[i] = linesData[i - 1];
+ }
+ linesData[pos].startPosition = value;
+ linesData[pos].handleSet = 0;
+}
+
+void LineVector::SetValue(int pos, int value) {
+ //Platform::DebugPrintf("SetValue[%d] = %d\n", pos, value);
+ if ((pos + 2) >= size) {
+ //Platform::DebugPrintf("Resize %d %d\n", size,pos);
+ Expand(pos + growSize);
+ //Platform::DebugPrintf("end Resize %d %d\n", size,pos);
+ lines = pos;
+ if (levels) {
+ ExpandLevels(pos + growSize);
+ }
+ }
+ linesData[pos].startPosition = value;
+}
+
+void LineVector::Remove(int pos) {
+ //Platform::DebugPrintf("Remove %d\n", pos);
+ // Retain the markers from the deleted line by oring them into the previous line
+ if (pos > 0) {
+ MergeMarkers(pos - 1);
+ }
+ for (int i = pos; i < lines; i++) {
+ linesData[i] = linesData[i + 1];
+ }
+ lines--;
+}
+
+int LineVector::LineFromPosition(int pos) {
+ //Platform::DebugPrintf("LineFromPostion %d lines=%d end = %d\n", pos, lines, linesData[lines].startPosition);
+ if (lines == 0)
+ return 0;
+ //Platform::DebugPrintf("LineFromPosition %d\n", pos);
+ if (pos >= linesData[lines].startPosition)
+ return lines - 1;
+ int lower = 0;
+ int upper = lines;
+ int middle = 0;
+ do {
+ middle = (upper + lower + 1) / 2; // Round high
+ if (pos < linesData[middle].startPosition) {
+ upper = middle - 1;
+ } else {
+ lower = middle;
+ }
+ } while (lower < upper);
+ //Platform::DebugPrintf("LineFromPostion %d %d %d\n", pos, lower, linesData[lower].startPosition, linesData[lower > 1 ? lower - 1 : 0].startPosition);
+ return lower;
+}
+
+int LineVector::AddMark(int line, int markerNum) {
+ handleCurrent++;
+ if (!linesData[line].handleSet) {
+ // Need new structure to hold marker handle
+ linesData[line].handleSet = new MarkerHandleSet;
+ if (!linesData[line].handleSet)
+ return - 1;
+ }
+ linesData[line].handleSet->InsertHandle(handleCurrent, markerNum);
+
+ return handleCurrent;
+}
+
+void LineVector::MergeMarkers(int pos) {
+ if (linesData[pos].handleSet || linesData[pos + 1].handleSet) {
+ if (linesData[pos].handleSet && linesData[pos + 1].handleSet) {
+ linesData[pos].handleSet->CombineWith(linesData[pos].handleSet);
+ linesData[pos].handleSet = 0;
+ }
+ }
+}
+
+void LineVector::DeleteMark(int line, int markerNum) {
+ if (linesData[line].handleSet) {
+ if (markerNum == -1) {
+ delete linesData[line].handleSet;
+ linesData[line].handleSet = 0;
+ } else {
+ linesData[line].handleSet->RemoveNumber(markerNum);
+ if (linesData[line].handleSet->Length() == 0) {
+ delete linesData[line].handleSet;
+ linesData[line].handleSet = 0;
+ }
+ }
+ }
+}
+
+void LineVector::DeleteMarkFromHandle(int markerHandle) {
+ int line = LineFromHandle(markerHandle);
+ if (line >= 0) {
+ linesData[line].handleSet->RemoveHandle(markerHandle);
+ if (linesData[line].handleSet->Length() == 0) {
+ delete linesData[line].handleSet;
+ linesData[line].handleSet = 0;
+ }
+ }
+}
+
+int LineVector::LineFromHandle(int markerHandle) {
+ for (int line = 0; line < lines; line++) {
+ if (linesData[line].handleSet) {
+ if (linesData[line].handleSet->Contains(markerHandle)) {
+ return line;
+ }
+ }
+ }
+ return - 1;
+}
+
+Action::Action() {
+ at = startAction;
+ position = 0;
+ data = 0;
+ lenData = 0;
+}
+
+Action::~Action() {
+ Destroy();
+}
+
+void Action::Create(actionType at_, int position_, char *data_, int lenData_) {
+ delete []data;
+ position = position_;
+ at = at_;
+ data = data_;
+ lenData = lenData_;
+}
+
+void Action::Destroy() {
+ delete []data;
+ data = 0;
+}
+
+void Action::Grab(Action *source) {
+ delete []data;
+
+ position = source->position;
+ at = source->at;
+ data = source->data;
+ lenData = source->lenData;
+
+ // Ownership of source data transferred to this
+ source->position = 0;
+ source->at = startAction;
+ source->data = 0;
+ source->lenData = 0;
+}
+
+// The undo history stores a sequence of user operations that represent the user's view of the
+// commands executed on the text.
+// Each user operation contains a sequence of text insertion and text deletion actions.
+// All the user operations are stored in a list of individual actions with 'start' actions used
+// as delimiters between user operations.
+// Initially there is one start action in the history.
+// As each action is performed, it is recorded in the history. The action may either become
+// part of the current user operation or may start a new user operation. If it is to be part of the
+// current operation, then it overwrites the current last action. If it is to be part of a new
+// operation, it is appended after the current last action.
+// After writing the new action, a new start action is appended at the end of the history.
+// The decision of whether to start a new user operation is based upon two factors. If a
+// compound operation has been explicitly started by calling BeginUndoAction and no matching
+// EndUndoAction (these calls nest) has been called, then the action is coalesced into the current
+// operation. If there is no outstanding BeginUndoAction call then a new operation is started
+// unless it looks as if the new action is caused by the user typing or deleting a stream of text.
+// Sequences that look like typing or deletion are coalesced into a single user operation.
+
+UndoHistory::UndoHistory() {
+
+ lenActions = 100;
+ actions = new Action[lenActions];
+ maxAction = 0;
+ currentAction = 0;
+ undoSequenceDepth = 0;
+ savePoint = 0;
+
+ actions[currentAction].Create(startAction);
+}
+
+UndoHistory::~UndoHistory() {
+ delete []actions;
+ actions = 0;
+}
+
+void UndoHistory::EnsureUndoRoom() {
+ //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, length, currentAction);
+ if (currentAction >= 2) {
+ // Have to test that there is room for 2 more actions in the array
+ // as two actions may be created by this function
+ if (currentAction >= (lenActions - 2)) {
+ // Run out of undo nodes so extend the array
+ int lenActionsNew = lenActions * 2;
+ Action *actionsNew = new Action[lenActionsNew];
+ if (!actionsNew)
+ return;
+ for (int act = 0; act <= currentAction; act++)
+ actionsNew[act].Grab(&actions[act]);
+ delete []actions;
+ lenActions = lenActionsNew;
+ actions = actionsNew;
+ }
+ }
+}
+
+void UndoHistory::AppendAction(actionType at, int position, char *data, int lengthData) {
+ EnsureUndoRoom();
+ //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction);
+ //Platform::DebugPrintf("^ %d action %d %d\n", actions[currentAction - 1].at,
+ // actions[currentAction - 1].position, actions[currentAction - 1].lenData);
+ if (currentAction >= 1) {
+ if (0 == undoSequenceDepth) {
+ // Top level actions may not always be coalesced
+ Action &actPrevious = actions[currentAction - 1];
+ // See if current action can be coalesced into previous action
+ // Will work if both are inserts or deletes and position is same
+ if (at != actPrevious.at) {
+ currentAction++;
+ } else if (currentAction == savePoint) {
+ currentAction++;
+ } else if ((at == removeAction) &&
+ ((position + lengthData * 2) != actPrevious.position)) {
+ // Removals must be at same position to coalesce
+ currentAction++;
+ } else if ((at == insertAction) &&
+ (position != (actPrevious.position + actPrevious.lenData*2))) {
+ // Insertions must be immediately after to coalesce
+ currentAction++;
+ } else {
+ //Platform::DebugPrintf("action coalesced\n");
+ }
+ } else {
+ currentAction++;
+ }
+ } else {
+ currentAction++;
+ }
+ actions[currentAction].Create(at, position, data, lengthData);
+ currentAction++;
+ actions[currentAction].Create(startAction);
+ maxAction = currentAction;
+}
+
+void UndoHistory::BeginUndoAction() {
+ EnsureUndoRoom();
+ if (undoSequenceDepth == 0) {
+ if (actions[currentAction].at != startAction) {
+ currentAction++;
+ actions[currentAction].Create(startAction);
+ maxAction = currentAction;
+ }
+ }
+ undoSequenceDepth++;
+}
+
+void UndoHistory::EndUndoAction() {
+ EnsureUndoRoom();
+ undoSequenceDepth--;
+ if (0 == undoSequenceDepth) {
+ if (actions[currentAction].at != startAction) {
+ currentAction++;
+ actions[currentAction].Create(startAction);
+ maxAction = currentAction;
+ }
+ }
+}
+
+void UndoHistory::DropUndoSequence() {
+ undoSequenceDepth = 0;
+}
+
+void UndoHistory::DeleteUndoHistory() {
+ for (int i = 1; i < maxAction; i++)
+ actions[i].Destroy();
+ maxAction = 0;
+ currentAction = 0;
+ actions[currentAction].Create(startAction);
+ savePoint = 0;
+}
+
+void UndoHistory::SetSavePoint() {
+ savePoint = currentAction;
+}
+
+bool UndoHistory::IsSavePoint() const {
+ return savePoint == currentAction;
+}
+
+bool UndoHistory::CanUndo() const {
+ return (currentAction > 0) && (maxAction > 0);
+}
+
+int UndoHistory::StartUndo() {
+ // Drop any trailing startAction
+ if (actions[currentAction].at == startAction && currentAction > 0)
+ currentAction--;
+
+ // Count the steps in this action
+ int act = currentAction;
+ while (actions[act].at != startAction && act > 0) {
+ act--;
+ }
+ return currentAction - act;
+}
+
+const Action &UndoHistory::UndoStep() {
+ return actions[currentAction--];
+}
+
+bool UndoHistory::CanRedo() const {
+ return maxAction > currentAction;
+}
+
+int UndoHistory::StartRedo() {
+ // Drop any leading startAction
+ if (actions[currentAction].at == startAction && currentAction < maxAction)
+ currentAction++;
+
+ // Count the steps in this action
+ int act = currentAction;
+ while (actions[act].at != startAction && act < maxAction) {
+ act++;
+ }
+ return act - currentAction;
+}
+
+const Action &UndoHistory::RedoStep() {
+ return actions[currentAction++];
+}
+
+CellBuffer::CellBuffer(int initialLength) {
+ body = new char[initialLength];
+ size = initialLength;
+ length = 0;
+ part1len = 0;
+ gaplen = initialLength;
+ part2body = body + gaplen;
+ readOnly = false;
+ collectingUndo = undoCollectAutoStart;
+}
+
+CellBuffer::~CellBuffer() {
+ delete []body;
+ body = 0;
+}
+
+void CellBuffer::GapTo(int position) {
+ if (position == part1len)
+ return;
+ if (position < part1len) {
+ int diff = part1len - position;
+ //Platform::DebugPrintf("Move gap backwards to %d diff = %d part1len=%d length=%d \n", position,diff, part1len, length);
+ for (int i = 0; i < diff; i++)
+ body[part1len + gaplen - i - 1] = body[part1len - i - 1];
+ } else { // position > part1len
+ int diff = position - part1len;
+ //Platform::DebugPrintf("Move gap forwards to %d diff =%d\n", position,diff);
+ for (int i = 0; i < diff; i++)
+ body[part1len + i] = body[part1len + gaplen + i];
+ }
+ part1len = position;
+ part2body = body + gaplen;
+}
+
+void CellBuffer::RoomFor(int insertionLength) {
+ //Platform::DebugPrintf("need room %d %d\n", gaplen, insertionLength);
+ if (gaplen <= insertionLength) {
+ //Platform::DebugPrintf("need room %d %d\n", gaplen, insertionLength);
+ GapTo(length);
+ int newSize = size + insertionLength + 4000;
+ //Platform::DebugPrintf("moved gap %d\n", newSize);
+ char *newBody = new char[newSize];
+ memcpy(newBody, body, size);
+ delete []body;
+ body = newBody;
+ gaplen += newSize - size;
+ part2body = body + gaplen;
+ size = newSize;
+ //Platform::DebugPrintf("end need room %d %d - size=%d length=%d\n", gaplen, insertionLength,size,length);
+ }
+}
+
+// To make it easier to write code that uses ByteAt, a position outside the range of the buffer
+// can be retrieved. All characters outside the range have the value '\0'.
+char CellBuffer::ByteAt(int position) {
+ if (position < part1len) {
+ if (position < 0) {
+ return '\0';
+ } else {
+ return body[position];
+ }
+ } else {
+ if (position >= length) {
+ return '\0';
+ } else {
+ return part2body[position];
+ }
+ }
+}
+
+void CellBuffer::SetByteAt(int position, char ch) {
+
+ if (position < 0) {
+ //Platform::DebugPrintf("Bad position %d\n",position);
+ return;
+ }
+ if (position >= length + 11) {
+ Platform::DebugPrintf("Very Bad position %d of %d\n", position, length);
+ //exit(2);
+ return;
+ }
+ if (position >= length) {
+ //Platform::DebugPrintf("Bad position %d of %d\n",position,length);
+ return;
+ }
+
+ if (position < part1len) {
+ body[position] = ch;
+ } else {
+ part2body[position] = ch;
+ }
+}
+
+char CellBuffer::CharAt(int position) {
+ return ByteAt(position*2);
+}
+
+void CellBuffer::GetCharRange(char *buffer, int position, int lengthRetrieve) {
+ if (lengthRetrieve < 0)
+ return;
+ if (position < 0)
+ return;
+ int bytePos = position * 2;
+ if ((bytePos + lengthRetrieve * 2) > length) {
+ Platform::DebugPrintf("Bad GetCharRange %d for %d of %d\n",bytePos,
+ lengthRetrieve, length);
+ return;
+ }
+ GapTo(0); // Move the buffer so its easy to subscript into it
+ char *pb = part2body + bytePos;
+ while (lengthRetrieve--) {
+ *buffer++ = *pb;
+ pb +=2;
+ }
+}
+
+char CellBuffer::StyleAt(int position) {
+ return ByteAt(position*2 + 1);
+}
+
+const char *CellBuffer::InsertString(int position, char *s, int insertLength) {
+ char *data = 0;
+ // InsertString and DeleteChars are the bottleneck though which all changes occur
+ if (!readOnly) {
+ if (collectingUndo) {
+ // Save into the undo/redo stack, but only the characters - not the formatting
+ // This takes up about half load time
+ data = new char[insertLength / 2];
+ for (int i = 0; i < insertLength / 2; i++) {
+ data[i] = s[i * 2];
+ }
+ uh.AppendAction(insertAction, position, data, insertLength / 2);
+ }
+
+ BasicInsertString(position, s, insertLength);
+ }
+ return data;
+}
+
+void CellBuffer::InsertCharStyle(int position, char ch, char style) {
+ char s[2];
+ s[0] = ch;
+ s[1] = style;
+ InsertString(position*2, s, 2);
+}
+
+bool CellBuffer::SetStyleAt(int position, char style, char mask) {
+ char curVal = ByteAt(position*2 + 1);
+ if ((curVal & mask) != style) {
+ SetByteAt(position*2 + 1, (curVal & ~mask) | style);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool CellBuffer::SetStyleFor(int position, int lengthStyle, char style, char mask) {
+ int bytePos = position * 2 + 1;
+ bool changed = false;
+ while (lengthStyle--) {
+ char curVal = ByteAt(bytePos);
+ if ((curVal & mask) != style) {
+ SetByteAt(bytePos, (curVal & ~mask) | style);
+ changed = true;
+ }
+ bytePos += 2;
+ }
+ return changed;
+}
+
+const char *CellBuffer::DeleteChars(int position, int deleteLength) {
+ // InsertString and DeleteChars are the bottleneck though which all changes occur
+ char *data = 0;
+ if (!readOnly) {
+ if (collectingUndo) {
+ // Save into the undo/redo stack, but only the characters - not the formatting
+ data = new char[deleteLength / 2];
+ for (int i = 0; i < deleteLength / 2; i++) {
+ data[i] = ByteAt(position + i * 2);
+ }
+ uh.AppendAction(removeAction, position, data, deleteLength / 2);
+ }
+
+ BasicDeleteChars(position, deleteLength);
+ }
+ return data;
+}
+
+int CellBuffer::ByteLength() {
+ return length;
+}
+
+int CellBuffer::Length() {
+ return ByteLength() / 2;
+}
+
+int CellBuffer::Lines() {
+ //Platform::DebugPrintf("Lines = %d\n", lv.lines);
+ return lv.lines;
+}
+
+int CellBuffer::LineStart(int line) {
+ if (line < 0)
+ return 0;
+ else if (line > lv.lines)
+ return length;
+ else
+ return lv.linesData[line].startPosition;
+}
+
+bool CellBuffer::IsReadOnly() {
+ return readOnly;
+}
+
+void CellBuffer::SetReadOnly(bool set) {
+ readOnly = set;
+}
+
+void CellBuffer::SetSavePoint() {
+ uh.SetSavePoint();
+}
+
+bool CellBuffer::IsSavePoint() {
+ return uh.IsSavePoint();
+}
+
+int CellBuffer::AddMark(int line, int markerNum) {
+ if ((line >= 0) && (line < lv.lines)) {
+ return lv.AddMark(line, markerNum);
+ }
+ return - 1;
+}
+
+void CellBuffer::DeleteMark(int line, int markerNum) {
+ if ((line >= 0) && (line < lv.lines)) {
+ lv.DeleteMark(line, markerNum);
+ }
+}
+
+void CellBuffer::DeleteMarkFromHandle(int markerHandle) {
+ lv.DeleteMarkFromHandle(markerHandle);
+}
+
+int CellBuffer::GetMark(int line) {
+ if ((line >= 0) && (line < lv.lines) && (lv.linesData[line].handleSet))
+ return lv.linesData[line].handleSet->MarkValue();
+ return 0;
+}
+
+void CellBuffer::DeleteAllMarks(int markerNum) {
+ for (int line = 0; line < lv.lines; line++) {
+ lv.DeleteMark(line, markerNum);
+ }
+}
+
+int CellBuffer::LineFromHandle(int markerHandle) {
+ return lv.LineFromHandle(markerHandle);
+}
+
+// Without undo
+
+void CellBuffer::BasicInsertString(int position, char *s, int insertLength) {
+ //Platform::DebugPrintf("Inserting at %d for %d\n", position, insertLength);
+ if (insertLength == 0)
+ return;
+ RoomFor(insertLength);
+ GapTo(position);
+
+ memcpy(body + part1len, s, insertLength);
+ length += insertLength;
+ part1len += insertLength;
+ gaplen -= insertLength;
+ part2body = body + gaplen;
+
+ int lineInsert = lv.LineFromPosition(position / 2) + 1;
+ // Point all the lines after the insertion point further along in the buffer
+ for (int lineAfter = lineInsert; lineAfter <= lv.lines; lineAfter++) {
+ lv.linesData[lineAfter].startPosition += insertLength / 2;
+ }
+ char chPrev = ' ';
+ if ((position - 2) >= 0)
+ chPrev = ByteAt(position - 2);
+ char chAfter = ' ';
+ if ((position + insertLength) < length)
+ chAfter = ByteAt(position + insertLength);
+ if (chPrev == '\r' && chAfter == '\n') {
+ //Platform::DebugPrintf("Splitting a crlf pair at %d\n", lineInsert);
+ // Splitting up a crlf pair at position
+ lv.InsertValue(lineInsert, position / 2);
+ lineInsert++;
+ }
+ char ch = ' ';
+ for (int i = 0; i < insertLength; i += 2) {
+ ch = s[i];
+ if (ch == '\r') {
+ //Platform::DebugPrintf("Inserting cr at %d\n", lineInsert);
+ lv.InsertValue(lineInsert, (position + i) / 2 + 1);
+ lineInsert++;
+ } else if (ch == '\n') {
+ if (chPrev == '\r') {
+ //Platform::DebugPrintf("Patching cr before lf at %d\n", lineInsert-1);
+ // Patch up what was end of line
+ lv.SetValue(lineInsert - 1, (position + i) / 2 + 1);
+ } else {
+ //Platform::DebugPrintf("Inserting lf at %d\n", lineInsert);
+ lv.InsertValue(lineInsert, (position + i) / 2 + 1);
+ lineInsert++;
+ }
+ }
+ chPrev = ch;
+ }
+ // Joining two lines where last insertion is cr and following text starts with lf
+ if (chAfter == '\n') {
+ if (ch == '\r') {
+ //Platform::DebugPrintf("Joining cr before lf at %d\n", lineInsert-1);
+ // End of line already in buffer so drop the newly created one
+ lv.Remove(lineInsert - 1);
+ }
+ }
+}
+
+void CellBuffer::BasicDeleteChars(int position, int deleteLength) {
+ //Platform::DebugPrintf("Deleting at %d for %d\n", position, deleteLength);
+ if (deleteLength == 0)
+ return;
+
+ if ((position == 0) && (deleteLength == length)) {
+ // If whole buffer is being deleted, faster to reinitialise lines data
+ // than to delete each line.
+ //printf("Whole buffer being deleted\n");
+ lv.Init();
+ } else {
+ // Have to fix up line positions before doing deletion as looking at text in buffer
+ // to work out which lines have been removed
+
+ int lineRemove = lv.LineFromPosition(position / 2) + 1;
+ // Point all the lines after the insertion point further along in the buffer
+ for (int lineAfter = lineRemove; lineAfter <= lv.lines; lineAfter++) {
+ lv.linesData[lineAfter].startPosition -= deleteLength / 2;
+ }
+ char chPrev = ' ';
+ if (position >= 2)
+ chPrev = ByteAt(position - 2);
+ char chBefore = chPrev;
+ char chNext = ' ';
+ if (position < length)
+ chNext = ByteAt(position);
+ bool ignoreNL = false;
+ if (chPrev == '\r' && chNext == '\n') {
+ //Platform::DebugPrintf("Deleting lf after cr, move line end to cr at %d\n", lineRemove);
+ // Move back one
+ lv.SetValue(lineRemove, position / 2);
+ lineRemove++;
+ ignoreNL = true; // First \n is not real deletion
+ }
+
+ char ch = chNext;
+ for (int i = 0; i < deleteLength; i += 2) {
+ chNext = ' ';
+ if ((position + i + 2) < length)
+ chNext = ByteAt(position + i + 2);
+ //Platform::DebugPrintf("Deleting %d %x\n", i, ch);
+ if (ch == '\r') {
+ if (chNext != '\n') {
+ //Platform::DebugPrintf("Removing cr end of line\n");
+ lv.Remove(lineRemove);
+ }
+ } else if ((ch == '\n') && !ignoreNL) {
+ //Platform::DebugPrintf("Removing lf end of line\n");
+ lv.Remove(lineRemove);
+ ignoreNL = false; // Further \n are not real deletions
+ }
+
+ ch = chNext;
+ }
+ // May have to fix up end if last deletion causes cr to be next to lf
+ // or removes one of a crlf pair
+ char chAfter = ' ';
+ if ((position + deleteLength) < length)
+ chAfter = ByteAt(position + deleteLength);
+ if (chBefore == '\r' && chAfter == '\n') {
+ //d.printf("Joining cr before lf at %d\n", lineRemove);
+ // Using lineRemove-1 as cr ended line before start of deletion
+ lv.Remove(lineRemove - 1);
+ lv.SetValue(lineRemove - 1, position / 2 + 1);
+ }
+ }
+ GapTo(position);
+ length -= deleteLength;
+ gaplen += deleteLength;
+ part2body = body + gaplen;
+}
+
+undoCollectionType CellBuffer::SetUndoCollection(undoCollectionType collectUndo) {
+ collectingUndo = collectUndo;
+ uh.DropUndoSequence();
+ return collectingUndo;
+}
+
+bool CellBuffer::IsCollectingUndo() {
+ return collectingUndo;
+}
+
+void CellBuffer::BeginUndoAction() {
+ uh.BeginUndoAction();
+}
+
+void CellBuffer::EndUndoAction() {
+ uh.EndUndoAction();
+}
+
+void CellBuffer::DeleteUndoHistory() {
+ uh.DeleteUndoHistory();
+}
+
+bool CellBuffer::CanUndo() {
+ return (!readOnly) && (uh.CanUndo());
+}
+
+int CellBuffer::StartUndo() {
+ return uh.StartUndo();
+}
+
+const Action &CellBuffer::UndoStep() {
+ const Action &actionStep = uh.UndoStep();
+ if (actionStep.at == insertAction) {
+ BasicDeleteChars(actionStep.position, actionStep.lenData*2);
+ } else if (actionStep.at == removeAction) {
+ char *styledData = new char[actionStep.lenData * 2];
+ for (int i = 0; i < actionStep.lenData; i++) {
+ styledData[i*2] = actionStep.data[i];
+ styledData[i*2+1] = 0;
+ }
+ BasicInsertString(actionStep.position, styledData, actionStep.lenData*2);
+ delete []styledData;
+ }
+ return actionStep;
+}
+
+bool CellBuffer::CanRedo() {
+ return (!readOnly) && (uh.CanRedo());
+}
+
+int CellBuffer::StartRedo() {
+ return uh.StartRedo();
+}
+
+const Action &CellBuffer::RedoStep() {
+ const Action &actionStep = uh.RedoStep();
+ if (actionStep.at == insertAction) {
+ char *styledData = new char[actionStep.lenData * 2];
+ for (int i = 0; i < actionStep.lenData; i++) {
+ styledData[i*2] = actionStep.data[i];
+ styledData[i*2+1] = 0;
+ }
+ BasicInsertString(actionStep.position, styledData, actionStep.lenData*2);
+ delete []styledData;
+ } else if (actionStep.at == removeAction) {
+ BasicDeleteChars(actionStep.position, actionStep.lenData*2);
+ }
+ return actionStep;
+}
+
+int CellBuffer::SetLineState(int line, int state) {
+ int stateOld = lineStates[line];
+ lineStates[line] = state;
+ return stateOld;
+}
+
+int CellBuffer::GetLineState(int line) {
+ return lineStates[line];
+}
+
+int CellBuffer::GetMaxLineState() {
+ return lineStates.Length();
+}
+
+int CellBuffer::SetLevel(int line, int level) {
+ int prev = 0;
+ if ((line >= 0) && (line < lv.lines)) {
+ if (!lv.levels) {
+ lv.ExpandLevels();
+ }
+ prev = lv.levels[line];
+ if (lv.levels[line] != level) {
+ lv.levels[line] = level;
+ }
+ }
+ return prev;
+}
+
+int CellBuffer::GetLevel(int line) {
+ if (lv.levels && (line >= 0) && (line < lv.lines)) {
+ return lv.levels[line];
+ } else {
+ return SC_FOLDLEVELBASE;
+ }
+}
+
diff --git a/src/Document.cxx b/src/Document.cxx index bfb52d36e..35ab4b056 100644 --- a/src/Document.cxx +++ b/src/Document.cxx @@ -1,799 +1,797 @@ -// Scintilla source code edit control -// Document.cxx - text document that handles notifications, DBCS, styling, words and end of line -// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org> -// The License.txt file describes the conditions under which this software may be distributed. - -#include <stdlib.h> -#include <string.h> -#include <stdio.h> -#include <ctype.h> - -#include "Platform.h" - -#include "Scintilla.h" -#include "SVector.h" -#include "CellBuffer.h" -#include "Document.h" - -Document::Document() { - refCount = 0; -#ifdef unix - eolMode = SC_EOL_LF; -#else - eolMode = SC_EOL_CRLF; -#endif - dbcsCodePage = 0; - stylingBits = 5; - stylingBitsMask = 0x1F; - stylingPos = 0; - stylingMask = 0; - for (int ch = 0; ch < 256; ch++) { - wordchars[ch] = isalnum(ch) || ch == '_'; - } - endStyled = 0; - enteredCount = 0; - tabInChars = 8; - watchers = 0; - lenWatchers = 0; -} - -Document::~Document() { - for (int i = 0; i < lenWatchers; i++) { - watchers[i].watcher->NotifyDeleted(this, watchers[i].userData); - } - delete []watchers; - watchers = 0; - lenWatchers = 0; -} - -// Increase reference count and return its previous value. -int Document::AddRef() { - return refCount++; -} - -// Decrease reference count and return its provius value. -// Delete the document if reference count reaches zero. -int Document::Release() { - int curRefCount = --refCount; - if (curRefCount == 0) - delete this; - return curRefCount; -} - -void Document::SetSavePoint() { - cb.SetSavePoint(); - NotifySavePoint(true); -} - -int Document::AddMark(int line, int markerNum) { - int prev = cb.AddMark(line, markerNum); - DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0); - NotifyModified(mh); - return prev; -} - -void Document::DeleteMark(int line, int markerNum) { - cb.DeleteMark(line, markerNum); - DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0); - NotifyModified(mh); -} - -void Document::DeleteMarkFromHandle(int markerHandle) { - cb.DeleteMarkFromHandle(markerHandle); - DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0); - NotifyModified(mh); -} - -void Document::DeleteAllMarks(int markerNum) { - cb.DeleteAllMarks(markerNum); - DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0); - NotifyModified(mh); -} - -int Document::LineStart(int line) { - return cb.LineStart(line); -} - -int Document::LineEnd(int line) { - if (line == LinesTotal() - 1) { - return LineStart(line + 1); - } else { - int position = LineStart(line + 1) - 1; - // 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; - } -} - -int Document::LineFromPosition(int pos) { - return cb.LineFromPosition(pos); -} - -int Document::LineEndPosition(int position) { - return LineEnd(LineFromPosition(position)); -} - -int Document::VCHomePosition(int position) { - int line = LineFromPosition(position); - int startPosition = LineStart(line); - int endLine = LineStart(line + 1) - 1; - int startText = startPosition; - while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t' ) ) - startText++; - if (position == startText) - return startPosition; - else - return startText; -} - -int Document::SetLevel(int line, int level) { - int prev = cb.SetLevel(line, level); - if (prev != level) { - DocModification mh(SC_MOD_CHANGEFOLD, LineStart(line), 0, 0, 0); - mh.line = line; - mh.foldLevelNow = level; - mh.foldLevelPrev = prev; - NotifyModified(mh); - } - return prev; -} - -static bool IsSubordinate(int levelStart, int levelTry) { - if (levelTry & SC_FOLDLEVELWHITEFLAG) - return true; - else - return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK); -} - -int Document::GetLastChild(int lineParent, int level) { - if (level == -1) - level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK; - int maxLine = LinesTotal(); - int lineMaxSubord = lineParent; - while (lineMaxSubord < maxLine-1) { - EnsureStyledTo(LineStart(lineMaxSubord+2)); - if (!IsSubordinate(level, GetLevel(lineMaxSubord+1))) - break; - lineMaxSubord++; - } - if (lineMaxSubord > lineParent) { - if (level > (GetLevel(lineMaxSubord+1) & SC_FOLDLEVELNUMBERMASK)) { - // Have chewed up some whitespace that belongs to a parent so seek back - if ((lineMaxSubord > lineParent) && (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG)) { - lineMaxSubord--; - } - } - } - return lineMaxSubord; -} - -int Document::GetFoldParent(int line) { - int level = GetLevel(line); - int lineLook = line-1; - while ((lineLook > 0) && ( - (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) || - ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level)) - ) { - lineLook--; - } - if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) && - ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) { - return lineLook; - } else { - return -1; - } -} - -int Document::ClampPositionIntoDocument(int pos) { - return Platform::Clamp(pos, 0, Length()); -} - -bool Document::IsCrLf(int pos) { - if (pos < 0) - return false; - if (pos >= (Length() - 1)) - return false; - return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n'); -} - -bool Document::IsDBCS(int pos) { -#if PLAT_WIN - if (dbcsCodePage) { - // Anchor DBCS calculations at start of line because start of line can - // not be a DBCS trail byte. - int startLine = pos; - while (startLine > 0 && cb.CharAt(startLine) != '\r' && cb.CharAt(startLine) != '\n') - startLine--; - while (startLine <= pos) { - if (IsDBCSLeadByteEx(dbcsCodePage, cb.CharAt(startLine))) { - startLine++; - if (startLine >= pos) - return true; - } - startLine++; - } - } - return false; -#else - return false; -#endif -} - -// Normalise a position so that it is not halfway through a two 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. -int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) { - //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir); - // If out of range, just return value - should be fixed up after - if (pos < 0) - return pos; - if (pos > Length()) - return pos; - - // Position 0 and Length() can not be between any two characters - if (pos == 0) - return pos; - if (pos == Length()) - return pos; - - // assert pos > 0 && pos < Length() - if (checkLineEnd && IsCrLf(pos - 1)) { - if (moveDir > 0) - return pos + 1; - else - return pos - 1; - } - - // Not between CR and LF - -#if PLAT_WIN - if (dbcsCodePage) { - // Anchor DBCS calculations at start of line because start of line can - // not be a DBCS trail byte. - int startLine = pos; - while (startLine > 0 && cb.CharAt(startLine) != '\r' && cb.CharAt(startLine) != '\n') - startLine--; - bool atLeadByte = false; - while (startLine < pos) { - if (atLeadByte) - atLeadByte = false; - else if (IsDBCSLeadByteEx(dbcsCodePage, cb.CharAt(startLine))) - atLeadByte = true; - else - atLeadByte = false; - startLine++; - //Platform::DebugPrintf("DBCS %s\n", atlead ? "D" : "-"); - } - - if (atLeadByte) { - // Position is between a lead byte and a trail byte - if (moveDir > 0) - return pos + 1; - else - return pos - 1; - } - } -#endif - - return pos; -} - -void Document::ModifiedAt(int pos) { - if (endStyled > pos) - endStyled = pos; -} - -// Document only modified by gateways DeleteChars, InsertStyledString, Undo, Redo, and SetStyleAt. -// SetStyleAt does not change the persistent state of a document - -// Unlike Undo, Redo, and InsertStyledString, the pos argument is a cell number not a char number -void Document::DeleteChars(int pos, int len) { - if (enteredCount == 0) { - enteredCount++; - if (cb.IsReadOnly()) - NotifyModifyAttempt(); - if (!cb.IsReadOnly()) { - int prevLinesTotal = LinesTotal(); - bool startSavePoint = cb.IsSavePoint(); - const char *text = cb.DeleteChars(pos*2, len * 2); - if (startSavePoint && cb.IsCollectingUndo()) - NotifySavePoint(!startSavePoint); - ModifiedAt(pos); - int modFlags = SC_MOD_DELETETEXT | SC_PERFORMED_USER; - DocModification mh(modFlags, pos, len, LinesTotal() - prevLinesTotal, text); - NotifyModified(mh); - } - enteredCount--; - } -} - -void Document::InsertStyledString(int position, char *s, int insertLength) { - if (enteredCount == 0) { - enteredCount++; - if (cb.IsReadOnly()) - NotifyModifyAttempt(); - if (!cb.IsReadOnly()) { - int prevLinesTotal = LinesTotal(); - bool startSavePoint = cb.IsSavePoint(); - const char *text = cb.InsertString(position, s, insertLength); - if (startSavePoint && cb.IsCollectingUndo()) - NotifySavePoint(!startSavePoint); - ModifiedAt(position / 2); - - int modFlags = SC_MOD_INSERTTEXT | SC_PERFORMED_USER; - DocModification mh(modFlags, position / 2, insertLength / 2, LinesTotal() - prevLinesTotal, text); - NotifyModified(mh); - } - enteredCount--; - } -} - -int Document::Undo() { - int newPos = 0; - if (enteredCount == 0) { - enteredCount++; - bool startSavePoint = cb.IsSavePoint(); - int steps = cb.StartUndo(); - Platform::DebugPrintf("Steps=%d\n", steps); - for (int step=0; step<steps; step++) { - int prevLinesTotal = LinesTotal(); - const Action &action = cb.UndoStep(); - int cellPosition = action.position / 2; - ModifiedAt(cellPosition); - newPos = cellPosition; - - int modFlags = SC_PERFORMED_UNDO; - // With undo, an insertion action becomes a deletion notification - if (action.at == removeAction) { - Platform::DebugPrintf("Insert of %d\n", action.lenData); - newPos += action.lenData; - modFlags |= SC_MOD_INSERTTEXT; - } else { - Platform::DebugPrintf("Remove of %d\n", action.lenData); - modFlags |= SC_MOD_DELETETEXT; - } - if (step == steps-1) - modFlags |= SC_LASTSTEPINUNDOREDO; - NotifyModified(DocModification(modFlags, cellPosition, action.lenData, - LinesTotal() - prevLinesTotal, action.data)); - } - - bool endSavePoint = cb.IsSavePoint(); - if (startSavePoint != endSavePoint) - NotifySavePoint(endSavePoint); - enteredCount--; - } - return newPos; -} - -int Document::Redo() { - int newPos = 0; - if (enteredCount == 0) { - enteredCount++; - bool startSavePoint = cb.IsSavePoint(); - int steps = cb.StartRedo(); - for (int step=0; step<steps; step++) { - int prevLinesTotal = LinesTotal(); - const Action &action = cb.RedoStep(); - int cellPosition = action.position / 2; - ModifiedAt(cellPosition); - newPos = cellPosition; - - int modFlags = SC_PERFORMED_REDO; - if (action.at == insertAction) { - newPos += action.lenData; - modFlags |= SC_MOD_INSERTTEXT; - } else { - modFlags |= SC_MOD_DELETETEXT; - } - if (step == steps-1) - modFlags |= SC_LASTSTEPINUNDOREDO; - NotifyModified(DocModification(modFlags, cellPosition, action.lenData, - LinesTotal() - prevLinesTotal, action.data)); - } - - bool endSavePoint = cb.IsSavePoint(); - if (startSavePoint != endSavePoint) - NotifySavePoint(endSavePoint); - enteredCount--; - } - return newPos; -} - -void Document::InsertChar(int pos, char ch) { - char chs[2]; - chs[0] = ch; - chs[1] = 0; - InsertStyledString(pos*2, chs, 2); -} - -// Insert a null terminated string -void Document::InsertString(int position, const char *s) { - InsertString(position, s, strlen(s)); -} - -// Insert a string with a length -void Document::InsertString(int position, const char *s, int insertLength) { - char *sWithStyle = new char[insertLength * 2]; - if (sWithStyle) { - for (int i = 0; i < insertLength; i++) { - sWithStyle[i*2] = s[i]; - sWithStyle[i*2 + 1] = 0; - } - InsertStyledString(position*2, sWithStyle, insertLength*2); - delete []sWithStyle; - } -} - -void Document::ChangeChar(int pos, char ch) { - DeleteChars(pos, 1); - InsertChar(pos, ch); -} - -void Document::DelChar(int pos) { - if (IsCrLf(pos)) { - DeleteChars(pos, 2); - } else if (IsDBCS(pos)) { - DeleteChars(pos, 2); - } else if (pos < Length()) { - DeleteChars(pos, 1); - } -} - -int Document::DelCharBack(int pos) { - if (pos <= 0) { - return pos; - } else if (IsCrLf(pos - 2)) { - DeleteChars(pos - 2, 2); - return pos - 2; - } else if (IsDBCS(pos - 1)) { - DeleteChars(pos - 2, 2); - return pos - 2; - } else { - DeleteChars(pos - 1, 1); - return pos - 1; - } -} - -void Document::Indent(bool forwards, int lineBottom, int lineTop) { - if (forwards) { - // Indent by a tab - for (int line = lineBottom; line >= lineTop; line--) { - InsertChar(LineStart(line), '\t'); - } - } else { - // Dedent - suck white space off the front of the line to dedent by equivalent of a tab - for (int line = lineBottom; line >= lineTop; line--) { - int ispc = 0; - while (ispc < tabInChars && cb.CharAt(LineStart(line) + ispc) == ' ') - ispc++; - int posStartLine = LineStart(line); - if (ispc == tabInChars) { - DeleteChars(posStartLine, ispc); - } else if (cb.CharAt(posStartLine + ispc) == '\t') { - DeleteChars(posStartLine, ispc + 1); - } else { // Hit a non-white - DeleteChars(posStartLine, ispc); - } - } - } -} - -void Document::ConvertLineEnds(int eolModeSet) { - BeginUndoAction(); - for (int pos = 0; pos < Length(); pos++) { - if (cb.CharAt(pos) == '\r') { - if (cb.CharAt(pos+1) == '\n') { - if (eolModeSet != SC_EOL_CRLF) { - DeleteChars(pos, 2); - if (eolModeSet == SC_EOL_CR) - InsertString(pos, "\r", 1); - else - InsertString(pos, "\n", 1); - } else { - pos++; - } - } else { - if (eolModeSet != SC_EOL_CR) { - DeleteChars(pos, 1); - if (eolModeSet == SC_EOL_CRLF) { - InsertString(pos, "\r\n", 2); - pos++; - } else { - InsertString(pos, "\n", 1); - } - } - } - } else if (cb.CharAt(pos) == '\n') { - if (eolModeSet != SC_EOL_LF) { - DeleteChars(pos, 1); - if (eolModeSet == SC_EOL_CRLF) { - InsertString(pos, "\r\n", 2); - pos++; - } else { - InsertString(pos, "\r", 1); - } - } - } - } - EndUndoAction(); -} - -bool Document::IsWordChar(unsigned char ch) { - return wordchars[ch]; -} - -int Document::ExtendWordSelect(int pos, int delta) { - if (delta < 0) { - while (pos > 0 && IsWordChar(cb.CharAt(pos - 1))) - pos--; - } else { - while (pos < (Length()) && IsWordChar(cb.CharAt(pos))) - pos++; - } - return pos; -} - -int Document::NextWordStart(int pos, int delta) { - if (delta < 0) { - while (pos > 0 && (cb.CharAt(pos - 1) == ' ' || cb.CharAt(pos - 1) == '\t')) - pos--; - if (isspace(cb.CharAt(pos - 1))) { // Back up to previous line - while (pos > 0 && isspace(cb.CharAt(pos - 1))) - pos--; - } else { - bool startAtWordChar = IsWordChar(cb.CharAt(pos - 1)); - while (pos > 0 && !isspace(cb.CharAt(pos - 1)) && (startAtWordChar == IsWordChar(cb.CharAt(pos - 1)))) - pos--; - } - } else { - bool startAtWordChar = IsWordChar(cb.CharAt(pos)); - while (pos < (Length()) && isspace(cb.CharAt(pos))) - pos++; - while (pos < (Length()) && !isspace(cb.CharAt(pos)) && (startAtWordChar == IsWordChar(cb.CharAt(pos)))) - pos++; - while (pos < (Length()) && (cb.CharAt(pos) == ' ' || cb.CharAt(pos) == '\t')) - pos++; - } - return pos; -} - -bool Document::IsWordAt(int start, int end) { - int lengthDoc = Length(); - if (start > 0) { - char ch = CharAt(start - 1); - if (IsWordChar(ch)) - return false; - } - if (end < lengthDoc - 1) { - char ch = CharAt(end); - if (IsWordChar(ch)) - return false; - } - return true; -} - -// Find text in document, supporting both forward and backward -// searches (just pass minPos > maxPos to do a backward search) -// Has not been tested with backwards DBCS searches yet. -long Document::FindText(int minPos, int maxPos, const char *s, bool caseSensitive, bool word) { - bool forward = minPos <= maxPos; - int increment = forward ? 1 : -1; - - // Range endpoints should not be inside DBCS characters, but just in case, move them. - int startPos = MovePositionOutsideChar(minPos, increment, false); - int endPos = MovePositionOutsideChar(maxPos, increment, false); - - // Compute actual search ranges needed - int lengthFind = strlen(s); - int endSearch = 0; - if (startPos <= endPos) { - endSearch = endPos - lengthFind + 1; - } else { - endSearch = endPos; - } - //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind); - char firstChar = s[0]; - if (!caseSensitive) - firstChar = toupper(firstChar); - int pos = startPos; - while (forward ? (pos < endSearch) : (pos >= endSearch)) { - char ch = CharAt(pos); - if (caseSensitive) { - if (ch == firstChar) { - bool found = true; - for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) { - ch = CharAt(pos + posMatch); - if (ch != s[posMatch]) - found = false; - } - if (found) { - if ((!word) || IsWordAt(pos, pos + lengthFind)) - return pos; - } - } - } else { - if (toupper(ch) == firstChar) { - bool found = true; - for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) { - ch = CharAt(pos + posMatch); - if (toupper(ch) != toupper(s[posMatch])) - found = false; - } - if (found) { - if ((!word) || IsWordAt(pos, pos + lengthFind)) - return pos; - } - } - } - pos += increment; - if (dbcsCodePage) { - // Ensure trying to match from start of character - pos = MovePositionOutsideChar(pos, increment, false); - } - } - //Platform::DebugPrintf("Not found\n"); - return - 1; -} - -int Document::LinesTotal() { - return cb.Lines(); -} - -void Document::ChangeCase(Range r, bool makeUpperCase) { - for (int pos=r.start; pos<r.end; pos++) { - char ch = CharAt(pos); - if (dbcsCodePage && IsDBCS(pos)) { - pos++; - } else { - if (makeUpperCase) { - if (islower(ch)) { - ChangeChar(pos, toupper(ch)); - } - } else { - if (isupper(ch)) { - ChangeChar(pos, tolower(ch)); - } - } - } - } -} - -void Document::SetWordChars(unsigned char *chars) { - int ch; - for (ch = 0; ch < 256; ch++) { - wordchars[ch] = false; - } - if (chars) { - while (*chars) { - wordchars[*chars] = true; - chars++; - } - } else { - for (ch = 0; ch < 256; ch++) { - wordchars[ch] = isalnum(ch) || ch == '_'; - } - } -} - -void Document::SetStylingBits(int bits) { - stylingBits = bits; - stylingBitsMask = 0; - for (int bit=0; bit<stylingBits; bit++) { - stylingBitsMask <<= 1; - stylingBitsMask |= 1; - } -} - -void Document::StartStyling(int position, char mask) { - stylingPos = position; - stylingMask = mask; -} - -void Document::SetStyleFor(int length, char style) { - if (enteredCount == 0) { - enteredCount++; - int prevEndStyled = endStyled; - if (cb.SetStyleFor(stylingPos, length, style, stylingMask)) { - DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER, - prevEndStyled, length); - NotifyModified(mh); - } - stylingPos += length; - endStyled = stylingPos; - enteredCount--; - } -} - -void Document::SetStyles(int length, char *styles) { - if (enteredCount == 0) { - enteredCount++; - int prevEndStyled = endStyled; - bool didChange = false; - for (int iPos = 0; iPos < length; iPos++, stylingPos++) { - if (cb.SetStyleAt(stylingPos, styles[iPos], stylingMask)) { - didChange = true; - } - } - endStyled = stylingPos; - if (didChange) { - DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER, - prevEndStyled, endStyled - prevEndStyled); - NotifyModified(mh); - } - enteredCount--; - } -} - -bool Document::EnsureStyledTo(int pos) { - // Ask the watchers to style, and stop as soon as one responds. - for (int i = 0; pos > GetEndStyled() && i < lenWatchers; i++) - watchers[i].watcher->NotifyStyleNeeded(this, watchers[i].userData, pos); - return pos <= GetEndStyled(); -} - -bool Document::AddWatcher(DocWatcher *watcher, void *userData) { - for (int i = 0; i < lenWatchers; i++) { - if ((watchers[i].watcher == watcher) && - (watchers[i].userData == userData)) - return false; - } - WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers + 1]; - if (!pwNew) - return false; - for (int j = 0; j < lenWatchers; j++) - pwNew[j] = watchers[j]; - pwNew[lenWatchers].watcher = watcher; - pwNew[lenWatchers].userData = userData; - delete []watchers; - watchers = pwNew; - lenWatchers++; - return true; -} - -bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) { - for (int i = 0; i < lenWatchers; i++) { - if ((watchers[i].watcher == watcher) && - (watchers[i].userData == userData)) { - if (lenWatchers == 1) { - delete []watchers; - watchers = 0; - lenWatchers = 0; - } else { - WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers]; - if (!pwNew) - return false; - for (int j = 0; j < lenWatchers - 1; j++) { - pwNew[j] = (j < i) ? watchers[j] : watchers[j + 1]; - } - delete []watchers; - watchers = pwNew; - lenWatchers--; - } - return true; - } - } - return false; -} - -void Document::NotifyModifyAttempt() { - for (int i = 0; i < lenWatchers; i++) { - watchers[i].watcher->NotifyModifyAttempt(this, watchers[i].userData); - } -} - -void Document::NotifySavePoint(bool atSavePoint) { - for (int i = 0; i < lenWatchers; i++) { - watchers[i].watcher->NotifySavePoint(this, watchers[i].userData, atSavePoint); - } -} - -void Document::NotifyModified(DocModification mh) { - for (int i = 0; i < lenWatchers; i++) { - watchers[i].watcher->NotifyModified(this, mh, watchers[i].userData); - } -} +// Scintilla source code edit control
+// Document.cxx - text document that handles notifications, DBCS, styling, words and end of line
+// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <ctype.h>
+
+#include "Platform.h"
+
+#include "Scintilla.h"
+#include "SVector.h"
+#include "CellBuffer.h"
+#include "Document.h"
+
+Document::Document() {
+ refCount = 0;
+#ifdef unix
+ eolMode = SC_EOL_LF;
+#else
+ eolMode = SC_EOL_CRLF;
+#endif
+ dbcsCodePage = 0;
+ stylingBits = 5;
+ stylingBitsMask = 0x1F;
+ stylingPos = 0;
+ stylingMask = 0;
+ for (int ch = 0; ch < 256; ch++) {
+ wordchars[ch] = isalnum(ch) || ch == '_';
+ }
+ endStyled = 0;
+ enteredCount = 0;
+ tabInChars = 8;
+ watchers = 0;
+ lenWatchers = 0;
+}
+
+Document::~Document() {
+ for (int i = 0; i < lenWatchers; i++) {
+ watchers[i].watcher->NotifyDeleted(this, watchers[i].userData);
+ }
+ delete []watchers;
+ watchers = 0;
+ lenWatchers = 0;
+}
+
+// Increase reference count and return its previous value.
+int Document::AddRef() {
+ return refCount++;
+}
+
+// Decrease reference count and return its provius value.
+// Delete the document if reference count reaches zero.
+int Document::Release() {
+ int curRefCount = --refCount;
+ if (curRefCount == 0)
+ delete this;
+ return curRefCount;
+}
+
+void Document::SetSavePoint() {
+ cb.SetSavePoint();
+ NotifySavePoint(true);
+}
+
+int Document::AddMark(int line, int markerNum) {
+ int prev = cb.AddMark(line, markerNum);
+ DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0);
+ NotifyModified(mh);
+ return prev;
+}
+
+void Document::DeleteMark(int line, int markerNum) {
+ cb.DeleteMark(line, markerNum);
+ DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0);
+ NotifyModified(mh);
+}
+
+void Document::DeleteMarkFromHandle(int markerHandle) {
+ cb.DeleteMarkFromHandle(markerHandle);
+ DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
+ NotifyModified(mh);
+}
+
+void Document::DeleteAllMarks(int markerNum) {
+ cb.DeleteAllMarks(markerNum);
+ DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
+ NotifyModified(mh);
+}
+
+int Document::LineStart(int line) {
+ return cb.LineStart(line);
+}
+
+int Document::LineEnd(int line) {
+ if (line == LinesTotal() - 1) {
+ return LineStart(line + 1);
+ } else {
+ int position = LineStart(line + 1) - 1;
+ // 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;
+ }
+}
+
+int Document::LineFromPosition(int pos) {
+ return cb.LineFromPosition(pos);
+}
+
+int Document::LineEndPosition(int position) {
+ return LineEnd(LineFromPosition(position));
+}
+
+int Document::VCHomePosition(int position) {
+ int line = LineFromPosition(position);
+ int startPosition = LineStart(line);
+ int endLine = LineStart(line + 1) - 1;
+ int startText = startPosition;
+ while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t' ) )
+ startText++;
+ if (position == startText)
+ return startPosition;
+ else
+ return startText;
+}
+
+int Document::SetLevel(int line, int level) {
+ int prev = cb.SetLevel(line, level);
+ if (prev != level) {
+ DocModification mh(SC_MOD_CHANGEFOLD, LineStart(line), 0, 0, 0);
+ mh.line = line;
+ mh.foldLevelNow = level;
+ mh.foldLevelPrev = prev;
+ NotifyModified(mh);
+ }
+ return prev;
+}
+
+static bool IsSubordinate(int levelStart, int levelTry) {
+ if (levelTry & SC_FOLDLEVELWHITEFLAG)
+ return true;
+ else
+ return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK);
+}
+
+int Document::GetLastChild(int lineParent, int level) {
+ if (level == -1)
+ level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK;
+ int maxLine = LinesTotal();
+ int lineMaxSubord = lineParent;
+ while (lineMaxSubord < maxLine-1) {
+ EnsureStyledTo(LineStart(lineMaxSubord+2));
+ if (!IsSubordinate(level, GetLevel(lineMaxSubord+1)))
+ break;
+ lineMaxSubord++;
+ }
+ if (lineMaxSubord > lineParent) {
+ if (level > (GetLevel(lineMaxSubord+1) & SC_FOLDLEVELNUMBERMASK)) {
+ // Have chewed up some whitespace that belongs to a parent so seek back
+ if ((lineMaxSubord > lineParent) && (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG)) {
+ lineMaxSubord--;
+ }
+ }
+ }
+ return lineMaxSubord;
+}
+
+int Document::GetFoldParent(int line) {
+ int level = GetLevel(line);
+ int lineLook = line-1;
+ while ((lineLook > 0) && (
+ (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) ||
+ ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level))
+ ) {
+ lineLook--;
+ }
+ if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) &&
+ ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) {
+ return lineLook;
+ } else {
+ return -1;
+ }
+}
+
+int Document::ClampPositionIntoDocument(int pos) {
+ return Platform::Clamp(pos, 0, Length());
+}
+
+bool Document::IsCrLf(int pos) {
+ if (pos < 0)
+ return false;
+ if (pos >= (Length() - 1))
+ return false;
+ return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
+}
+
+bool Document::IsDBCS(int pos) {
+#if PLAT_WIN
+ if (dbcsCodePage) {
+ // Anchor DBCS calculations at start of line because start of line can
+ // not be a DBCS trail byte.
+ int startLine = pos;
+ while (startLine > 0 && cb.CharAt(startLine) != '\r' && cb.CharAt(startLine) != '\n')
+ startLine--;
+ while (startLine <= pos) {
+ if (IsDBCSLeadByteEx(dbcsCodePage, cb.CharAt(startLine))) {
+ startLine++;
+ if (startLine >= pos)
+ return true;
+ }
+ startLine++;
+ }
+ }
+ return false;
+#else
+ return false;
+#endif
+}
+
+// Normalise a position so that it is not halfway through a two 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.
+int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
+ //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
+ // If out of range, just return value - should be fixed up after
+ if (pos < 0)
+ return pos;
+ if (pos > Length())
+ return pos;
+
+ // Position 0 and Length() can not be between any two characters
+ if (pos == 0)
+ return pos;
+ if (pos == Length())
+ return pos;
+
+ // assert pos > 0 && pos < Length()
+ if (checkLineEnd && IsCrLf(pos - 1)) {
+ if (moveDir > 0)
+ return pos + 1;
+ else
+ return pos - 1;
+ }
+
+ // Not between CR and LF
+
+#if PLAT_WIN
+ if (dbcsCodePage) {
+ // Anchor DBCS calculations at start of line because start of line can
+ // not be a DBCS trail byte.
+ int startLine = pos;
+ while (startLine > 0 && cb.CharAt(startLine) != '\r' && cb.CharAt(startLine) != '\n')
+ startLine--;
+ bool atLeadByte = false;
+ while (startLine < pos) {
+ if (atLeadByte)
+ atLeadByte = false;
+ else if (IsDBCSLeadByteEx(dbcsCodePage, cb.CharAt(startLine)))
+ atLeadByte = true;
+ else
+ atLeadByte = false;
+ startLine++;
+ //Platform::DebugPrintf("DBCS %s\n", atlead ? "D" : "-");
+ }
+
+ if (atLeadByte) {
+ // Position is between a lead byte and a trail byte
+ if (moveDir > 0)
+ return pos + 1;
+ else
+ return pos - 1;
+ }
+ }
+#endif
+
+ return pos;
+}
+
+void Document::ModifiedAt(int pos) {
+ if (endStyled > pos)
+ endStyled = pos;
+}
+
+// Document only modified by gateways DeleteChars, InsertStyledString, Undo, Redo, and SetStyleAt.
+// SetStyleAt does not change the persistent state of a document
+
+// Unlike Undo, Redo, and InsertStyledString, the pos argument is a cell number not a char number
+void Document::DeleteChars(int pos, int len) {
+ if (enteredCount == 0) {
+ enteredCount++;
+ if (cb.IsReadOnly())
+ NotifyModifyAttempt();
+ if (!cb.IsReadOnly()) {
+ int prevLinesTotal = LinesTotal();
+ bool startSavePoint = cb.IsSavePoint();
+ const char *text = cb.DeleteChars(pos*2, len * 2);
+ if (startSavePoint && cb.IsCollectingUndo())
+ NotifySavePoint(!startSavePoint);
+ ModifiedAt(pos);
+ int modFlags = SC_MOD_DELETETEXT | SC_PERFORMED_USER;
+ DocModification mh(modFlags, pos, len, LinesTotal() - prevLinesTotal, text);
+ NotifyModified(mh);
+ }
+ enteredCount--;
+ }
+}
+
+void Document::InsertStyledString(int position, char *s, int insertLength) {
+ if (enteredCount == 0) {
+ enteredCount++;
+ if (cb.IsReadOnly())
+ NotifyModifyAttempt();
+ if (!cb.IsReadOnly()) {
+ int prevLinesTotal = LinesTotal();
+ bool startSavePoint = cb.IsSavePoint();
+ const char *text = cb.InsertString(position, s, insertLength);
+ if (startSavePoint && cb.IsCollectingUndo())
+ NotifySavePoint(!startSavePoint);
+ ModifiedAt(position / 2);
+
+ int modFlags = SC_MOD_INSERTTEXT | SC_PERFORMED_USER;
+ DocModification mh(modFlags, position / 2, insertLength / 2, LinesTotal() - prevLinesTotal, text);
+ NotifyModified(mh);
+ }
+ enteredCount--;
+ }
+}
+
+int Document::Undo() {
+ int newPos = 0;
+ if (enteredCount == 0) {
+ enteredCount++;
+ bool startSavePoint = cb.IsSavePoint();
+ int steps = cb.StartUndo();
+ //Platform::DebugPrintf("Steps=%d\n", steps);
+ for (int step=0; step<steps; step++) {
+ int prevLinesTotal = LinesTotal();
+ const Action &action = cb.UndoStep();
+ int cellPosition = action.position / 2;
+ ModifiedAt(cellPosition);
+ newPos = cellPosition;
+
+ int modFlags = SC_PERFORMED_UNDO;
+ // With undo, an insertion action becomes a deletion notification
+ if (action.at == removeAction) {
+ newPos += action.lenData;
+ modFlags |= SC_MOD_INSERTTEXT;
+ } else {
+ modFlags |= SC_MOD_DELETETEXT;
+ }
+ if (step == steps-1)
+ modFlags |= SC_LASTSTEPINUNDOREDO;
+ NotifyModified(DocModification(modFlags, cellPosition, action.lenData,
+ LinesTotal() - prevLinesTotal, action.data));
+ }
+
+ bool endSavePoint = cb.IsSavePoint();
+ if (startSavePoint != endSavePoint)
+ NotifySavePoint(endSavePoint);
+ enteredCount--;
+ }
+ return newPos;
+}
+
+int Document::Redo() {
+ int newPos = 0;
+ if (enteredCount == 0) {
+ enteredCount++;
+ bool startSavePoint = cb.IsSavePoint();
+ int steps = cb.StartRedo();
+ for (int step=0; step<steps; step++) {
+ int prevLinesTotal = LinesTotal();
+ const Action &action = cb.RedoStep();
+ int cellPosition = action.position / 2;
+ ModifiedAt(cellPosition);
+ newPos = cellPosition;
+
+ int modFlags = SC_PERFORMED_REDO;
+ if (action.at == insertAction) {
+ newPos += action.lenData;
+ modFlags |= SC_MOD_INSERTTEXT;
+ } else {
+ modFlags |= SC_MOD_DELETETEXT;
+ }
+ if (step == steps-1)
+ modFlags |= SC_LASTSTEPINUNDOREDO;
+ NotifyModified(DocModification(modFlags, cellPosition, action.lenData,
+ LinesTotal() - prevLinesTotal, action.data));
+ }
+
+ bool endSavePoint = cb.IsSavePoint();
+ if (startSavePoint != endSavePoint)
+ NotifySavePoint(endSavePoint);
+ enteredCount--;
+ }
+ return newPos;
+}
+
+void Document::InsertChar(int pos, char ch) {
+ char chs[2];
+ chs[0] = ch;
+ chs[1] = 0;
+ InsertStyledString(pos*2, chs, 2);
+}
+
+// Insert a null terminated string
+void Document::InsertString(int position, const char *s) {
+ InsertString(position, s, strlen(s));
+}
+
+// Insert a string with a length
+void Document::InsertString(int position, const char *s, int insertLength) {
+ char *sWithStyle = new char[insertLength * 2];
+ if (sWithStyle) {
+ for (int i = 0; i < insertLength; i++) {
+ sWithStyle[i*2] = s[i];
+ sWithStyle[i*2 + 1] = 0;
+ }
+ InsertStyledString(position*2, sWithStyle, insertLength*2);
+ delete []sWithStyle;
+ }
+}
+
+void Document::ChangeChar(int pos, char ch) {
+ DeleteChars(pos, 1);
+ InsertChar(pos, ch);
+}
+
+void Document::DelChar(int pos) {
+ if (IsCrLf(pos)) {
+ DeleteChars(pos, 2);
+ } else if (IsDBCS(pos)) {
+ DeleteChars(pos, 2);
+ } else if (pos < Length()) {
+ DeleteChars(pos, 1);
+ }
+}
+
+int Document::DelCharBack(int pos) {
+ if (pos <= 0) {
+ return pos;
+ } else if (IsCrLf(pos - 2)) {
+ DeleteChars(pos - 2, 2);
+ return pos - 2;
+ } else if (IsDBCS(pos - 1)) {
+ DeleteChars(pos - 2, 2);
+ return pos - 2;
+ } else {
+ DeleteChars(pos - 1, 1);
+ return pos - 1;
+ }
+}
+
+void Document::Indent(bool forwards, int lineBottom, int lineTop) {
+ if (forwards) {
+ // Indent by a tab
+ for (int line = lineBottom; line >= lineTop; line--) {
+ InsertChar(LineStart(line), '\t');
+ }
+ } else {
+ // Dedent - suck white space off the front of the line to dedent by equivalent of a tab
+ for (int line = lineBottom; line >= lineTop; line--) {
+ int ispc = 0;
+ while (ispc < tabInChars && cb.CharAt(LineStart(line) + ispc) == ' ')
+ ispc++;
+ int posStartLine = LineStart(line);
+ if (ispc == tabInChars) {
+ DeleteChars(posStartLine, ispc);
+ } else if (cb.CharAt(posStartLine + ispc) == '\t') {
+ DeleteChars(posStartLine, ispc + 1);
+ } else { // Hit a non-white
+ DeleteChars(posStartLine, ispc);
+ }
+ }
+ }
+}
+
+void Document::ConvertLineEnds(int eolModeSet) {
+ BeginUndoAction();
+ for (int pos = 0; pos < Length(); pos++) {
+ if (cb.CharAt(pos) == '\r') {
+ if (cb.CharAt(pos+1) == '\n') {
+ if (eolModeSet != SC_EOL_CRLF) {
+ DeleteChars(pos, 2);
+ if (eolModeSet == SC_EOL_CR)
+ InsertString(pos, "\r", 1);
+ else
+ InsertString(pos, "\n", 1);
+ } else {
+ pos++;
+ }
+ } else {
+ if (eolModeSet != SC_EOL_CR) {
+ DeleteChars(pos, 1);
+ if (eolModeSet == SC_EOL_CRLF) {
+ InsertString(pos, "\r\n", 2);
+ pos++;
+ } else {
+ InsertString(pos, "\n", 1);
+ }
+ }
+ }
+ } else if (cb.CharAt(pos) == '\n') {
+ if (eolModeSet != SC_EOL_LF) {
+ DeleteChars(pos, 1);
+ if (eolModeSet == SC_EOL_CRLF) {
+ InsertString(pos, "\r\n", 2);
+ pos++;
+ } else {
+ InsertString(pos, "\r", 1);
+ }
+ }
+ }
+ }
+ EndUndoAction();
+}
+
+bool Document::IsWordChar(unsigned char ch) {
+ return wordchars[ch];
+}
+
+int Document::ExtendWordSelect(int pos, int delta) {
+ if (delta < 0) {
+ while (pos > 0 && IsWordChar(cb.CharAt(pos - 1)))
+ pos--;
+ } else {
+ while (pos < (Length()) && IsWordChar(cb.CharAt(pos)))
+ pos++;
+ }
+ return pos;
+}
+
+int Document::NextWordStart(int pos, int delta) {
+ if (delta < 0) {
+ while (pos > 0 && (cb.CharAt(pos - 1) == ' ' || cb.CharAt(pos - 1) == '\t'))
+ pos--;
+ if (isspace(cb.CharAt(pos - 1))) { // Back up to previous line
+ while (pos > 0 && isspace(cb.CharAt(pos - 1)))
+ pos--;
+ } else {
+ bool startAtWordChar = IsWordChar(cb.CharAt(pos - 1));
+ while (pos > 0 && !isspace(cb.CharAt(pos - 1)) && (startAtWordChar == IsWordChar(cb.CharAt(pos - 1))))
+ pos--;
+ }
+ } else {
+ bool startAtWordChar = IsWordChar(cb.CharAt(pos));
+ while (pos < (Length()) && isspace(cb.CharAt(pos)))
+ pos++;
+ while (pos < (Length()) && !isspace(cb.CharAt(pos)) && (startAtWordChar == IsWordChar(cb.CharAt(pos))))
+ pos++;
+ while (pos < (Length()) && (cb.CharAt(pos) == ' ' || cb.CharAt(pos) == '\t'))
+ pos++;
+ }
+ return pos;
+}
+
+bool Document::IsWordAt(int start, int end) {
+ int lengthDoc = Length();
+ if (start > 0) {
+ char ch = CharAt(start - 1);
+ if (IsWordChar(ch))
+ return false;
+ }
+ if (end < lengthDoc - 1) {
+ char ch = CharAt(end);
+ if (IsWordChar(ch))
+ return false;
+ }
+ return true;
+}
+
+// Find text in document, supporting both forward and backward
+// searches (just pass minPos > maxPos to do a backward search)
+// Has not been tested with backwards DBCS searches yet.
+long Document::FindText(int minPos, int maxPos, const char *s, bool caseSensitive, bool word) {
+ bool forward = minPos <= maxPos;
+ int increment = forward ? 1 : -1;
+
+ // Range endpoints should not be inside DBCS characters, but just in case, move them.
+ int startPos = MovePositionOutsideChar(minPos, increment, false);
+ int endPos = MovePositionOutsideChar(maxPos, increment, false);
+
+ // Compute actual search ranges needed
+ int lengthFind = strlen(s);
+ int endSearch = 0;
+ if (startPos <= endPos) {
+ endSearch = endPos - lengthFind + 1;
+ } else {
+ endSearch = endPos;
+ }
+ //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
+ char firstChar = s[0];
+ if (!caseSensitive)
+ firstChar = toupper(firstChar);
+ int pos = startPos;
+ while (forward ? (pos < endSearch) : (pos >= endSearch)) {
+ char ch = CharAt(pos);
+ if (caseSensitive) {
+ if (ch == firstChar) {
+ bool found = true;
+ for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) {
+ ch = CharAt(pos + posMatch);
+ if (ch != s[posMatch])
+ found = false;
+ }
+ if (found) {
+ if ((!word) || IsWordAt(pos, pos + lengthFind))
+ return pos;
+ }
+ }
+ } else {
+ if (toupper(ch) == firstChar) {
+ bool found = true;
+ for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) {
+ ch = CharAt(pos + posMatch);
+ if (toupper(ch) != toupper(s[posMatch]))
+ found = false;
+ }
+ if (found) {
+ if ((!word) || IsWordAt(pos, pos + lengthFind))
+ return pos;
+ }
+ }
+ }
+ pos += increment;
+ if (dbcsCodePage) {
+ // Ensure trying to match from start of character
+ pos = MovePositionOutsideChar(pos, increment, false);
+ }
+ }
+ //Platform::DebugPrintf("Not found\n");
+ return - 1;
+}
+
+int Document::LinesTotal() {
+ return cb.Lines();
+}
+
+void Document::ChangeCase(Range r, bool makeUpperCase) {
+ for (int pos=r.start; pos<r.end; pos++) {
+ char ch = CharAt(pos);
+ if (dbcsCodePage && IsDBCS(pos)) {
+ pos++;
+ } else {
+ if (makeUpperCase) {
+ if (islower(ch)) {
+ ChangeChar(pos, toupper(ch));
+ }
+ } else {
+ if (isupper(ch)) {
+ ChangeChar(pos, tolower(ch));
+ }
+ }
+ }
+ }
+}
+
+void Document::SetWordChars(unsigned char *chars) {
+ int ch;
+ for (ch = 0; ch < 256; ch++) {
+ wordchars[ch] = false;
+ }
+ if (chars) {
+ while (*chars) {
+ wordchars[*chars] = true;
+ chars++;
+ }
+ } else {
+ for (ch = 0; ch < 256; ch++) {
+ wordchars[ch] = isalnum(ch) || ch == '_';
+ }
+ }
+}
+
+void Document::SetStylingBits(int bits) {
+ stylingBits = bits;
+ stylingBitsMask = 0;
+ for (int bit=0; bit<stylingBits; bit++) {
+ stylingBitsMask <<= 1;
+ stylingBitsMask |= 1;
+ }
+}
+
+void Document::StartStyling(int position, char mask) {
+ stylingPos = position;
+ stylingMask = mask;
+}
+
+void Document::SetStyleFor(int length, char style) {
+ if (enteredCount == 0) {
+ enteredCount++;
+ int prevEndStyled = endStyled;
+ if (cb.SetStyleFor(stylingPos, length, style, stylingMask)) {
+ DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
+ prevEndStyled, length);
+ NotifyModified(mh);
+ }
+ stylingPos += length;
+ endStyled = stylingPos;
+ enteredCount--;
+ }
+}
+
+void Document::SetStyles(int length, char *styles) {
+ if (enteredCount == 0) {
+ enteredCount++;
+ int prevEndStyled = endStyled;
+ bool didChange = false;
+ for (int iPos = 0; iPos < length; iPos++, stylingPos++) {
+ if (cb.SetStyleAt(stylingPos, styles[iPos], stylingMask)) {
+ didChange = true;
+ }
+ }
+ endStyled = stylingPos;
+ if (didChange) {
+ DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
+ prevEndStyled, endStyled - prevEndStyled);
+ NotifyModified(mh);
+ }
+ enteredCount--;
+ }
+}
+
+bool Document::EnsureStyledTo(int pos) {
+ // Ask the watchers to style, and stop as soon as one responds.
+ for (int i = 0; pos > GetEndStyled() && i < lenWatchers; i++)
+ watchers[i].watcher->NotifyStyleNeeded(this, watchers[i].userData, pos);
+ return pos <= GetEndStyled();
+}
+
+bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
+ for (int i = 0; i < lenWatchers; i++) {
+ if ((watchers[i].watcher == watcher) &&
+ (watchers[i].userData == userData))
+ return false;
+ }
+ WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers + 1];
+ if (!pwNew)
+ return false;
+ for (int j = 0; j < lenWatchers; j++)
+ pwNew[j] = watchers[j];
+ pwNew[lenWatchers].watcher = watcher;
+ pwNew[lenWatchers].userData = userData;
+ delete []watchers;
+ watchers = pwNew;
+ lenWatchers++;
+ return true;
+}
+
+bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) {
+ for (int i = 0; i < lenWatchers; i++) {
+ if ((watchers[i].watcher == watcher) &&
+ (watchers[i].userData == userData)) {
+ if (lenWatchers == 1) {
+ delete []watchers;
+ watchers = 0;
+ lenWatchers = 0;
+ } else {
+ WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers];
+ if (!pwNew)
+ return false;
+ for (int j = 0; j < lenWatchers - 1; j++) {
+ pwNew[j] = (j < i) ? watchers[j] : watchers[j + 1];
+ }
+ delete []watchers;
+ watchers = pwNew;
+ lenWatchers--;
+ }
+ return true;
+ }
+ }
+ return false;
+}
+
+void Document::NotifyModifyAttempt() {
+ for (int i = 0; i < lenWatchers; i++) {
+ watchers[i].watcher->NotifyModifyAttempt(this, watchers[i].userData);
+ }
+}
+
+void Document::NotifySavePoint(bool atSavePoint) {
+ for (int i = 0; i < lenWatchers; i++) {
+ watchers[i].watcher->NotifySavePoint(this, watchers[i].userData, atSavePoint);
+ }
+}
+
+void Document::NotifyModified(DocModification mh) {
+ for (int i = 0; i < lenWatchers; i++) {
+ watchers[i].watcher->NotifyModified(this, mh, watchers[i].userData);
+ }
+}
diff --git a/src/KeyWords.cxx b/src/KeyWords.cxx index bc7882367..91ce04433 100644 --- a/src/KeyWords.cxx +++ b/src/KeyWords.cxx @@ -1,43 +1,45 @@ -// SciTE - Scintilla based Text Editor -// KeyWords.cxx - colourise for particular languages -// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org> -// The License.txt file describes the conditions under which this software may be distributed. - -#include <stdlib.h> -#include <string.h> -#include <ctype.h> -#include <stdio.h> -#include <stdarg.h> - -#include "Platform.h" - -#include "PropSet.h" -#include "Accessor.h" -#include "KeyWords.h" -#include "Scintilla.h" -#include "SciLexer.h" - -LexerModule *LexerModule::base = 0; - -LexerModule::LexerModule(int language_, LexerFunction fn_) : - language(language_), fn(fn_) { - next = base; - base = this; -} - -void LexerModule::Colourise(unsigned int startPos, int lengthDoc, int initStyle, - int language, WordList *keywordlists[], StylingContext &styler) { - LexerModule *lm = base; - while (lm) { - if (lm->language == language) { - lm->fn(startPos, lengthDoc, initStyle, keywordlists, styler); - return; - } - lm = lm->next; - } - // Unknown language - // Null language means all style bytes are 0 so just mark the end - no need to fill in. - styler.StartAt(startPos + lengthDoc - 1); - styler.StartSegment(startPos + lengthDoc - 1); - styler.ColourTo(startPos + lengthDoc - 1, 0); -} +// SciTE - Scintilla based Text Editor
+// KeyWords.cxx - colourise for particular languages
+// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+
+#include "Platform.h"
+
+#include "PropSet.h"
+#include "Accessor.h"
+#include "KeyWords.h"
+#include "Scintilla.h"
+#include "SciLexer.h"
+
+LexerModule *LexerModule::base = 0;
+
+LexerModule::LexerModule(int language_, LexerFunction fn_) :
+ language(language_), fn(fn_) {
+ next = base;
+ base = this;
+}
+
+void LexerModule::Colourise(unsigned int startPos, int lengthDoc, int initStyle,
+ int language, WordList *keywordlists[], StylingContext &styler) {
+ LexerModule *lm = base;
+ while (lm) {
+ if (lm->language == language) {
+ lm->fn(startPos, lengthDoc, initStyle, keywordlists, styler);
+ return;
+ }
+ lm = lm->next;
+ }
+ // Unknown language
+ // Null language means all style bytes are 0 so just mark the end - no need to fill in.
+ if (lengthDoc > 0) {
+ styler.StartAt(startPos + lengthDoc - 1);
+ styler.StartSegment(startPos + lengthDoc - 1);
+ styler.ColourTo(startPos + lengthDoc - 1, 0);
+ }
+}
diff --git a/src/Style.cxx b/src/Style.cxx index 3faca473f..42f9dea78 100644 --- a/src/Style.cxx +++ b/src/Style.cxx @@ -1,100 +1,101 @@ -// Scintilla source code edit control -// Style.cxx - defines the font and colour style for a class of text -// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org> -// The License.txt file describes the conditions under which this software may be distributed. - -#include <string.h> - -#include "Platform.h" - -#include "Style.h" - -Style::Style() { - aliasOfDefaultFont = true; - Clear(Colour(0,0,0), Colour(0xff,0xff,0xff), - Platform::DefaultFontSize(), 0, - false, false, false); -} - -Style::~Style() { - if (aliasOfDefaultFont) - font.SetID(0); - else - font.Release(); - aliasOfDefaultFont = false; -} - -Style &Style::operator=(const Style &source) { - if (this == &source) - return *this; - Clear(Colour(0,0,0), Colour(0xff,0xff,0xff), - 0, 0, - false, false, false); - fore.desired = source.fore.desired; - back.desired = source.back.desired; - bold = source.bold; - italic = source.italic; - size = source.size; - eolFilled = source.eolFilled; - return *this; -} - -void Style::Clear(Colour fore_, Colour back_, int size_, const char *fontName_, - bool bold_, bool italic_, bool eolFilled_) { - fore.desired = fore_; - back.desired = back_; - bold = bold_; - italic = italic_; - size = size_; - fontName = fontName_; - eolFilled = eolFilled_; - if (aliasOfDefaultFont) - font.SetID(0); - else - font.Release(); - aliasOfDefaultFont = false; -} - -bool Style::EquivalentFontTo(const Style *other) const { - if (bold != other->bold || - italic != other->italic || - size != other->size) - return false; - if (fontName == other->fontName) - return true; - if (!fontName) - return false; - if (!other->fontName) - return false; - return strcmp(fontName, other->fontName) == 0; -} - -void Style::Realise(Surface &surface, int zoomLevel, Style *defaultStyle) { - int sizeZoomed = size + zoomLevel; - if (sizeZoomed <= 2) // Hangs if sizeZoomed <= 1 - sizeZoomed = 2; - - if (aliasOfDefaultFont) - font.SetID(0); - else - font.Release(); - int deviceHeight = (sizeZoomed * surface.LogPixelsY()) / 72; - aliasOfDefaultFont = defaultStyle && EquivalentFontTo(defaultStyle); - if (aliasOfDefaultFont) { - font.SetID(defaultStyle->font.GetID()); - } else if (fontName) { - font.Create(fontName, deviceHeight, bold, italic); - } else { - font.SetID(0); - } - - ascent = surface.Ascent(font); - descent = surface.Descent(font); - // Probably more typographically correct to include leading - // but that means more complex drawing as leading must be erased - //lineHeight = surface.ExternalLeading() + surface.Height(); - externalLeading = surface.ExternalLeading(font); - lineHeight = surface.Height(font); - aveCharWidth = surface.AverageCharWidth(font); - spaceWidth = surface.WidthChar(font, ' '); -} +// Scintilla source code edit control
+// Style.cxx - defines the font and colour style for a class of text
+// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <string.h>
+
+#include "Platform.h"
+
+#include "Style.h"
+
+Style::Style() {
+ aliasOfDefaultFont = true;
+ Clear(Colour(0,0,0), Colour(0xff,0xff,0xff),
+ Platform::DefaultFontSize(), 0,
+ false, false, false);
+}
+
+Style::~Style() {
+ if (aliasOfDefaultFont)
+ font.SetID(0);
+ else
+ font.Release();
+ aliasOfDefaultFont = false;
+}
+
+Style &Style::operator=(const Style &source) {
+ if (this == &source)
+ return *this;
+ Clear(Colour(0,0,0), Colour(0xff,0xff,0xff),
+ 0, 0,
+ false, false, false);
+ fore.desired = source.fore.desired;
+ back.desired = source.back.desired;
+ bold = source.bold;
+ italic = source.italic;
+ size = source.size;
+ eolFilled = source.eolFilled;
+ return *this;
+}
+
+void Style::Clear(Colour fore_, Colour back_, int size_, const char *fontName_,
+ bool bold_, bool italic_, bool eolFilled_) {
+ fore.desired = fore_;
+ back.desired = back_;
+ bold = bold_;
+ italic = italic_;
+ size = size_;
+ fontName = fontName_;
+ eolFilled = eolFilled_;
+ if (aliasOfDefaultFont)
+ font.SetID(0);
+ else
+ font.Release();
+ aliasOfDefaultFont = false;
+}
+
+bool Style::EquivalentFontTo(const Style *other) const {
+ if (bold != other->bold ||
+ italic != other->italic ||
+ size != other->size)
+ return false;
+ if (fontName == other->fontName)
+ return true;
+ if (!fontName)
+ return false;
+ if (!other->fontName)
+ return false;
+ return strcmp(fontName, other->fontName) == 0;
+}
+
+void Style::Realise(Surface &surface, int zoomLevel, Style *defaultStyle) {
+ int sizeZoomed = size + zoomLevel;
+ if (sizeZoomed <= 2) // Hangs if sizeZoomed <= 1
+ sizeZoomed = 2;
+
+ if (aliasOfDefaultFont)
+ font.SetID(0);
+ else
+ font.Release();
+ int deviceHeight = (sizeZoomed * surface.LogPixelsY()) / 72;
+ aliasOfDefaultFont = defaultStyle &&
+ (EquivalentFontTo(defaultStyle) || !fontName);
+ if (aliasOfDefaultFont) {
+ font.SetID(defaultStyle->font.GetID());
+ } else if (fontName) {
+ font.Create(fontName, deviceHeight, bold, italic);
+ } else {
+ font.SetID(0);
+ }
+
+ ascent = surface.Ascent(font);
+ descent = surface.Descent(font);
+ // Probably more typographically correct to include leading
+ // but that means more complex drawing as leading must be erased
+ //lineHeight = surface.ExternalLeading() + surface.Height();
+ externalLeading = surface.ExternalLeading(font);
+ lineHeight = surface.Height(font);
+ aveCharWidth = surface.AverageCharWidth(font);
+ spaceWidth = surface.WidthChar(font, ' ');
+}
diff --git a/src/ViewStyle.cxx b/src/ViewStyle.cxx index 903ae94f4..a67ee21a0 100644 --- a/src/ViewStyle.cxx +++ b/src/ViewStyle.cxx @@ -1,226 +1,227 @@ -// Scintilla source code edit control -// ViewStyle.cxx - store information on how the document is to be viewed -// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org> -// The License.txt file describes the conditions under which this software may be distributed. - -#include <string.h> - -#include "Platform.h" - -#include "Scintilla.h" -#include "Indicator.h" -#include "LineMarker.h" -#include "Style.h" -#include "ViewStyle.h" - -MarginStyle::MarginStyle() : - symbol(false), width(16), mask(0xffffffff), sensitive(false) { -} - -// A list of the fontnames - avoids wasting space in each style -FontNames::FontNames() { - max = 0; -} - -FontNames::~FontNames() { - Clear(); -} - -void FontNames::Clear() { - for (int i=0;i<max;i++) { - delete []names[i]; - } - max = 0; -} - -const char *FontNames::Save(const char *name) { - if (!name) - return 0; - for (int i=0;i<max;i++) { - if (strcmp(names[i], name) == 0) { - return names[i]; - } - } - names[max] = new char[strlen(name) + 1]; - strcpy(names[max], name); - max++; - return names[max-1]; -} - -ViewStyle::ViewStyle() { - Init(); -} - -ViewStyle::ViewStyle(const ViewStyle &source) { - Init(); - for (unsigned int sty=0;sty<(sizeof(styles)/sizeof(styles[0]));sty++) { - styles[sty] = source.styles[sty]; - // Can't just copy fontname as its lifetime is relative to its owning ViewStyle - styles[sty].fontName = fontNames.Save(source.styles[sty].fontName); - } - for (int mrk=0;mrk<=MARKER_MAX;mrk++) { - markers[mrk] = source.markers[mrk]; - } - for (int ind=0;ind<=INDIC_MAX;ind++) { - indicators[ind] = source.indicators[ind]; - } - - selforeset = source.selforeset; - selforeground.desired = source.selforeground.desired; - selbackset = source.selbackset; - selbackground.desired = source.selbackground.desired; - selbar.desired = source.selbar.desired; - selbarlight.desired = source.selbarlight.desired; - caretcolour.desired = source.caretcolour.desired; - edgecolour.desired = source.edgecolour.desired; - leftMarginWidth = source.leftMarginWidth; - rightMarginWidth = source.rightMarginWidth; - for (int i=0;i < margins; i++) { - ms[i] = source.ms[i]; - } - symbolMargin = source.symbolMargin; - maskInLine = source.maskInLine; - fixedColumnWidth = source.fixedColumnWidth; - zoomLevel = source.zoomLevel; - viewWhitespace = source.viewWhitespace; - viewEOL = source.viewEOL; - showMarkedLines = source.showMarkedLines; -} - -ViewStyle::~ViewStyle() { -} - -void ViewStyle::Init() { - fontNames.Clear(); - - indicators[0].style = INDIC_SQUIGGLE; - indicators[0].fore = Colour(0, 0x7f, 0); - indicators[1].style = INDIC_TT; - indicators[1].fore = Colour(0, 0, 0xff); - indicators[2].style = INDIC_PLAIN; - indicators[2].fore = Colour(0xff, 0, 0); - - lineHeight = 1; - maxAscent = 1; - maxDescent = 1; - aveCharWidth = 8; - spaceWidth = 8; - - selforeset = false; - selforeground.desired = Colour(0xff, 0, 0); - selbackset = true; - selbackground.desired = Colour(0xc0, 0xc0, 0xc0); - selbar.desired = Platform::Chrome(); - selbarlight.desired = Platform::ChromeHighlight(); - styles[STYLE_LINENUMBER].fore.desired = Colour(0, 0, 0); - styles[STYLE_LINENUMBER].back.desired = Platform::Chrome(); - //caretcolour.desired = Colour(0xff, 0, 0); - caretcolour.desired = Colour(0, 0, 0); - edgecolour.desired = Colour(0xc0, 0xc0, 0xc0); - - leftMarginWidth = 1; - rightMarginWidth = 1; - ms[0].symbol = false; - ms[0].width = 0; - ms[0].mask = 0; - ms[1].symbol = true; - ms[1].width = 16; - ms[1].mask = ~SC_MASK_FOLDERS; - ms[2].symbol = true; - ms[2].width = 14; // Nice width for arrows - ms[2].mask = SC_MASK_FOLDERS; - ms[2].width = 0; // Nice width for arrows - ms[2].mask = 0; - fixedColumnWidth = leftMarginWidth; - symbolMargin = false; - maskInLine = 0xffffffff; - for (int margin=0; margin < margins; margin++) { - fixedColumnWidth += ms[margin].width; - symbolMargin = symbolMargin || ms[margin].symbol; - if (ms[margin].width > 0) - maskInLine &= ~ms[margin].mask; - } - zoomLevel = 0; - viewWhitespace = false; - viewEOL = false; - showMarkedLines = true; -} - -void ViewStyle::RefreshColourPalette(Palette &pal, bool want) { - unsigned int i; - for (i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) { - pal.WantFind(styles[i].fore, want); - pal.WantFind(styles[i].back, want); - } - for (i=0;i<(sizeof(indicators)/sizeof(indicators[0]));i++) { - pal.WantFind(indicators[i].fore, want); - } - for (i=0;i<(sizeof(markers)/sizeof(markers[0]));i++) { - pal.WantFind(markers[i].fore, want); - pal.WantFind(markers[i].back, want); - } - pal.WantFind(selforeground, want); - pal.WantFind(selbackground, want); - pal.WantFind(selbar, want); - pal.WantFind(selbarlight, want); - pal.WantFind(caretcolour, want); - pal.WantFind(edgecolour, want); -} - -void ViewStyle::Refresh(Surface &surface) { - selbar.desired = Platform::Chrome(); - selbarlight.desired = Platform::ChromeHighlight(); - styles[STYLE_DEFAULT].Realise(surface, zoomLevel); - maxAscent = styles[STYLE_DEFAULT].ascent; - maxDescent = styles[STYLE_DEFAULT].descent; - for (unsigned int i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) { - if (i != STYLE_DEFAULT) { - styles[i].Realise(surface, zoomLevel, &styles[STYLE_DEFAULT]); - if (maxAscent < styles[i].ascent) - maxAscent = styles[i].ascent; - if (maxDescent < styles[i].descent) - maxDescent = styles[i].descent; - } - } - - lineHeight = maxAscent + maxDescent; - aveCharWidth = styles[STYLE_DEFAULT].aveCharWidth; - spaceWidth = styles[STYLE_DEFAULT].spaceWidth; - - fixedColumnWidth = leftMarginWidth; - symbolMargin = false; - maskInLine = 0xffffffff; - for (int margin=0; margin < margins; margin++) { - fixedColumnWidth += ms[margin].width; - symbolMargin = symbolMargin || ms[margin].symbol; - if (ms[margin].width > 0) - maskInLine &= ~ms[margin].mask; - } -} - -void ViewStyle::ResetDefaultStyle() { - styles[STYLE_DEFAULT].Clear(Colour(0,0,0), Colour(0xff,0xff,0xff), - Platform::DefaultFontSize(), fontNames.Save(Platform::DefaultFont()), - false, false, false); -} - -void ViewStyle::ClearStyles() { - // Reset all styles to be like the default style - for (unsigned int i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) { - if (i != STYLE_DEFAULT) { - styles[i].Clear( - styles[STYLE_DEFAULT].fore.desired, - styles[STYLE_DEFAULT].back.desired, - styles[STYLE_DEFAULT].size, - styles[STYLE_DEFAULT].fontName, - styles[STYLE_DEFAULT].bold, - styles[STYLE_DEFAULT].italic, - styles[STYLE_DEFAULT].eolFilled); - } - } - styles[STYLE_LINENUMBER].back.desired = Platform::Chrome(); -} - -void ViewStyle::SetStyleFontName(int styleIndex, const char *name) { - styles[styleIndex].fontName = fontNames.Save(name); -} +// Scintilla source code edit control
+// ViewStyle.cxx - store information on how the document is to be viewed
+// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
+// The License.txt file describes the conditions under which this software may be distributed.
+
+#include <string.h>
+
+#include "Platform.h"
+
+#include "Scintilla.h"
+#include "Indicator.h"
+#include "LineMarker.h"
+#include "Style.h"
+#include "ViewStyle.h"
+
+MarginStyle::MarginStyle() :
+ symbol(false), width(16), mask(0xffffffff), sensitive(false) {
+}
+
+// A list of the fontnames - avoids wasting space in each style
+FontNames::FontNames() {
+ max = 0;
+}
+
+FontNames::~FontNames() {
+ Clear();
+}
+
+void FontNames::Clear() {
+ for (int i=0;i<max;i++) {
+ delete []names[i];
+ }
+ max = 0;
+}
+
+const char *FontNames::Save(const char *name) {
+ if (!name)
+ return 0;
+ for (int i=0;i<max;i++) {
+ if (strcmp(names[i], name) == 0) {
+ return names[i];
+ }
+ }
+ names[max] = new char[strlen(name) + 1];
+ strcpy(names[max], name);
+ max++;
+ return names[max-1];
+}
+
+ViewStyle::ViewStyle() {
+ Init();
+}
+
+ViewStyle::ViewStyle(const ViewStyle &source) {
+ Init();
+ for (unsigned int sty=0;sty<(sizeof(styles)/sizeof(styles[0]));sty++) {
+ styles[sty] = source.styles[sty];
+ // Can't just copy fontname as its lifetime is relative to its owning ViewStyle
+ styles[sty].fontName = fontNames.Save(source.styles[sty].fontName);
+ }
+ for (int mrk=0;mrk<=MARKER_MAX;mrk++) {
+ markers[mrk] = source.markers[mrk];
+ }
+ for (int ind=0;ind<=INDIC_MAX;ind++) {
+ indicators[ind] = source.indicators[ind];
+ }
+
+ selforeset = source.selforeset;
+ selforeground.desired = source.selforeground.desired;
+ selbackset = source.selbackset;
+ selbackground.desired = source.selbackground.desired;
+ selbar.desired = source.selbar.desired;
+ selbarlight.desired = source.selbarlight.desired;
+ caretcolour.desired = source.caretcolour.desired;
+ edgecolour.desired = source.edgecolour.desired;
+ leftMarginWidth = source.leftMarginWidth;
+ rightMarginWidth = source.rightMarginWidth;
+ for (int i=0;i < margins; i++) {
+ ms[i] = source.ms[i];
+ }
+ symbolMargin = source.symbolMargin;
+ maskInLine = source.maskInLine;
+ fixedColumnWidth = source.fixedColumnWidth;
+ zoomLevel = source.zoomLevel;
+ viewWhitespace = source.viewWhitespace;
+ viewEOL = source.viewEOL;
+ showMarkedLines = source.showMarkedLines;
+}
+
+ViewStyle::~ViewStyle() {
+}
+
+void ViewStyle::Init() {
+ fontNames.Clear();
+ ResetDefaultStyle();
+
+ indicators[0].style = INDIC_SQUIGGLE;
+ indicators[0].fore = Colour(0, 0x7f, 0);
+ indicators[1].style = INDIC_TT;
+ indicators[1].fore = Colour(0, 0, 0xff);
+ indicators[2].style = INDIC_PLAIN;
+ indicators[2].fore = Colour(0xff, 0, 0);
+
+ lineHeight = 1;
+ maxAscent = 1;
+ maxDescent = 1;
+ aveCharWidth = 8;
+ spaceWidth = 8;
+
+ selforeset = false;
+ selforeground.desired = Colour(0xff, 0, 0);
+ selbackset = true;
+ selbackground.desired = Colour(0xc0, 0xc0, 0xc0);
+ selbar.desired = Platform::Chrome();
+ selbarlight.desired = Platform::ChromeHighlight();
+ styles[STYLE_LINENUMBER].fore.desired = Colour(0, 0, 0);
+ styles[STYLE_LINENUMBER].back.desired = Platform::Chrome();
+ //caretcolour.desired = Colour(0xff, 0, 0);
+ caretcolour.desired = Colour(0, 0, 0);
+ edgecolour.desired = Colour(0xc0, 0xc0, 0xc0);
+
+ leftMarginWidth = 1;
+ rightMarginWidth = 1;
+ ms[0].symbol = false;
+ ms[0].width = 0;
+ ms[0].mask = 0;
+ ms[1].symbol = true;
+ ms[1].width = 16;
+ ms[1].mask = ~SC_MASK_FOLDERS;
+ ms[2].symbol = true;
+ ms[2].width = 14; // Nice width for arrows
+ ms[2].mask = SC_MASK_FOLDERS;
+ ms[2].width = 0; // Nice width for arrows
+ ms[2].mask = 0;
+ fixedColumnWidth = leftMarginWidth;
+ symbolMargin = false;
+ maskInLine = 0xffffffff;
+ for (int margin=0; margin < margins; margin++) {
+ fixedColumnWidth += ms[margin].width;
+ symbolMargin = symbolMargin || ms[margin].symbol;
+ if (ms[margin].width > 0)
+ maskInLine &= ~ms[margin].mask;
+ }
+ zoomLevel = 0;
+ viewWhitespace = false;
+ viewEOL = false;
+ showMarkedLines = true;
+}
+
+void ViewStyle::RefreshColourPalette(Palette &pal, bool want) {
+ unsigned int i;
+ for (i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) {
+ pal.WantFind(styles[i].fore, want);
+ pal.WantFind(styles[i].back, want);
+ }
+ for (i=0;i<(sizeof(indicators)/sizeof(indicators[0]));i++) {
+ pal.WantFind(indicators[i].fore, want);
+ }
+ for (i=0;i<(sizeof(markers)/sizeof(markers[0]));i++) {
+ pal.WantFind(markers[i].fore, want);
+ pal.WantFind(markers[i].back, want);
+ }
+ pal.WantFind(selforeground, want);
+ pal.WantFind(selbackground, want);
+ pal.WantFind(selbar, want);
+ pal.WantFind(selbarlight, want);
+ pal.WantFind(caretcolour, want);
+ pal.WantFind(edgecolour, want);
+}
+
+void ViewStyle::Refresh(Surface &surface) {
+ selbar.desired = Platform::Chrome();
+ selbarlight.desired = Platform::ChromeHighlight();
+ styles[STYLE_DEFAULT].Realise(surface, zoomLevel);
+ maxAscent = styles[STYLE_DEFAULT].ascent;
+ maxDescent = styles[STYLE_DEFAULT].descent;
+ for (unsigned int i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) {
+ if (i != STYLE_DEFAULT) {
+ styles[i].Realise(surface, zoomLevel, &styles[STYLE_DEFAULT]);
+ if (maxAscent < styles[i].ascent)
+ maxAscent = styles[i].ascent;
+ if (maxDescent < styles[i].descent)
+ maxDescent = styles[i].descent;
+ }
+ }
+
+ lineHeight = maxAscent + maxDescent;
+ aveCharWidth = styles[STYLE_DEFAULT].aveCharWidth;
+ spaceWidth = styles[STYLE_DEFAULT].spaceWidth;
+
+ fixedColumnWidth = leftMarginWidth;
+ symbolMargin = false;
+ maskInLine = 0xffffffff;
+ for (int margin=0; margin < margins; margin++) {
+ fixedColumnWidth += ms[margin].width;
+ symbolMargin = symbolMargin || ms[margin].symbol;
+ if (ms[margin].width > 0)
+ maskInLine &= ~ms[margin].mask;
+ }
+}
+
+void ViewStyle::ResetDefaultStyle() {
+ styles[STYLE_DEFAULT].Clear(Colour(0,0,0), Colour(0xff,0xff,0xff),
+ Platform::DefaultFontSize(), fontNames.Save(Platform::DefaultFont()),
+ false, false, false);
+}
+
+void ViewStyle::ClearStyles() {
+ // Reset all styles to be like the default style
+ for (unsigned int i=0;i<(sizeof(styles)/sizeof(styles[0]));i++) {
+ if (i != STYLE_DEFAULT) {
+ styles[i].Clear(
+ styles[STYLE_DEFAULT].fore.desired,
+ styles[STYLE_DEFAULT].back.desired,
+ styles[STYLE_DEFAULT].size,
+ styles[STYLE_DEFAULT].fontName,
+ styles[STYLE_DEFAULT].bold,
+ styles[STYLE_DEFAULT].italic,
+ styles[STYLE_DEFAULT].eolFilled);
+ }
+ }
+ styles[STYLE_LINENUMBER].back.desired = Platform::Chrome();
+}
+
+void ViewStyle::SetStyleFontName(int styleIndex, const char *name) {
+ styles[styleIndex].fontName = fontNames.Save(name);
+}
|