1 // Scintilla source code edit control
3 ** Text document that handles notifications, DBCS, styling, words and end of line.
5 // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
6 // The License.txt file describes the conditions under which this software may be distributed.
15 #include "Scintilla.h"
17 #include "CellBuffer.h"
21 // This is ASCII specific but is safe with chars >= 0x80
22 static inline bool isspacechar(unsigned char ch
) {
23 return (ch
== ' ') || ((ch
>= 0x09) && (ch
<= 0x0d));
26 static inline bool IsPunctuation(char ch
) {
27 return isascii(ch
) && ispunct(ch
);
30 static inline bool IsADigit(char ch
) {
31 return isascii(ch
) && isdigit(ch
);
34 static inline bool IsLowerCase(char ch
) {
35 return isascii(ch
) && islower(ch
);
38 static inline bool IsUpperCase(char ch
) {
39 return isascii(ch
) && isupper(ch
);
42 Document::Document() {
47 eolMode
= SC_EOL_CRLF
;
51 stylingBitsMask
= 0x1F;
53 SetDefaultCharClasses(true);
57 enteredReadOnlyCount
= 0;
60 actualIndentInChars
= 8;
63 backspaceUnindents
= false;
72 Document::~Document() {
73 for (int i
= 0; i
< lenWatchers
; i
++) {
74 watchers
[i
].watcher
->NotifyDeleted(this, watchers
[i
].userData
);
85 // Increase reference count and return its previous value.
86 int Document::AddRef() {
90 // Decrease reference count and return its previous value.
91 // Delete the document if reference count reaches zero.
92 int Document::Release() {
93 int curRefCount
= --refCount
;
99 void Document::SetSavePoint() {
101 NotifySavePoint(true);
104 int Document::AddMark(int line
, int markerNum
) {
105 int prev
= cb
.AddMark(line
, markerNum
);
106 DocModification
mh(SC_MOD_CHANGEMARKER
, LineStart(line
), 0, 0, 0);
111 void Document::DeleteMark(int line
, int markerNum
) {
112 cb
.DeleteMark(line
, markerNum
);
113 DocModification
mh(SC_MOD_CHANGEMARKER
, LineStart(line
), 0, 0, 0);
117 void Document::DeleteMarkFromHandle(int markerHandle
) {
118 cb
.DeleteMarkFromHandle(markerHandle
);
119 DocModification
mh(SC_MOD_CHANGEMARKER
, 0, 0, 0, 0);
123 void Document::DeleteAllMarks(int markerNum
) {
124 cb
.DeleteAllMarks(markerNum
);
125 DocModification
mh(SC_MOD_CHANGEMARKER
, 0, 0, 0, 0);
129 int Document::LineStart(int line
) {
130 return cb
.LineStart(line
);
133 int Document::LineEnd(int line
) {
134 if (line
== LinesTotal() - 1) {
135 return LineStart(line
+ 1);
137 int position
= LineStart(line
+ 1) - 1;
138 // When line terminator is CR+LF, may need to go back one more
139 if ((position
> LineStart(line
)) && (cb
.CharAt(position
- 1) == '\r')) {
146 int Document::LineFromPosition(int pos
) {
147 return cb
.LineFromPosition(pos
);
150 int Document::LineEndPosition(int position
) {
151 return LineEnd(LineFromPosition(position
));
154 int Document::VCHomePosition(int position
) {
155 int line
= LineFromPosition(position
);
156 int startPosition
= LineStart(line
);
157 int endLine
= LineStart(line
+ 1) - 1;
158 int startText
= startPosition
;
159 while (startText
< endLine
&& (cb
.CharAt(startText
) == ' ' || cb
.CharAt(startText
) == '\t' ) )
161 if (position
== startText
)
162 return startPosition
;
167 int Document::SetLevel(int line
, int level
) {
168 int prev
= cb
.SetLevel(line
, level
);
170 DocModification
mh(SC_MOD_CHANGEFOLD
| SC_MOD_CHANGEMARKER
,
171 LineStart(line
), 0, 0, 0);
173 mh
.foldLevelNow
= level
;
174 mh
.foldLevelPrev
= prev
;
180 static bool IsSubordinate(int levelStart
, int levelTry
) {
181 if (levelTry
& SC_FOLDLEVELWHITEFLAG
)
184 return (levelStart
& SC_FOLDLEVELNUMBERMASK
) < (levelTry
& SC_FOLDLEVELNUMBERMASK
);
187 int Document::GetLastChild(int lineParent
, int level
) {
189 level
= GetLevel(lineParent
) & SC_FOLDLEVELNUMBERMASK
;
190 int maxLine
= LinesTotal();
191 int lineMaxSubord
= lineParent
;
192 while (lineMaxSubord
< maxLine
- 1) {
193 EnsureStyledTo(LineStart(lineMaxSubord
+ 2));
194 if (!IsSubordinate(level
, GetLevel(lineMaxSubord
+ 1)))
198 if (lineMaxSubord
> lineParent
) {
199 if (level
> (GetLevel(lineMaxSubord
+ 1) & SC_FOLDLEVELNUMBERMASK
)) {
200 // Have chewed up some whitespace that belongs to a parent so seek back
201 if (GetLevel(lineMaxSubord
) & SC_FOLDLEVELWHITEFLAG
) {
206 return lineMaxSubord
;
209 int Document::GetFoldParent(int line
) {
210 int level
= GetLevel(line
) & SC_FOLDLEVELNUMBERMASK
;
211 int lineLook
= line
- 1;
212 while ((lineLook
> 0) && (
213 (!(GetLevel(lineLook
) & SC_FOLDLEVELHEADERFLAG
)) ||
214 ((GetLevel(lineLook
) & SC_FOLDLEVELNUMBERMASK
) >= level
))
218 if ((GetLevel(lineLook
) & SC_FOLDLEVELHEADERFLAG
) &&
219 ((GetLevel(lineLook
) & SC_FOLDLEVELNUMBERMASK
) < level
)) {
226 int Document::ClampPositionIntoDocument(int pos
) {
227 return Platform::Clamp(pos
, 0, Length());
230 bool Document::IsCrLf(int pos
) {
233 if (pos
>= (Length() - 1))
235 return (cb
.CharAt(pos
) == '\r') && (cb
.CharAt(pos
+ 1) == '\n');
238 static const int maxBytesInDBCSCharacter
=5;
240 int Document::LenChar(int pos
) {
243 } else if (IsCrLf(pos
)) {
245 } else if (SC_CP_UTF8
== dbcsCodePage
) {
246 unsigned char ch
= static_cast<unsigned char>(cb
.CharAt(pos
));
250 if (ch
>= (0x80 + 0x40 + 0x20))
252 int lengthDoc
= Length();
253 if ((pos
+ len
) > lengthDoc
)
254 return lengthDoc
-pos
;
257 } else if (dbcsCodePage
) {
258 char mbstr
[maxBytesInDBCSCharacter
+1];
260 for (i
=0; i
<Platform::DBCSCharMaxLength(); i
++) {
261 mbstr
[i
] = cb
.CharAt(pos
+i
);
264 return Platform::DBCSCharLength(dbcsCodePage
, mbstr
);
270 // Normalise a position so that it is not halfway through a two byte character.
271 // This can occur in two situations -
272 // When lines are terminated with \r\n pairs which should be treated as one character.
273 // When displaying DBCS text such as Japanese.
274 // If moving, move the position in the indicated direction.
275 int Document::MovePositionOutsideChar(int pos
, int moveDir
, bool checkLineEnd
) {
276 //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
277 // If out of range, just return minimum/maximum value.
283 // assert pos > 0 && pos < Length()
284 if (checkLineEnd
&& IsCrLf(pos
- 1)) {
291 // Not between CR and LF
294 if (SC_CP_UTF8
== dbcsCodePage
) {
295 unsigned char ch
= static_cast<unsigned char>(cb
.CharAt(pos
));
296 while ((pos
> 0) && (pos
< Length()) && (ch
>= 0x80) && (ch
< (0x80 + 0x40))) {
297 // ch is a trail byte
302 ch
= static_cast<unsigned char>(cb
.CharAt(pos
));
305 // Anchor DBCS calculations at start of line because start of line can
306 // not be a DBCS trail byte.
307 int posCheck
= LineStart(LineFromPosition(pos
));
308 while (posCheck
< pos
) {
309 char mbstr
[maxBytesInDBCSCharacter
+1];
311 for(i
=0;i
<Platform::DBCSCharMaxLength();i
++) {
312 mbstr
[i
] = cb
.CharAt(posCheck
+i
);
316 int mbsize
= Platform::DBCSCharLength(dbcsCodePage
, mbstr
);
317 if (posCheck
+ mbsize
== pos
) {
319 } else if (posCheck
+ mbsize
> pos
) {
321 return posCheck
+ mbsize
;
334 void Document::ModifiedAt(int pos
) {
339 // Document only modified by gateways DeleteChars, InsertStyledString, Undo, Redo, and SetStyleAt.
340 // SetStyleAt does not change the persistent state of a document
342 // Unlike Undo, Redo, and InsertStyledString, the pos argument is a cell number not a char number
343 bool Document::DeleteChars(int pos
, int len
) {
346 if ((pos
+ len
) > Length())
348 if (cb
.IsReadOnly() && enteredReadOnlyCount
== 0) {
349 enteredReadOnlyCount
++;
350 NotifyModifyAttempt();
351 enteredReadOnlyCount
--;
353 if (enteredCount
!= 0) {
357 if (!cb
.IsReadOnly()) {
360 SC_MOD_BEFOREDELETE
| SC_PERFORMED_USER
,
363 int prevLinesTotal
= LinesTotal();
364 bool startSavePoint
= cb
.IsSavePoint();
365 const char *text
= cb
.DeleteChars(pos
* 2, len
* 2);
366 if (startSavePoint
&& cb
.IsCollectingUndo())
367 NotifySavePoint(!startSavePoint
);
368 if ((pos
< Length()) || (pos
== 0))
374 SC_MOD_DELETETEXT
| SC_PERFORMED_USER
,
376 LinesTotal() - prevLinesTotal
, text
));
380 return !cb
.IsReadOnly();
384 * Insert a styled string (char/style pairs) with a length.
386 bool Document::InsertStyledString(int position
, char *s
, int insertLength
) {
387 if (cb
.IsReadOnly() && enteredReadOnlyCount
== 0) {
388 enteredReadOnlyCount
++;
389 NotifyModifyAttempt();
390 enteredReadOnlyCount
--;
392 if (enteredCount
!= 0) {
396 if (!cb
.IsReadOnly()) {
399 SC_MOD_BEFOREINSERT
| SC_PERFORMED_USER
,
400 position
/ 2, insertLength
/ 2,
402 int prevLinesTotal
= LinesTotal();
403 bool startSavePoint
= cb
.IsSavePoint();
404 const char *text
= cb
.InsertString(position
, s
, insertLength
);
405 if (startSavePoint
&& cb
.IsCollectingUndo())
406 NotifySavePoint(!startSavePoint
);
407 ModifiedAt(position
/ 2);
410 SC_MOD_INSERTTEXT
| SC_PERFORMED_USER
,
411 position
/ 2, insertLength
/ 2,
412 LinesTotal() - prevLinesTotal
, text
));
416 return !cb
.IsReadOnly();
419 int Document::Undo() {
421 if (enteredCount
== 0) {
423 bool startSavePoint
= cb
.IsSavePoint();
424 int steps
= cb
.StartUndo();
425 //Platform::DebugPrintf("Steps=%d\n", steps);
426 for (int step
= 0; step
< steps
; step
++) {
427 int prevLinesTotal
= LinesTotal();
428 const Action
&action
= cb
.GetUndoStep();
429 if (action
.at
== removeAction
) {
430 NotifyModified(DocModification(
431 SC_MOD_BEFOREINSERT
| SC_PERFORMED_UNDO
, action
));
433 NotifyModified(DocModification(
434 SC_MOD_BEFOREDELETE
| SC_PERFORMED_UNDO
, action
));
436 cb
.PerformUndoStep();
437 int cellPosition
= action
.position
/ 2;
438 ModifiedAt(cellPosition
);
439 newPos
= cellPosition
;
441 int modFlags
= SC_PERFORMED_UNDO
;
442 // With undo, an insertion action becomes a deletion notification
443 if (action
.at
== removeAction
) {
444 newPos
+= action
.lenData
;
445 modFlags
|= SC_MOD_INSERTTEXT
;
447 modFlags
|= SC_MOD_DELETETEXT
;
449 if (step
== steps
- 1)
450 modFlags
|= SC_LASTSTEPINUNDOREDO
;
451 NotifyModified(DocModification(modFlags
, cellPosition
, action
.lenData
,
452 LinesTotal() - prevLinesTotal
, action
.data
));
455 bool endSavePoint
= cb
.IsSavePoint();
456 if (startSavePoint
!= endSavePoint
)
457 NotifySavePoint(endSavePoint
);
463 int Document::Redo() {
465 if (enteredCount
== 0) {
467 bool startSavePoint
= cb
.IsSavePoint();
468 int steps
= cb
.StartRedo();
469 for (int step
= 0; step
< steps
; step
++) {
470 int prevLinesTotal
= LinesTotal();
471 const Action
&action
= cb
.GetRedoStep();
472 if (action
.at
== insertAction
) {
473 NotifyModified(DocModification(
474 SC_MOD_BEFOREINSERT
| SC_PERFORMED_REDO
, action
));
476 NotifyModified(DocModification(
477 SC_MOD_BEFOREDELETE
| SC_PERFORMED_REDO
, action
));
479 cb
.PerformRedoStep();
480 ModifiedAt(action
.position
/ 2);
481 newPos
= action
.position
/ 2;
483 int modFlags
= SC_PERFORMED_REDO
;
484 if (action
.at
== insertAction
) {
485 newPos
+= action
.lenData
;
486 modFlags
|= SC_MOD_INSERTTEXT
;
488 modFlags
|= SC_MOD_DELETETEXT
;
490 if (step
== steps
- 1)
491 modFlags
|= SC_LASTSTEPINUNDOREDO
;
493 DocModification(modFlags
, action
.position
/ 2, action
.lenData
,
494 LinesTotal() - prevLinesTotal
, action
.data
));
497 bool endSavePoint
= cb
.IsSavePoint();
498 if (startSavePoint
!= endSavePoint
)
499 NotifySavePoint(endSavePoint
);
506 * Insert a single character.
508 bool Document::InsertChar(int pos
, char ch
) {
512 return InsertStyledString(pos
*2, chs
, 2);
516 * Insert a null terminated string.
518 bool Document::InsertString(int position
, const char *s
) {
519 return InsertString(position
, s
, strlen(s
));
523 * Insert a string with a length.
525 bool Document::InsertString(int position
, const char *s
, size_t insertLength
) {
526 bool changed
= false;
527 char *sWithStyle
= new char[insertLength
* 2];
529 for (size_t i
= 0; i
< insertLength
; i
++) {
530 sWithStyle
[i
*2] = s
[i
];
531 sWithStyle
[i
*2 + 1] = 0;
533 changed
= InsertStyledString(position
*2, sWithStyle
,
534 static_cast<int>(insertLength
*2));
540 void Document::ChangeChar(int pos
, char ch
) {
545 void Document::DelChar(int pos
) {
546 DeleteChars(pos
, LenChar(pos
));
549 void Document::DelCharBack(int pos
) {
552 } else if (IsCrLf(pos
- 2)) {
553 DeleteChars(pos
- 2, 2);
554 } else if (dbcsCodePage
) {
555 int startChar
= MovePositionOutsideChar(pos
- 1, -1, false);
556 DeleteChars(startChar
, pos
- startChar
);
558 DeleteChars(pos
- 1, 1);
562 static bool isindentchar(char ch
) {
563 return (ch
== ' ') || (ch
== '\t');
566 static int NextTab(int pos
, int tabSize
) {
567 return ((pos
/ tabSize
) + 1) * tabSize
;
570 static void CreateIndentation(char *linebuf
, int length
, int indent
, int tabSize
, bool insertSpaces
) {
571 length
--; // ensure space for \0
573 while ((indent
>= tabSize
) && (length
> 0)) {
579 while ((indent
> 0) && (length
> 0)) {
587 int Document::GetLineIndentation(int line
) {
589 if ((line
>= 0) && (line
< LinesTotal())) {
590 int lineStart
= LineStart(line
);
591 int length
= Length();
592 for (int i
= lineStart
;i
< length
;i
++) {
593 char ch
= cb
.CharAt(i
);
597 indent
= NextTab(indent
, tabInChars
);
605 void Document::SetLineIndentation(int line
, int indent
) {
606 int indentOfLine
= GetLineIndentation(line
);
609 if (indent
!= indentOfLine
) {
611 CreateIndentation(linebuf
, sizeof(linebuf
), indent
, tabInChars
, !useTabs
);
612 int thisLineStart
= LineStart(line
);
613 int indentPos
= GetLineIndentPosition(line
);
614 DeleteChars(thisLineStart
, indentPos
- thisLineStart
);
615 InsertString(thisLineStart
, linebuf
);
619 int Document::GetLineIndentPosition(int line
) {
622 int pos
= LineStart(line
);
623 int length
= Length();
624 while ((pos
< length
) && isindentchar(cb
.CharAt(pos
))) {
630 int Document::GetColumn(int pos
) {
632 int line
= LineFromPosition(pos
);
633 if ((line
>= 0) && (line
< LinesTotal())) {
634 for (int i
= LineStart(line
);i
< pos
;) {
635 char ch
= cb
.CharAt(i
);
637 column
= NextTab(column
, tabInChars
);
639 } else if (ch
== '\r') {
641 } else if (ch
== '\n') {
645 i
= MovePositionOutsideChar(i
+ 1, 1);
652 int Document::FindColumn(int line
, int column
) {
653 int position
= LineStart(line
);
654 int columnCurrent
= 0;
655 if ((line
>= 0) && (line
< LinesTotal())) {
656 while ((columnCurrent
< column
) && (position
< Length())) {
657 char ch
= cb
.CharAt(position
);
659 columnCurrent
= NextTab(columnCurrent
, tabInChars
);
661 } else if (ch
== '\r') {
663 } else if (ch
== '\n') {
667 position
= MovePositionOutsideChar(position
+ 1, 1);
674 void Document::Indent(bool forwards
, int lineBottom
, int lineTop
) {
675 // Dedent - suck white space off the front of the line to dedent by equivalent of a tab
676 for (int line
= lineBottom
; line
>= lineTop
; line
--) {
677 int indentOfLine
= GetLineIndentation(line
);
679 SetLineIndentation(line
, indentOfLine
+ IndentSize());
681 SetLineIndentation(line
, indentOfLine
- IndentSize());
685 // Convert line endings for a piece of text to a particular mode.
686 // Stop at len or when a NUL is found.
687 // Caller must delete the returned pointer.
688 char *Document::TransformLineEnds(int *pLenOut
, const char *s
, size_t len
, int eolMode
) {
689 char *dest
= new char[2 * len
+ 1];
690 const char *sptr
= s
;
692 for (size_t i
= 0; (i
< len
) && (*sptr
!= '\0'); i
++) {
693 if (*sptr
== '\n' || *sptr
== '\r') {
694 if (eolMode
== SC_EOL_CR
) {
696 } else if (eolMode
== SC_EOL_LF
) {
698 } else { // eolMode == SC_EOL_CRLF
702 if ((*sptr
== '\r') && (i
+1 < len
) && (*(sptr
+1) == '\n')) {
712 *pLenOut
= (dptr
- dest
) - 1;
716 void Document::ConvertLineEnds(int eolModeSet
) {
719 for (int pos
= 0; pos
< Length(); pos
++) {
720 if (cb
.CharAt(pos
) == '\r') {
721 if (cb
.CharAt(pos
+ 1) == '\n') {
723 if (eolModeSet
== SC_EOL_CR
) {
724 DeleteChars(pos
+ 1, 1); // Delete the LF
725 } else if (eolModeSet
== SC_EOL_LF
) {
726 DeleteChars(pos
, 1); // Delete the CR
732 if (eolModeSet
== SC_EOL_CRLF
) {
733 InsertString(pos
+ 1, "\n", 1); // Insert LF
735 } else if (eolModeSet
== SC_EOL_LF
) {
736 InsertString(pos
, "\n", 1); // Insert LF
737 DeleteChars(pos
+ 1, 1); // Delete CR
740 } else if (cb
.CharAt(pos
) == '\n') {
742 if (eolModeSet
== SC_EOL_CRLF
) {
743 InsertString(pos
, "\r", 1); // Insert CR
745 } else if (eolModeSet
== SC_EOL_CR
) {
746 InsertString(pos
, "\r", 1); // Insert CR
747 DeleteChars(pos
+ 1, 1); // Delete LF
755 int Document::ParaDown(int pos
) {
756 int line
= LineFromPosition(pos
);
757 while (line
< LinesTotal() && LineStart(line
) != LineEnd(line
)) { // skip non-empty lines
760 while (line
< LinesTotal() && LineStart(line
) == LineEnd(line
)) { // skip empty lines
763 if (line
< LinesTotal())
764 return LineStart(line
);
765 else // end of a document
766 return LineEnd(line
-1);
769 int Document::ParaUp(int pos
) {
770 int line
= LineFromPosition(pos
);
772 while (line
>= 0 && LineStart(line
) == LineEnd(line
)) { // skip empty lines
775 while (line
>= 0 && LineStart(line
) != LineEnd(line
)) { // skip non-empty lines
779 return LineStart(line
);
782 Document::charClassification
Document::WordCharClass(unsigned char ch
) {
783 if ((SC_CP_UTF8
== dbcsCodePage
) && (ch
>= 0x80))
785 return charClass
[ch
];
789 * Used by commmands that want to select whole words.
790 * Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0.
792 int Document::ExtendWordSelect(int pos
, int delta
, bool onlyWordCharacters
) {
793 charClassification ccStart
= ccWord
;
795 if (!onlyWordCharacters
)
796 ccStart
= WordCharClass(cb
.CharAt(pos
-1));
797 while (pos
> 0 && (WordCharClass(cb
.CharAt(pos
- 1)) == ccStart
))
800 if (!onlyWordCharacters
)
801 ccStart
= WordCharClass(cb
.CharAt(pos
));
802 while (pos
< (Length()) && (WordCharClass(cb
.CharAt(pos
)) == ccStart
))
805 return MovePositionOutsideChar(pos
, delta
);
809 * Find the start of the next word in either a forward (delta >= 0) or backwards direction
811 * This is looking for a transition between character classes although there is also some
812 * additional movement to transit white space.
813 * Used by cursor movement by word commands.
815 int Document::NextWordStart(int pos
, int delta
) {
817 while (pos
> 0 && (WordCharClass(cb
.CharAt(pos
- 1)) == ccSpace
))
820 charClassification ccStart
= WordCharClass(cb
.CharAt(pos
-1));
821 while (pos
> 0 && (WordCharClass(cb
.CharAt(pos
- 1)) == ccStart
)) {
826 charClassification ccStart
= WordCharClass(cb
.CharAt(pos
));
827 while (pos
< (Length()) && (WordCharClass(cb
.CharAt(pos
)) == ccStart
))
829 while (pos
< (Length()) && (WordCharClass(cb
.CharAt(pos
)) == ccSpace
))
836 * Find the end of the next word in either a forward (delta >= 0) or backwards direction
838 * This is looking for a transition between character classes although there is also some
839 * additional movement to transit white space.
840 * Used by cursor movement by word commands.
842 int Document::NextWordEnd(int pos
, int delta
) {
845 charClassification ccStart
= WordCharClass(cb
.CharAt(pos
-1));
846 if (ccStart
!= ccSpace
) {
847 while (pos
> 0 && WordCharClass(cb
.CharAt(pos
- 1)) == ccStart
) {
851 while (pos
> 0 && WordCharClass(cb
.CharAt(pos
- 1)) == ccSpace
) {
856 while (pos
< Length() && WordCharClass(cb
.CharAt(pos
)) == ccSpace
) {
859 if (pos
< Length()) {
860 charClassification ccStart
= WordCharClass(cb
.CharAt(pos
));
861 while (pos
< Length() && WordCharClass(cb
.CharAt(pos
)) == ccStart
) {
870 * Check that the character at the given position is a word or punctuation character and that
871 * the previous character is of a different character class.
873 bool Document::IsWordStartAt(int pos
) {
875 charClassification ccPos
= WordCharClass(CharAt(pos
));
876 return (ccPos
== ccWord
|| ccPos
== ccPunctuation
) &&
877 (ccPos
!= WordCharClass(CharAt(pos
- 1)));
883 * Check that the character at the given position is a word or punctuation character and that
884 * the next character is of a different character class.
886 bool Document::IsWordEndAt(int pos
) {
887 if (pos
< Length()) {
888 charClassification ccPrev
= WordCharClass(CharAt(pos
-1));
889 return (ccPrev
== ccWord
|| ccPrev
== ccPunctuation
) &&
890 (ccPrev
!= WordCharClass(CharAt(pos
)));
896 * Check that the given range is has transitions between character classes at both
897 * ends and where the characters on the inside are word or punctuation characters.
899 bool Document::IsWordAt(int start
, int end
) {
900 return IsWordStartAt(start
) && IsWordEndAt(end
);
903 // The comparison and case changing functions here assume ASCII
904 // or extended ASCII such as the normal Windows code page.
906 static inline char MakeUpperCase(char ch
) {
907 if (ch
< 'a' || ch
> 'z')
910 return static_cast<char>(ch
- 'a' + 'A');
913 static inline char MakeLowerCase(char ch
) {
914 if (ch
< 'A' || ch
> 'Z')
917 return static_cast<char>(ch
- 'A' + 'a');
920 // Define a way for the Regular Expression code to access the document
921 class DocumentIndexer
: public CharacterIndexer
{
925 DocumentIndexer(Document
*pdoc_
, int end_
) :
926 pdoc(pdoc_
), end(end_
) {
929 virtual char CharAt(int index
) {
930 if (index
< 0 || index
>= end
)
933 return pdoc
->CharAt(index
);
938 * Find text in document, supporting both forward and backward
939 * searches (just pass minPos > maxPos to do a backward search)
940 * Has not been tested with backwards DBCS searches yet.
942 long Document::FindText(int minPos
, int maxPos
, const char *s
,
943 bool caseSensitive
, bool word
, bool wordStart
, bool regExp
, bool posix
,
947 pre
= new RESearch();
951 int increment
= (minPos
<= maxPos
) ? 1 : -1;
953 int startPos
= minPos
;
956 // Range endpoints should not be inside DBCS characters, but just in case, move them.
957 startPos
= MovePositionOutsideChar(startPos
, 1, false);
958 endPos
= MovePositionOutsideChar(endPos
, 1, false);
960 const char *errmsg
= pre
->Compile(s
, *length
, caseSensitive
, posix
);
964 // Find a variable in a property file: \$(\([A-Za-z0-9_.]+\))
965 // Replace first '.' with '-' in each property file variable reference:
966 // Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\))
968 int lineRangeStart
= LineFromPosition(startPos
);
969 int lineRangeEnd
= LineFromPosition(endPos
);
970 if ((increment
== 1) &&
971 (startPos
>= LineEnd(lineRangeStart
)) &&
972 (lineRangeStart
< lineRangeEnd
)) {
973 // the start position is at end of line or between line end characters.
975 startPos
= LineStart(lineRangeStart
);
979 char searchEnd
= s
[*length
- 1];
980 int lineRangeBreak
= lineRangeEnd
+ increment
;
981 for (int line
= lineRangeStart
; line
!= lineRangeBreak
; line
+= increment
) {
982 int startOfLine
= LineStart(line
);
983 int endOfLine
= LineEnd(line
);
984 if (increment
== 1) {
985 if (line
== lineRangeStart
) {
986 if ((startPos
!= startOfLine
) && (s
[0] == '^'))
987 continue; // Can't match start of line if start position after start of line
988 startOfLine
= startPos
;
990 if (line
== lineRangeEnd
) {
991 if ((endPos
!= endOfLine
) && (searchEnd
== '$'))
992 continue; // Can't match end of line if end position before end of line
996 if (line
== lineRangeEnd
) {
997 if ((endPos
!= startOfLine
) && (s
[0] == '^'))
998 continue; // Can't match start of line if end position after start of line
999 startOfLine
= endPos
;
1001 if (line
== lineRangeStart
) {
1002 if ((startPos
!= endOfLine
) && (searchEnd
== '$'))
1003 continue; // Can't match end of line if start position before end of line
1004 endOfLine
= startPos
+1;
1008 DocumentIndexer
di(this, endOfLine
);
1009 int success
= pre
->Execute(di
, startOfLine
, endOfLine
);
1011 pos
= pre
->bopat
[0];
1012 lenRet
= pre
->eopat
[0] - pre
->bopat
[0];
1013 if (increment
== -1) {
1014 // Check for the last match on this line.
1015 int repetitions
= 1000; // Break out of infinite loop
1016 while (success
&& (pre
->eopat
[0] <= (endOfLine
+1)) && (repetitions
--)) {
1017 success
= pre
->Execute(di
, pos
+1, endOfLine
+1);
1019 if (pre
->eopat
[0] <= (minPos
+1)) {
1020 pos
= pre
->bopat
[0];
1021 lenRet
= pre
->eopat
[0] - pre
->bopat
[0];
1036 bool forward
= minPos
<= maxPos
;
1037 int increment
= forward
? 1 : -1;
1039 // Range endpoints should not be inside DBCS characters, but just in case, move them.
1040 int startPos
= MovePositionOutsideChar(minPos
, increment
, false);
1041 int endPos
= MovePositionOutsideChar(maxPos
, increment
, false);
1043 // Compute actual search ranges needed
1044 int lengthFind
= *length
;
1045 if (lengthFind
== -1)
1046 lengthFind
= static_cast<int>(strlen(s
));
1047 int endSearch
= endPos
;
1048 if (startPos
<= endPos
) {
1049 endSearch
= endPos
- lengthFind
+ 1;
1051 //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
1052 char firstChar
= s
[0];
1054 firstChar
= static_cast<char>(MakeUpperCase(firstChar
));
1056 while (forward
? (pos
< endSearch
) : (pos
>= endSearch
)) {
1057 char ch
= CharAt(pos
);
1058 if (caseSensitive
) {
1059 if (ch
== firstChar
) {
1061 for (int posMatch
= 1; posMatch
< lengthFind
&& found
; posMatch
++) {
1062 ch
= CharAt(pos
+ posMatch
);
1063 if (ch
!= s
[posMatch
])
1067 if ((!word
&& !wordStart
) ||
1068 word
&& IsWordAt(pos
, pos
+ lengthFind
) ||
1069 wordStart
&& IsWordStartAt(pos
))
1074 if (MakeUpperCase(ch
) == firstChar
) {
1076 for (int posMatch
= 1; posMatch
< lengthFind
&& found
; posMatch
++) {
1077 ch
= CharAt(pos
+ posMatch
);
1078 if (MakeUpperCase(ch
) != MakeUpperCase(s
[posMatch
]))
1082 if ((!word
&& !wordStart
) ||
1083 word
&& IsWordAt(pos
, pos
+ lengthFind
) ||
1084 wordStart
&& IsWordStartAt(pos
))
1090 if (dbcsCodePage
&& (pos
>= 0)) {
1091 // Ensure trying to match from start of character
1092 pos
= MovePositionOutsideChar(pos
, increment
, false);
1096 //Platform::DebugPrintf("Not found\n");
1100 const char *Document::SubstituteByPosition(const char *text
, int *length
) {
1103 delete []substituted
;
1105 DocumentIndexer
di(this, Length());
1106 if (!pre
->GrabMatches(di
))
1108 unsigned int lenResult
= 0;
1109 for (int i
= 0; i
< *length
; i
++) {
1110 if (text
[i
] == '\\') {
1111 if (text
[i
+ 1] >= '1' && text
[i
+ 1] <= '9') {
1112 unsigned int patNum
= text
[i
+ 1] - '0';
1113 lenResult
+= pre
->eopat
[patNum
] - pre
->bopat
[patNum
];
1116 switch (text
[i
+ 1]) {
1132 substituted
= new char[lenResult
+ 1];
1135 char *o
= substituted
;
1136 for (int j
= 0; j
< *length
; j
++) {
1137 if (text
[j
] == '\\') {
1138 if (text
[j
+ 1] >= '1' && text
[j
+ 1] <= '9') {
1139 unsigned int patNum
= text
[j
+ 1] - '0';
1140 unsigned int len
= pre
->eopat
[patNum
] - pre
->bopat
[patNum
];
1141 if (pre
->pat
[patNum
]) // Will be null if try for a match that did not occur
1142 memcpy(o
, pre
->pat
[patNum
], len
);
1179 *length
= lenResult
;
1183 int Document::LinesTotal() {
1187 void Document::ChangeCase(Range r
, bool makeUpperCase
) {
1188 for (int pos
= r
.start
; pos
< r
.end
; pos
++) {
1189 int len
= LenChar(pos
);
1190 if (dbcsCodePage
&& (len
> 1)) {
1193 char ch
= CharAt(pos
);
1194 if (makeUpperCase
) {
1195 if (IsLowerCase(ch
)) {
1196 ChangeChar(pos
, static_cast<char>(MakeUpperCase(ch
)));
1199 if (IsUpperCase(ch
)) {
1200 ChangeChar(pos
, static_cast<char>(MakeLowerCase(ch
)));
1207 void Document::SetDefaultCharClasses(bool includeWordClass
) {
1208 // Initialize all char classes to default values
1209 for (int ch
= 0; ch
< 256; ch
++) {
1210 if (ch
== '\r' || ch
== '\n')
1211 charClass
[ch
] = ccNewLine
;
1212 else if (ch
< 0x20 || ch
== ' ')
1213 charClass
[ch
] = ccSpace
;
1214 else if (includeWordClass
&& (ch
>= 0x80 || isalnum(ch
) || ch
== '_'))
1215 charClass
[ch
] = ccWord
;
1217 charClass
[ch
] = ccPunctuation
;
1221 void Document::SetCharClasses(const unsigned char *chars
, charClassification newCharClass
) {
1222 // Apply the newCharClass to the specifed chars
1225 charClass
[*chars
] = newCharClass
;
1231 void Document::SetStylingBits(int bits
) {
1233 stylingBitsMask
= 0;
1234 for (int bit
= 0; bit
< stylingBits
; bit
++) {
1235 stylingBitsMask
<<= 1;
1236 stylingBitsMask
|= 1;
1240 void Document::StartStyling(int position
, char mask
) {
1242 endStyled
= position
;
1245 bool Document::SetStyleFor(int length
, char style
) {
1246 if (enteredCount
!= 0) {
1250 style
&= stylingMask
;
1251 int prevEndStyled
= endStyled
;
1252 if (cb
.SetStyleFor(endStyled
, length
, style
, stylingMask
)) {
1253 DocModification
mh(SC_MOD_CHANGESTYLE
| SC_PERFORMED_USER
,
1254 prevEndStyled
, length
);
1257 endStyled
+= length
;
1263 bool Document::SetStyles(int length
, char *styles
) {
1264 if (enteredCount
!= 0) {
1268 int prevEndStyled
= endStyled
;
1269 bool didChange
= false;
1271 for (int iPos
= 0; iPos
< length
; iPos
++, endStyled
++) {
1272 PLATFORM_ASSERT(endStyled
< Length());
1273 if (cb
.SetStyleAt(endStyled
, styles
[iPos
], stylingMask
)) {
1279 DocModification
mh(SC_MOD_CHANGESTYLE
| SC_PERFORMED_USER
,
1280 prevEndStyled
, lastChange
);
1288 bool Document::EnsureStyledTo(int pos
) {
1289 if (pos
> GetEndStyled()) {
1290 IncrementStyleClock();
1291 // Ask the watchers to style, and stop as soon as one responds.
1292 for (int i
= 0; pos
> GetEndStyled() && i
< lenWatchers
; i
++) {
1293 watchers
[i
].watcher
->NotifyStyleNeeded(this, watchers
[i
].userData
, pos
);
1296 return pos
<= GetEndStyled();
1299 void Document::IncrementStyleClock() {
1301 if (styleClock
> 0x100000) {
1306 bool Document::AddWatcher(DocWatcher
*watcher
, void *userData
) {
1307 for (int i
= 0; i
< lenWatchers
; i
++) {
1308 if ((watchers
[i
].watcher
== watcher
) &&
1309 (watchers
[i
].userData
== userData
))
1312 WatcherWithUserData
*pwNew
= new WatcherWithUserData
[lenWatchers
+ 1];
1315 for (int j
= 0; j
< lenWatchers
; j
++)
1316 pwNew
[j
] = watchers
[j
];
1317 pwNew
[lenWatchers
].watcher
= watcher
;
1318 pwNew
[lenWatchers
].userData
= userData
;
1325 bool Document::RemoveWatcher(DocWatcher
*watcher
, void *userData
) {
1326 for (int i
= 0; i
< lenWatchers
; i
++) {
1327 if ((watchers
[i
].watcher
== watcher
) &&
1328 (watchers
[i
].userData
== userData
)) {
1329 if (lenWatchers
== 1) {
1334 WatcherWithUserData
*pwNew
= new WatcherWithUserData
[lenWatchers
];
1337 for (int j
= 0; j
< lenWatchers
- 1; j
++) {
1338 pwNew
[j
] = (j
< i
) ? watchers
[j
] : watchers
[j
+ 1];
1350 void Document::NotifyModifyAttempt() {
1351 for (int i
= 0; i
< lenWatchers
; i
++) {
1352 watchers
[i
].watcher
->NotifyModifyAttempt(this, watchers
[i
].userData
);
1356 void Document::NotifySavePoint(bool atSavePoint
) {
1357 for (int i
= 0; i
< lenWatchers
; i
++) {
1358 watchers
[i
].watcher
->NotifySavePoint(this, watchers
[i
].userData
, atSavePoint
);
1362 void Document::NotifyModified(DocModification mh
) {
1363 for (int i
= 0; i
< lenWatchers
; i
++) {
1364 watchers
[i
].watcher
->NotifyModified(this, mh
, watchers
[i
].userData
);
1368 bool Document::IsWordPartSeparator(char ch
) {
1369 return (WordCharClass(ch
) == ccWord
) && IsPunctuation(ch
);
1372 int Document::WordPartLeft(int pos
) {
1375 char startChar
= cb
.CharAt(pos
);
1376 if (IsWordPartSeparator(startChar
)) {
1377 while (pos
> 0 && IsWordPartSeparator(cb
.CharAt(pos
))) {
1382 startChar
= cb
.CharAt(pos
);
1384 if (IsLowerCase(startChar
)) {
1385 while (pos
> 0 && IsLowerCase(cb
.CharAt(pos
)))
1387 if (!IsUpperCase(cb
.CharAt(pos
)) && !IsLowerCase(cb
.CharAt(pos
)))
1389 } else if (IsUpperCase(startChar
)) {
1390 while (pos
> 0 && IsUpperCase(cb
.CharAt(pos
)))
1392 if (!IsUpperCase(cb
.CharAt(pos
)))
1394 } else if (IsADigit(startChar
)) {
1395 while (pos
> 0 && IsADigit(cb
.CharAt(pos
)))
1397 if (!IsADigit(cb
.CharAt(pos
)))
1399 } else if (IsPunctuation(startChar
)) {
1400 while (pos
> 0 && IsPunctuation(cb
.CharAt(pos
)))
1402 if (!IsPunctuation(cb
.CharAt(pos
)))
1404 } else if (isspacechar(startChar
)) {
1405 while (pos
> 0 && isspacechar(cb
.CharAt(pos
)))
1407 if (!isspacechar(cb
.CharAt(pos
)))
1409 } else if (!isascii(startChar
)) {
1410 while (pos
> 0 && !isascii(cb
.CharAt(pos
)))
1412 if (isascii(cb
.CharAt(pos
)))
1422 int Document::WordPartRight(int pos
) {
1423 char startChar
= cb
.CharAt(pos
);
1424 int length
= Length();
1425 if (IsWordPartSeparator(startChar
)) {
1426 while (pos
< length
&& IsWordPartSeparator(cb
.CharAt(pos
)))
1428 startChar
= cb
.CharAt(pos
);
1430 if (!isascii(startChar
)) {
1431 while (pos
< length
&& !isascii(cb
.CharAt(pos
)))
1433 } else if (IsLowerCase(startChar
)) {
1434 while (pos
< length
&& IsLowerCase(cb
.CharAt(pos
)))
1436 } else if (IsUpperCase(startChar
)) {
1437 if (IsLowerCase(cb
.CharAt(pos
+ 1))) {
1439 while (pos
< length
&& IsLowerCase(cb
.CharAt(pos
)))
1442 while (pos
< length
&& IsUpperCase(cb
.CharAt(pos
)))
1445 if (IsLowerCase(cb
.CharAt(pos
)) && IsUpperCase(cb
.CharAt(pos
- 1)))
1447 } else if (IsADigit(startChar
)) {
1448 while (pos
< length
&& IsADigit(cb
.CharAt(pos
)))
1450 } else if (IsPunctuation(startChar
)) {
1451 while (pos
< length
&& IsPunctuation(cb
.CharAt(pos
)))
1453 } else if (isspacechar(startChar
)) {
1454 while (pos
< length
&& isspacechar(cb
.CharAt(pos
)))
1462 bool IsLineEndChar(char c
) {
1463 return (c
== '\n' || c
== '\r');
1466 int Document::ExtendStyleRange(int pos
, int delta
, bool singleLine
) {
1467 int sStart
= cb
.StyleAt(pos
);
1469 while (pos
> 0 && (cb
.StyleAt(pos
) == sStart
) && (!singleLine
|| !IsLineEndChar(cb
.CharAt(pos
))) )
1473 while (pos
< (Length()) && (cb
.StyleAt(pos
) == sStart
) && (!singleLine
|| !IsLineEndChar(cb
.CharAt(pos
))) )