PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Tools/MaterialEditor/wxscintilla_1.69.2/src/scintilla/src/Document.cxx

https://bitbucket.org/CaptainOz/ogre
C++ | 1577 lines | 1360 code | 117 blank | 100 comment | 566 complexity | 879187bc2cfc765604850d49a32f0e60 MD5 | raw file
Possible License(s): LGPL-2.1, MIT
  1. // Scintilla source code edit control
  2. /** @file Document.cxx
  3. ** Text document that handles notifications, DBCS, styling, words and end of line.
  4. **/
  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.
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <ctype.h>
  11. #include "Platform.h"
  12. #include "Scintilla.h"
  13. #include "SVector.h"
  14. #include "CellBuffer.h"
  15. #include "CharClassify.h"
  16. #include "Document.h"
  17. #include "RESearch.h"
  18. // This is ASCII specific but is safe with chars >= 0x80
  19. static inline bool isspacechar(unsigned char ch) {
  20. return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d));
  21. }
  22. static inline bool IsPunctuation(char ch) {
  23. return isascii(ch) && ispunct(ch);
  24. }
  25. static inline bool IsADigit(char ch) {
  26. return isascii(ch) && isdigit(ch);
  27. }
  28. static inline bool IsLowerCase(char ch) {
  29. return isascii(ch) && islower(ch);
  30. }
  31. static inline bool IsUpperCase(char ch) {
  32. return isascii(ch) && isupper(ch);
  33. }
  34. Document::Document() {
  35. refCount = 0;
  36. #ifdef unix
  37. eolMode = SC_EOL_LF;
  38. #else
  39. eolMode = SC_EOL_CRLF;
  40. #endif
  41. dbcsCodePage = 0;
  42. stylingBits = 5;
  43. stylingBitsMask = 0x1F;
  44. stylingMask = 0;
  45. endStyled = 0;
  46. styleClock = 0;
  47. enteredCount = 0;
  48. enteredReadOnlyCount = 0;
  49. tabInChars = 8;
  50. indentInChars = 0;
  51. actualIndentInChars = 8;
  52. useTabs = true;
  53. tabIndents = true;
  54. backspaceUnindents = false;
  55. watchers = 0;
  56. lenWatchers = 0;
  57. matchesValid = false;
  58. pre = 0;
  59. substituted = 0;
  60. }
  61. Document::~Document() {
  62. for (int i = 0; i < lenWatchers; i++) {
  63. watchers[i].watcher->NotifyDeleted(this, watchers[i].userData);
  64. }
  65. delete []watchers;
  66. watchers = 0;
  67. lenWatchers = 0;
  68. delete pre;
  69. pre = 0;
  70. delete []substituted;
  71. substituted = 0;
  72. }
  73. // Increase reference count and return its previous value.
  74. int Document::AddRef() {
  75. return refCount++;
  76. }
  77. // Decrease reference count and return its previous value.
  78. // Delete the document if reference count reaches zero.
  79. int Document::Release() {
  80. int curRefCount = --refCount;
  81. if (curRefCount == 0)
  82. delete this;
  83. return curRefCount;
  84. }
  85. void Document::SetSavePoint() {
  86. cb.SetSavePoint();
  87. NotifySavePoint(true);
  88. }
  89. int Document::AddMark(int line, int markerNum) {
  90. int prev = cb.AddMark(line, markerNum);
  91. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  92. mh.line = line;
  93. NotifyModified(mh);
  94. return prev;
  95. }
  96. void Document::AddMarkSet(int line, int valueSet) {
  97. unsigned int m = valueSet;
  98. for (int i = 0; m; i++, m >>= 1)
  99. if (m & 1)
  100. cb.AddMark(line, i);
  101. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  102. mh.line = line;
  103. NotifyModified(mh);
  104. }
  105. void Document::DeleteMark(int line, int markerNum) {
  106. cb.DeleteMark(line, markerNum);
  107. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  108. mh.line = line;
  109. NotifyModified(mh);
  110. }
  111. void Document::DeleteMarkFromHandle(int markerHandle) {
  112. cb.DeleteMarkFromHandle(markerHandle);
  113. DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
  114. mh.line = -1;
  115. NotifyModified(mh);
  116. }
  117. void Document::DeleteAllMarks(int markerNum) {
  118. cb.DeleteAllMarks(markerNum);
  119. DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
  120. mh.line = -1;
  121. NotifyModified(mh);
  122. }
  123. int Document::LineStart(int line) {
  124. return cb.LineStart(line);
  125. }
  126. int Document::LineEnd(int line) {
  127. if (line == LinesTotal() - 1) {
  128. return LineStart(line + 1);
  129. } else {
  130. int position = LineStart(line + 1) - 1;
  131. // When line terminator is CR+LF, may need to go back one more
  132. if ((position > LineStart(line)) && (cb.CharAt(position - 1) == '\r')) {
  133. position--;
  134. }
  135. return position;
  136. }
  137. }
  138. int Document::LineFromPosition(int pos) {
  139. return cb.LineFromPosition(pos);
  140. }
  141. int Document::LineEndPosition(int position) {
  142. return LineEnd(LineFromPosition(position));
  143. }
  144. int Document::VCHomePosition(int position) {
  145. int line = LineFromPosition(position);
  146. int startPosition = LineStart(line);
  147. int endLine = LineStart(line + 1) - 1;
  148. int startText = startPosition;
  149. while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t' ) )
  150. startText++;
  151. if (position == startText)
  152. return startPosition;
  153. else
  154. return startText;
  155. }
  156. int Document::SetLevel(int line, int level) {
  157. int prev = cb.SetLevel(line, level);
  158. if (prev != level) {
  159. DocModification mh(SC_MOD_CHANGEFOLD | SC_MOD_CHANGEMARKER,
  160. LineStart(line), 0, 0, 0);
  161. mh.line = line;
  162. mh.foldLevelNow = level;
  163. mh.foldLevelPrev = prev;
  164. NotifyModified(mh);
  165. }
  166. return prev;
  167. }
  168. static bool IsSubordinate(int levelStart, int levelTry) {
  169. if (levelTry & SC_FOLDLEVELWHITEFLAG)
  170. return true;
  171. else
  172. return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK);
  173. }
  174. int Document::GetLastChild(int lineParent, int level) {
  175. if (level == -1)
  176. level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK;
  177. int maxLine = LinesTotal();
  178. int lineMaxSubord = lineParent;
  179. while (lineMaxSubord < maxLine - 1) {
  180. EnsureStyledTo(LineStart(lineMaxSubord + 2));
  181. if (!IsSubordinate(level, GetLevel(lineMaxSubord + 1)))
  182. break;
  183. lineMaxSubord++;
  184. }
  185. if (lineMaxSubord > lineParent) {
  186. if (level > (GetLevel(lineMaxSubord + 1) & SC_FOLDLEVELNUMBERMASK)) {
  187. // Have chewed up some whitespace that belongs to a parent so seek back
  188. if (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG) {
  189. lineMaxSubord--;
  190. }
  191. }
  192. }
  193. return lineMaxSubord;
  194. }
  195. int Document::GetFoldParent(int line) {
  196. int level = GetLevel(line) & SC_FOLDLEVELNUMBERMASK;
  197. int lineLook = line - 1;
  198. while ((lineLook > 0) && (
  199. (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) ||
  200. ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level))
  201. ) {
  202. lineLook--;
  203. }
  204. if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) &&
  205. ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) {
  206. return lineLook;
  207. } else {
  208. return -1;
  209. }
  210. }
  211. int Document::ClampPositionIntoDocument(int pos) {
  212. return Platform::Clamp(pos, 0, Length());
  213. }
  214. bool Document::IsCrLf(int pos) {
  215. if (pos < 0)
  216. return false;
  217. if (pos >= (Length() - 1))
  218. return false;
  219. return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
  220. }
  221. static const int maxBytesInDBCSCharacter=5;
  222. int Document::LenChar(int pos) {
  223. if (pos < 0) {
  224. return 1;
  225. } else if (IsCrLf(pos)) {
  226. return 2;
  227. } else if (SC_CP_UTF8 == dbcsCodePage) {
  228. unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
  229. if (ch < 0x80)
  230. return 1;
  231. int len = 2;
  232. if (ch >= (0x80 + 0x40 + 0x20))
  233. len = 3;
  234. int lengthDoc = Length();
  235. if ((pos + len) > lengthDoc)
  236. return lengthDoc -pos;
  237. else
  238. return len;
  239. } else if (dbcsCodePage) {
  240. char mbstr[maxBytesInDBCSCharacter+1];
  241. int i;
  242. for (i=0; i<Platform::DBCSCharMaxLength(); i++) {
  243. mbstr[i] = cb.CharAt(pos+i);
  244. }
  245. mbstr[i] = '\0';
  246. return Platform::DBCSCharLength(dbcsCodePage, mbstr);
  247. } else {
  248. return 1;
  249. }
  250. }
  251. // Normalise a position so that it is not halfway through a two byte character.
  252. // This can occur in two situations -
  253. // When lines are terminated with \r\n pairs which should be treated as one character.
  254. // When displaying DBCS text such as Japanese.
  255. // If moving, move the position in the indicated direction.
  256. int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) {
  257. //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
  258. // If out of range, just return minimum/maximum value.
  259. if (pos <= 0)
  260. return 0;
  261. if (pos >= Length())
  262. return Length();
  263. // PLATFORM_ASSERT(pos > 0 && pos < Length());
  264. if (checkLineEnd && IsCrLf(pos - 1)) {
  265. if (moveDir > 0)
  266. return pos + 1;
  267. else
  268. return pos - 1;
  269. }
  270. // Not between CR and LF
  271. if (dbcsCodePage) {
  272. if (SC_CP_UTF8 == dbcsCodePage) {
  273. unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
  274. while ((pos > 0) && (pos < Length()) && (ch >= 0x80) && (ch < (0x80 + 0x40))) {
  275. // ch is a trail byte
  276. if (moveDir > 0)
  277. pos++;
  278. else
  279. pos--;
  280. ch = static_cast<unsigned char>(cb.CharAt(pos));
  281. }
  282. } else {
  283. // Anchor DBCS calculations at start of line because start of line can
  284. // not be a DBCS trail byte.
  285. int posCheck = LineStart(LineFromPosition(pos));
  286. while (posCheck < pos) {
  287. char mbstr[maxBytesInDBCSCharacter+1];
  288. int i;
  289. for(i=0;i<Platform::DBCSCharMaxLength();i++) {
  290. mbstr[i] = cb.CharAt(posCheck+i);
  291. }
  292. mbstr[i] = '\0';
  293. int mbsize = Platform::DBCSCharLength(dbcsCodePage, mbstr);
  294. if (posCheck + mbsize == pos) {
  295. return pos;
  296. } else if (posCheck + mbsize > pos) {
  297. if (moveDir > 0) {
  298. return posCheck + mbsize;
  299. } else {
  300. return posCheck;
  301. }
  302. }
  303. posCheck += mbsize;
  304. }
  305. }
  306. }
  307. return pos;
  308. }
  309. void Document::ModifiedAt(int pos) {
  310. if (endStyled > pos)
  311. endStyled = pos;
  312. }
  313. void Document::CheckReadOnly() {
  314. if (cb.IsReadOnly() && enteredReadOnlyCount == 0) {
  315. enteredReadOnlyCount++;
  316. NotifyModifyAttempt();
  317. enteredReadOnlyCount--;
  318. }
  319. }
  320. // Document only modified by gateways DeleteChars, InsertStyledString, Undo, Redo, and SetStyleAt.
  321. // SetStyleAt does not change the persistent state of a document
  322. // Unlike Undo, Redo, and InsertStyledString, the pos argument is a cell number not a char number
  323. bool Document::DeleteChars(int pos, int len) {
  324. if (len == 0)
  325. return false;
  326. if ((pos + len) > Length())
  327. return false;
  328. CheckReadOnly();
  329. if (enteredCount != 0) {
  330. return false;
  331. } else {
  332. enteredCount++;
  333. if (!cb.IsReadOnly()) {
  334. NotifyModified(
  335. DocModification(
  336. SC_MOD_BEFOREDELETE | SC_PERFORMED_USER,
  337. pos, len,
  338. 0, 0));
  339. int prevLinesTotal = LinesTotal();
  340. bool startSavePoint = cb.IsSavePoint();
  341. const char *text = cb.DeleteChars(pos * 2, len * 2);
  342. if (startSavePoint && cb.IsCollectingUndo())
  343. NotifySavePoint(!startSavePoint);
  344. if ((pos < Length()) || (pos == 0))
  345. ModifiedAt(pos);
  346. else
  347. ModifiedAt(pos-1);
  348. NotifyModified(
  349. DocModification(
  350. SC_MOD_DELETETEXT | SC_PERFORMED_USER,
  351. pos, len,
  352. LinesTotal() - prevLinesTotal, text));
  353. }
  354. enteredCount--;
  355. }
  356. return !cb.IsReadOnly();
  357. }
  358. /**
  359. * Insert a styled string (char/style pairs) with a length.
  360. */
  361. bool Document::InsertStyledString(int position, char *s, int insertLength) {
  362. CheckReadOnly();
  363. if (enteredCount != 0) {
  364. return false;
  365. } else {
  366. enteredCount++;
  367. if (!cb.IsReadOnly()) {
  368. NotifyModified(
  369. DocModification(
  370. SC_MOD_BEFOREINSERT | SC_PERFORMED_USER,
  371. position / 2, insertLength / 2,
  372. 0, s));
  373. int prevLinesTotal = LinesTotal();
  374. bool startSavePoint = cb.IsSavePoint();
  375. const char *text = cb.InsertString(position, s, insertLength);
  376. if (startSavePoint && cb.IsCollectingUndo())
  377. NotifySavePoint(!startSavePoint);
  378. ModifiedAt(position / 2);
  379. NotifyModified(
  380. DocModification(
  381. SC_MOD_INSERTTEXT | SC_PERFORMED_USER,
  382. position / 2, insertLength / 2,
  383. LinesTotal() - prevLinesTotal, text));
  384. }
  385. enteredCount--;
  386. }
  387. return !cb.IsReadOnly();
  388. }
  389. int Document::Undo() {
  390. int newPos = -1;
  391. CheckReadOnly();
  392. if (enteredCount == 0) {
  393. enteredCount++;
  394. if (!cb.IsReadOnly()) {
  395. bool startSavePoint = cb.IsSavePoint();
  396. bool multiLine = false;
  397. int steps = cb.StartUndo();
  398. //Platform::DebugPrintf("Steps=%d\n", steps);
  399. for (int step = 0; step < steps; step++) {
  400. const int prevLinesTotal = LinesTotal();
  401. const Action &action = cb.GetUndoStep();
  402. if (action.at == removeAction) {
  403. NotifyModified(DocModification(
  404. SC_MOD_BEFOREINSERT | SC_PERFORMED_UNDO, action));
  405. } else {
  406. NotifyModified(DocModification(
  407. SC_MOD_BEFOREDELETE | SC_PERFORMED_UNDO, action));
  408. }
  409. cb.PerformUndoStep();
  410. int cellPosition = action.position;
  411. ModifiedAt(cellPosition);
  412. newPos = cellPosition;
  413. int modFlags = SC_PERFORMED_UNDO;
  414. // With undo, an insertion action becomes a deletion notification
  415. if (action.at == removeAction) {
  416. newPos += action.lenData;
  417. modFlags |= SC_MOD_INSERTTEXT;
  418. } else {
  419. modFlags |= SC_MOD_DELETETEXT;
  420. }
  421. if (steps > 1)
  422. modFlags |= SC_MULTISTEPUNDOREDO;
  423. const int linesAdded = LinesTotal() - prevLinesTotal;
  424. if (linesAdded != 0)
  425. multiLine = true;
  426. if (step == steps - 1) {
  427. modFlags |= SC_LASTSTEPINUNDOREDO;
  428. if (multiLine)
  429. modFlags |= SC_MULTILINEUNDOREDO;
  430. }
  431. NotifyModified(DocModification(modFlags, cellPosition, action.lenData,
  432. linesAdded, action.data));
  433. }
  434. bool endSavePoint = cb.IsSavePoint();
  435. if (startSavePoint != endSavePoint)
  436. NotifySavePoint(endSavePoint);
  437. }
  438. enteredCount--;
  439. }
  440. return newPos;
  441. }
  442. int Document::Redo() {
  443. int newPos = -1;
  444. CheckReadOnly();
  445. if (enteredCount == 0) {
  446. enteredCount++;
  447. if (!cb.IsReadOnly()) {
  448. bool startSavePoint = cb.IsSavePoint();
  449. bool multiLine = false;
  450. int steps = cb.StartRedo();
  451. for (int step = 0; step < steps; step++) {
  452. const int prevLinesTotal = LinesTotal();
  453. const Action &action = cb.GetRedoStep();
  454. if (action.at == insertAction) {
  455. NotifyModified(DocModification(
  456. SC_MOD_BEFOREINSERT | SC_PERFORMED_REDO, action));
  457. } else {
  458. NotifyModified(DocModification(
  459. SC_MOD_BEFOREDELETE | SC_PERFORMED_REDO, action));
  460. }
  461. cb.PerformRedoStep();
  462. ModifiedAt(action.position);
  463. newPos = action.position;
  464. int modFlags = SC_PERFORMED_REDO;
  465. if (action.at == insertAction) {
  466. newPos += action.lenData;
  467. modFlags |= SC_MOD_INSERTTEXT;
  468. } else {
  469. modFlags |= SC_MOD_DELETETEXT;
  470. }
  471. if (steps > 1)
  472. modFlags |= SC_MULTISTEPUNDOREDO;
  473. const int linesAdded = LinesTotal() - prevLinesTotal;
  474. if (linesAdded != 0)
  475. multiLine = true;
  476. if (step == steps - 1) {
  477. modFlags |= SC_LASTSTEPINUNDOREDO;
  478. if (multiLine)
  479. modFlags |= SC_MULTILINEUNDOREDO;
  480. }
  481. NotifyModified(
  482. DocModification(modFlags, action.position, action.lenData,
  483. linesAdded, action.data));
  484. }
  485. bool endSavePoint = cb.IsSavePoint();
  486. if (startSavePoint != endSavePoint)
  487. NotifySavePoint(endSavePoint);
  488. }
  489. enteredCount--;
  490. }
  491. return newPos;
  492. }
  493. /**
  494. * Insert a single character.
  495. */
  496. bool Document::InsertChar(int pos, char ch) {
  497. char chs[2];
  498. chs[0] = ch;
  499. chs[1] = 0;
  500. return InsertStyledString(pos*2, chs, 2);
  501. }
  502. /**
  503. * Insert a null terminated string.
  504. */
  505. bool Document::InsertString(int position, const char *s) {
  506. return InsertString(position, s, strlen(s));
  507. }
  508. /**
  509. * Insert a string with a length.
  510. */
  511. bool Document::InsertString(int position, const char *s, size_t insertLength) {
  512. bool changed = false;
  513. if (insertLength > 0) {
  514. char *sWithStyle = new char[insertLength * 2];
  515. if (sWithStyle) {
  516. for (size_t i = 0; i < insertLength; i++) {
  517. sWithStyle[i*2] = s[i];
  518. sWithStyle[i*2 + 1] = 0;
  519. }
  520. changed = InsertStyledString(position*2, sWithStyle,
  521. static_cast<int>(insertLength*2));
  522. delete []sWithStyle;
  523. }
  524. }
  525. return changed;
  526. }
  527. void Document::ChangeChar(int pos, char ch) {
  528. DeleteChars(pos, 1);
  529. InsertChar(pos, ch);
  530. }
  531. void Document::DelChar(int pos) {
  532. DeleteChars(pos, LenChar(pos));
  533. }
  534. void Document::DelCharBack(int pos) {
  535. if (pos <= 0) {
  536. return;
  537. } else if (IsCrLf(pos - 2)) {
  538. DeleteChars(pos - 2, 2);
  539. } else if (dbcsCodePage) {
  540. int startChar = MovePositionOutsideChar(pos - 1, -1, false);
  541. DeleteChars(startChar, pos - startChar);
  542. } else {
  543. DeleteChars(pos - 1, 1);
  544. }
  545. }
  546. static bool isindentchar(char ch) {
  547. return (ch == ' ') || (ch == '\t');
  548. }
  549. static int NextTab(int pos, int tabSize) {
  550. return ((pos / tabSize) + 1) * tabSize;
  551. }
  552. static void CreateIndentation(char *linebuf, int length, int indent, int tabSize, bool insertSpaces) {
  553. length--; // ensure space for \0
  554. if (!insertSpaces) {
  555. while ((indent >= tabSize) && (length > 0)) {
  556. *linebuf++ = '\t';
  557. indent -= tabSize;
  558. length--;
  559. }
  560. }
  561. while ((indent > 0) && (length > 0)) {
  562. *linebuf++ = ' ';
  563. indent--;
  564. length--;
  565. }
  566. *linebuf = '\0';
  567. }
  568. int Document::GetLineIndentation(int line) {
  569. int indent = 0;
  570. if ((line >= 0) && (line < LinesTotal())) {
  571. int lineStart = LineStart(line);
  572. int length = Length();
  573. for (int i = lineStart;i < length;i++) {
  574. char ch = cb.CharAt(i);
  575. if (ch == ' ')
  576. indent++;
  577. else if (ch == '\t')
  578. indent = NextTab(indent, tabInChars);
  579. else
  580. return indent;
  581. }
  582. }
  583. return indent;
  584. }
  585. void Document::SetLineIndentation(int line, int indent) {
  586. int indentOfLine = GetLineIndentation(line);
  587. if (indent < 0)
  588. indent = 0;
  589. if (indent != indentOfLine) {
  590. char linebuf[1000];
  591. CreateIndentation(linebuf, sizeof(linebuf), indent, tabInChars, !useTabs);
  592. int thisLineStart = LineStart(line);
  593. int indentPos = GetLineIndentPosition(line);
  594. BeginUndoAction();
  595. DeleteChars(thisLineStart, indentPos - thisLineStart);
  596. InsertString(thisLineStart, linebuf);
  597. EndUndoAction();
  598. }
  599. }
  600. int Document::GetLineIndentPosition(int line) {
  601. if (line < 0)
  602. return 0;
  603. int pos = LineStart(line);
  604. int length = Length();
  605. while ((pos < length) && isindentchar(cb.CharAt(pos))) {
  606. pos++;
  607. }
  608. return pos;
  609. }
  610. int Document::GetColumn(int pos) {
  611. int column = 0;
  612. int line = LineFromPosition(pos);
  613. if ((line >= 0) && (line < LinesTotal())) {
  614. for (int i = LineStart(line);i < pos;) {
  615. char ch = cb.CharAt(i);
  616. if (ch == '\t') {
  617. column = NextTab(column, tabInChars);
  618. i++;
  619. } else if (ch == '\r') {
  620. return column;
  621. } else if (ch == '\n') {
  622. return column;
  623. } else {
  624. column++;
  625. i = MovePositionOutsideChar(i + 1, 1);
  626. }
  627. }
  628. }
  629. return column;
  630. }
  631. int Document::FindColumn(int line, int column) {
  632. int position = LineStart(line);
  633. int columnCurrent = 0;
  634. if ((line >= 0) && (line < LinesTotal())) {
  635. while ((columnCurrent < column) && (position < Length())) {
  636. char ch = cb.CharAt(position);
  637. if (ch == '\t') {
  638. columnCurrent = NextTab(columnCurrent, tabInChars);
  639. position++;
  640. } else if (ch == '\r') {
  641. return position;
  642. } else if (ch == '\n') {
  643. return position;
  644. } else {
  645. columnCurrent++;
  646. position = MovePositionOutsideChar(position + 1, 1);
  647. }
  648. }
  649. }
  650. return position;
  651. }
  652. void Document::Indent(bool forwards, int lineBottom, int lineTop) {
  653. // Dedent - suck white space off the front of the line to dedent by equivalent of a tab
  654. for (int line = lineBottom; line >= lineTop; line--) {
  655. int indentOfLine = GetLineIndentation(line);
  656. if (forwards) {
  657. if (LineStart(line) < LineEnd(line)) {
  658. SetLineIndentation(line, indentOfLine + IndentSize());
  659. }
  660. } else {
  661. SetLineIndentation(line, indentOfLine - IndentSize());
  662. }
  663. }
  664. }
  665. // Convert line endings for a piece of text to a particular mode.
  666. // Stop at len or when a NUL is found.
  667. // Caller must delete the returned pointer.
  668. char *Document::TransformLineEnds(int *pLenOut, const char *s, size_t len, int eolMode) {
  669. char *dest = new char[2 * len + 1];
  670. const char *sptr = s;
  671. char *dptr = dest;
  672. for (size_t i = 0; (i < len) && (*sptr != '\0'); i++) {
  673. if (*sptr == '\n' || *sptr == '\r') {
  674. if (eolMode == SC_EOL_CR) {
  675. *dptr++ = '\r';
  676. } else if (eolMode == SC_EOL_LF) {
  677. *dptr++ = '\n';
  678. } else { // eolMode == SC_EOL_CRLF
  679. *dptr++ = '\r';
  680. *dptr++ = '\n';
  681. }
  682. if ((*sptr == '\r') && (i+1 < len) && (*(sptr+1) == '\n')) {
  683. i++;
  684. sptr++;
  685. }
  686. sptr++;
  687. } else {
  688. *dptr++ = *sptr++;
  689. }
  690. }
  691. *dptr++ = '\0';
  692. *pLenOut = (dptr - dest) - 1;
  693. return dest;
  694. }
  695. void Document::ConvertLineEnds(int eolModeSet) {
  696. BeginUndoAction();
  697. for (int pos = 0; pos < Length(); pos++) {
  698. if (cb.CharAt(pos) == '\r') {
  699. if (cb.CharAt(pos + 1) == '\n') {
  700. // CRLF
  701. if (eolModeSet == SC_EOL_CR) {
  702. DeleteChars(pos + 1, 1); // Delete the LF
  703. } else if (eolModeSet == SC_EOL_LF) {
  704. DeleteChars(pos, 1); // Delete the CR
  705. } else {
  706. pos++;
  707. }
  708. } else {
  709. // CR
  710. if (eolModeSet == SC_EOL_CRLF) {
  711. InsertString(pos + 1, "\n", 1); // Insert LF
  712. pos++;
  713. } else if (eolModeSet == SC_EOL_LF) {
  714. InsertString(pos, "\n", 1); // Insert LF
  715. DeleteChars(pos + 1, 1); // Delete CR
  716. }
  717. }
  718. } else if (cb.CharAt(pos) == '\n') {
  719. // LF
  720. if (eolModeSet == SC_EOL_CRLF) {
  721. InsertString(pos, "\r", 1); // Insert CR
  722. pos++;
  723. } else if (eolModeSet == SC_EOL_CR) {
  724. InsertString(pos, "\r", 1); // Insert CR
  725. DeleteChars(pos + 1, 1); // Delete LF
  726. }
  727. }
  728. }
  729. EndUndoAction();
  730. }
  731. bool Document::IsWhiteLine(int line) {
  732. int currentChar = LineStart(line);
  733. int endLine = LineEnd(line);
  734. while (currentChar < endLine) {
  735. if (cb.CharAt(currentChar) != ' ' && cb.CharAt(currentChar) != '\t') {
  736. return false;
  737. }
  738. ++currentChar;
  739. }
  740. return true;
  741. }
  742. int Document::ParaUp(int pos) {
  743. int line = LineFromPosition(pos);
  744. line--;
  745. while (line >= 0 && IsWhiteLine(line)) { // skip empty lines
  746. line--;
  747. }
  748. while (line >= 0 && !IsWhiteLine(line)) { // skip non-empty lines
  749. line--;
  750. }
  751. line++;
  752. return LineStart(line);
  753. }
  754. int Document::ParaDown(int pos) {
  755. int line = LineFromPosition(pos);
  756. while (line < LinesTotal() && !IsWhiteLine(line)) { // skip non-empty lines
  757. line++;
  758. }
  759. while (line < LinesTotal() && IsWhiteLine(line)) { // skip empty lines
  760. line++;
  761. }
  762. if (line < LinesTotal())
  763. return LineStart(line);
  764. else // end of a document
  765. return LineEnd(line-1);
  766. }
  767. CharClassify::cc Document::WordCharClass(unsigned char ch) {
  768. if ((SC_CP_UTF8 == dbcsCodePage) && (ch >= 0x80))
  769. return CharClassify::ccWord;
  770. return charClass.GetClass(ch);
  771. }
  772. /**
  773. * Used by commmands that want to select whole words.
  774. * Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0.
  775. */
  776. int Document::ExtendWordSelect(int pos, int delta, bool onlyWordCharacters) {
  777. CharClassify::cc ccStart = CharClassify::ccWord;
  778. if (delta < 0) {
  779. if (!onlyWordCharacters)
  780. ccStart = WordCharClass(cb.CharAt(pos-1));
  781. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart))
  782. pos--;
  783. } else {
  784. if (!onlyWordCharacters)
  785. ccStart = WordCharClass(cb.CharAt(pos));
  786. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
  787. pos++;
  788. }
  789. return MovePositionOutsideChar(pos, delta);
  790. }
  791. /**
  792. * Find the start of the next word in either a forward (delta >= 0) or backwards direction
  793. * (delta < 0).
  794. * This is looking for a transition between character classes although there is also some
  795. * additional movement to transit white space.
  796. * Used by cursor movement by word commands.
  797. */
  798. int Document::NextWordStart(int pos, int delta) {
  799. if (delta < 0) {
  800. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace))
  801. pos--;
  802. if (pos > 0) {
  803. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
  804. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart)) {
  805. pos--;
  806. }
  807. }
  808. } else {
  809. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
  810. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
  811. pos++;
  812. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace))
  813. pos++;
  814. }
  815. return pos;
  816. }
  817. /**
  818. * Find the end of the next word in either a forward (delta >= 0) or backwards direction
  819. * (delta < 0).
  820. * This is looking for a transition between character classes although there is also some
  821. * additional movement to transit white space.
  822. * Used by cursor movement by word commands.
  823. */
  824. int Document::NextWordEnd(int pos, int delta) {
  825. if (delta < 0) {
  826. if (pos > 0) {
  827. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
  828. if (ccStart != CharClassify::ccSpace) {
  829. while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == ccStart) {
  830. pos--;
  831. }
  832. }
  833. while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace) {
  834. pos--;
  835. }
  836. }
  837. } else {
  838. while (pos < Length() && WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace) {
  839. pos++;
  840. }
  841. if (pos < Length()) {
  842. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
  843. while (pos < Length() && WordCharClass(cb.CharAt(pos)) == ccStart) {
  844. pos++;
  845. }
  846. }
  847. }
  848. return pos;
  849. }
  850. /**
  851. * Check that the character at the given position is a word or punctuation character and that
  852. * the previous character is of a different character class.
  853. */
  854. bool Document::IsWordStartAt(int pos) {
  855. if (pos > 0) {
  856. CharClassify::cc ccPos = WordCharClass(CharAt(pos));
  857. return (ccPos == CharClassify::ccWord || ccPos == CharClassify::ccPunctuation) &&
  858. (ccPos != WordCharClass(CharAt(pos - 1)));
  859. }
  860. return true;
  861. }
  862. /**
  863. * Check that the character at the given position is a word or punctuation character and that
  864. * the next character is of a different character class.
  865. */
  866. bool Document::IsWordEndAt(int pos) {
  867. if (pos < Length()) {
  868. CharClassify::cc ccPrev = WordCharClass(CharAt(pos-1));
  869. return (ccPrev == CharClassify::ccWord || ccPrev == CharClassify::ccPunctuation) &&
  870. (ccPrev != WordCharClass(CharAt(pos)));
  871. }
  872. return true;
  873. }
  874. /**
  875. * Check that the given range is has transitions between character classes at both
  876. * ends and where the characters on the inside are word or punctuation characters.
  877. */
  878. bool Document::IsWordAt(int start, int end) {
  879. return IsWordStartAt(start) && IsWordEndAt(end);
  880. }
  881. // The comparison and case changing functions here assume ASCII
  882. // or extended ASCII such as the normal Windows code page.
  883. static inline char MakeUpperCase(char ch) {
  884. if (ch < 'a' || ch > 'z')
  885. return ch;
  886. else
  887. return static_cast<char>(ch - 'a' + 'A');
  888. }
  889. static inline char MakeLowerCase(char ch) {
  890. if (ch < 'A' || ch > 'Z')
  891. return ch;
  892. else
  893. return static_cast<char>(ch - 'A' + 'a');
  894. }
  895. // Define a way for the Regular Expression code to access the document
  896. class DocumentIndexer : public CharacterIndexer {
  897. Document *pdoc;
  898. int end;
  899. public:
  900. DocumentIndexer(Document *pdoc_, int end_) :
  901. pdoc(pdoc_), end(end_) {
  902. }
  903. virtual ~DocumentIndexer() {
  904. }
  905. virtual char CharAt(int index) {
  906. if (index < 0 || index >= end)
  907. return 0;
  908. else
  909. return pdoc->CharAt(index);
  910. }
  911. };
  912. /**
  913. * Find text in document, supporting both forward and backward
  914. * searches (just pass minPos > maxPos to do a backward search)
  915. * Has not been tested with backwards DBCS searches yet.
  916. */
  917. long Document::FindText(int minPos, int maxPos, const char *s,
  918. bool caseSensitive, bool word, bool wordStart, bool regExp, bool posix,
  919. int *length) {
  920. if (regExp) {
  921. if (!pre)
  922. pre = new RESearch(&charClass);
  923. if (!pre)
  924. return -1;
  925. int increment = (minPos <= maxPos) ? 1 : -1;
  926. int startPos = minPos;
  927. int endPos = maxPos;
  928. // Range endpoints should not be inside DBCS characters, but just in case, move them.
  929. startPos = MovePositionOutsideChar(startPos, 1, false);
  930. endPos = MovePositionOutsideChar(endPos, 1, false);
  931. const char *errmsg = pre->Compile(s, *length, caseSensitive, posix);
  932. if (errmsg) {
  933. return -1;
  934. }
  935. // Find a variable in a property file: \$(\([A-Za-z0-9_.]+\))
  936. // Replace first '.' with '-' in each property file variable reference:
  937. // Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\))
  938. // Replace: $(\1-\2)
  939. int lineRangeStart = LineFromPosition(startPos);
  940. int lineRangeEnd = LineFromPosition(endPos);
  941. if ((increment == 1) &&
  942. (startPos >= LineEnd(lineRangeStart)) &&
  943. (lineRangeStart < lineRangeEnd)) {
  944. // the start position is at end of line or between line end characters.
  945. lineRangeStart++;
  946. startPos = LineStart(lineRangeStart);
  947. }
  948. int pos = -1;
  949. int lenRet = 0;
  950. char searchEnd = s[*length - 1];
  951. int lineRangeBreak = lineRangeEnd + increment;
  952. for (int line = lineRangeStart; line != lineRangeBreak; line += increment) {
  953. int startOfLine = LineStart(line);
  954. int endOfLine = LineEnd(line);
  955. if (increment == 1) {
  956. if (line == lineRangeStart) {
  957. if ((startPos != startOfLine) && (s[0] == '^'))
  958. continue; // Can't match start of line if start position after start of line
  959. startOfLine = startPos;
  960. }
  961. if (line == lineRangeEnd) {
  962. if ((endPos != endOfLine) && (searchEnd == '$'))
  963. continue; // Can't match end of line if end position before end of line
  964. endOfLine = endPos;
  965. }
  966. } else {
  967. if (line == lineRangeEnd) {
  968. if ((endPos != startOfLine) && (s[0] == '^'))
  969. continue; // Can't match start of line if end position after start of line
  970. startOfLine = endPos;
  971. }
  972. if (line == lineRangeStart) {
  973. if ((startPos != endOfLine) && (searchEnd == '$'))
  974. continue; // Can't match end of line if start position before end of line
  975. endOfLine = startPos;
  976. }
  977. }
  978. DocumentIndexer di(this, endOfLine);
  979. int success = pre->Execute(di, startOfLine, endOfLine);
  980. if (success) {
  981. pos = pre->bopat[0];
  982. lenRet = pre->eopat[0] - pre->bopat[0];
  983. if (increment == -1) {
  984. // Check for the last match on this line.
  985. int repetitions = 1000; // Break out of infinite loop
  986. while (success && (pre->eopat[0] <= endOfLine) && (repetitions--)) {
  987. success = pre->Execute(di, pos+1, endOfLine);
  988. if (success) {
  989. if (pre->eopat[0] <= minPos) {
  990. pos = pre->bopat[0];
  991. lenRet = pre->eopat[0] - pre->bopat[0];
  992. } else {
  993. success = 0;
  994. }
  995. }
  996. }
  997. }
  998. break;
  999. }
  1000. }
  1001. *length = lenRet;
  1002. return pos;
  1003. } else {
  1004. bool forward = minPos <= maxPos;
  1005. int increment = forward ? 1 : -1;
  1006. // Range endpoints should not be inside DBCS characters, but just in case, move them.
  1007. int startPos = MovePositionOutsideChar(minPos, increment, false);
  1008. int endPos = MovePositionOutsideChar(maxPos, increment, false);
  1009. // Compute actual search ranges needed
  1010. int lengthFind = *length;
  1011. if (lengthFind == -1)
  1012. lengthFind = static_cast<int>(strlen(s));
  1013. int endSearch = endPos;
  1014. if (startPos <= endPos) {
  1015. endSearch = endPos - lengthFind + 1;
  1016. }
  1017. //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
  1018. char firstChar = s[0];
  1019. if (!caseSensitive)
  1020. firstChar = static_cast<char>(MakeUpperCase(firstChar));
  1021. int pos = forward ? startPos : (startPos - 1);
  1022. while (forward ? (pos < endSearch) : (pos >= endSearch)) {
  1023. char ch = CharAt(pos);
  1024. if (caseSensitive) {
  1025. if (ch == firstChar) {
  1026. bool found = true;
  1027. if (pos + lengthFind > Platform::Maximum(startPos, endPos)) found = false;
  1028. for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) {
  1029. ch = CharAt(pos + posMatch);
  1030. if (ch != s[posMatch])
  1031. found = false;
  1032. }
  1033. if (found) {
  1034. if ((!word && !wordStart) ||
  1035. word && IsWordAt(pos, pos + lengthFind) ||
  1036. wordStart && IsWordStartAt(pos))
  1037. return pos;
  1038. }
  1039. }
  1040. } else {
  1041. if (MakeUpperCase(ch) == firstChar) {
  1042. bool found = true;
  1043. if (pos + lengthFind > Platform::Maximum(startPos, endPos)) found = false;
  1044. for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) {
  1045. ch = CharAt(pos + posMatch);
  1046. if (MakeUpperCase(ch) != MakeUpperCase(s[posMatch]))
  1047. found = false;
  1048. }
  1049. if (found) {
  1050. if ((!word && !wordStart) ||
  1051. word && IsWordAt(pos, pos + lengthFind) ||
  1052. wordStart && IsWordStartAt(pos))
  1053. return pos;
  1054. }
  1055. }
  1056. }
  1057. pos += increment;
  1058. if (dbcsCodePage && (pos >= 0)) {
  1059. // Ensure trying to match from start of character
  1060. pos = MovePositionOutsideChar(pos, increment, false);
  1061. }
  1062. }
  1063. }
  1064. //Platform::DebugPrintf("Not found\n");
  1065. return -1;
  1066. }
  1067. const char *Document::SubstituteByPosition(const char *text, int *length) {
  1068. if (!pre)
  1069. return 0;
  1070. delete []substituted;
  1071. substituted = 0;
  1072. DocumentIndexer di(this, Length());
  1073. if (!pre->GrabMatches(di))
  1074. return 0;
  1075. unsigned int lenResult = 0;
  1076. for (int i = 0; i < *length; i++) {
  1077. if (text[i] == '\\') {
  1078. if (text[i + 1] >= '1' && text[i + 1] <= '9') {
  1079. unsigned int patNum = text[i + 1] - '0';
  1080. lenResult += pre->eopat[patNum] - pre->bopat[patNum];
  1081. i++;
  1082. } else {
  1083. switch (text[i + 1]) {
  1084. case 'a':
  1085. case 'b':
  1086. case 'f':
  1087. case 'n':
  1088. case 'r':
  1089. case 't':
  1090. case 'v':
  1091. i++;
  1092. }
  1093. lenResult++;
  1094. }
  1095. } else {
  1096. lenResult++;
  1097. }
  1098. }
  1099. substituted = new char[lenResult + 1];
  1100. if (!substituted)
  1101. return 0;
  1102. char *o = substituted;
  1103. for (int j = 0; j < *length; j++) {
  1104. if (text[j] == '\\') {
  1105. if (text[j + 1] >= '1' && text[j + 1] <= '9') {
  1106. unsigned int patNum = text[j + 1] - '0';
  1107. unsigned int len = pre->eopat[patNum] - pre->bopat[patNum];
  1108. if (pre->pat[patNum]) // Will be null if try for a match that did not occur
  1109. memcpy(o, pre->pat[patNum], len);
  1110. o += len;
  1111. j++;
  1112. } else {
  1113. j++;
  1114. switch (text[j]) {
  1115. case 'a':
  1116. *o++ = '\a';
  1117. break;
  1118. case 'b':
  1119. *o++ = '\b';
  1120. break;
  1121. case 'f':
  1122. *o++ = '\f';
  1123. break;
  1124. case 'n':
  1125. *o++ = '\n';
  1126. break;
  1127. case 'r':
  1128. *o++ = '\r';
  1129. break;
  1130. case 't':
  1131. *o++ = '\t';
  1132. break;
  1133. case 'v':
  1134. *o++ = '\v';
  1135. break;
  1136. default:
  1137. *o++ = '\\';
  1138. j--;
  1139. }
  1140. }
  1141. } else {
  1142. *o++ = text[j];
  1143. }
  1144. }
  1145. *o = '\0';
  1146. *length = lenResult;
  1147. return substituted;
  1148. }
  1149. int Document::LinesTotal() {
  1150. return cb.Lines();
  1151. }
  1152. void Document::ChangeCase(Range r, bool makeUpperCase) {
  1153. for (int pos = r.start; pos < r.end;) {
  1154. int len = LenChar(pos);
  1155. if (len == 1) {
  1156. char ch = CharAt(pos);
  1157. if (makeUpperCase) {
  1158. if (IsLowerCase(ch)) {
  1159. ChangeChar(pos, static_cast<char>(MakeUpperCase(ch)));
  1160. }
  1161. } else {
  1162. if (IsUpperCase(ch)) {
  1163. ChangeChar(pos, static_cast<char>(MakeLowerCase(ch)));
  1164. }
  1165. }
  1166. }
  1167. pos += len;
  1168. }
  1169. }
  1170. void Document::SetDefaultCharClasses(bool includeWordClass) {
  1171. charClass.SetDefaultCharClasses(includeWordClass);
  1172. }
  1173. void Document::SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass) {
  1174. charClass.SetCharClasses(chars, newCharClass);
  1175. }
  1176. void Document::SetStylingBits(int bits) {
  1177. stylingBits = bits;
  1178. stylingBitsMask = 0;
  1179. for (int bit = 0; bit < stylingBits; bit++) {
  1180. stylingBitsMask <<= 1;
  1181. stylingBitsMask |= 1;
  1182. }
  1183. }
  1184. void Document::StartStyling(int position, char mask) {
  1185. stylingMask = mask;
  1186. endStyled = position;
  1187. }
  1188. bool Document::SetStyleFor(int length, char style) {
  1189. if (enteredCount != 0) {
  1190. return false;
  1191. } else {
  1192. enteredCount++;
  1193. style &= stylingMask;
  1194. int prevEndStyled = endStyled;
  1195. if (cb.SetStyleFor(endStyled, length, style, stylingMask)) {
  1196. DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
  1197. prevEndStyled, length);
  1198. NotifyModified(mh);
  1199. }
  1200. endStyled += length;
  1201. enteredCount--;
  1202. return true;
  1203. }
  1204. }
  1205. bool Document::SetStyles(int length, char *styles) {
  1206. if (enteredCount != 0) {
  1207. return false;
  1208. } else {
  1209. enteredCount++;
  1210. bool didChange = false;
  1211. int startMod = 0;
  1212. int endMod = 0;
  1213. for (int iPos = 0; iPos < length; iPos++, endStyled++) {
  1214. PLATFORM_ASSERT(endStyled < Length());
  1215. if (cb.SetStyleAt(endStyled, styles[iPos], stylingMask)) {
  1216. if (!didChange) {
  1217. startMod = endStyled;
  1218. }
  1219. didChange = true;
  1220. endMod = endStyled;
  1221. }
  1222. }
  1223. if (didChange) {
  1224. DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
  1225. startMod, endMod - startMod + 1);
  1226. NotifyModified(mh);
  1227. }
  1228. enteredCount--;
  1229. return true;
  1230. }
  1231. }
  1232. bool Document::EnsureStyledTo(int pos) {
  1233. if (pos > GetEndStyled()) {
  1234. IncrementStyleClock();
  1235. // Ask the watchers to style, and stop as soon as one responds.
  1236. for (int i = 0; pos > GetEndStyled() && i < lenWatchers; i++) {
  1237. watchers[i].watcher->NotifyStyleNeeded(this, watchers[i].userData, pos);
  1238. }
  1239. }
  1240. return pos <= GetEndStyled();
  1241. }
  1242. void Document::IncrementStyleClock() {
  1243. styleClock++;
  1244. if (styleClock > 0x100000) {
  1245. styleClock = 0;
  1246. }
  1247. }
  1248. bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
  1249. for (int i = 0; i < lenWatchers; i++) {
  1250. if ((watchers[i].watcher == watcher) &&
  1251. (watchers[i].userData == userData))
  1252. return false;
  1253. }
  1254. WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers + 1];
  1255. if (!pwNew)
  1256. return false;
  1257. for (int j = 0; j < lenWatchers; j++)
  1258. pwNew[j] = watchers[j];
  1259. pwNew[lenWatchers].watcher = watcher;
  1260. pwNew[lenWatchers].userData = userData;
  1261. delete []watchers;
  1262. watchers = pwNew;
  1263. lenWatchers++;
  1264. return true;
  1265. }
  1266. bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) {
  1267. for (int i = 0; i < lenWatchers; i++) {
  1268. if ((watchers[i].watcher == watcher) &&
  1269. (watchers[i].userData == userData)) {
  1270. if (lenWatchers == 1) {
  1271. delete []watchers;
  1272. watchers = 0;
  1273. lenWatchers = 0;
  1274. } else {
  1275. WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers];
  1276. if (!pwNew)
  1277. return false;
  1278. for (int j = 0; j < lenWatchers - 1; j++) {
  1279. pwNew[j] = (j < i) ? watchers[j] : watchers[j + 1];
  1280. }
  1281. delete []watchers;
  1282. watchers = pwNew;
  1283. lenWatchers--;
  1284. }
  1285. return true;
  1286. }
  1287. }
  1288. return false;
  1289. }
  1290. void Document::NotifyModifyAttempt() {
  1291. for (int i = 0; i < lenWatchers; i++) {
  1292. watchers[i].watcher->NotifyModifyAttempt(this, watchers[i].userData);
  1293. }
  1294. }
  1295. void Document::NotifySavePoint(bool atSavePoint) {
  1296. for (int i = 0; i < lenWatchers; i++) {
  1297. watchers[i].watcher->NotifySavePoint(this, watchers[i].userData, atSavePoint);
  1298. }
  1299. }
  1300. void Document::NotifyModified(DocModification mh) {
  1301. for (int i = 0; i < lenWatchers; i++) {
  1302. watchers[i].watcher->NotifyModified(this, mh, watchers[i].userData);
  1303. }
  1304. }
  1305. bool Document::IsWordPartSeparator(char ch) {
  1306. return (WordCharClass(ch) == CharClassify::ccWord) && IsPunctuation(ch);
  1307. }
  1308. int Document::WordPartLeft(int pos) {
  1309. if (pos > 0) {
  1310. --pos;
  1311. char startChar = cb.CharAt(pos);
  1312. if (IsWordPartSeparator(startChar)) {
  1313. while (pos > 0 && IsWordPartSeparator(cb.CharAt(pos))) {
  1314. --pos;
  1315. }
  1316. }
  1317. if (pos > 0) {
  1318. startChar = cb.CharAt(pos);
  1319. --pos;
  1320. if (IsLowerCase(startChar)) {
  1321. while (pos > 0 && IsLowerCase(cb.CharAt(pos)))
  1322. --pos;
  1323. if (!IsUpperCase(cb.CharAt(pos)) && !IsLowerCase(cb.CharAt(pos)))
  1324. ++pos;
  1325. } else if (IsUpperCase(startChar)) {
  1326. while (pos > 0 && IsUpperCase(cb.CharAt(pos)))
  1327. --pos;
  1328. if (!IsUpperCase(cb.CharAt(pos)))
  1329. ++pos;
  1330. } else if (IsADigit(startChar)) {
  1331. while (pos > 0 && IsADigit(cb.CharAt(pos)))
  1332. --pos;
  1333. if (!IsADigit(cb.CharAt(pos)))
  1334. ++pos;
  1335. } else if (IsPunctuation(startChar)) {
  1336. while (pos > 0 && IsPunctuation(cb.CharAt(pos)))
  1337. --pos;
  1338. if (!IsPunctuation(cb.CharAt(pos)))
  1339. ++pos;
  1340. } else if (isspacechar(startChar)) {
  1341. while (pos > 0 && isspacechar(cb.CharAt(pos)))
  1342. --pos;
  1343. if (!isspacechar(cb.CharAt(pos)))
  1344. ++pos;
  1345. } else if (!isascii(startChar)) {
  1346. while (pos > 0 && !isascii(cb.CharAt(pos)))
  1347. --pos;
  1348. if (isascii(cb.CharAt(pos)))
  1349. ++pos;
  1350. } else {
  1351. ++pos;
  1352. }
  1353. }
  1354. }
  1355. return pos;
  1356. }
  1357. int Document::WordPartRight(int pos) {
  1358. char startChar = cb.CharAt(pos);
  1359. int length = Length();
  1360. if (IsWordPartSeparator(startChar)) {
  1361. while (pos < length && IsWordPartSeparator(cb.CharAt(pos)))
  1362. ++pos;
  1363. startChar = cb.CharAt(pos);
  1364. }
  1365. if (!isascii(startChar)) {
  1366. while (pos < length && !isascii(cb.CharAt(pos)))
  1367. ++pos;
  1368. } else if (IsLowerCase(startChar)) {
  1369. while (pos < length && IsLowerCase(cb.CharAt(pos)))
  1370. ++pos;
  1371. } else if (IsUpperCase(startChar)) {
  1372. if (IsLowerCase(cb.CharAt(pos + 1))) {
  1373. ++pos;
  1374. while (pos < length && IsLowerCase(cb.CharAt(pos)))
  1375. ++pos;
  1376. } else {
  1377. while (pos < length && IsUpperCase(cb.CharAt(pos)))
  1378. ++pos;
  1379. }
  1380. if (IsLowerCase(cb.CharAt(pos)) && IsUpperCase(cb.CharAt(pos - 1)))
  1381. --pos;
  1382. } else if (IsADigit(startChar)) {
  1383. while (pos < length && IsADigit(cb.CharAt(pos)))
  1384. ++pos;
  1385. } else if (IsPunctuation(startChar)) {
  1386. while (pos < length && IsPunctuation(cb.CharAt(pos)))
  1387. ++pos;
  1388. } else if (isspacechar(startChar)) {
  1389. while (pos < length && isspacechar(cb.CharAt(pos)))
  1390. ++pos;
  1391. } else {
  1392. ++pos;
  1393. }
  1394. return pos;
  1395. }
  1396. bool IsLineEndChar(char c) {
  1397. return (c == '\n' || c == '\r');
  1398. }
  1399. int Document::ExtendStyleRange(int pos, int delta, bool singleLine) {
  1400. int sStart = cb.StyleAt(pos);
  1401. if (delta < 0) {
  1402. while (pos > 0 && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))) )
  1403. pos--;
  1404. pos++;
  1405. } else {
  1406. while (pos < (Length()) && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))) )
  1407. pos++;
  1408. }
  1409. return pos;
  1410. }
  1411. static char BraceOpposite(char ch) {
  1412. switch (ch) {
  1413. case '(':
  1414. return ')';
  1415. case ')':
  1416. return '(';
  1417. case '[':
  1418. return ']';
  1419. case ']':
  1420. return '[';
  1421. case '{':
  1422. return '}';
  1423. case '}':
  1424. return '{';
  1425. case '<':
  1426. return '>';
  1427. case '>':
  1428. return '<';
  1429. default:
  1430. return '\0';
  1431. }
  1432. }
  1433. // TODO: should be able to extend styled region to find matching brace
  1434. int Document::BraceMatch(int position, int /*maxReStyle*/) {
  1435. char chBrace = CharAt(position);
  1436. char chSeek = BraceOpposite(chBrace);
  1437. if (chSeek == '\0')
  1438. return - 1;
  1439. char styBrace = static_cast<char>(StyleAt(position) & stylingBitsMask);
  1440. int direction = -1;
  1441. if (chBrace == '(' || chBrace == '[' || chBrace == '{' || chBrace == '<')
  1442. direction = 1;
  1443. int depth = 1;
  1444. position = position + direction;
  1445. while ((position >= 0) && (position < Length())) {
  1446. position = MovePositionOutsideChar(position, direction);
  1447. char chAtPos = CharAt(position);
  1448. char styAtPos = static_cast<char>(StyleAt(position) & stylingBitsMask);
  1449. if ((position > GetEndStyled()) || (styAtPos == styBrace)) {
  1450. if (chAtPos == chBrace)
  1451. depth++;
  1452. if (chAtPos == chSeek)
  1453. depth--;
  1454. if (depth == 0)
  1455. return position;
  1456. }
  1457. position = position + direction;
  1458. }
  1459. return - 1;
  1460. }